# Learning by developing

## Programming – Java, OCJP 6: T-3. Assignments and operators:

Types of Integer:

• Decimal (Base 10): int x = 10;(no prefix)

• Hexadecimal (Base 16): int x = 0x10; (prefix ‘0x’, which value is 16)

• Octal (Base 8): int x = 010; (prefix ‘0’, which value is 8).

Types of floating point:

• 36.37 = double(casting needed).

• 36.37F = float.

Characteristics of characters:

• They appear between ” and there might be special chars such as ‘u'(unicode), ‘t'(tabulator) or ‘n'(line return).

• They are ‘int’ without sign,so if you add one value which is “negative” or greater than the size of an int, then we would lose precission(it would trunkate but would not give an error) and so, if we do not want to lose precission, we would need to do a “casting”.

The result of one expression involving integers(int, short, byte) is always an int. If you sum two bytes(byte a= b+c (b,c, = bytes) and assign it to one byte, it will result in a compiler error, since it may overflow.

A boolean cannot be assigned to anything but to other boolean(not to int).

If you sum one int and one string and the result is stored in one string, the int is automatically converted tostring. E.g.: int x = 10. String a = ” something”; String b = x +a = “10 something”.

++i: first increment and then assign. I++: first assign and then increment.

>>> are the unsigned right shift: puts ‘0’ in the left/right side when shifting.

Note: <<< DOES NOT EXIST!

Bitwise operations: &(AND), ^(XOR), |(OR), ~(NOT).

Logical operations: &&(AND), ||(OR).

Logical operators check the expression from left to right and, if something fails, it does not continue looking the rest of expressions. Bitwise operations do it until the end. So 1 | 1 will result in TRUE, but it will check everything, so that it can fail.

Note: & and &&: if both == true, both return true, the same with | and ||.

Primitive implicit casting:

Complex operators, such as +=, -=, *=and |= doimplicit casting to the type you are operating, so:

byte b = 1;

b+=2; <– is CORRECT since it does casting

BUT:

b = b+2; <– IS NOT CORRECT , since any operation which includes “integer” numbers, will return an “int” as a result, and so casting is needed).

The primitives can contain any variable from its position and previous to it:

 Position Data type Can contain 1 Byte Current position + previous 2 Short Current position + previous 3 Char Current position 4 Int Current position + previous 5 Long Current position + previous 6 Float Current position + previous 7 Double Current position + previous

Asigning literals to variables: If the literal is bigger than the variable size, the variable is trunkated(if it is explicitly casted) and so some bits can be lost or it would give an “Error. Possible loss of precission” if it is not casted.

Asign one value of one primitive to another one: Copies the value(so they do not copy references like with objects).

Variable lifes:

 Static variables Created when the class is loaded and alive until the class is unloaded from the JVM. Instance variables Created when an instance is initialized and alive while the instance exists. Local variables Alive while the method stays in the stack Block variables Alive while the block is being executed.

Default variable initialization values:

 Variable type Default value Object’s reference null(not referencing any object) byte,short,int,long 0 float,double 0.0 boolean False char ‘u0000′

Symbols: NI = Not initialized value, IV = Inner values(for an array content/cells):

Array variables:

• If the array is a local variable(method):

• NI: does not have any value, not even null (so if you compare to null, it gives an error)

• If the array is an instance variable(object):

• NI: It would point to null if it is not initialized(it is an object).

• IV: If the array has been initialized but its cells/contents have not been. The values of the cells will always(in local/instance arrays) be initialized to its default value(see previous table).

Primitive variables and objects:

• If the primitive/object is a local variable(method):

• NI: do not have any value, not even null (so if you compare to null, it gives an error)

• If the primitive/object is an instance variable(object):

• NI: It would point to null if it is not initialized(if it is an object) and to its default value(if it is a primitive).

Wrappers:

 Primitive Wrapper Class Constructor arguments boolean Boolean boolean or String byte Byte byte or String char Character char double Double double or String flat Float float,double or String int Integer int or String long Long long or String short Short short or String
 Method (s – static, n = NFE exception) Boolean Byte Character Double Float Integer Long Short ByteValue X X X X X X DoubleValue X X X X X X FloatValue X X X X X X IntValue X X X X X X LongValue X X X X X X ShortValue X X X X X X ParseXxx (s,n) x X X X X X ParseXxx (with radix) (s,n) X X X X ValueOf (s,n) S X X X X X X ValueOf (with radix) (s,n) X X X X toString X X X X X X X X ToString (primitive) (s) X X X X X X X X toString (primitive,radix) (s) X X

