Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
**********************************
OPERATIONS
*********************************
--These types are defined in java. Floating-point arithmetic never throws except
ions, even when performing illegal operations, like dividing zero by zero or tak
ing the square root of a negative number.
double inf = 1.0/0.0; // Infinity
double neginf = -1.0/0.0; // Negative Infinity
double negzero = -1.0/inf; // Negative zero
double NaN = 0.0/0.0; // Not-a-number (NaN)
--When operating with integers, trying to compute a value modulo zero causes an
ArithmeticException. When working with floating-point values, anything modulo 0
.0 evaluates to NaN, as does infinity modulo anything.
--The sign of modulo result is the same as the sign of the first operand.
--The + operator (and the related += operator) also concatenates, or joins, st
rings. If either of the operands to + is a string, the operator converts the o
ther operand to a string.
--To test whether a floatingpoint value is NaN, use the Float.isNan()or Double.i
sNan()method.
--if (data != null && i < data.length && data[i] != -1)
... the second and first conditions are not guaranteed to operate if first i
s false. Compare with ||.
The second and third comparisons in this expression would cause errors if the
first or second comparisons evaluated to false. Fortunately, we dont have to wor
ry about this because of the conditional behavior of the && operator.
--The
instanceof operator can be used only with reference types and objects,
not primitive types and values. instanceof requires an object or array value a
s its left operand and the name of a reference type as its right operand. It eva
luates to true if the object or array is an instance of the specified type; it r
eturns false otherwise.
*****************************************
FLOW CONTROL
*****************************************
--for loop syntax: Both the initialize and update expressions of a for loop
can use a comma to separate multiple initializations and update expressions. For
example:
for(int i = 0, j = 10 ; i < 10 ; i++, j--)
sum += i * j;
--for loops are not restricted to loops that count numbers. For example, you mig
ht use a for loop to iterate through the elements of a linked list:
for(Node n = listHead; n != null; n = n.nextNode())
process(n);
--foreach loop is used for handling collections of objects that need to be loope
d over.
for( declaration : expression )
statement
Or better in more descriptive way: read as "for each variable in collection"
for( variable : collection )
statement
--The break statement causes the Java interpreter to immediately exit the innermo
st containing while, do, for, or switch statement (It has to be ome of these typ
es of statements). If followed by the name of a containing labeled statement, br
eak causes the Java interpreter to immediately exit the named block, which can b
e any kind of statement (in this case, not just a loop or switch; that s why we
say block).
--Continue: While a break statement exits a loop, a continue statement quits
the current iteration of a loop and starts the next one. The continue statement,
in both its unlabeled and labeled forms, can be used only within a while, do, o
r for loop. When used without a label, continue causes the innermost loop to sta
rt a new iteration. When used with a label that is the name of a containing loop
, it causes the named loop to start a new iteration.
--NOTE: With the continue statement, update condition gets evaluated in the fo
r loop but not in the equivalent whileloop, before the loop is iterated again.
--return statement: A returnstatement tells the Java interpreter to stop executi
ng the current method. If the method is declared to return a value, the returns
tatement must be followed by an expression. The value of the expression becomes
the return value of the method.
***********************************
METHODS
***********************************
--The values passed to a method need not have exactly the same type as specified
in the signature, but they must be convertible to those types without casting.
--If a method uses the throw statement to throw a checked exception, or if it ca
lls some other method that throws a checked exception and does not catch or hand
le that exception, the method must declare that it can throw that exception.
--If a class is declared final, all the methods of the class are implicitly fina
l. A final method cannot be overidden or hidden by a subclass.
--All private methods are implicitly final ; anyway, they are only accessible
in the class they are defined. They are invisible to subclasses.
--The
native modifier specifies that the method implementation is written in
some native language such as C and is provided externally to the Java program. Li
ke abstract methods, native methods have no body: the curly braces are replaced
with a semicolon. Native methods are used to interface Java code to existing lib
raries written in C or C++.
--The synchronized modifier prevents two threads from executing a method at th
e same time. Thread must obtain a lock on the method s class (if static method)
or on the relevant instance of the class (for non-static methods). Note that met
hods can themselves thread safe in other ways, so don t rely on this.
--Methods may be declared to accept, and may be invoked with, variable number of
arguments. Such methods are commonly
known as varargs methods. E.g.
public static int max(int first, int ... rest) {
Declared by following the type of the last argument to the method with an ell
ipsis (), indicating that this last argument can be repeated zero or more times.
They operate by converting the variable number of arguments into an array. To th
e Java runtime, the max() method is indistinguishable from this one:
--Eight primitive types are defined by the Java language, and the programmer can
not define new primitive types. Reference types are user-defined, so there is an
unlimited number of them.
--Primitive types represent single values. Reference types are aggregate types t
hat hold zero or more primitive values or objects.
--Primitive types require between one and eight bytes of memory. When a primitiv
e value is stored in a variable or passed to a method, the computer makes a copy
of the bytes that hold the value. Two copies are now present.
--Objects, on the other hand, may require substantially more memory. Memory to s
tore an object is dynamically allocated on the heap when the object is created a
nd this memory is automatically garbage collected when the object is no longer nee
ded. When an object is assigned to a variable or passed to a method, the memory
that represents the object is not copied. Instead, only a reference to that memo
ry is stored in the variable or passed to the method. There is still a single co
py of the object.
--The equality operator (==) tests whether two references refer to the same obje
ct; it does not test whether two objects have the same content! But when used wi
th primitive values, it simply tests whether two values are identical (i.e., whe
ther they have exactly the same bits).
--To test whether two objects have equal content, pass one of them to the equals
() method of the other:
eg. object1.equals(object2)
--All objects inherit an equals() method (from Object), but the default implemen
tation simply uses == to test for identity of references, not equality of conte
nt. A class that wants to allow objects to be compared for equality can define i
ts own version of the equals() method. Point class, for instance, does not do t
his, but the String class does. You can call the equals() method on an array,
but it is the same as using the == operator, because arrays always inherit the
default equals() method that compares references rather than array content. You
can compare arrays for equality with the convenience method java.util.Arrays.equ
als() to get equality of content.
--The wrapper classes Boolean, Byte, Short, Character, Integer, Long, Float,
and Double are immutable, final classes which are usually used when you want to
store primitive values in collections such as java.util.List.
--When you assign a value to a variable or pass a value to a method, boxing or u
nboxing conversions are automatically performed. Because Java performs boxing an
d unboxing automatically, this language feature is often known as autoboxing.
eg.
umber
Integer i = 1; // this is a boxing conversion
int j = i; // i is unboxed here
i++; // i is unboxed, incremented, and then boxed up again
Integer k = i+2; // i is unboxed and the sum is boxed up again
i = null;
j = i; // unboxing here throws a NullPointerException
--Autoboxing makes dealing with collections much easier as well:
eg.
List<Integer> numbers = new ArrayList<>(); // Create a List of I
nteger
numbers.add(-1); // Box int to Integer
int i = numbers.get(0); // Unbox Integer to int
*******************************
PACKAGE AND IMPORTS
******************************
--If you are developing a Java application and will not be releasing any of the
classes for reuse by others, you do not have to worry about unforeseen naming co
nflicts. One common approach is to use the application name as the main package
name (it may have subpackages beneath it).
--API developers should use there domain name, with its elements reversed, as th
e prefix for all their package names. This makes their classes have universally
unique fully qualified names and avoid name conflict with classes in the APIs de
veloped by others.
--import declarations must appear at the start of a Java file, immediately after
the package declaration, if there is one, and before any type definitions.
--A form of import is the on-demand type import, where you specify the name of a p
ackage followed by the characters .* to indicate that any type from that packa
ge may be used without its package name. This does not explicitly import all typ
es as may be assumed. Only types that you actually use in your code are imported
, not just everything in the package.
--You can import the static members of types by using the keywords "import stati
c". This means you can import static methods and fields (usually constants) from
classes directly.
--Using static member import declarations for constants is generally a better te
chnique than implementing an interface that defines the constants.
--If you use static import to import static methods from a class in which there
is more than one static method with that name (method overloading), java always
picks one of the methods depending on the parameters you passed and the method s
arguments. (So, you only really import a name not a particular method, the me
thod is decided when you make a call). It is even legal to import static methods
with the same name from two or more different types as long as the methods all
have different signatures.
Here is one naturalexample:
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
--Java packages do not nest, so javanut.ch03.different is just a different package
than javanut.ch03; it is not contained inside it or related to it in any way.
********************************************************************************
*******************
OO PROGRAMMING CONCEPTS: CLASS, INTERFACE, ENUM and ANNOTATED TYPES
********************************************************************************
*******************
--An object is a collection of data and the methods that operate on that data; t
he data fields and methods of an object are called its members.
--From Java 8 onward, interfaces may use the keyword default to modify a metho
d and to indicate that the method specified in the interface is optional.
--Classes and interfaces are the most important of the five fundamental referenc
e types defined by Java. Arrays, enumerated types (or enums), and annotation types
(usually just called annotations) are the other three.
--Enums are a specialized kind of class and annotations are a specialized kind o
f interface.
--If a method is optional, the interface file must include a default implementat
ion (hence the choice of keyword) which will be used by all implementing classes
that do not provide an implementation of the optional method.
--Enums are a specialized kind of class and annotations are a specialized kind o
f interface.
--Class defination is exemplefied below, with keywords in the given order: acces
s modifier, other modifiers and annotation, keyword class, name, extends other c
lass, implements some method(s) separeted by commas.
eg. public class Integer extends Number implements Serializable, Comparable
{
// class members go here
}
--A generic class may also have type parameters and wildcards as part of its def
inition.
--An abstract class is one whose implementation is incomplete and cannot be i
nstantiated. Any class with one or more abstract methods must be declared abstr
act.
--The final modifier specifies that the class may not be extended. A class can
not be declared to be both abstract and final.
*****************************
1. Fields and Methosd
*****************************
--The use of public static fields that are not final is almost never a good pra
cticeas multiple threads could update the field and cause behavior that is extrem
ely hard to debug.
--The key point to understand about a static field is that there is only a singl
e copy of it.
--A class method can use any class fields and class methods of its own class (or
of any other class), but it cannot use any instance fields or instance methods
because class methods are not associated with an instance of the class. Recall t
hat we always have a this reference to the current object. But class methods a
re not associated with a specific instance, so have no this reference, and no
access to instance fields.
--Any field or method declared without the static modifier is an instance field
or method.
--Every instance (object) of the class has its own copy of instance field. They
are the fields every object of the class must have; eg. every Circle object must
have a radius, so radius should be defined as an instance field not class field
.
--Instance fields define object s state, while instance methods define the objec
t s behavior.
--On the other hand, class fields and methods are just utility fields and utilit
y methods.
--Instance fields are the key to object-oriented programming. Instance fields ho
ld the state of an object; the values of those fields make one object distinct f
rom another.
--In code outside the class, to access an instance method or instance field, the
name of that instance method or field must be prefixed with a reference to the
object of the class that contains it. For example, if the variable c holds a ref
erence to a Circle object, we use the expression c.r to refer to the radius of
that Circle object:
eg.
Circle c = new Circle();
// Create a Circle object; store a ref i
n c
c.r = 2.0;
// Assign a value to its instance field
r
Circle d = new Circle();
// Create a different Circle object
d.r = c.r * 2;
// Make this one twice as big
--To use an instance method from outside the class in which it is defined, we mu
st prefix it with a reference to the instance that is to be operated on. For exa
mple:
Circle c = new Circle();
c.r = 2.0;
double a = c.area();
able c
ct
--Instance methods are not restricted: they can use any member (field or method)
of their class, whether it is declared static or not.
--The this keyword is used as a reference to the current class object. You can
use the this keyword explicitly when you want to make it clear that a method
is accessing its own class fields and/or methods. For example, we can rewrite
--If a constructor does not invoke a superclass constructor, Java does so implic
itly. Also, Java implicitly adds a constructor to a class declared without any c
onstructor. This default constructor does nothing but invoke the super class con
structor.
--In general, if a class does not define a no-argument constructor, all its subc
lasses must define constructors that explicitly invoke the superclass constructo
r with the necessary arguments.
--If both subclass and superclass declare the same instance field, say r, then
r // Refers to the subclass field
this.r // Refers to the subclass field
super.r // Refers to the superclass field
or we can just write
((SuperclassName) this).r // Refers to field r of the Superclass. This
way of casting this to a superclass works at any depth of inheritance.
--In code that you write, you should avoid declaring fields with names that hide
superclass fields. It is almost always a sign of bad code.
--As for class field (static), we can always refer to a class field by prependin
g the name of the desired class; such as Circle.PI to refer to the static PI fie
ld in class Circle.
--When we cast an instance (object) of a subclass to a superclass and assign it
to an instance of the superclass as shown below, where b is an instance of B
, a subclass of A :
//Here we see a salient difference between instace field and instance me
thods.
A a = (A) b; // Casts b to an instance of class A
System.out.println(a.i); // Now refers to A.i (Both A and B defined a da
ta i). B.i nomore hides A.i
System.out.println(a.f()); // Still refers to B.f() (Both defined f(), a
n instance method in both). B.f() overrides A.f()
System.out.println(a.g()); // Refers to A.g() (Both defined g(), a class
method in both). A.g(), a class method, is never overidden.
System.out.println(A.g()); // A better way to invoke A.g()
Here, we understand that although Java treats the fields and methods of a clas
s analogously in many ways, method overriding is not like field hiding at all. Y
ou can refer to hidden fields simply by casting an object to an instance of the
appropriate superclass, but you cannot invoke overridden instance methods with t
his technique.
--Virtual method lookup at runtime: in the above case, the interpreter looks up
the appropriate f() method to call for an object by checking the actual runtime
type of the object referred to by the variable a , starting the lookup from thi
s class; if the actual runtime type is A it calls the f() in A , if the actua
l runtime type is B it calls the f() in B . In the above case b is an actua
l instance of B , so it uses the f() in B .
--To invoke the overriden method in a superclass, we use the super keyword, an
d we can do the same for a hidden field: if a subclass defines an instance field
i and an instance method f() to hide and override the ones in its superclass
respectively, we can simply access the ones in the superclass from within the su
bclass as follows:
super.i //or A.i if the superclass is A .
and
super.f() // or A.f(). Whenever super is used virtual method lookup
starts at the superclass and move up the hierarchy, it will not even bother to c
heck the method in the subclass.
respectively. Note that, in the previous code, the expression super.f() is not
the same as ((A)this).f()
-- super , as used above, can be used only to invoke an overridden method FROM
WITHIN the class that overrides it, and not by an external code using the subcla
ss.
--For narrowing conversion, only cast an object to the type of a subclass if you
are sure, based on the logic of your program, that the object is actually an in
stance of the subclass. If it is not, the interpreter throws a ClassCastExceptio
gram...
String s = (String) o;
*******************************************
5. Data Hiding and Encapsulation
*******************************************
--The most important reason for encapsulation is to hide the internal implementa
tion details of your class.
--Call a method from outside to change any field in the inside, that method can
be sure to do everything necessary to keep the state of your class consistent.
--Similarly, if a class defines certain methods or fields for internal use only,
hiding these methods and fields prevents users of the class from calling them.
--If you don t want a static (class member which only one copy is created when t
he class is loaded) member to be accessible to anyone other than this class, you
can declare it private static .
--Default access is more restrictive than protectedas default access does not all
ow access by subclasses outside the package.
--If B is a subclass of A, and A has a protected field say name , then B inheri
ts that field and can use it in its code by calling, for example, super.name e
ven if B is in another different package. However, instances (objects) of B cann
ot read the protected fields from the instances (objects) of A except if both A
and B reside within the same package.
--Use public only for methods and constants that form part of the public API of
the class. The only acceptable usage of public fields is for constants or immuta
ble objects, and they must be also declared final.
--Use protected for fields and methods that arent required by most programmers us
ing the class but that may be of interest to anyone creating a subclass as part
of a different package.
--Use the default package visibility for fields and methods that are internal im
plementation details but are used by cooperating classes in the same package.
--If you are not sure whether to use protected, package, or private accessibilit
y, start with private. If this is overly restrictive, you can always relax the a
ccess restrictions slightly (or provide accessor methods, in the case of fields)
.
*******************************************
JAVA TYPE SYSTEM
*******************************************
************************
1. Interface
************************