Wednesday, January 18, 2017

Operation of If-else condition in java

If-else

------------------------------------------------------------------------------------------------
Syntax:1if(Condition)
{
  ----- instructions-----
}

Syntax:2.
if(Condition)
{
  ----- instructions-----
}
else
{
----instructions----
}

Syntax:3.
if(Condition)
{
  ----- instructions-----
}
else if(condition)
{
------instruction---
}
------
-----
------
else
{
----instructions----
}

EX:1. 
class Test
{
public static void main(String[] args)
{
int i = 10;
int j;
if(i == 10)
{
j = 20;
}
System.out.println(j);
}
}

Status: Compilation Error: J not initiated.

EX:2.
class Test
{
public static void main(String[] args)
{
int i = 10;
int j;
if(i == 10)
{
j = 20;
}
else
{
j = 30;
}
System.out.println(j);
}
}
Status: No Compilation Error.
OP: 20

EX:3.
class Test
{
public static void main(String[] args)
{
int i = 10;
int j;
if(i == 10)
{
j = 20;
}
else if(i == 20)
{
j = 30;
}
System.out.println(j);
}
}
Status: Compilation Error.

EX:4. 
class Test
{
public static void main(String[] args)
{
int i = 10;
int j;
if(i == 10)
{
j = 20;
}
else if(i == 20)
{
j = 30;
}
else
{
j = 40;
}
System.out.println(j);
}
}
Status: No compilation Error.
OP: 20

EX:5.
class Test
{
public static void main(String[] args)
{
final int i = 10;
int j;
if(i == 10)
{
j = 20;
}
System.out.println(j);
}
}
Status: No compilation Error.

EX:6. 
class Test
{
public static void main(String[] args)
{
int j;
if(true)
{
j = 20;
}

System.out.println(j);
}
}
Status: No compilation Error
OP: 20



Reasons:
1. In Java, only class level variables are having default values, local variables are not having default values. If we declare local variable in java application then we must provide initialization for that local variable explicitly either at he same declaration statement or at least be for accessing that local variable. if we access any local variable without initialization then compiler will rise an error like "variable xxx might not have been initialized".

EX:
class A
{
int i;
void m1()
{
int j;
System.out.println(i); // No Error
System.out.println(j); // Error
j = 20;
System.out.println(j); // No Error
}
}

-----------------------------------

2. There are two types of conditional expressions:
1. Constant Expression
2. Variable Expression

A. Constant Expressions:
--> It includes only constants under final constants, it would be evaluated by compiler.
EX 1:
i. if(10 == 10) {    }
ii. if(true) {    }
iii. final int i = 10;
     if(i == 10) {    }


B. Variable Expressions:
--> These expressions includes at least one non-final variable and these expressions are evaluated by JVM.
EX:
i. int i = 10;
   int j = 10;
   if(i == j) {    }

ii. int i = 10;
    if(i == 10) {   }


----------------------------------------------------------------

You may also like -->  Reserve Keyword in JAVA

No comments:

Post a Comment