'if' selection statements

'if' selection statements are used for the below reason -


If you want any statement to be executed only when the condition passes. Then we have to go with if selection statements.  i.e. Lets say there is a software at park entrance, which says -> for children below 10 years they charge entrace ticket at Rs 50 and for others its free. So in this case we can use if selection statement, when age less than 10 years is true, Rs 50 should be assigned to the ticket price. if selection statement is one of the 'Control Flow' Statements.

Program to demonstrate the if condition statement when the condition provided to it results true            

class IfConditionTrue
{
   public static void main(String args[])
   {
      int a=3,b=4;

           if(a<b)    // The statements inside the if block will get executed only if the condition is true i.e. if(a<b) -> if(3<4) -> if(true)
           {
                System.out.println("You are Lucky");
            }

   }
 }

Output of this Program:

You are Lucky

As the result of the condition provide in the if statement i.e. a<b is true, the if statement will execute all the statements provided in the if block, so it executed System.out.println("You are lucky"); statement.
Program to demonstrate the if condition statement when the condition provided to it results false

class IfConditionFalse
{
   public static void main(String args[])
   {
      int a=4,b=3;

            if(a<b)  // The statement inside the if block wont get executed if the condition is false i.e. if(a<b) -> if(4<3) -> if(false)
           {
               System.out.println("You are lucky");
            }

    }
 }

Output of this program:  (No Output)

The program runs without any errors but nothing will get printed as the condition provided in the if statement i.e. a<b results false as a result, all the statements inside the if statement block wont get executed. Hence in this program nothing got printed.

Program to compare two variables using if statement and print the comparison result

class IfConditionCompare
{
   public static void main(String args[])
   {
      int x=4,y=4;

       if(x<y)
       {
         System.out.println("x is less than y");
       }

       if(x>y)
     {
        System.out.println("x is greater than y");
       }

       if(x==y)
      {
        System.out.println("x is equal to y");
       }

   }
 }

Output of this program:

x is equal to y 
If.....else... Statement  (program demonstration)

/* As you have seen in the above programs, that the statements inside the if block wont execute if the conditions fails, and hence the program wont print anything. But we can add addition else block to the if block, so that the program can execute the statements inside the else block if the if block condition fails. */

class IfElse
{
   public static void main(String args[])
   {
      int x=4,y=3;

       if(x<y)
       {
        System.out.println("x is less than y");
       }
       else                                         // else block will get executed when the if condition fails
       {
         System.out.println("x is greater than y");
       }
   }
 }

Output of this program:

x is greater than y

Since the if condition failed, the statement inside the else block got executed.
If statements  can be written without blocks i.e. without { and } flower braces if there is a single statement inside the block -  (Program  Demonstration)

class IfElseWithoutBraces
{
   public static void main(String args[])
   {

       int a=2,b=2;

       if(a==b)
           System.out.println("a is equal to b");
       else
           System.out.println("a is not equal to b");

    }
 }

Output of this program:

a is equal to b

Observe that this program still works if we wont provide any flower braces to the if..else statements. Any how this is only possible if we have a single statement inside the if or else blocks.
Nested Ifs - (Program Demonstration)

 if...else...statements inside another if..else..statements will result in nested Ifs.

class NestedIf
{
   public static void main(String args[])
   {

        int a=3,b=4,c=5,d=3;

        if(a==d)
        {
           System.out.println("We are inside the Outer 'if' block");

              if(b>c)
                 System.out.println(" I know this text in the inner 'if' block is not going to be printed on execution as the condition of this inner 'if' block results fail");
              else
                 System.out.println("We are inside the inner 'else' block");
        }
        else
           System.out.println("I know this text in the outer 'else' block is not going to be printed on execution as the condition of the inner 'if' block results pass");

    }
 }

Output of this program:

We are inside the Outer 'if' block 
We are inside the inner 'else' block
 if-else-if Ladder (Program demonstration)

As you can see in our previous program where we have executed the 'if' block if the condition results true and executing the 'else' block without any condition. But in this if-else-if ladder, we will add condition to the 'else' part until all our conditions gets finished.

class IfElseIf
{
   public static void main(String args[])
   {

        int a=3,b=4,c=5;

        if(a==4)
           System.out.println("This will get printed if the a==4 condition resutls ture, else it will check for the next condition in the else-if part");
        else if(b==5)
          System.out.println("This will get printed if the b==5 condition results true, else it will check for the next condition in the else-if part");
       else if(c==6)
           System.out.println("This will get printed if the c==6 condition results true, else it will check for the next condition in the else-if part");
         else
           System.out.println("All the above conditions failed, hence this statement got executed and printed");
    }
 }

Output of this program:

All the above conditions failed, hence this statement got executed and printed

