Author: saqibkhan

  • Java Switch Statement

    The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

    In other words, the switch statement tests the equality of a variable against multiple values.

    Points to Remember

    • There can be one or N number of case values for a switch expression.
    • The case value must be of switch expression type only. The case value must be literal or constant. It doesn’t allow variables.
    • The case values must be unique. In case of duplicate value, it renders compile-time error.
    • The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
    • Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
    • The case value can have a default label which is optional.

    Syntax:

    itch(expression){    
    
    case value1:    
    
     //code to be executed;    
    
     break;  //optional  
    
    case value2:    
    
     //code to be executed;    
    
     break;  //optional  
    
    ......    
    
        
    
    default:     
    
      code to be executed if all cases are not matched;  
    
    }    

      Flowchart of Switch Statement

      flow of switch statement in java

      Example:

      SwitchExample.java

      public class SwitchExample {  
      
      public static void main(String[] args) {  
      
          //Declaring a variable for switch expression  
      
          int number=20;  
      
          //Switch expression  
      
          switch(number){  
      
          //Case statements  
      
          case 10: System.out.println("10");  
      
          break;  
      
          case 20: System.out.println("20");  
      
          break;  
      
          case 30: System.out.println("30");  
      
          break;  
      
          //Default case statement  
      
          default:System.out.println("Not in 10, 20 or 30");  
      
          }  
      
      }  
      
      }

      Output:

      20
      

      Finding Month Example:

      SwitchMonthExample.javaHTML

      //Java Program to demonstrate the example of Switch statement  
      
      //where we are printing month name for the given number  
      
      public class SwitchMonthExample {    
      
      public static void main(String[] args) {    
      
          //Specifying month number  
      
          int month=7;    
      
          String monthString="";  
      
          //Switch statement  
      
          switch(month){    
      
          //case statements within the switch block  
      
          case 1: monthString="1 - January";  
      
          break;    
      
          case 2: monthString="2 - February";  
      
          break;    
      
          case 3: monthString="3 - March";  
      
          break;    
      
          case 4: monthString="4 - April";  
      
          break;    
      
          case 5: monthString="5 - May";  
      
          break;    
      
          case 6: monthString="6 - June";  
      
          break;    
      
          case 7: monthString="7 - July";  
      
          break;    
      
          case 8: monthString="8 - August";  
      
          break;    
      
          case 9: monthString="9 - September";  
      
          break;    
      
          case 10: monthString="10 - October";  
      
          break;    
      
          case 11: monthString="11 - November";  
      
          break;    
      
          case 12: monthString="12 - December";  
      
          break;    
      
          default:System.out.println("Invalid Month!");    
      
          }    
      
          //Printing month of the given number  
      
          System.out.println(monthString);  
      
      }    
      
      }   

      Output:

      7 - July
      

      Program to check Vowel or Consonant:

      If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.

      SwitchVowelExample.java

      public class SwitchVowelExample {    
      
      public static void main(String[] args) {    
      
          char ch='O';    
      
          switch(ch)  
      
          {  
      
              case 'a':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'e':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'i':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'o':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'u':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'A':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'E':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'I':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'O':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              case 'U':   
      
                  System.out.println("Vowel");  
      
                  break;  
      
              default:   
      
                  System.out.println("Consonant");  
      
          }  
      
      }    
      
      }  

        Output:

        Vowel
        

        Java Switch Statement is fall-through

        The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present.

        Example:

        SwitchExample2.java

        //Java Switch Example where we are omitting the  
        
        //break statement  
        
        public class SwitchExample2 {  
        
        public static void main(String[] args) {  
        
            int number=20;  
        
            //switch expression with int value  
        
            switch(number){  
        
            //switch cases without break statements  
        
            case 10: System.out.println("10");  
        
            case 20: System.out.println("20");  
        
            case 30: System.out.println("30");  
        
            default:System.out.println("Not in 10, 20 or 30");  
        
            }  
        
        }  
        
        }

        Output:

        20
        30
        Not in 10, 20 or 30
        

        Java Switch Statement with String

        Java allows us to use strings in switch expression since Java SE 7. The case statement should be string literal.

        Example:

        SwitchStringExample.java

        //Java Program to demonstrate the use of Java Switch  
        
        //statement with String  
        
        public class SwitchStringExample {    
        
        public static void main(String[] args) {    
        
            //Declaring String variable  
        
            String levelString="Expert";  
        
            int level=0;  
        
            //Using String in Switch expression  
        
            switch(levelString){    
        
            //Using String Literal in Switch case  
        
            case "Beginner": level=1;  
        
            break;    
        
            case "Intermediate": level=2;  
        
            break;    
        
            case "Expert": level=3;  
        
            break;    
        
            default: level=0;  
        
            break;  
        
            }    
        
            System.out.println("Your Level is: "+level);  
        
        }    
        
        }

        Output:

        Your Level is: 3
        

        Java Nested Switch Statement

        We can use switch statement inside other switch statement in Java. It is known as nested switch statement.

        Example:

        NestedSwitchExample.java

        //Java Program to demonstrate the use of Java Nested Switch  
        
        public class NestedSwitchExample {    
        
            public static void main(String args[])  
        
              {  
        
              //C - CSE, E - ECE, M - Mechanical  
        
                char branch = 'C';                 
        
                int collegeYear = 4;  
        
                switch( collegeYear )  
        
                {  
        
                    case 1:  
        
                        System.out.println("English, Maths, Science");  
        
                        break;  
        
                    case 2:  
        
                        switch( branch )   
        
                        {  
        
                            case 'C':  
        
                                System.out.println("Operating System, Java, Data Structure");  
        
                                break;  
        
                            case 'E':  
        
                                System.out.println("Micro processors, Logic switching theory");  
        
                                break;  
        
                            case 'M':  
        
                                System.out.println("Drawing, Manufacturing Machines");  
        
                                break;  
        
                        }  
        
                        break;  
        
                    case 3:  
        
                        switch( branch )   
        
                        {  
        
                            case 'C':  
        
                                System.out.println("Computer Organization, MultiMedia");  
        
                                break;  
        
                            case 'E':  
        
                                System.out.println("Fundamentals of Logic Design, Microelectronics");  
        
                                break;  
        
                            case 'M':  
        
                                System.out.println("Internal Combustion Engines, Mechanical Vibration");  
        
                                break;  
        
                        }  
        
                        break;  
        
                    case 4:  
        
                        switch( branch )   
        
                        {  
        
                            case 'C':  
        
                                System.out.println("Data Communication and Networks, MultiMedia");  
        
                                break;  
        
                            case 'E':  
        
                                System.out.println("Embedded System, Image Processing");  
        
                                break;  
        
                            case 'M':  
        
                                System.out.println("Production Technology, Thermal Engineering");  
        
                                break;  
        
                        }  
        
                        break;  
        
                }  
        
            }  
        
        }

        Output:

        Data Communication and Networks, MultiMedia
        

        Java Enum in Switch Statement

        Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma.

        Example:

        JavaSwitchEnumExample.java

        //Java Program to demonstrate the use of Enum  
        
        //in switch statement  
        
        public class JavaSwitchEnumExample {      
        
               public enum Day {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
        
               public static void main(String args[])    
        
               {    
        
                 Day[] DayNow = Day.values();    
        
                   for (Day Now : DayNow)    
        
                   {    
        
                        switch (Now)    
        
                        {    
        
                            case Sun:    
        
                                System.out.println("Sunday");    
        
                                break;    
        
                            case Mon:    
        
                                System.out.println("Monday");    
        
                                break;    
        
                            case Tue:    
        
                                System.out.println("Tuesday");    
        
                                break;         
        
                            case Wed:    
        
                                System.out.println("Wednesday");    
        
                                break;    
        
                            case Thu:    
        
                                System.out.println("Thursday");    
        
                                break;    
        
                            case Fri:    
        
                                System.out.println("Friday");    
        
                                break;    
        
                            case Sat:    
        
                                System.out.println("Saturday");    
        
                                break;    
        
                        }    
        
                    }    
        
                }    
        
        }

        Output:

        Sunday
        Monday
        Twesday
        Wednesday
        Thursday
        Friday
        Saturday
        

        Java Wrapper in Switch Statement

        Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

        Example:

        WrapperInSwitchCaseExample.java

        //Java Program to demonstrate the use of Wrapper class  
        
        //in switch statement  
        
        public class WrapperInSwitchCaseExample {       
        
               public static void main(String args[])  
        
               {         
        
                    Integer age = 18;        
        
                    switch (age)  
        
                    {  
        
                        case (16):            
        
                            System.out.println("You are under 18.");  
        
                            break;  
        
                        case (18):                
        
                            System.out.println("You are eligible for vote.");  
        
                            break;  
        
                        case (65):                
        
                            System.out.println("You are senior citizen.");  
        
                            break;  
        
                        default:  
        
                            System.out.println("Please give the valid age.");  
        
                            break;  
        
                    }             
        
                }  
        
        }

        Output:

        You are eligible for vote.
        
      1. Java If-else Statement

        The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.

        • if statement
        • if-else statement
        • if-else-if ladder
        • nested if statement

        Java if Statement

        The Java if statement tests the condition. It executes the if block if condition is true.

        Syntax:

        if(condition){  
        
        //code to be executed  
        
        } 
          if statement in java

          Example:

          //Java Program to demonstate the use of if statement.  
          
          public class IfExample {  
          
          public static void main(String[] args) {  
          
              //defining an 'age' variable  
          
              int age=20;  
          
              //checking the age  
          
              if(age>18){  
          
                  System.out.print("Age is greater than 18");  
          
              }  
          
          }  
          
          }

          Output:

          Age is greater than 18
          

          Java if-else Statement

          The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.

          Syntax:

          if(condition){  
          
          //code if condition is true  
          
          }else{  
          
          //code if condition is false  
          
          } 
            if-else statement in java

            Example:

            //A Java Program to demonstrate the use of if-else statement.  
            
            //It is a program of odd and even number.  
            
            public class IfElseExample {  
            
            public static void main(String[] args) {  
            
                //defining a variable  
            
                int number=13;  
            
                //Check if the number is divisible by 2 or not  
            
                if(number%2==0){  
            
                    System.out.println("even number");  
            
                }else{  
            
                    System.out.println("odd number");  
            
                }  
            
            }  
            
            }

            Output:

            odd number
            

            Leap Year Example:

            A year is leap, if it is divisible by 4 and 400. But, not by 100.

            public class LeapYearExample {    
            
            public static void main(String[] args) {    
            
                int year=2020;    
            
                if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){  
            
                    System.out.println("LEAP YEAR");  
            
                }  
            
                else{  
            
                    System.out.println("COMMON YEAR");  
            
                }  
            
            }    
            
            }    

              Output:

              LEAP YEAR
              

              Using Ternary Operator

              We can also use ternary operator (? 🙂 to perform the task of if…else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.

              Example:

              public class IfElseTernaryExample {    
              
              public static void main(String[] args) {    
              
                  int number=13;    
              
                  //Using ternary operator  
              
                  String output=(number%2==0)?"even number":"odd number";    
              
                  System.out.println(output);  
              
              }    
              
              }    

                Output:

                odd number
                

                Java if-else-if ladder Statement

                The if-else-if ladder statement executes one condition from multiple statements.

                Syntax:

                if(condition1){  
                
                //code to be executed if condition1 is true  
                
                }else if(condition2){  
                
                //code to be executed if condition2 is true  
                
                }  
                
                else if(condition3){  
                
                //code to be executed if condition3 is true  
                
                }  
                
                ...  
                
                else{  
                
                //code to be executed if all the conditions are false  
                
                } 
                  if-else-if ladder statement in java

                  Example:

                  //Java Program to demonstrate the use of If else-if ladder.  
                  
                  //It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.  
                  
                  public class IfElseIfExample {  
                  
                  public static void main(String[] args) {  
                  
                      int marks=65;  
                  
                        
                  
                      if(marks<50){  
                  
                          System.out.println("fail");  
                  
                      }  
                  
                      else if(marks>=50 && marks<60){  
                  
                          System.out.println("D grade");  
                  
                      }  
                  
                      else if(marks>=60 && marks<70){  
                  
                          System.out.println("C grade");  
                  
                      }  
                  
                      else if(marks>=70 && marks<80){  
                  
                          System.out.println("B grade");  
                  
                      }  
                  
                      else if(marks>=80 && marks<90){  
                  
                          System.out.println("A grade");  
                  
                      }else if(marks>=90 && marks<100){  
                  
                          System.out.println("A+ grade");  
                  
                      }else{  
                  
                          System.out.println("Invalid!");  
                  
                      }  
                  
                  }  
                  
                  } 

                    Output:

                    C grade
                    

                    Program to check POSITIVE, NEGATIVE or ZERO:

                    public class PositiveNegativeExample {    
                    
                    public static void main(String[] args) {    
                    
                        int number=-13;    
                    
                        if(number>0){  
                    
                        System.out.println("POSITIVE");  
                    
                        }else if(number<0){  
                    
                        System.out.println("NEGATIVE");  
                    
                        }else{  
                    
                        System.out.println("ZERO");  
                    
                       }  
                    
                    }    
                    
                    }  

                      Output:

                      NEGATIVE
                      

                      Java Nested if statement

                      The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.

                      Syntax:

                      if(condition){    
                      
                           //code to be executed    
                      
                                if(condition){  
                      
                                   //code to be executed    
                      
                          }    
                      
                      } 
                        Java Nested If Statement

                        Example:

                        //Java Program to demonstrate the use of Nested If Statement.  
                        
                        public class JavaNestedIfExample {    
                        
                        public static void main(String[] args) {    
                        
                            //Creating two variables for age and weight  
                        
                            int age=20;  
                        
                            int weight=80;    
                        
                            //applying condition on age and weight  
                        
                            if(age>=18){    
                        
                                if(weight>50){  
                        
                                    System.out.println("You are eligible to donate blood");  
                        
                                }    
                        
                            }    
                        
                        }}

                        Output:

                        You are eligible to donate blood
                        

                        Example 2:

                        //Java Program to demonstrate the use of Nested If Statement.    
                        
                        public class JavaNestedIfExample2 {      
                        
                        public static void main(String[] args) {      
                        
                            //Creating two variables for age and weight    
                        
                            int age=25;    
                        
                            int weight=48;      
                        
                            //applying condition on age and weight    
                        
                            if(age>=18){      
                        
                                if(weight>50){    
                        
                                    System.out.println("You are eligible to donate blood");    
                        
                                } else{  
                        
                                    System.out.println("You are not eligible to donate blood");    
                        
                                }  
                        
                            } else{  
                        
                              System.out.println("Age must be greater than 18");  
                        
                            }  
                        
                        }  }

                        Output:

                        You are not eligible to donate blood
                        
                      1. Java Control Statements | Control Flow in Java

                        Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.

                        Java provides three types of control flow statements.

                        1. Decision Making statements
                          • if statements
                          • switch statement
                        2. Loop statements
                          • do while loop
                          • while loop
                          • for loop
                          • for-each loop
                        3. Jump statements
                          • break statement
                          • continue statement

                        Decision-Making statements:

                        As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.

                        1) If Statement:

                        In Java, the “if” statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below.

                        1. Simple if statement
                        2. if-else statement
                        3. if-else-if ladder
                        4. Nested if-statement

                        Let’s understand the if-statements one by one.

                        1) Simple if statement:

                        It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

                        Syntax of if statement is given below.

                        if(condition) {    
                        
                        statement 1; //executes when condition is true   
                        
                        }    

                          Consider the following example in which we have used the if statement in the java code.

                          Student.java

                          Student.java

                          public class Student {    
                          
                          public static void main(String[] args) {    
                          
                          int x = 10;    
                          
                          int y = 12;    
                          
                          if(x+y > 20) {    
                          
                          System.out.println("x + y is greater than 20");    
                          
                          }    
                          
                          }      
                          
                          }   

                            Output:

                            x + y is greater than 20
                            

                            2) if-else statement

                            The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

                            Syntax:

                            if(condition) {    
                            
                            statement 1; //executes when condition is true   
                            
                            }  
                            
                            else{  
                            
                            statement 2; //executes when condition is false   
                            
                            } 

                              Consider the following example.

                              Student.java

                              public class Student {  
                              
                              public static void main(String[] args) {  
                              
                              int x = 10;  
                              
                              int y = 12;  
                              
                              if(x+y < 10) {  
                              
                              System.out.println("x + y is less than      10");  
                              
                              }   else {  
                              
                              System.out.println("x + y is greater than 20");  
                              
                              }  
                              
                              }  
                              
                              }

                                Output:

                                x + y is greater than 20
                                

                                3) if-else-if ladder:

                                The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.

                                Syntax of if-else-if statement is given below.

                                if(condition 1) {    
                                
                                statement 1; //executes when condition 1 is true   
                                
                                }  
                                
                                else if(condition 2) {  
                                
                                statement 2; //executes when condition 2 is true   
                                
                                }  
                                
                                else {  
                                
                                statement 2; //executes when all the conditions are false   
                                
                                }

                                Consider the following example.

                                Student.java

                                public class Student {  
                                
                                public static void main(String[] args) {  
                                
                                String city = "Delhi";  
                                
                                if(city == "Meerut") {  
                                
                                System.out.println("city is meerut");  
                                
                                }else if (city == "Noida") {  
                                
                                System.out.println("city is noida");  
                                
                                }else if(city == "Agra") {  
                                
                                System.out.println("city is agra");  
                                
                                }else {  
                                
                                System.out.println(city);  
                                
                                }  
                                
                                }  
                                
                                }  

                                  Output:

                                  Delhi
                                  

                                  4. Nested if-statement

                                  In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.

                                  Syntax of Nested if-statement is given below.

                                  if(condition 1) {    
                                  
                                  statement 1; //executes when condition 1 is true   
                                  
                                  if(condition 2) {  
                                  
                                  statement 2; //executes when condition 2 is true   
                                  
                                  }  
                                  
                                  else{  
                                  
                                  statement 2; //executes when condition 2 is false   
                                  
                                  }  
                                  
                                  } 

                                    Consider the following example.

                                    Student.java

                                    public class Student {    
                                    
                                    public static void main(String[] args) {    
                                    
                                    String address = "Delhi, India";    
                                    
                                        
                                    
                                    if(address.endsWith("India")) {    
                                    
                                    if(address.contains("Meerut")) {    
                                    
                                    System.out.println("Your city is Meerut");    
                                    
                                    }else if(address.contains("Noida")) {    
                                    
                                    System.out.println("Your city is Noida");    
                                    
                                    }else {    
                                    
                                    System.out.println(address.split(",")[0]);    
                                    
                                    }    
                                    
                                    }else {    
                                    
                                    System.out.println("You are not living in India");    
                                    
                                    }    
                                    
                                    }    
                                    
                                    }   

                                      Output:

                                      Delhi
                                      

                                      Switch Statement:

                                      In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.

                                      Points to be noted about switch statement:

                                      • The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
                                      • Cases cannot be duplicate
                                      • Default statement is executed when any of the case doesn’t match the value of expression. It is optional.
                                      • Break statement terminates the switch block when the condition is satisfied.
                                        It is optional, if not used, next case is executed.
                                      • While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.

                                      The syntax to use the switch statement is given below.

                                      switch (expression){  
                                      
                                          case value1:  
                                      
                                           statement1;  
                                      
                                           break;  
                                      
                                          .  
                                      
                                          .  
                                      
                                          .  
                                      
                                          case valueN:  
                                      
                                           statementN;  
                                      
                                           break;  
                                      
                                          default:  
                                      
                                           default statement;  
                                      
                                      } 

                                        Consider the following example to understand the flow of the switch statement.

                                        Student.java

                                        public class Student implements Cloneable {  
                                        
                                        public static void main(String[] args) {  
                                        
                                        int num = 2;  
                                        
                                        switch (num){  
                                        
                                        case 0:  
                                        
                                        System.out.println("number is 0");  
                                        
                                        break;  
                                        
                                        case 1:  
                                        
                                        System.out.println("number is 1");  
                                        
                                        break;  
                                        
                                        default:  
                                        
                                        System.out.println(num);  
                                        
                                        }  
                                        
                                        }  
                                        
                                        } 

                                          Output:

                                          2
                                          

                                          While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.

                                          Loop Statements

                                          In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.

                                          In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.

                                          1. for loop
                                          2. while loop
                                          3. do-while loop

                                          Let’s understand the loop statements one by one.

                                          Java for loop

                                          In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.

                                          for(initialization, condition, increment/decrement) {    
                                          
                                          //block of statements    
                                          
                                          }    

                                            The flow chart for the for-loop is given below.

                                            Control Flow in Java

                                            Consider the following example to understand the proper functioning of the for loop in java.

                                            Calculation.java

                                            public class Calculattion {  
                                            
                                            public static void main(String[] args) {  
                                            
                                            // TODO Auto-generated method stub  
                                            
                                            int sum = 0;  
                                            
                                            for(int j = 1; j<=10; j++) {  
                                            
                                            sum = sum + j;  
                                            
                                            }  
                                            
                                            System.out.println("The sum of first 10 natural numbers is " + sum);  
                                            
                                            }  
                                            
                                            }

                                            Output:

                                            The sum of first 10 natural numbers is 55
                                            

                                            Java for-each loop

                                            Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don’t need to update the loop variable. The syntax to use the for-each loop in java is given below.

                                            for(data_type var : array_name/collection_name){    
                                            
                                            //statements    
                                            
                                            }  

                                              Consider the following example to understand the functioning of the for-each loop in Java.

                                              Calculation.java

                                              public class Calculation {    
                                              
                                              public static void main(String[] args) {    
                                              
                                              // TODO Auto-generated method stub    
                                              
                                              String[] names = {"Java","C","C++","Python","JavaScript"};    
                                              
                                              System.out.println("Printing the content of the array names:\n");    
                                              
                                              for(String name:names) {    
                                              
                                              System.out.println(name);    
                                              
                                              }    
                                              
                                              }    
                                              
                                              }    

                                                Output:

                                                Printing the content of the array names:
                                                
                                                Java
                                                C
                                                C++
                                                Python
                                                JavaScript
                                                

                                                Java while loop

                                                The while loop is also used to iterate over the number of statements multiple times. However, if we don’t know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn’t take place inside the loop statement in while loop.

                                                It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.

                                                The syntax of the while loop is given below.

                                                while(condition){    
                                                
                                                //looping statements    
                                                
                                                }   

                                                  The flow chart for the while loop is given in the following image.

                                                  Control Flow in Java

                                                  Consider the following example.

                                                  Calculation .java

                                                  public class Calculation {    
                                                  
                                                  public static void main(String[] args) {    
                                                  
                                                  // TODO Auto-generated method stub    
                                                  
                                                  int i = 0;    
                                                  
                                                  System.out.println("Printing the list of first 10 even numbers \n");    
                                                  
                                                  while(i<=10) {    
                                                  
                                                  System.out.println(i);    
                                                  
                                                  i = i + 2;    
                                                  
                                                  }    
                                                  
                                                  }    
                                                  
                                                  }   

                                                    Output:

                                                    Printing the list of first 10 even numbers 
                                                    
                                                    0
                                                    2
                                                    4
                                                    6
                                                    8
                                                    10
                                                    

                                                    Java do-while loop

                                                    The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.

                                                    It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.

                                                    do     
                                                    
                                                    {    
                                                    
                                                    //statements    
                                                    
                                                    } while (condition);  

                                                      The flow chart of the do-while loop is given in the following image.

                                                      Control Flow in Java

                                                      Consider the following example to understand the functioning of the do-while loop in Java.

                                                      Calculation.java

                                                      public class Calculation {    
                                                      
                                                      public static void main(String[] args) {    
                                                      
                                                      // TODO Auto-generated method stub    
                                                      
                                                      int i = 0;    
                                                      
                                                      System.out.println("Printing the list of first 10 even numbers \n");    
                                                      
                                                      do {    
                                                      
                                                      System.out.println(i);    
                                                      
                                                      i = i + 2;    
                                                      
                                                      }while(i<=10);    
                                                      
                                                      }    
                                                      
                                                      }  

                                                        Output:

                                                        Printing the list of first 10 even numbers 
                                                        0
                                                        2
                                                        4
                                                        6
                                                        8
                                                        10
                                                        

                                                        Jump Statements

                                                        Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are two types of jump statements in Java, i.e., break and continue.

                                                        Java break statement

                                                        As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

                                                        The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement.

                                                        The break statement example with for loop

                                                        Consider the following example in which we have used the break statement with the for loop.

                                                        BreakExample.java

                                                        public class BreakExample {  
                                                        
                                                          
                                                        
                                                        public static void main(String[] args) {  
                                                        
                                                        // TODO Auto-generated method stub  
                                                        
                                                        for(int i = 0; i<= 10; i++) {  
                                                        
                                                        System.out.println(i);  
                                                        
                                                        if(i==6) {  
                                                        
                                                        break;  
                                                        
                                                        }  
                                                        
                                                        }  
                                                        
                                                        }  
                                                        
                                                        }

                                                        Output:

                                                        0
                                                        1
                                                        2
                                                        3
                                                        4
                                                        5
                                                        6
                                                        

                                                        break statement example with labeled for loop

                                                        Calculation.java

                                                        public class Calculation {    
                                                        
                                                            
                                                        
                                                        public static void main(String[] args) {    
                                                        
                                                        // TODO Auto-generated method stub    
                                                        
                                                        a:    
                                                        
                                                        for(int i = 0; i<= 10; i++) {    
                                                        
                                                        b:    
                                                        
                                                        for(int j = 0; j<=15;j++) {    
                                                        
                                                        c:    
                                                        
                                                        for (int k = 0; k<=20; k++) {    
                                                        
                                                        System.out.println(k);    
                                                        
                                                        if(k==5) {    
                                                        
                                                        break a;    
                                                        
                                                        }    
                                                        
                                                        }    
                                                        
                                                        }    
                                                        
                                                            
                                                        
                                                        }    
                                                        
                                                        }    
                                                        
                                                            
                                                        
                                                            
                                                        
                                                        }   

                                                          Output:

                                                          0
                                                          1
                                                          2
                                                          3
                                                          4
                                                          5
                                                          

                                                          Java continue statement

                                                          Unlike break statement, the continue statement doesn’t break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.

                                                          Consider the following example to understand the functioning of the continue statement in Java.

                                                          public class ContinueExample {  
                                                          
                                                            
                                                          
                                                          public static void main(String[] args) {  
                                                          
                                                          // TODO Auto-generated method stub  
                                                          
                                                            
                                                          
                                                          for(int i = 0; i<= 2; i++) {  
                                                          
                                                            
                                                          
                                                          for (int j = i; j<=5; j++) {  
                                                          
                                                            
                                                          
                                                          if(j == 4) {  
                                                          
                                                          continue;  
                                                          
                                                          }  
                                                          
                                                          System.out.println(j);  
                                                          
                                                          }  
                                                          
                                                          }  
                                                          
                                                          }  
                                                          
                                                            
                                                          
                                                          } 

                                                            Output:

                                                            0
                                                            1
                                                            2
                                                            3
                                                            5
                                                            1
                                                            2
                                                            3
                                                            5
                                                            2
                                                            3
                                                            5
                                                            
                                                          1. Java Keywords

                                                            Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so they cannot be used as a variable or object name or class name.

                                                            List of Java Keywords

                                                            A list of Java keywords or reserved words are given below:

                                                            1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It can have abstract and non-abstract methods.
                                                            2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
                                                            3. break: Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified conditions.
                                                            4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
                                                            5. case: Java case keyword is used with the switch statements to mark blocks of text.
                                                            6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
                                                            7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
                                                            8. class: Java class keyword is used to declare a class.
                                                            9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
                                                            10. default: Java default keyword is used to specify the default block of code in a switch statement.
                                                            11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.
                                                            12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
                                                            13. else: Java else keyword is used to indicate the alternative branches in an if statement.
                                                            14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
                                                            15. extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
                                                            16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a variable. It is used to restrict the user from updating the value of the variable.
                                                            17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether an exception is handled or not.
                                                            18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
                                                            19. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.
                                                            20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
                                                            21. implements: Java implements keyword is used to implement an interface.
                                                            22. import: Java import keyword makes classes and interfaces available and accessible to the current source code.
                                                            23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
                                                            24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
                                                            25. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
                                                            26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
                                                            27. native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
                                                            28. new: Java new keyword is used to create new objects.
                                                            29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
                                                            30. package: Java package keyword is used to declare a Java package that includes the classes.
                                                            31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
                                                            32. protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but through inheritance only. It can’t be applied with the class.
                                                            33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
                                                            34. return: Java return keyword is used to return from a method when its execution is complete.
                                                            35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
                                                            36. static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly used for memory management.
                                                            37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
                                                            38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the immediate parent class method.
                                                            39. switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
                                                            40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
                                                            41. this: Java this keyword can be used to refer the current object in a method or constructor.
                                                            42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exceptions. It is followed by an instance.
                                                            43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.
                                                            44. transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
                                                            45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
                                                            46. void: Java void keyword is used to specify that a method does not have a return value.
                                                            47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
                                                            48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use the while loop.
                                                          2. Operators in Java

                                                            Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

                                                            There are many types of operators in Java which are given below:

                                                            • Unary Operator,
                                                            • Arithmetic Operator,
                                                            • Shift Operator,
                                                            • Relational Operator,
                                                            • Bitwise Operator,
                                                            • Logical Operator,
                                                            • Ternary Operator and
                                                            • Assignment Operator.

                                                            Java Operator Precedence

                                                            Operator TypeCategoryPrecedence
                                                            Unarypostfixexpr++ expr--
                                                            prefix++expr --expr +expr -expr ~ !
                                                            Arithmeticmultiplicative* / %
                                                            additive+ -
                                                            Shiftshift<< >> >>>
                                                            Relationalcomparison< > <= >= instanceof
                                                            equality== !=
                                                            Bitwisebitwise AND&
                                                            bitwise exclusive OR^
                                                            bitwise inclusive OR|
                                                            Logicallogical AND&&
                                                            logical OR||
                                                            Ternaryternary? :
                                                            Assignmentassignment= += -= *= /= %= &= ^= |= <<= >>= >>>=

                                                            Java Unary Operator

                                                            The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

                                                            • incrementing/decrementing a value by one
                                                            • negating an expression
                                                            • inverting the value of a boolean

                                                            Java Unary Operator Example: ++ and —

                                                            public class OperatorExample{  
                                                            
                                                            public static void main(String args[]){  
                                                            
                                                            int x=10;  
                                                            
                                                            System.out.println(x++);//10 (11)  
                                                            
                                                            System.out.println(++x);//12  
                                                            
                                                            System.out.println(x--);//12 (11)  
                                                            
                                                            System.out.println(--x);//10  
                                                            
                                                            }} 

                                                              Output:

                                                              10
                                                              12
                                                              12
                                                              10
                                                              

                                                              Java Unary Operator Example 2: ++ and —

                                                              public class OperatorExample{  
                                                              
                                                              public static void main(String args[]){  
                                                              
                                                              int a=10;  
                                                              
                                                              int b=10;  
                                                              
                                                              System.out.println(a++ + ++a);//10+12=22  
                                                              
                                                              System.out.println(b++ + b++);//10+11=21  
                                                              
                                                                
                                                              
                                                              }}

                                                              Output:

                                                              22
                                                              21
                                                              

                                                              Java Unary Operator Example: ~ and !

                                                              public class OperatorExample{  
                                                              
                                                              public static void main(String args[]){  
                                                              
                                                              int a=10;  
                                                              
                                                              int b=-10;  
                                                              
                                                              boolean c=true;  
                                                              
                                                              boolean d=false;  
                                                              
                                                              System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
                                                              
                                                              System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
                                                              
                                                              System.out.println(!c);//false (opposite of boolean value)  
                                                              
                                                              System.out.println(!d);//true  
                                                              
                                                              }}  

                                                                Output:

                                                                -11
                                                                9
                                                                false
                                                                true
                                                                

                                                                Java Arithmetic Operators

                                                                Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

                                                                Java Arithmetic Operator Example

                                                                public class OperatorExample{  
                                                                
                                                                public static void main(String args[]){  
                                                                
                                                                int a=10;  
                                                                
                                                                int b=5;  
                                                                
                                                                System.out.println(a+b);//15  
                                                                
                                                                System.out.println(a-b);//5  
                                                                
                                                                System.out.println(a*b);//50  
                                                                
                                                                System.out.println(a/b);//2  
                                                                
                                                                System.out.println(a%b);//0  
                                                                
                                                                }} 

                                                                  Output:

                                                                  15
                                                                  5
                                                                  50
                                                                  2
                                                                  0
                                                                  

                                                                  Java Arithmetic Operator Example: Expression

                                                                  public class OperatorExample{  
                                                                  
                                                                  public static void main(String args[]){  
                                                                  
                                                                  System.out.println(10*10/5+3-1*4/2);  
                                                                  
                                                                  }} 

                                                                    Output:

                                                                    21
                                                                    

                                                                    Java Left Shift Operator

                                                                    The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

                                                                    Java Left Shift Operator Example

                                                                    public class OperatorExample{  
                                                                    
                                                                    public static void main(String args[]){  
                                                                    
                                                                    System.out.println(10<<2);//10*2^2=10*4=40  
                                                                    
                                                                    System.out.println(10<<3);//10*2^3=10*8=80  
                                                                    
                                                                    System.out.println(20<<2);//20*2^2=20*4=80  
                                                                    
                                                                    System.out.println(15<<4);//15*2^4=15*16=240  
                                                                    
                                                                    }} 

                                                                      Output:

                                                                      40
                                                                      80
                                                                      80
                                                                      240
                                                                      

                                                                      Java Right Shift Operator

                                                                      The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand.

                                                                      Java Right Shift Operator Example

                                                                      public OperatorExample{  
                                                                      
                                                                      public static void main(String args[]){  
                                                                      
                                                                      System.out.println(10>>2);//10/2^2=10/4=2  
                                                                      
                                                                      System.out.println(20>>2);//20/2^2=20/4=5  
                                                                      
                                                                      System.out.println(20>>3);//20/2^3=20/8=2  
                                                                      
                                                                      }} 

                                                                        Output:

                                                                        2
                                                                        5
                                                                        2
                                                                        

                                                                        Java Shift Operator Example: >> vs >>>

                                                                        public class OperatorExample{  
                                                                        
                                                                        public static void main(String args[]){  
                                                                        
                                                                            //For positive number, >> and >>> works same  
                                                                        
                                                                            System.out.println(20>>2);  
                                                                        
                                                                            System.out.println(20>>>2);  
                                                                        
                                                                            //For negative number, >>> changes parity bit (MSB) to 0  
                                                                        
                                                                            System.out.println(-20>>2);  
                                                                        
                                                                            System.out.println(-20>>>2);  
                                                                        
                                                                        }} 

                                                                          Output:

                                                                          5
                                                                          5
                                                                          -5
                                                                          1073741819
                                                                          

                                                                          Java AND Operator Example: Logical && and Bitwise &

                                                                          The logical && operator doesn’t check the second condition if the first condition is false. It checks the second condition only if the first one is true.

                                                                          The bitwise & operator always checks both conditions whether first condition is true or false.

                                                                          public class OperatorExample{  
                                                                          
                                                                          public static void main(String args[]){  
                                                                          
                                                                          int a=10;  
                                                                          
                                                                          int b=5;  
                                                                          
                                                                          int c=20;  
                                                                          
                                                                          System.out.println(a<b&&a<c);//false && true = false  
                                                                          
                                                                          System.out.println(a<b&a<c);//false & true = false  
                                                                          
                                                                          }} 

                                                                            Output:

                                                                            false
                                                                            false
                                                                            

                                                                            Java AND Operator Example: Logical && vs Bitwise &

                                                                            public class OperatorExample{  
                                                                            
                                                                            public static void main(String args[]){  
                                                                            
                                                                            int a=10;  
                                                                            
                                                                            int b=5;  
                                                                            
                                                                            int c=20;  
                                                                            
                                                                            System.out.println(a<b&&a++<c);//false && true = false  
                                                                            
                                                                            System.out.println(a);//10 because second condition is not checked  
                                                                            
                                                                            System.out.println(a<b&a++<c);//false && true = false  
                                                                            
                                                                            System.out.println(a);//11 because second condition is checked  
                                                                            
                                                                            }} 

                                                                              Output:

                                                                              false
                                                                              10
                                                                              false
                                                                              11
                                                                              

                                                                              Java OR Operator Example: Logical || and Bitwise |

                                                                              The logical || operator doesn’t check the second condition if the first condition is true. It checks the second condition only if the first one is false.

                                                                              The bitwise | operator always checks both conditions whether first condition is true or false.

                                                                              public class OperatorExample{  
                                                                              
                                                                              public static void main(String args[]){  
                                                                              
                                                                              int a=10;  
                                                                              
                                                                              int b=5;  
                                                                              
                                                                              int c=20;  
                                                                              
                                                                              System.out.println(a>b||a<c);//true || true = true  
                                                                              
                                                                              System.out.println(a>b|a<c);//true | true = true  
                                                                              
                                                                              //|| vs |  
                                                                              
                                                                              System.out.println(a>b||a++<c);//true || true = true  
                                                                              
                                                                              System.out.println(a);//10 because second condition is not checked  
                                                                              
                                                                              System.out.println(a>b|a++<c);//true | true = true  
                                                                              
                                                                              System.out.println(a);//11 because second condition is checked  
                                                                              
                                                                              }} 

                                                                                Output:

                                                                                true
                                                                                true
                                                                                true
                                                                                10
                                                                                true
                                                                                11
                                                                                

                                                                                Java Ternary Operator

                                                                                Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands.

                                                                                Java Ternary Operator Example

                                                                                public class OperatorExample{  
                                                                                
                                                                                public static void main(String args[]){  
                                                                                
                                                                                int a=2;  
                                                                                
                                                                                int b=5;  
                                                                                
                                                                                int min=(a<b)?a:b;  
                                                                                
                                                                                System.out.println(min);  
                                                                                
                                                                                }} 

                                                                                  Output:

                                                                                  2
                                                                                  

                                                                                  Another Example:

                                                                                  public class OperatorExample{  
                                                                                  
                                                                                  public static void main(String args[]){  
                                                                                  
                                                                                  int a=10;  
                                                                                  
                                                                                  int b=5;  
                                                                                  
                                                                                  int min=(a<b)?a:b;  
                                                                                  
                                                                                  System.out.println(min);  
                                                                                  
                                                                                  }}  

                                                                                    Output:

                                                                                    5
                                                                                    

                                                                                    Java Assignment Operator

                                                                                    Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.

                                                                                    Java Assignment Operator Example

                                                                                    public class OperatorExample{  
                                                                                    
                                                                                    public static void main(String args[]){  
                                                                                    
                                                                                    int a=10;  
                                                                                    
                                                                                    int b=20;  
                                                                                    
                                                                                    a+=4;//a=a+4 (a=10+4)  
                                                                                    
                                                                                    b-=4;//b=b-4 (b=20-4)  
                                                                                    
                                                                                    System.out.println(a);  
                                                                                    
                                                                                    System.out.println(b);  
                                                                                    
                                                                                    }} 

                                                                                      Output:

                                                                                      14
                                                                                      16
                                                                                      

                                                                                      Java Assignment Operator Example

                                                                                      public class OperatorExample{  
                                                                                      
                                                                                      public static void main(String[] args){  
                                                                                      
                                                                                      int a=10;  
                                                                                      
                                                                                      a+=3;//10+3  
                                                                                      
                                                                                      System.out.println(a);  
                                                                                      
                                                                                      a-=4;//13-4  
                                                                                      
                                                                                      System.out.println(a);  
                                                                                      
                                                                                      a*=2;//9*2  
                                                                                      
                                                                                      System.out.println(a);  
                                                                                      
                                                                                      a/=2;//18/2  
                                                                                      
                                                                                      System.out.println(a);  
                                                                                      
                                                                                      }}  

                                                                                        Output:

                                                                                        13
                                                                                        9
                                                                                        18
                                                                                        9
                                                                                        

                                                                                        Java Assignment Operator Example: Adding short

                                                                                        public class OperatorExample{  
                                                                                        
                                                                                        public static void main(String args[]){  
                                                                                        
                                                                                        short a=10;  
                                                                                        
                                                                                        short b=10;  
                                                                                        
                                                                                        //a+=b;//a=a+b internally so fine  
                                                                                        
                                                                                        a=a+b;//Compile time error because 10+10=20 now int  
                                                                                        
                                                                                        System.out.println(a);  
                                                                                        
                                                                                        }}

                                                                                        Output:

                                                                                        Compile time error
                                                                                        

                                                                                        After type cast:

                                                                                        public class OperatorExample{  
                                                                                        
                                                                                        public static void main(String args[]){  
                                                                                        
                                                                                        short a=10;  
                                                                                        
                                                                                        short b=10;  
                                                                                        
                                                                                        a=(short)(a+b);//20 which is int now converted to short  
                                                                                        
                                                                                        System.out.println(a);  
                                                                                        
                                                                                        }} 

                                                                                          Output:

                                                                                          20
                                                                                          
                                                                                        1. Unicode System

                                                                                          Unicode is a universal international standard character encoding that is capable of representing most of the world’s written languages.

                                                                                          Why java uses Unicode System?

                                                                                          Before Unicode, there were many language standards:
                                                                                          ASCII (American Standard Code for Information Interchange) for the United States.ISO 8859-1 for Western European Language.KOI-8 for Russian.GB18030 and BIG-5 for chinese, and so on.

                                                                                          Problem

                                                                                          This caused two problems:A particular code value corresponds to different letters in the various language standards.The encodings for languages with large character sets have variable length.Some common characters are encoded as single bytes, other require two or more byte.

                                                                                          Solution

                                                                                          To solve these problems, a new language standard was developed i.e. Unicode System.
                                                                                          In unicode, character holds 2 byte, so java also uses 2 byte for characters.
                                                                                          lowest value:\u0000
                                                                                          highest value:\uFFFF
                                                                                        2. Data Types in Java

                                                                                          Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

                                                                                          1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
                                                                                          2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

                                                                                          Java Primitive Data Types

                                                                                          In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.

                                                                                          Java is a statically-typed programming language. It means, all variables must be declared before its use. That is why we need to declare variable’s type and name.

                                                                                          There are 8 types of primitive data types:

                                                                                          • boolean data type
                                                                                          • byte data type
                                                                                          • char data type
                                                                                          • short data type
                                                                                          • int data type
                                                                                          • long data type
                                                                                          • float data type
                                                                                          • double data type
                                                                                          Java Data Types
                                                                                          Data TypeDefault ValueDefault size
                                                                                          booleanfalse1 bit
                                                                                          char‘\u0000’2 byte
                                                                                          byte01 byte
                                                                                          short02 byte
                                                                                          int04 byte
                                                                                          long0L8 byte
                                                                                          float0.0f4 byte
                                                                                          double0.0d8 byte

                                                                                          Boolean Data Type

                                                                                          The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions.

                                                                                          The Boolean data type specifies one bit of information, but its “size” can’t be defined precisely.

                                                                                          Example:

                                                                                          Boolean one = false  

                                                                                          Byte Data Type

                                                                                          The byte data type is an example of primitive data type. It isan 8-bit signed two’s complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

                                                                                          The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of “int” data type.

                                                                                          Example:

                                                                                          byte a = 10, byte b = -20  

                                                                                          Short Data Type

                                                                                          The short data type is a 16-bit signed two’s complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

                                                                                          The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer.

                                                                                          Example:

                                                                                          short s = 10000, short r = -5000  

                                                                                          Int Data Type

                                                                                          The int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

                                                                                          The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

                                                                                          Example:

                                                                                          int a = 100000, int b = -200000  

                                                                                          Long Data Type

                                                                                          The long data type is a 64-bit two’s complement integer. Its value-range lies between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is – 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a range of values more than those provided by int.

                                                                                          Example:

                                                                                          long a = 100000L, long b = -200000L  

                                                                                          Float Data Type

                                                                                          The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.

                                                                                          Example:

                                                                                          float f1 = 234.5f  

                                                                                          Double Data Type

                                                                                          The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.

                                                                                          Example:

                                                                                          double d1 = 12.3  

                                                                                          Char Data Type

                                                                                          The char data type is a single 16-bit Unicode character. Its value-range lies between ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive).The char data type is used to store characters.

                                                                                          Example:

                                                                                          char letterA = 'A'  

                                                                                          Why char uses 2 byte in java and what is \u0000 ?

                                                                                          It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode system. To get detail explanation about Unicode visit next page.

                                                                                        3. Java Variables

                                                                                          A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

                                                                                          Variable is a name of memory location. There are three types of variables in java: local, instance and static.

                                                                                          There are two types of data types in Java: primitive and non-primitive.

                                                                                          Variable

                                                                                          A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of “vary + able” which means its value can be changed.

                                                                                          variables in java
                                                                                          int data=50;//Here data is variable  

                                                                                          Types of Variables

                                                                                          There are three types of variables in Java:

                                                                                          • local variable
                                                                                          • instance variable
                                                                                          • static variable
                                                                                          types of variables in java

                                                                                          1) Local Variable

                                                                                          A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren’t even aware that the variable exists.

                                                                                          A local variable cannot be defined with “static” keyword.

                                                                                          2) Instance Variable

                                                                                          A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

                                                                                          It is called an instance variable because its value is instance-specific and is not shared among instances.

                                                                                          3) Static variable

                                                                                          A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.

                                                                                          Example to understand the types of variables in java

                                                                                          public class A  
                                                                                          
                                                                                          {  
                                                                                          
                                                                                              static int m=100;//static variable  
                                                                                          
                                                                                              void method()  
                                                                                          
                                                                                              {    
                                                                                          
                                                                                                  int n=90;//local variable    
                                                                                          
                                                                                              }  
                                                                                          
                                                                                              public static void main(String args[])  
                                                                                          
                                                                                              {  
                                                                                          
                                                                                                  int data=50;//instance variable    
                                                                                          
                                                                                              }  
                                                                                          
                                                                                          }//end of class 

                                                                                            Java Variable Example: Add Two Numbers

                                                                                            public class Simple{    
                                                                                            
                                                                                            public static void main(String[] args){    
                                                                                            
                                                                                            int a=10;    
                                                                                            
                                                                                            int b=10;    
                                                                                            
                                                                                            int c=a+b;    
                                                                                            
                                                                                            System.out.println(c);    
                                                                                            
                                                                                            }  
                                                                                            
                                                                                            }  

                                                                                              Output:

                                                                                              20
                                                                                              

                                                                                              Java Variable Example: Widening

                                                                                              public class Simple{  
                                                                                              
                                                                                              public static void main(String[] args){  
                                                                                              
                                                                                              int a=10;  
                                                                                              
                                                                                              float f=a;  
                                                                                              
                                                                                              System.out.println(a);  
                                                                                              
                                                                                              System.out.println(f);  
                                                                                              
                                                                                              }}

                                                                                              Output:

                                                                                              10
                                                                                              10.0
                                                                                              

                                                                                              Java Variable Example: Narrowing (Typecasting)

                                                                                              public class Simple{  
                                                                                              
                                                                                              public static void main(String[] args){  
                                                                                              
                                                                                              float f=10.5f;  
                                                                                              
                                                                                              //int a=f;//Compile time error  
                                                                                              
                                                                                              int a=(int)f;  
                                                                                              
                                                                                              System.out.println(f);  
                                                                                              
                                                                                              System.out.println(a);  
                                                                                              
                                                                                              }} 

                                                                                                Output:

                                                                                                10.5
                                                                                                10
                                                                                                

                                                                                                Java Variable Example: Overflow

                                                                                                class Simple{  
                                                                                                
                                                                                                public static void main(String[] args){  
                                                                                                
                                                                                                //Overflow  
                                                                                                
                                                                                                int a=130;  
                                                                                                
                                                                                                byte b=(byte)a;  
                                                                                                
                                                                                                System.out.println(a);  
                                                                                                
                                                                                                System.out.println(b);  
                                                                                                
                                                                                                }}

                                                                                                Output:

                                                                                                130
                                                                                                -126
                                                                                                

                                                                                                Java Variable Example: Adding Lower Type

                                                                                                class Simple{  
                                                                                                
                                                                                                public static void main(String[] args){  
                                                                                                
                                                                                                byte a=10;  
                                                                                                
                                                                                                byte b=10;  
                                                                                                
                                                                                                //byte c=a+b;//Compile Time Error: because a+b=20 will be int  
                                                                                                
                                                                                                byte c=(byte)(a+b);  
                                                                                                
                                                                                                System.out.println(c);  
                                                                                                
                                                                                                }} 

                                                                                                  Output:

                                                                                                  20
                                                                                                  
                                                                                                1. JVM (Java Virtual Machine) Architecture

                                                                                                  JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

                                                                                                  JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

                                                                                                  What is JVM

                                                                                                  It is:

                                                                                                  1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.
                                                                                                  2. An implementation Its implementation is known as JRE (Java Runtime Environment).
                                                                                                  3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.

                                                                                                  What it does

                                                                                                  The JVM performs following operation:

                                                                                                  • Loads code
                                                                                                  • Verifies code
                                                                                                  • Executes code
                                                                                                  • Provides runtime environment

                                                                                                  JVM provides definitions for the:

                                                                                                  • Memory area
                                                                                                  • Class file format
                                                                                                  • Register set
                                                                                                  • Garbage-collected heap
                                                                                                  • Fatal error reporting etc.

                                                                                                  JVM Architecture

                                                                                                  Let’s understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.

                                                                                                  JVM Architecture

                                                                                                  1) Classloader

                                                                                                  Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

                                                                                                  1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.
                                                                                                  2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
                                                                                                  3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles from classpath. By default, classpath is set to current directory. You can change the classpath using “-cp” or “-classpath” switch. It is also known as Application classloader.
                                                                                                  //Let's see an example to print the classloader name  
                                                                                                  
                                                                                                  public class ClassLoaderExample  
                                                                                                  
                                                                                                  {  
                                                                                                  
                                                                                                      public static void main(String[] args)  
                                                                                                  
                                                                                                      {  
                                                                                                  
                                                                                                          // Let's print the classloader name of current class.   
                                                                                                  
                                                                                                          //Application/System classloader will load this class  
                                                                                                  
                                                                                                          Class c=ClassLoaderExample.class;  
                                                                                                  
                                                                                                          System.out.println(c.getClassLoader());  
                                                                                                  
                                                                                                          //If we print the classloader name of String, it will print null because it is an  
                                                                                                  
                                                                                                          //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader  
                                                                                                  
                                                                                                          System.out.println(String.class.getClassLoader());  
                                                                                                  
                                                                                                      }  
                                                                                                  
                                                                                                  }

                                                                                                  Output:

                                                                                                  sun.misc.Launcher$AppClassLoader@4e0e2f2a
                                                                                                  null
                                                                                                  

                                                                                                  These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend the ClassLoader class.

                                                                                                  2) Class(Method) Area

                                                                                                  Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

                                                                                                  3) Heap

                                                                                                  It is the runtime data area in which objects are allocated.

                                                                                                  4) Stack

                                                                                                  Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.

                                                                                                  Each thread has a private JVM stack, created at the same time as thread.

                                                                                                  A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

                                                                                                  5) Program Counter Register

                                                                                                  PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

                                                                                                  6) Native Method Stack

                                                                                                  It contains all the native methods used in the application.

                                                                                                  7) Execution Engine

                                                                                                  It contains:

                                                                                                  1. A virtual processor
                                                                                                  2. Interpreter: Read bytecode stream then execute the instructions.
                                                                                                  3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here, the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

                                                                                                  8) Java Native Interface

                                                                                                  Java Native Interface (JNI) is a framework which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or interact with OS libraries.

                                                                                                2. Difference between JDK, JRE, and JVM

                                                                                                  We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the brief overview of JVM here.

                                                                                                  If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let’s see the differences between the JDK, JRE, and JVM.

                                                                                                  JVM

                                                                                                  JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn’t physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode.

                                                                                                  JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the JVM: specificationimplementation, and instance.

                                                                                                  The JVM performs the following main tasks:

                                                                                                  • Loads code
                                                                                                  • Verifies code
                                                                                                  • Executes code
                                                                                                  • Provides runtime environment

                                                                                                  JRE

                                                                                                  JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

                                                                                                  The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

                                                                                                  JRE

                                                                                                  JDK

                                                                                                  JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.

                                                                                                  JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

                                                                                                  • Standard Edition Java Platform
                                                                                                  • Enterprise Edition Java Platform
                                                                                                  • Micro Edition Java Platform

                                                                                                  The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java Application.

                                                                                                  JDK