Category: Java Tutorial

  • Java – do while Loop with Example

    Sometimes it is necessary that the block or statement must be executed at least once but if the condition is initially at a false state then the block will not be executed.
    So for the situation where a block of code must be executed at least once, a do-while loop comes in play.

    dowhile is an exit-control loop that is it checks the condition after the first execution of the block. And it keeps executing the block until the condition state is false.

    Flowchart for do-While loop in Java:

    Syntax of do..while loop:

    do
     {
      statements..
     }while (condition);

    Example of a do-while loop in java:

     public class dowhileloopTest
     { 
       public static void main(String args[]) 
       { 
        int a = 1; 
        do
        { 
           //will be executed once
           System.out.println("Value of x:" + a); 
           a++; 
        } 
        while (a < 5); 
      } 
     }

    Output:

     Value of x:1
     Value of x:2
     Value of x:3
     Value of x:4

  • Java – Switch Case Statement with Example

    A switch statement allows a variable to be tested for equality against multiple values. It provides the case for the different blocks of code to be executed.

    Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.

    It can also have an optional break that is useful to exit the switch otherwise it continues to the next case.

    Flowchart for switch statement in java:

    switch statement

    Syntax of switch statements:

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

    Example of a switch-case statement in Java:

      public class SwitchTest 
      {  
        public static void main(String[] args) 
        {  
          int num = 5;  
          //Switch expression  
          switch(num)
          {  
            //Case statements  
            case 3: System.out.println("Number 3");  
            break;  
            case 5: System.out.println("Number 5");  
            break;  
            case 8: System.out.println("Number 8");  
            break;  
            //Default case
            default: System.out.println("Not matched");  
          }  
        }  
      }

    Output switch-case statement:

     Number 5

    For practice you can look at this article: Currency Conversion Program in Java


  • Java – if-else if ladder with Example

    This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and rest will be bypassed.

    If none of the conditions is true then the final else statement at the end will be executed.

    Flowchart diagram for if-else if statement in java:

    if elseif statement

    Syntax of if-else-if ladder statement:

    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
    {  
       //final esle if all the above condition are false 
    }

    Example of nested-if statement in Java:

     public class IfElseIfTest 
     {
       public static void main(String args[]) 
       {
         int num1 = 10, num2 = 20;
    
         if (num1 > num2) {
             System.out.println("num1 is greater");
         }
         else if(num2 > num1){
            System.out.println("num2 is greater");
         }       
         else {
            System.out.println("Both are same");
         }
       }
     }

    Output:

    num2 is greater

  • Java – nested-if statement with Example

    Nested-if statement allows the user to use if block inside the other if block. And the inner if is executed only if the outer if is true in condition.

    Flowchart for nested-if statement in Java:

    nested-if statement

    Syntax of nested if statement:

    if(condition1)
     {    
        //block of code to be executed    
        if(condition2)
        {  
          //block of code to be executed    
        }    
     } 

    Example of a nested-if statement in Java:

     public class NestedIfTest 
     {
        public static void main(String args[]) 
        {
        int num1 = 20;
        int num2 = 30;
    
        if( num1 >= 10 ) 
        {
            if( num2 >= 15 ) 
            {
                System.out.println("a and b both are true");
            }
        System.out.println("code inside the first if statement");
        }
        }
     }

    Output:

     a and b both are true
     code inside the first if statement

  • Java – if-else statement with Example

    There are two-part in an if-else statement. First is the if statement, here it checks for the condition to be true and if it is true then it will execute the code present inside the if-block. But if the condition is false then the code inside the else statement will be executed.

    Flowchart for if-else statement in Java:

    if-else statement

    Syntax of an if-else statement:

     if (condition) 
     {
      //code executed if condition true 
     }
     else
     {
      //code executed if condition false 
     }

    Example of an if-else statement in Java:

    public class IfElseTest 
    { 
      public static void main(String args[]) 
      { 
        int a = 5; 
    
        if (a < 10) 
        {
            System.out.println("If statement executed"); 
        }
        else
        {
            System.out.println("Else statement executed"); 
        }
      } 
    }

    Output:

    If statement executed

  • Java – if statement

    Among the decision making statements, if- statement is the most simple one.

    It checks if the condition is true or not, and if it is true then it executes the block of code inside if otherwise, it will not. The block that is executed is placed within the curly braces({}).

    Flowchart for if statement in java:

    Syntax of if statement in Java:

     if (boolean expression)
     {
      /* if expression is true */
      statements... ; /* Execute statements */
      }

    Example of if statement in Java:

    public class IfTest 
    {
      public static void main(String args[]) 
      {
        int a = 5;
    
        if( a < 10)  //checks for condition
        {
           System.out.println("If statement executed");
        }
      }
    }

    Output:

    If statement executed

  • Java – Garbage Collection

    Garbage collection in java is a way in which the unreachable objects are destroyed to free up space in memory.

    JVM creates a heap area which is called runtime data area, where all the objects are stored. And the space in that area is limited so it is needed to manage this area efficiently by removing the objects that are no longer required or are unused. And therefore, this process of removing the unused objects present in the heap area is known as Garbage collection.

    It runs automatically in the background and is a part of a memory management system in Java.
    Unlike Java, c/c++ doesn’t support Garbage collection.

    Benefits/Advantages of using garbage Collection:

    • Removal of unreferenced objects present in a heap memory makes the memory more efficient for use.
    • The automatic removal of objects makes it faster and users do not need to make an extra effort.

    finalize() method:

    Before destroying an object, the finalize() method is called by Garbage Collector for performing the cleanup process. And once it’s done, Garbage Collector destroys that object.

    The finalize() method is present in an Object Class as:

     protected void finalize(){} 

    gc() method:

    This method is used when needed to invoke the garbage Collector for the cleanup process.

     public static void gc() {} 

    Example of Garbage Collection in Java:

    public class GarbageCollectionTest
     {  
      public void finalize()
      {
         System.out.println("Garbage Collected");
      } 
     
      public static void main(String args[])
      {  
       GarbageCollectionTest g1=new GarbageCollectionTest();  
       GarbageCollectionTest g2=new GarbageCollectionTest();  
      
       g1=null;  
       g2=null;  
      
       System.gc();  
      }  
     }

    Output of Garbage Collection:

     Garbage Collected
     Garbage Collected

  • Java – Packages and its types with example

    Packages in Java are a way to pack(group) a number of related types such as classes, interfaces, enumerations, and annotations together into a single unit. Think of it as a container for the classes.

    Packages are used to avoid name conflicts, provide a good structure to the projects with maintainable code that consists of many classes.

    Reason to use Packages(advantages):

    • It provides the reusability of the same code again and again in the program by creating a class inside a package for that particular task.
    • The name of the two classes can be defined by the same name in two different packages and we can avoid name conflicts using packages.
    • We can hide the classes in packages if the user doesn’t want it to be accessed by other packages.
    • Hundreds of classes used in packages are organized in a better way so that when needed it can be easily accessed by the programmer.

    Creating Package in Java:

    We can create a package in java by declaring the keyword ‘package’ followed by the ‘packageName‘.
    Syntax:

     package mypack;

    Syntax to compile the program.

     javac -d Destination/Directory_folder file_name.java

    Note:
    The -d in here specifies the destination/directory to put the generated class file.
    Other directory names can be used such as d:/xyz (in case of windows) etc.
    And to keep the package within the same directory we need to use. (dot).

    Syntax to run the Java Program:

    java package_Name.Class_Name

    Let us see it in an example:

    //save as CreatingPack.java  
     package pack1;  
     public class CreatingPack
     {  
      public static void main(String args[])
      {  
        System.out.println("Hello! I am Package");  
      }  
     }

    To compile:

     javac -d . CreatingPack.java 

    To run:

     java pack1.CreatingPack

    Output:

     Hello! I am Package

    import Keywords:

    If the user needs to access or use the class of some other package in his/her current package, then it can be done with the help of the import keyword. import keyword imports the packages with reference to all classes or a particular class of that imported package.

    This keyword is used to import both Built-in Packages and User-defined Packages. You can see the use of import below in examples.

    Accessing Classes from Packages:

    It can be done in the following ways,

    1. Using fully qualified name:

    When we use a fully qualified name then we do not need to use import but need to use a fully qualified name every time we want to access the class or interfaces of that other package.

    Example of Using fully qualified name in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1
     {  
      public void display()
      {
        System.out.println("Display Accessed");
      }  
     }
    
     //save by class2.java  
     package mypack2;  
     class class2
     {  
      public static void main(String args[])
      {  
        pack1.Class1 obj = new pack1.Class1(); //using fully qualified name  
        obj.display();  
      }  
     }

    Output:

    Display Accessed

    2. import only selected class from a package:

    This is the way in which the user can only access those classes that are required from the package. This is done by import packageName.className

    Example of importing only selected class from a package in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1 
     {  
      public void display() 
      {
        System.out.println("Display Accessed");
      }  
     }  
    
     //save by Class2.java  
     package pack2;  
     import pack1.Class1;  //class1 is accesed from pack1 package
     class Class2 
     {  
      public static void main(String args[]) 
      {  
        Class1 obj = new Class1();  
        obj.display();  
      }  
     } 

    Output:

    Display Accessed

    3. import all the classes from a selected package:

    ‘*’ is used instead of className when the package is imported. But the classes and packages that are present inside the sub-packages cannot be accessed. This can be done by import packageName.*;

    Example of import all the classes from a selected package in Java:

    //save by Class1.java  
     package pack1;  
     public class Class1
     {  
      public void display() 
      {
       System.out.println("Display Accessed");
      }  
     }  
    
     //save by Class2.java  
     package pack2;  
     import pack1.*; //importing all classes from pack1 package   
     class Class2 
     {  
      public static void main(String args[]) 
      {  
       Class1 obj = new Class1();  
       obj.display();  
      }  
     }

    Output:

     Display Accessed

    Sub-Packages:

    The package within another package is called sub-package.

    Example of Sub-packages in Java:

    If we create a package called ‘Add’ inside a package named ‘AddNumber’ then the Add is called sub-package and it will be declared as package AddNumber.Add

     //saved  Addition.java
     public class Addition 
     {
      int sum(int x, int y)
      {
        return x*y;
      }
     }

    And to use this class present in a sub-package we can either import the package or use fully qualified name.

    Importing a package:

     import AddNumber.Add.Addition;

    using a fully qualified name:

     AddNumber.Add.Addition obj = new AddNumber.Add.Addition();

    Categories of packages:

    • Built-in Packages (Java API)
    • User-defined Packages (self-created)

    1. Built-in Packages (Java API) :

    These are already defined packages in Java. Java APIs are the already defined classes that are provided for free use.

    The mostly use built-in packages are:

    • java.lang
      Contains classes for primitive data types, strings, math operations, threads, and exception.
    • java.util
      contains utility classes such as vectors, hash tables, dates, etc.
    • java.io
      Stream classes for input/output operations.
    • java.awt
      Contain classes for implementing GUI such as buttons, menus, etc.
    • java.net
      Classes for networking operations.
    • java.applet
      Contain classes for creating and implementing applets.

    Example: If the user input is required, we import Scanner and following is the way to do it:

    import java.util.Scanner

    2. User-defined Packages (self-created):

    These packages are created/defined by the user themself. Users need to create a directory ‘egPackage‘ and name should match with the name of the package. Then the user can create a class (EgClass) inside that directory by declaring the first name as the package name.

     // Name of the package must must match with the directory where the file is saved
     package egPackage;
    
     public class EgClass
     {
      public void detail(String s)
      {        
       System.out.println(s);        
      }
     }

    And now the user can use this package in another program by importing it.

    //importing the class 'EgClass' from egPackage
     import egPackage.EgClass;
    
     public class DisplayClass 
     {
      public static void main(String args[]) 
      {       
       String disp = "Diplaying the details";
    
       EgClass obj = new EgClass();
    
       obj.detail(disp);
      }
     }

    Output:

     Diplaying the details
  • Java – Method Overriding with Example, Super Keyword

    In any object-oriented programming language, Method Overriding is a feature that allows the user to declare a method with the same name in a sub-class that is already present in a parent-class.

    That is when a sub-class inherits from its super-class and both have the same-named method than by overriding features, different tasks can be applied to both of the methods.

    Method overriding is used for runtime Polymorphism.

    Example of method overriding in Java:

     class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class breed extends Dog 
     {
        public void display() 
        {
            System.out.println("Breed: German Shepard");
        }
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            Dog d = new Dog();   // Animal reference and object
            Dog b = new breed();   // Animal reference but Dog object
    
            d.display();   // runs the method in Animal class
            b.display();   // runs the method in Dog class
        }
     }

    Output method overriding:

    Cat meows
    I am A Dog
    Breed: German Shepard

    Explanation:
    In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and runs the method that belongs to that particular object.

    Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.

    But look at the below example:

     class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class breed extends Dog 
     {
        public void display() 
        {
            System.out.println("Breed: German Shepard");
        }
        public void dogSleep()
        {
        System.out.println("Dog is Sleeping");
        }
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            Dog d = new Dog();   // Animal reference and object
            Dog b = new breed();   // Animal reference but Dog object
    
            d.display();   // runs the method in Animal class
            b.display();   // runs the method in Dog class
            b.dogSleep();
        }
     }

    Output:

     BreedTest.java:31: error: cannot find symbol
           b.dogSleep();
            ^

    Here it shows an error for the method doSleep() because the object created is of type Dog that does not have the dogSleep() method and is not Overriden in the breed class.


    Rules for Overriding a Method:

    • The Overriden and Overriding methods must have the same name and the same argument list.
    • Method Overriding requires Inheritance of a class otherwise the method cannot be overridden.
    • Restriction to use Access-modifier, that is if a, access-modifier of the method is declared public in a parent class then it cannot be an overriding method of a sub-class or child-class cannot have protected, private and default access-modifier.
    • private, static and final methods cannot be overridden as they are local to the class. But the static method can be re-declared.
    • A child class within the same package as the instance’s parent class can override any parent class method that is not declared private or final.
    • Constructors cannot be overridden.
    • Overriding method (that is the method present in the sub-class) can throw unchecked exceptions, whether the Overriden method (that is the method present in the parent-class) throws an exception or not.

    Use of Super keyword in Method Overriding:

    The super keyword in Java is used in the sub-class for calling the inherited parent class method/constructor. When we execute super.myMethodName in sub-class inside the method, it invokes the method of parent-class having method name ‘myMethodName’.

    Example of Super keyword in Method Overriding:

    class Dog 
     {
        public void display() 
        {
            System.out.println("I am A Dog");
        }
     }
    
     class Breed extends Dog 
     {
        public void display() 
        {
            super.display();
            System.out.println("Breed: German Shepard");
        }
        
     }
    
     public class BreedTest 
     {
    
        public static void main(String args[]) 
        {
            
            Breed b = new Breed();
    
            b.display(); 
            
            
        }
     }

    Output:

    I am A Dog
    Breed: German Shepard

    In this example, we create the Object for Breed class. And ‘super.display()’ calls the ‘display()‘ method from the Dog class that is the parent class. and hence we get ‘I am a Dog‘ result too.
    But if we eliminate ‘super.display()‘ then we only get the result as ‘Breed: German Shepard‘.


  • Java – Method Overloading with Example

    Method Overloading is one of the features in a class having more than one method with the same name. It is the same as Constructor Overloading in java. The methods are differed by their input parameter that is the data type, the number of parameters, and the order of the parameter list.

    Note that: Method overloading is not possible by changing the return type of methods.

    Now let us see the different ways of overloading methods.

    There are two different ways in which the method can be overloaded:

    1. Method overloading, by changing the data type of Arguments.
    2. Method overloading, by changing the number of the argument.

    1. Method overloading by changing the data type of Arguments.

    In this method, the user needs to change the data-type of passing argument for two different methods of the same name and the parameter list must match with that data type accordingly.

    The following program shows the example of using Method overloading by changing the data type of Arguments in Java:

    class MethOverloadingTest
     {
        void add (int x, int y)
        {
        System.out.println("sum is "+(x+y)) ;
        }
        void add (double x, double y)
        {
        System.out.println("sum is "+(x+y));
        }
     }
    
     public class Main
     {  
        public static void main (String[] args)
        {
        MethOverloadingTest  sum = new MethOverloadingTest();
        sum.add (5,5);      // method with int parameter is called.
        sum.add (5.5, 5.5); //method with float parameter is called.
        }
     }

    The output of Method overloading:

    sum is 10
    sum is 11.0


    2. Method overloading by changing the number of the argument.

    Another way is by changing the number of arguments that is the number of parameters passed when called. We can also keep the argument empty and it will recognize the method with an empty parameter list.

    Following is the example method overloading by changing the number of arguments in Java:

    class MethOverloadingTest2
     {
        void Info()
        {
         System.out.println("Argument List is empty") ;
        }
        void Info (String c, int id)
        {
         System.out.println("\nName:"+c+" Id:"+id);
        }
        void Info (String c, int id, int age)
        {
         System.out.println("\nName:"+c+" Id:"+id+" Age:"+age);
        }
     }
    
     public class Main
     {  
        public static void main (String[] args)
        {
          MethOverloadingTest2  sum = new MethOverloadingTest2();
          sum.Info(); //method with empty parameter is called.
          sum.Info ("Karan",1101);      // method with two parameter is called.
          sum.Info ("Prashant",1102,23); //method with three parameter is called.
        }
     }

    The output of Method overloading:

    Argument List is empty

    Name:Karan Id:1101

    Name:Prashant Id:1102 Age:23