Lets go through the program once:

  1. started with if(a==4) i..e. 3==4 i.e. false, hence the statement inside the 'if' block didn't execute. (The program would have ended if  if(a==4) resulted true)
  2. Next it executed else if(b==5) i.e. b==5 -> 4==5 -> false. Hence the statement inside else if(b==5) didn't execute. (The program would have ended if else if(b==5) resulted true)
  3. Next it executed else if(c==6) i.e. c==6 -> 5==6 -> false. Hence the statement inside else if(c==6) didn't execute (The program would have ended if else if(c==6) resulted true)
  4. Next it executed 'else' block and printed "All the above conditions failed, hence this statement got executed and printed"  

Operator Precedence

The following row shows the order of precedence for Java operators:


 Highest  ( )    !    *   /  %  +   -  >  >=  <  <=  ==  !=  &   |  ?:  =  Lowest 

As its not possible to go through the examples of how each and every operator is having priority over other operator, I'm going to example the operator precedence with  only one example.

Program to demonstrate the difference before and after using the high priority operator '( )'                                                                                        

class OperatorPrecedence
{
   public static void main(String args[])
   {
      int a=3,b=4,c=5,d,e;

      d=a*b+c;    // without using high priority operator '( )' -> a*b+c i.e. 3*4+c i.e. 12+c i.e. 12+5 i.e. 17
      e=a*(b+c);  //After using high priority operator '( )' -> a*(b+c) i.e. a*(4+5) i.e. a*9 i.e. 3*9 i.e. 27

      System.out.println("Without using the parenthesis the result is "+d);
      System.out.println("After using the parenthesis the result is "+e);

   }
}
Output of this program:

Without using the parenthesis the result is 17
After using the parenthesis the result is 27

Assignment and '?' operator


Program to demonstrate basic assignment operator usage                                                                                                                                                                                                                                      

class AssignmentOperator
{
   public static void main(String args[])
   {
      int a;
      a=5;       //Here we are using assignment operator '=' to assign value '5' to variable 'a'
      System.out.println(a);
   }
 }

Output of this program:

5
Program to demonstrate assignment operator assigning a single value to more than one variable in a single statement

class AssignmentOperator2
{
   public static void main(String args[])
   {
      int a,b,c;
      a=b=c=5;    //Here we are using assignment operator '=' to assign value '5' to variables 'a','b' and 'c' in a single statement
      System.out.println(a);
      System.out.println(b);
      System.out.println(c);

   }
 }

5
5
5

Program to demonstrate '?' operator

class QuestionOperator
{
   public static void main(String args[])
   {
      int i=10;

      int k= i<0 ? -i: i;    // i<0 is true then -i after the question mark will be assigned to variable 'k' else value of i will be assigned

      System.out.println("k="+k);

   }
 }

Output of this program:

k=10
Another Program to demonstrate the '?' operator

class QuestionOperator
{
   public static void main(String args[])
   {
      int i=-10;

      int k= i<0 ? -i: i;     // i<0 is true then -i after the question mark will be assigned to variable 'k' else value of i will be assigned

      System.out.println("k="+k);

   }
 }

Output of this program:

k=10

Boolean Logical Operators


Program to demonstrate the Logical And operator  '&'                                                                                                                               

class LogicalAnd
{
   public static void main(String args[])
   {
      boolean a=true,b=false;

      System.out.println(a&a);    // & stands for logical And operator, a&a will perform true&true operation and will result in true as both the variables holds true
      System.out.println(a&b);   // a&b i.e. true&false, this will result in false as one of the variable holds false
      System.out.println(b&a);   // b&a i.e. false&true, this will result in false as one of the variable holds false
      System.out.println(b&b);   // b&b i.e. false&false, this will result in false as both the variables holds false

   }
 }

Output of this program:

true
false
false
false
Program to demonstrate the Logical OR operator  '|'

class LogicalOR
{
   public static void main(String args[])
   {
      boolean a=true,b=false;

      System.out.println(a|a);    // '|' stands for logical OR operator, a|a will perform true|true operation and will result in true as both the variables holds true
      System.out.println(a|b);    // a|b i.e. true|false, this will result in true as one of the variable holds true
      System.out.println(b|a);   // b|a i.e. false|true, this will result in true as one of the variable holds true
      System.out.println(b|b);    // b|b i.e. false|false, this will result in false as both the variables holds false

   }
 }

Output of this program:

true
true
true
false

Program to demonstrate the Logical NOT operator '!'

class LogicalNOT
{
   public static void main(String args[])
   {
      boolean a=true,b=false;
      System.out.println(!a);     // '!' stand for NOT operator, as the value of a is true so the value of !a will be !true i.e. false
        System.out.println(!b);     // '!' stand for NOT operator, as the value of b is false so the value of !b will be !false i.e. true
   }
 }

Output of this program:

false
true

Relational Operators


Program to demonstrate the relational operator '==' (i.e.Equal to)                                                                                                       


class OperatorEqualTo
{
   public static void main(String args[])
   {
       int a=3,b=3;
       System.out.println(a==b);     //a==b will return 'true' as 3==3 is true
   }
 }

Output of this program:

true