Essential method signatures for Wrapper conversion:

 primitive xxxValue() Convert a Wrapper to a primitive primitive parseXxx(String) Convert a String to a primitive Wrapper valueOf(String) Convert a String to a Wrapper

Wrapper classes:

Integer i1 = new Integer(50);

Integer i2 = new Integer(“50″);

Integer i2 = new Integer(x); int x = 50;

Character c = new Character(‘A’);

ValueOf() method: All wrappers classes, except Character, define a static method called valueOf(), giving the WRAPPER object corresponding to the primitive value representing the String argument. E.g.: Float.valueOf(“1.5f”); Integer.valueOf(“2″)

parseX methods: E.g.: parseInt, parseDouble, parseFloat, parseLong, parseByte, parseShort. It takes one String as the argument and converts it to its corresponding PRIMITIVE.

Base Conversion: Integer and Long have toBinaryString(), toOctalString() E.g.: String aux = toHexString(25)

Autoboxing and unboxing: In general wrappers can be using as a primitive.

• Autoboxing: Gets into the wrapper(Integer) the primitive(int) automatically.

• Boxing: Gets the primitive into the wrapper.

• Unboxing:Obtains the primitive from the wrapper.

Comparisson operators(overriden/not) with wrappers:

 != Compeares references(not overriden) Equals() and == Compare values(overriden). If we compare with “==”a wrapper and a primitive, the wrapper makes “unboxing”to itself before comparing.

Note: It is legal to do:

Boolean f1 = true;(wrapper does unboxing).

if((f1=false)){ System.out.println(“hola”);} <– this would, first set f1 = false and check value of f1, so the expression would be false and “hola” would not be printed.

Static blocks and Inits:

 Code which will be executed: Execution order: 1st. Static blocks in order(code in class). 2nd. Instance init blocks({}) when variable is created(new) <– So if A extends from B and B extends from C it would be: C.instance blocks, C.constructor, B instance blocks, B.constructor and A.instance blocks and A.constructor. 3rd. Constructor of the variable. Result of the execution of the previous code: E.g.: C extends B. B extends A. “new C()”: 1st All static in order of class. 2nd. A init blocks(). 3rd. A.A() constructor. 4th. B.init blocks 5th.B.B() constructor. 6th.C.init blocks. 7th.C.C() constructor.

Passing variables to methods:

• A primitive that is passed(input argument in a method) will be passed as a copy.

• An object that is passed to a method, will result in a reference to the object that is passed, so that its attributes can be changed with object.method().

Garbage Collection:

Java Virtual Machine decides when to run the garbage collector, which is a low priority thread that runs periodically, releasing memory used by objects that are not needed anymore. The algorithm changes depending on the virtual machine. If there is not enough memory an “OutOfMemoryError” exception is launched(if the garbage collector can not free enough memory).

You can request the garbage collector, but not force it: System.gc() or Runtime.getRuntime().gc();

Note: When asked about garbage collection and objects: don’t count primitives inside objects, but do count other objects

Eligibility for garbage collection:

 An object that was created had one reference variable pointing to it. If the reference variable is pointed to null, then the object has no more references and is eligible for being collected. Additionally, all the objects created locally in a method are eligible for GC when the method returns, unless they are exported out of the method(returned/thrown as an exception). Objects that refer to each other can still be eligible for GC if no live thread can access either of them. 1. Integer object refers to o1. <– Eligible for GC after line 3, where o1 points to other object and it is not pointed by any variable anymore. The “new String”object from line 2 does NOT become eligible for GC after line 4 since o1 = o2 and if o2 = null, o1 is still pointing to it.

Finalize method: Do necessary cleanup before the GC removes the object from memory. It is the method called by the GC on an object when GC determines that there are no more references to the object and it is defined in the Object class. It can be overriden to add additional clean up:

protected void finalize() throws Throwable.

Note: if you run finalize() in an object by yourself, it will be ineligible for GC. The “finalize” method will not be called again by the GC, it won’t run more than once.

Note: GC makes no guarantees: finalize() may never run.

Note2: when you are asked in the line “x”, is in that precisse moment, not until that moment. So the methods called before would have finished already. Important: variables inside object are also collectable when the reference to that object dissapear.

Note: This happens also if it is an “isolation island” where an object has a reference to a variable of its same class:

**********************************************

The books I have used are these ones, which I strongly recommend. You can support this blog buying them through this links:

and

For OCJP version 7, I would recommend:

Categories: Java