Control Structures
if statement
if statement is used to execute specific statements conditionally
if(expression){
//here goes your statement
}else{
}
if(i==10){
System.out.println("i==10");
}
if ((i<35) && (i>20)){
System.out.println("i between 20 and 35");
}
if(i<5) System.out.println("i< 5");else System.out.println("i> 5");
Nested if
if(i==2) System.out.println("i== 2");else if (i==4)System.out.println("i==4"); else if (i==10)System.out.println("i==10"); else
System.out.println("not in sepcified range");
Ternary operator
()?: the ternary operator is handy for small comparison and assign statements like
int z=(i==10)?10:i*10;this ststement compares the value of i to 10 ifit is equal to 10 then 10 is assigned to z else i*10 is assigned to z.
Switch Case
The switch case statement is handy replacement for nested if with sepecific variable values.
general syntax
switch(i){
case val1: //statements
break;
case val2://statement;
break;
default://statements;
}
all the case statement should be terminated by break except default or the last case statement.the default will execute for all unspecified conditions
switch(i){
case 1: System.out.println("one");break;
case 2:System.out.println("two");break;
default:System.out.println("others");
}
if variable i will have 0,1,2,3 values, 1 and 2 will execute the respective case statements and 0 and 3 will execute default statements.
Loops
for
general syntax
for(declare start expression;repeat condition;change exprseeion)
eg
for (int i=0;i<10;i++){
//execute the block of statements 10 times
//where i will have values 0-9
}
you can have multiple variable initialisation and change expression while a single repeat conditions seperated by commas
e.g.
for(int i=0,j=0;((i<10) && (j <20));i++,j+=2){
System.out.println(" i="+i+" j="+j);
}
all following form are legible in java
for(;;){
// an infinite loop
}
for(;i<10;i++){
//statement where i is previously declared
}
While Loop
general syntax
while(expression){
//statements to repeat
}
e.g.
int i=0;
while(i<10){
//statements will repeat 10 times utill i is equal to 10
System.out.println(i++);
}
int i=0,j=100;
while((i<10) && (j >0)){
//other statements
i++;
j-=10;
}
do while Loop
general syntax
d{//repeat ststements
}while(expression);
do while is same as the while loop except that one execution of the do while is gaurenteed as the expression is evaluated last.
e.g.
int i=10;
d{
i++;
}while(i<10);
//this is expected to work as the i value is evaluated as the last statement
//but only once
int j=0;
do{
//will iterate 10 times
System.out.println(j++);
}while(j<10);
< Primitive Types and Strings and operators
< Primitive Types and Strings |
Content |
Function Overloading , Access specifiers and modifiers > |