Program to demonstrate the relational operator '!=' (i.e.Not Equal to)


class OperatorNotEqualTo
{
   public static void main(String args[])
   {
       int a=3,b=3;
       System.out.println(a!=b);      //a!=b will return 'false' as 3!=3 is false
   }
 }

Output of this program:

false

Program to demonstrate the relational operator '<' (i.e. less than)


class OperatorLessThan
{
   public static void main(String args[])
   {
       int a=3,b=4,c=6;

       System.out.print(" a is less than b is "); System.out.println(a<b);
       System.out.print(" c is less than b is "); System.out.println(c<b);
   }
 }

Output of this program:

a is less than b is true
c is less than b is false
Program to demonstrate the relational operator '>' (i.e. greater than)


class OperatorLessThan
{
   public static void main(String args[])
   {
       int a=3,b=4,c=6;

       System.out.print(" a is greater than b is ");
       System.out.println(a>b);
       System.out.print(" c is greater than b is ");
       System.out.println(c>b);
   }
 }

Output of this program:

a is greater than b is false
c is greater than b is true

Program to demonstrate the relational operator '<=' (i.e.less than or Equal to)

class OperatorLessThanOrEqualTo
{
   public static void main(String args[])
   {
       int a=3,b=3,c=6;

       System.out.print(" a is less than or equal to b is ");
       System.out.println(a<=b);     //a and b are equal hence a<=b will return true
       System.out.print(" a is less than or equal to c is ");
       System.out.println(a<=c);    // a is less than c hence a<=c will return true
       System.out.print(" c is less than or equal to b is ");
       System.out.println(c<=b);   // c is neither less than b nor equal to b hence c<=b will return false
   }
 }

Output of this program:

a is less than or equal to b is true
a is less than or equal to c is true
c is less than or equal to b is false
Program to demonstrate the relational operator '>=' (i.e. greater than or Equal to)


class OperatorLessThanOrEqualTo
{
   public static void main(String args[])
   {
       int a=3,b=3,c=6;

       System.out.print(" a is less than or equal to b is ");
       System.out.println(a>=b);     //a and b are equal hence a>=b will return true
       System.out.print(" a is less than or equal to c is ");
       System.out.println(a>=c);    // a is neither greater than c  nor equal to c hence a>=c will return false
       System.out.print(" c is less than or equal to b is ");
       System.out.println(c>=b);   // c is greater than b  hence c>=b will return true
   }
 }

Output of this program:

a is greater than or equal to b is true
a is greater than or equal to c is false
c is greater than or equal to b is true

Arithmetic Operators

Operators in Java are just symbols used to perform operations on the provided data. Lets say we have an operator + , which is used to add values or values stored in variables.


Example -

1+2  //Here plus symbol is an operator which can be used to perform addition of two numbers.

Like this we have many operators which perform various operations. Lets learn them practically by following the current and few next posts.


Addition operator - Program to demonstrate the Addition operator

class Addition
{
  public static void main(String args[])
  {
    int a=1+9;    // '+' is the operator used for addition i.e. '+' symbol adds 1 and 9 numbers
    System.out.println("a="+a);
  }
}

Output of this program:

a=10
                                                                                                                                               
Adding two decimal numbers and storing in an int type variable

