# Learning by developing

## Programming – Java, OCJP 6: T-4. Language fundamentals:

P { margin-bottom: 0.08in; }A:link { }

Conditional operator: x= (expression) ? 1:2;

This means that, if the expression is true, x=1, if it is false, then x = 2.

It is also valid with the ternary operator to set different conditions one inside the other:

Conditional operator: x= (expression) ? 1:((expression 2)? res1:res2);

This means that, if expression is false, then expression 2 would be checked and the result assigned.

Integer i = 42;

E.g.: String s = (i<40)?”life”:(i>50)?”universe”:”everything”;

The result is that s = “everything” since i>40(go to 1st expression, false) and i<50(right expression, false to (i>50))

Long circuit comparators(check both expressions before returning the value): & and | (and/or).

Short circuit comparators(check the first expression and, depending on its value, checks the second one or returns): && and ||. E.g.: && would check the left expression and, if it is false, would automatically return false. || would be similar, but would already return true if the first expression is true withot checking the second one.

For-declarations:

Valid to declare variables inside the first block of the for(many,not only one).

 for(int x=0, y=0; x=z.length; x++){ ..}

This is NOT valid:

 for(int x=0, int y=0; x=z.length; x++){ ..}

See the coma, it should be int x =0; int y =0;

Note: In a FOR loop, the expression (x++ means the same as ++x) happens once the iteration is done, so:

 for(int x=0; x<0; x++){ ..} == for(int x=0; x<0;++x){ ..}

1st. X= 0;

2nd. If x<0; execute body

3rd. Execute x++ or ++x (is the same).

While(or DO-while()) loop:

 x1 = 0; while(++x1<3) exits = x1;

1st. x = x+1;

2nd. if x1<3, execute loop.

Difference with:

 x1 = 0; while(x1++<3) exits = x1;

1st. if x1<3, execute loop

2nd. x1= x1 +1; // IMPORTANT ++x <3, first increases and then compares

Labels:

 public class HelloWorld{ public static void main(String []args){ asereje: for(int i=0; i<5; i++){ for(int j =0 ; j<2; j++){ System.out.println(“inside the break”); break asereje; } } System.out.println(“Hello World”); } }

The break breaks the label(a continue would continue the most outer for). This would be the output:

 Compiling the source code…. \$javac /tmp/136521760016989/HelloWorld.java 2>&1 Executing the program…. \$java -classpath /tmp/136521760016989/ HelloWorld inside the break Hello World

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

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