Blog

  • 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


  • Method in Java

    Java Method is a collection of statements that are put together to perform some specific task. To run the methods, it should be called and it returns the value to the caller. Users can pass data to the methods and those data are known as parameters. They are also known as a function.

    It allows the user to reuse the code as many times without rewriting the code and therefore act as a time saver.

    Syntax of method:

     modifier returnType methodName (Parameter List) 
     {
        // method body
     }
    
     //example
     public int calculate(int x, int y) 
     {
        // statements
     }

    Explanation:

    Modifier:

    It is optional and defines the access type of a method. In the above example, the ‘public’ is the modifier of the method calculates.

    Return Type:

    The return type is for returning the value by defining the data-type of the method or void is used if the method does not return a value. In the above example, ‘int’ is the data type for the return type.

    MethodName:

    It is the name given to the method to identify the specific method. ‘calculate is the method name in the above example.

    Parameter List:

    These are the input parameters with their specific data types. The passed parameter data type must match with the parameter list of a method and also the order in which it is passed and must be separated by commas(,). If there are no parameters, the user needs to use an empty parentheses ‘()’. ‘int x, int y’ is the parameter list in the above example.

    Method body:

    The method body is enclosed within the curly braces'{}’. It defines the task of a method within the curly braces.


    Call A Method:

    To use the method and its functionality in a program it must be called. To call a method, the user needs to write the method name followed by two parentheses ‘()’ and a semicolon ‘;’. When a program calls a method, the control of a program remains with the method and then again return the control to the caller in two conditions:

    1. If completes all the statements within the curly braces ‘{}’.
    2. If the return statement is executed.

    Basic example to call a method more than once with empty parameter List in Java:

    public class MethodTest 
     {
     //creating a void method
        static void myMethod() 
        {
        System.out.println("I am called");
        }
    
        public static void main(String[] args) 
        {
        myMethod();//method called
        myMethod();//method called
        }
     }

    Output:

     I am called
     I am called 

    Void Keyword:

    This Keyword allows us to create methods that do not return any values.

    Basic example to find the max number with method parameter and with return type in Java:

    public class MethodTest 
     {
       //creating a method //static method mean accessing the static variable without object
        public static int maxMethod(int a, int b) 
        {
         int max;
         if (a < b)
            max = b;
         else
            max = a;
    
         return max; //returning the result and also return the control
        }
        
        public static void main(String[] args) 
        {
         int x = 20;
         int y = 25;
         int z = maxMethod(x, y);
         System.out.println("The Maximum Value : " + z);
        }
     }

    Output:

     The Maximum Value : 25

    Method Types

    There are two types of method:

    • Standard Library Methods
    • User-defined Methods: In the above part we lean about the User-defined methods.

    Standard Library Methods:

    These methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

    Some example of Standard Library Methods:

    • print() -use to print the String.  And it comes under java.io.PrintSteam
    • sqrt() -use to find the square root of the number and it is a method of Math class

  • Inner Class in Java

    Java Inner class is also known as the nested class is a class within the class, method, or block declared inside class or interface. The use of the inner class is to group the classes or interfaces logically in one place so that it becomes easy to read and maintain.

    Java Inner class is of two types:

    A. Non-static nested classes

    • Member inner class
    • Anonymous inner class
    • Local inner class

    B. Static nested classes


    A. Non-static nested classes in Java: (Inner class)

    It is one of the types of java Inner class. As we have learned from the Access modifiers that we cannot declare a class with ‘private’ modifiers. But the inner class, that is the member of the other class is declared then we can have the inner classes as ‘private’.

    An inner class is of the following types:

    • Member inner class
    • Anonymous inner class
    • Local inner class

    1. Member inner class:

    It is a Non-static nested class (inner class) that is declared inside a class and outside all the methods or blocks. If we declare it as private then that inner class cannot be invoked from an object outside the outer class of that inner class.

    Syntax for member inner class in Java:

    class OuterClass
     {  
      //code  
      class InnerClass
      {  
       //code  
      } 
     
      //methods
    
     } 

    Let us use it in a program:

    In the following example, we declare the private inner class within the outer class, which also contains a method ‘displayingInner()’ that instantiates an inner class and invokes the method that is present inside the inner class.

    And the Main class instantiates the Outerclass class and invokes the method ‘displayingInner()’, that is the nesting done here.

    Note: That the InneerClass cannot be accessed outside the outer class because of its private modifier but it can be accessed by the method inside the OuterClass.

    To demonstrate the example if Member inner Class in Java:

    class OuterClass 
     {
        
       // inner class declaring as private
       private class InnerClass 
       {
         public void displayInner() 
         {
           System.out.println("Inner class Acceseed");
         }
       }
        
       // method for accessing the inner class
       void displayingInner() 
       {
         InnerClass in = new InnerClass();
         in.displayInner();
       }
     }
        
     public class Main 
     {
    
       public static void main(String args[]) 
       {
        // Instantiating the outer class 
        OuterClass out = new OuterClass();
          
        // Accessing the displayingInner method.
        out.displayingInner();
        }
     }

    Output:

    Inner class Acceseed

    2. Anonymous inner class:

    Anonymous inner class is a class that does not contain the class name. They are used in a class or interface whenever the user needs to override the methods. The declaration and instantiation of the Anonymous inner class are done at the same time.

    There are two ways in which this class can be created. They are:

    • First Subclass or maybe abstract
    • Second interface

    Let us see it individually:

    Example of Anonymous inner class Using class in Java:

    abstract class Dog
     {  
        abstract void bark();  
     }  
     public class TestAnonymousInner
     {  
      public static void main(String args[])
      {  
        //An anonymous class
        Dog d = new Dog()
        {  
         void bark()
         {
          System.out.println("The dog is barking");
         }  
        };
        
        d.bark();  
      }  
     }

    Output:

    The dog is barking

    Example of Anonymous inner class using interface in Java:

    interface Dog
     { 
      void display(); 
     }
    
     public class Flavor2Demo 
     { 
       public static void main(String[] args) 
       {
        // An anonymous class 
        Dog d = new Dog() 
        { 
         public void display() 
         { 
            System.out.println("I am a good Dog"); 
         } 
        }; 
        
         d.display(); 
       } 
    } 

    Output:

    I am a good Dog

    3. Local inner class:

    The class that is declared within the method of an outer class is called the Local inner class or method-local inner class. As the name suggests local, that is its restriction is within that method only, just like a local variable.

    Example to demonstrate the local inner class in Java:

    public class OuterClass
    {  
      void MethodOuter()
      {  
       System.out.println("Outer Class Method");
            
       class LocalClass   //Local Inner class
       {  
        void MethodInner()
        {
          System.out.println("Inner Class Method");
        }  
       }  
        LocalClass c = new LocalClass();  
        c.MethodInner();  
      }
        
        public static void main(String args[])
        {  
         OuterClass o = new OuterClass();  
         o.MethodOuter();  
      }  
    }

    Output:

    Outer Class Method
    Inner Class Method


    B. Static nested classes:

    If a class within another class that is the nested class has the static modifier declared in it, then it is called a static nested class. As this class is applied static, it will not be able to access the instance variables and methods of the outer class, it can only access the static member of the outer class.

    Example: Accessing static method of a static class in Java,

    public class OuterClass
     {  
      void MethodOuter()
      {  
       System.out.println("Outer Class Method");
        
       class LocalClass   //Local Inner class
       {  
        void MethodInner()
        {
          System.out.println("Inner Class Method");
        }  
       }  
       LocalClass c = new LocalClass();  
       c.MethodInner();  
      }
    
      public static void main(String args[])
      {  
        OuterClass o = new OuterClass();  
        o.MethodOuter();  
      }  
     }

    Output Static nested classes:

    I am Inner Class