class AddingDecimalsStoringInt
{
  public static void main(String args[])
  {
     int a=5.5+3.2;   //Adding two decimal numbers i.e. 5.5 and 3.2 and storing the result in the int type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

Error "Required int values but found decimal values" 

i.e. We cant assign decimal values to the int type variables.
If we replace the statement int a=5.5+3.2; to int a=(int)5.5+(int)3.2; i.e. by adding type cast to the decimal values, the program will not throw the error, instead it will output a=8 i.e. digits after the decimal points will be ignored while adding.
Adding two int numbers and storing in an double type variable

class AddingIntegersStoringDouble
{
  public static void main(String args[])
  {
     double a=5+3;     //Adding two integers i.e. 5 and 3 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=8.0

Adding two decimal numbers and storing in a double type variable

class AddingDecimalNumbersStoringDouble
{
  public static void main(String args[])
  {
     double a=5.5+3.2;    //Adding two decimal numbers i.e. 5.5 and 3.2 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=8.7
Subtraction operator - Program to demonstrate the Subtraction operator

class Subtraction
{
  public static void main(String args[])
  {
     int a=9-1;    // '-' is the operator used for subtraction i.e. '-' symbol deducts 1 from 9.
     System.out.println("a="+a);
  }
}

Output of this program:

a=8
Subtracting two decimal numbers and storing in an int type variable

class SubtractingDecimalsStoringInt
{
  public static void main(String args[])
  {
     int a=5.5-3.2;    //Subtracting two decimal numbers i.e. deducting 3.2 from 5.5 and storing the result in the int type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

Error "Required int values but found decimal values" 

i.e. We cant assign decimal values to the int type variables.
If we replace the statement int a=5.5-3.2; to int a=(int)5.5-(int)3.2; i.e. by adding type cast to the decimal values, the program will not throw the error, instead it will output a=2 i.e. digits after the decimal points will be ignored while subtracting.
Subtracting two int numbers and storing in an double type variable

class SubtractingIntegersStoringDouble
{
  public static void main(String args[])
  {
     double a=5-3;     //Subtracting two integers i.e.Deducting 3 from 5 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=2.0
Subtracting two decimal numbers and storing in a double type variable

class SubtractingDecimalNumbersStoringDouble
{
  public static void main(String args[])
  {
     double a=5.5-3.2;    //Subtracting two decimal numbers i.e. deducting 3.2 from 5.5 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=2.3
Multiplication operator - Program to demonstrate the Multiplication operator

class Multiplication
{
  public static void main(String args[])
  {
     int a=9*1;    // '*' is the operator used for Multiplication i.e. '*' symbol multiplies 9 with 1.
     System.out.println("a="+a);
  }
}

Output of this program:

a=9

Multiplying two decimal numbers and storing in an int type variable

class MultiplyingDecimalsStoringInt
{
  public static void main(String args[])
  {
     int a=5.5*3.2;     //Multiplying two decimal numbers i.e. 5.5 from 3.2 and storing the result in the int type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

Error "Required int values but found decimal values" 

i.e. We cant assign decimal values to the int type variables.
If we replace the statement int a=5.5*3.2; to int a=(int)5.5*(int)3.2; i.e. by adding type cast to the decimal values, the program will not throw the error, instead it will output a=15 i.e. digits after the decimal points will be ignored while multiplying.
Multiplying two int numbers and storing in an double type variable

class MultiplyingIntegersStoringDouble
{
  public static void main(String args[])
  {
     double a=5*3;     //Multiplying two integers i.e. 5 and 3 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=15.0
Multiplying two decimal numbers and storing in a double type variable

class MultiplyingDecimalNumbersStoringDouble
{
  public static void main(String args[])
  {
     double a=5.5*3.2;    //Multiplying two decimal numbers i.e. 5.5 from 3.2 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=17.6
Division operator - Programs to demonstrate the Division operator

class Division
{
  public static void main(String args[])
  {
     int a=10/5;   // '/' is the operator used for Division i.e. '/' symbol divides 10 by 5.
     System.out.println("a="+a);
  }
}

Output of this program:

a=2

Dividing two decimal numbers and storing in an int type variable

class DividingDecimalsStoringInt
{
  public static void main(String args[])
  {
     int a=5.5/3.2;       //Dividing two decimal numbers i.e. Dividing 5.5 by 3.2 and storing the result in the int type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

Error "Required int values but found decimal values" 

i.e. We cant assign decimal values to the int type variables.
If we replace the statement int a=5.5/3.2; to int a=(int)5.5/(int)3.2; i.e. by adding type cast to the decimal values, the program will not throw the error, instead it will output a=1 i.e. digits after the decimal points will be ignored while dividing.
Dividing two int numbers and storing in an double type variable

class DividingIntegersStoringDouble
{
  public static void main(String args[])
  {
     double a=5/3;     //Dividing two integers i.e. Dividing 5 by 3 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=1.0
Dividing two decimal numbers and storing in a double type variable

class DividingDecimalNumbersStoringDouble
{
  public static void main(String args[])
  {
     double a=5.0/3;     //Dividing two decimal numbers i.e. Dividing 5.0 by 3 and storing the result in the double type variable 'a'

     System.out.println("a="+a);

  }
}

Output of this program:

a=1.6666666666666667

If you clearly observed the different between the last two programs, they are almost same but the statement double a=5/3; in program one is written as the statement double a=5.0/3;  i.e. in the first statement double a=5/3; though the result of the integers gets stored in double type variable the output value is 1.0 instead of 1.6666666666666667 because in the 5/3 operation, both 5 and 3 are integers hence the result will be calculated by ignoring the digits after the decimal point value i.e. 1 is the result of 5/3 operation but when assigned to double a; variable , it gets converted to 1.0. Where as in the statement double a=5.0/3; one of the value is a decimal in 5.0/3 operation hence the result will be in decimal format only i.e. 1.6666666666666667 and later it gets assigned to variable a which of double type as 1.66666666666666667.
Modulus operator 

The Modulus operator '%' returns the reminder of a division operator.
Program to demonstrate the operation of modulus operator on integers

class ModulusIntegers
{
  public static void main(String args[])
  {
     int a=8%3;    //Finding the reminder of 8 when divided by 3 using the modulus operator '%'

     System.out.println("a="+a);

  }
}

Output of this program:

a=2
Program to demonstrate the operation of modulus operator on decimals

class ModulusDecimals
{
  public static void main(String args[])
  {
     double a=8.568%3;   //Finding the reminder of 8.568 when divided by 3 using the modulus operator '%'
     System.out.println("a="+a);
  }
}

Output of this program:

a=2.567999999999999

Compound Assignment Operators

Java provides special operators called Compound Assignment operators which combine an arithmetic operation with an assignment '='
Program to demonstrate the '+=' compound assignment operator

class PlusEqualCompoundAssignmentOperator
{
   public static void main(String args[])
   {
      int a=4;
      a+=4;   //Using Compound assignment operator to increment the variable 'a' value by 4 i.e. 4+4
      System.out.println("a="+a);
   }
}

Output of this program:

a=8

The a+=4; statement works like a=a+4 i.e. a=4+4; i.e. a=8
Program to demonstrate the '-=' compound assignment operator

class MinusEqualCompoundAssignmentOperator
{
   public static void main(String args[])
   {
      int a=4;
      a-=4;    //Using Compound assignment operator to decrement the variable 'a' value by 4 i.e. 4-4
      System.out.println("a="+a);
   }
}

Output of this program:

a=0

The a-=4; statement works like a=a-4 i.e. a=4-4; i.e. a=0
Program to demonstrate the '*=' compound assignment operator

class MultiplyEqualCompoundAssignmentOperator
{
   public static void main(String args[])
   {
      int a=4;
      a*=4;   //Using Compound assignment operator to multiply the variable 'a' value by 4 i.e. 4*4
      System.out.println("a="+a);
   }
}

Output of this program:

a=16

The a*=4; statement works like a=a*4 i.e. a=4*4; i.e. a=16
Program to demonstrate the '%=' compound assignment operator

class PercentileEqualCompoundAssignmentOperator
{
   public static void main(String args[])
   {
      int a=4;
      a%=3;    //Using Compound assignment operator to find the reminder after dividing the variable 'a' value by 3
      System.out.println("a="+a);
   }
}

Output of this program:

a=1

The a%=3; statement works like a=a%3 i.e. a=4%3; i.e. a=1
Program to demonstrate the increment operator ++VariableName

class PrefixIncrementOperator
{
   public static void main(String args[])
   {
      int a=4;
      ++a;     //Increment the value of variable 'a' by one
      System.out.println("a="+a);
   }
}

Output of this program:

a=5

Observe the value of variable 'a' got incremented by 1 i.e. a=a+1 i.e. a=4+1 i.e. a=5
Program to demonstrate the increment operator VariableName++

class PostfixIncrementOperator
{
   public static void main(String args[])
   {
      int a=4;
      a++;      //Increment the value of variable 'a' by one
      System.out.println("a="+a);
   }
}

Output of this program:

a=5

Observe the value of variable 'a' got incremented by 1 i.e. a=a+1 i.e. a=4+1 i.e. a=5
Program to demonstrate the difference between the increment operators ++VariableName  & VariableName++ 

So what is the difference between the prefix increment operator and postfix increment operator. To understand it first we have to understand the below program:

class PrefixVsPostfix
{
   public static void main(String args[])
   {
      int a=1;
      int b=1;
 
      System.out.println("The value of variable 'a' before incremental using prefix operator="+a);
      System.out.print("The value of variable 'a' while incremental using prefix operator=");
      System.out.println(++a);
      System.out.print("The value of variable 'a' after incremental using prefix operator=");
      System.out.println(a);
 
      System.out.println();
 
      System.out.println("The value of variable 'b' before incremental using postfix operator="+b);
      System.out.print("The value of variable 'b' while incremental using postfix operator=");
      System.out.println(b++);
      System.out.print("The value of variable 'a' after incremental using postfix operator=");
      System.out.println(b) ;
   }
 }

Output of this program:

The value of variable 'a' before incremental using prefix operator=1
The value of variable 'a' while incremental using prefix operator=2    (Incremented and printed)
The value of variable 'a' after incremental using prefix operator=2

The value of variable 'b' before incremental using postfix operator=1
The value of variable 'b' while incremental using postfix operator=1 (Printed without increment)
The value of variable 'b' after incremental using postfix operator=2  (Incremented here)

So the output clearly explains the difference between the prefix and postfix incremental operators.
Another program to demonstrate the difference between the increment operators ++VariableName  & VariableName++ 

class PrefixVsPostfix
{
   public static void main(String args[])
   {
      int a=1;
      int b=2;
      int c=++b;    // Here the value of variable 'b' will get incremented first and then the incremented value gets assinged to vartiable 'c'
      int d=a++;    // Here the value of variable 'a' will get assigned to variable 'd' and later the value of variable 'a' gets incremented
 
      System.out.println("a="+a);
      System.out.println("b="+b);
      System.out.println("c="+c);
      System.out.println("d="+d);
 
   }
 }

a=2
b=3
c=3
d=1
Program to demonstrate the decrement operator --VariableName

class PrefixDecrementOperator
{
   public static void main(String args[])
   {
      int a=4;
      --a;     //decrements the value of variable 'a' by one
      System.out.println("a="+a);
   }
}

Output of this program:

a=3

Observe the value of variable 'a' got decremented by 1 i.e. a=a-1 i.e. a=4-1 i.e. a=3
Program to demonstrate the decrement operator VariableName--

class PostfixDecrementOperator
{
   public static void main(String args[])
   {
      int a=4;
      a--;     //decrements the value of variable 'a' by one
      System.out.println("a="+a);
   }
}

Output of this program:

a=3

Observe the value of variable 'a' got decremented by 1 i.e. a=a-1 i.e. a=4-1 i.e. a=3
Program to demonstrate the difference between the decrement operators --VariableName  & VariableName--

So what is the difference between the prefix decrement operator and postfix decrement operator. To understand it first we have to understand the below program:

class PrefixVsPostfix
{
   public static void main(String args[])
   {
      int a=1;
      int b=1;
 
      System.out.println("The value of variable 'a' before decrement using prefix operator="+a);
      System.out.print("The value of variable 'a' while decrement using prefix operator=");
      System.out.println(--a);
      System.out.print("The value of variable 'a' after decrement using prefix operator=");
      System.out.println(a);
 
      System.out.println();
 
      System.out.println("The value of variable 'b' before decrement using postfix operator="+b);
      System.out.print("The value of variable 'b' while decrement using postfix operator=");
      System.out.println(b--);
      System.out.print("The value of variable 'a' after decrement using postfix operator=");
      System.out.println(b) ;
   }
 }

Output of this program:

The value of variable 'a' before decrement using prefix operator=1
The value of variable 'a' while incremental using prefix operator=0  (decremented and printed)
The value of variable 'a' after incremental using prefix operator=0

The value of variable 'b' before incremental using postfix operator=1
The value of variable 'b' while incremental using postfix operator=1 (Printed without decremented)
The value of variable 'b' after incremental using postfix operator=0 (decremented here)

So the output clearly explains the difference between the prefix and postfix decrement operators.
Another program to demonstrate the difference between the decrement operators --VariableName  & VariableName--

class PrefixVsPostfix
{
   public static void main(String args[])
   {
      int a=1;
      int b=2;
      int c=--b;    // Here the value of variable 'b' will get decremented first and then the decremented value gets assigned to variable 'c'
      int d=a--;    // Here the value of variable 'a' will get assigned to variable 'd' and later the value of variable 'a' gets decremented
 
      System.out.println("a="+a);
      System.out.println("b="+b);
      System.out.println("c="+c);
      System.out.println("d="+d);
 
   }
 }

a=0
b=1
c=1
d=1

Arrays

An array is a group of like typed variables that are referred to by a common name. So, unlike variables which hold a single value, arrays hold more than one fixed number of values.


Example -> int a variable -> holds a single integer value

Example -> int a[10] variable -> holds 10 integer values

 The above array example can store 10 values, by assigning the values to the variable indexes 0 to 9. i.e. we can assing 10 values like  a[0] = 1, a[1] = 5, a[2] = 8, ........a[9]=3

How a normal variable holds a value ?

Suppose there is an integer variable a which hold a value 5 as shown below

int a = 5;

Lets use the below diagram to understand how an integer variable stores a value -

How an array variable holds the value ?

Suppose there is an integer array variable which stores the 3 values 5, 7 and 9 as shown below

int a[] = new int[3]; //can assign three values

a[0] = 5;   //first value
a[1] = 7;  //second value
a[2] = 9;  //third value

Lets use the below diagram to understand how an integer array variable stores more than one value  -


Single Dimension Arrays -

All the array variable which store the values using single index i.e.. [] are knows as Single Dimension Arrays.

Lets understand the single dimension array using the below diagram -


Example of a Single Dimension array -

int a[] = new int[3];  
a[0] = 5;
a[1] = 7;
a[2] = 9;

Lets break the above statements and understand -

int a[] -> Defines the variable a[] as an integer variable. So this variable stores only the integer values.
int[3] -> Stores 3 values using a[0], a[1] and a[2]
a[0] = 5; -> 0 is the index value of the array and stores the first value 5
a[1] = 7; -> 1 is the index value of the array and stores the second value 7
a[2] = 9; -> 2 is the index value of the array and stores the third value 9

a[0], a[1] and a[2] are called as array elements i.e. a[0], a[1] and a[2] are the elements of the array a[].


Program to demonstrate a single dimensional array:

class Array1
{
   public static void main(String args[])
   {
       int a[]=new int[4];    // This means the number of values this array can store is 4 i.e. a[0],a[1],a[2],a[3]

       a[0] = 11;
       a[1] = 25;
       a[2] = 36;
       a[3] = 42;

       int total;
       total = a[0]+a[1]+a[2]+a[3];

       System.out.println("Total Sum="+total);

   }
}

Output of this program:

Total Sum=114


Program to demonstrate the single dimensional array by initializing the array during declaration itself

class Array2
{
   public static void main(String args[])
   {
       int a[]={11,25,36,42};   //Initializing the array during its declaration
       int total;
       total = a[0]+a[1]+a[2]+a[3];

       System.out.println("Total Sum="+total);
   }
}

Output of this program:

Total Sum=114




Two Dimensional Arrays -

All the array variables which store the values using two indexes [][] are known as Two Dimension Arrays.

variable[Row Index][Column Index]

Lets understand the two dimension array using the below diagram -


Example of a Two Dimension array -

int a[][] = new a[2][2];

a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;

Understand the below program to understand the two dimensional array concept perfectly.

Pre-requisites to be read to understand the for loop inside the below program -

   49. Arithmetic Operators
   50. Relational Operators
   51. Boolean Logical Operators
   52. Assignment and '?' operator
   53. Operator Precedence
   54. 'if' selection statements
   55. 'switch' selection statements
   56. 'while' iteration statements
   57. 'do-while' iteration statements
   58. 'for' iterative statements
   59. 'break' jump statement
   60. 'continue' jump statements

Program to demonstrate a two dimensional array

class TwoDArray1
{
   public static void main(String args[])
   {
       int a[][]=new int[2][3];
       int i,j,k=0;

        for(i=0;i<2;i++)
        {
           for(j=0;j<3;j++)
           {
            a[i][j]=k;
            k++;
            System.out.print(a[i][j]+ " ");
         }
 System.out.println();
      }

    }
  }

Output of this program:

0 1 2
3 4 5




Program to demonstrate a two dimensional array in which the sizes of the second dimension are not equal

class TwoDArray2
{
   public static void main(String args[])
   {
       int a[][]=new int[4][];
       a[0]=new int[1];
       a[1]=new int[2];
       a[2]=new int[3];
       a[3]=new int[4];

       int i,j,k=0;

        for(i=0;i<4;i++)
        {
           for(j=0;j<i+1;j++)
           {
           a[i][j]=k;
           k++;
           System.out.print(a[i][j]+ " ");
   }
 System.out.println();
    }

   }
}

Output of this program:

0 
1 2
3 4 5
6 7 8 9




Program to demonstrate initializing a two dimensional array during array declaration

class TwoDArray3
{
   public static void main(String args[])
   {
       int a[][]={ {0,1,2}, {3,4,5}, {6,7,8}, {9,10,11} };

       int i,j;

        for(i=0;i<4;i++)
        {
           for(j=0;j<3;j++)
           {
            System.out.print(a[i][j]+ " ");
         }
       System.out.println();
       }

   }
}

Output of this program:

0 1 2
3 4 5
6 7 8
9 10 11



Three Dimensional Arrays -

A three dimensional array contains 3 indexes i.e. [][][] as shown below -

variable[Number Of 2D Arrays][Row index][Column index]

The diagram of three dimension array will be as shown below -



Program to demonstrate a three dimensional array

class TwoDArray4
{
   public static void main(String args[])
   {
       int a[][][]=new int[2][3][4];

       int i,j,k,l=0;

       for(i=0;i<2;i++)
       {
         for(j=0;j<3;j++)
        {
            for(k=0;k<4;k++)
            {
              a[i][j][k]=l;
              l++;
             System.out.print(a[i][j][k]+ " ");
             }
          System.out.println( );
       }
       System.out.println( );
       }
   }
}

Output of this program:

0 1 2 3
4 5 6 7
8 9 10 11

12  13 14 15
16 17 18 19
20 21 22 23

Type conversion

It is fairly common to assign a value of one type to a variable of another type.



If the two types are compatible, then Java will perform the conversion automatically.

Program to demonstrate that Java will perform the conversion automatically when the value and variables types are different but compatible.

class LongVariableIntegerValue
{
   public static void main(String args[])
   {
         long a=123;    // We have assigned an integer value to a variable which is declared as long knowing that the both types are different but compatible
         System.out.println("a="+a);
   }
 }

Output of this program:

a=123

In this program, Java performed the conversion automatically though the data types of the variable (i.e. long) and value (i.e. int) are different but compatible.



However, not all the types are compatible and thus Java can't perform conversion automatically for incompatible types.

Program to demonstrate that Java wont perform the conversion automatically when the value and variables types are not compatible.

class IntVariableDecimalValue
{
   public static void main(String args[])
   {
         int a=123.456;    // We have assigned a decimal value to a variable which is declared as int knowing that both types are not compatible
         System.out.println("a="+a);
   }
}

Output of this program:

Error "Possible loss of precision int a=123.456"

In this program, Java didn't perform the conversion automatically as the data types of the value and variable are not compatible



Fortunately it is still possible to obtain a conversion between the incompatible types using cast which performs an explicit conversion between incompatible types.

Program to demonstrate the usage of cast in converting the integer value to byte value while assigning the integer value to a byte variable. 

class CastByteVariableIntValue
{
   public static void main(String args[])
   {
         byte a = (byte)12345;  // We've used (byte) cast for converting the integer value '12345' in to byte format before storing in the byte variable 'a'

         System.out.println("a="+a);
   }
}

Output of the program:

a=57 

Observer that (byte) cast in this program converted the integer value 12345 into a byte value 57.



Program to demonstrate the usage of cast in converting the decimal value to int value while assigning the decimal value to an int variable. 

class CastIntVariableDecimalValue
{
   public static void main(String args[])
   {

         int a=(int) 323.142;   // We've used (int) cast for converting the decimal value '323.142' in to int format before storing in the int variable 'a'

         System.out.println("a="+a);

   }
}

Output of the program:

a=323

Observer that (int) cast in this program converted the decimal value 323.142 into an int value 323.



Program to demonstrate that Values in the expression gets promoted to match the second argument to each binary operator.

 class PromotedType
{
   public static void main(String args[])
   {

         int a=5;             // a is of int type
         double b=0.55;  // b is of double type

         System.out.println(a+b);  // The result of a+b expression will get promoted to double as one of the variable i.e. 'b' has type double and other variable 'a' has type int 

   }
}

Output of this program:

5.55 

Observe that the result is promoted to double type, when the variable 'a' is integer and variable 'b' is double.

Scope of Variables

Scope till which the variable can be accessible is defined by blocks in Java Programming. A block beings with an open curly brace and ends by a closing curly brace as shown below:












In Java, two major scopes are those which are defined by a class and method.

class Examplemethod Example

   class ClassName
   {

   }


    public static void MethodName( )
   {

    }

opening and closing curly braces of the class
will define the scope. class scope wont be
explained in this post and will be explained
while explaining the class concept in detail.
opening and closing curly braces of the
 method will define the scope. Method
scope will be explained in this post.

As a general rule, variables declared inside a scope are not visible to code that is defined outside the scope (i.e. outside the opening and closing curly braces).


Program to demonstrate that a variable declared in a method is not visible to the other methods

class VariableScope1
{
public static void main(String args[])
{
int a=5;
AccessVariable( );  // Calling AccessVariable() method, which will in turn will try to print the variable 'a' whose scope is limited to this method only
    }

    public static void AccessVariable( )
    {
System.out.println("a = "+a);     //Trying to print the variable 'a' whose scope is limited to main( ) method only
    }
}

Output of this program:

Error "Cannot find symbol 'a' in System.out.println("a= "+a); statement"

After observing the output its very clear that variable declared in the main( ) method is not visible to the AccessVariable( ) method. i.e. The scope of the variable 'a' is limited to the main( ) method only and cant be accessed outside by any code outside the main( ) method.


Scopes can be nested. When this occurs, the outer scope encloses the inner scope. The objects declared in the outer scope will be visible to code with in the inner scope. How ever the reverse is not true i.e. the objects declared in the inner scope will be not visible outside it.



Program to demonstrate the objects declared in the outer scope will be visible to the code with in the inner scope

class OuterScopeObject
{
     public static void main(String args[])
     {                                                             // Outer scope started
          int a=5;

          if(a>0)        
          {                                                        // Inner scope started
               System.out.println("a="+a);
          }                                                      // Inner scope ended
   
      }                                                                     // Outer scope ended

}

Output of this program:

a=5

The variable 'a' is declared and initialized in the outer loop i.e. main( ) method loop. Where as the value of the variable 'a' got printed in the inner loop i.e. if condition loop. So now its very clear that objects declared in the outer scope will be visible to the code with in the inner scope.



Program to demonstrate the objects declared in the inner scope will not be visible outside it


class InnerScopeObject
{
     public static void main(String args[])
     {                             // Outer scope started

              if(true)
              {                      // Inner scope started
                    int a=5;
              }                     // Inner scope ended

        System.out.println("a="+a);

      }                           // Outer scope ended

 }


Output of this program:

Error "Cannot find the symbol 'a' in the System.out.println("a="+a);"

The variable 'a' is declared and initialized in the inner loop i.e. inside the if condition loop. Where as the program tried to print it in the outside loop i.e. main( ) method loop, but was failed do that. So now its clear that objects declared inside the loop will be not be visible outside it.


Variables cannot be used prior to their declaration

Program to demonstrate that the variables cannot be used prior to their declaration

class UseAndDeclare
{
     public static void main(String args[])
     {
 a=5;   //First use the variable
 int a;  //Second declare the above used variable

       System.out.println("a="+a);

     }
 }

Output of this program:

Error "Cannot find the symbol 'a' in the a=5; "

This means Java is not able to identify  'a' as int type variable, though we have declared the variable 'a'  after using it.



The variable that is declared outside the loop cannot be declared again inside the loop

Program to demonstrate that you cannot declare the same variable inside the loop which is already declared outside the loop.


class SameVariableDeclaration
{
     public static void main(String args[])
     {
 int a;

 if(true)
 {
             int a;
           }

     }
 }

Output of this program:

Error "  'a' is already declared in the main( ) method"

This means that we cant define the same variable inside the loop if it is already declared outside the loop.