Categories
Java

Super Keyword in Java | Learn in 2 mins

The super keyword is Java, refers to the immediate parent class of the current class. It is used to access variables, methods, and constructors of the parent class.

Here are some examples of how the super keyword can be used in Java:

  1. Accessing variables of the parent class:
class Child extends Parent {
  int x = 10;
  int y = 20;

  void display() {
    System.out.println(x);
    System.out.println(y);
    System.out.println(super.x);
    System.out.println(super.y);
  }
}

In this example, the Child class has two variables x and y, which are shadowing the variables of the same name in the Parent class. To access the variables of the Parent class, you can use the super keyword.

  1. Accessing methods of the parent class:
class Child extends Parent {
  void display() {
    super.display();
  }
}

In this example, the Child class has a method called display() that calls the display() method of the Parent class using the super keyword.

  1. Calling the parent class constructor:
class Child extends Parent {
  Child() {
    super();
  }
}

In this example, the Child class has a constructor that calls the constructor of the Parent class using the super keyword.

It is important to note that the super keyword must be used before the parent class’ variables, methods, and constructors are accessed or called.

Categories
Java

Wrapper classes in Java with Examples

In Java, which is an Object Oriented Programming Language, everything revolves around Classes and Objects.

Java’s Collection Framework is a collection of rich sets of  data structures and various useful algorithms to manipulate different Data structures in it. Java’s mostly used primary operations are performed on built in data types like int, float double etc…. However, Java Collection Framework works only on Objects. to leverage the advantage of Collection Framework to these primary data types, we have Wrapper classes for each primary data type.

In Java we have 8 primitive types. They are byte, short, int, long, float, double, char and boolean. To leverage the Object Oriented advantages, Java introduced Wrapper classes for these Primitive types.

Below are the list of primitive types and their Wrapper classes

Primitive TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

So, in short, Wrapper Classes are used to convert primitive data types into objects and vice versa.

Let’s have a quick look with some Java code example on Wrapper classes

// Converting primitive types to Wrapper classes Example
int i = 12;
Integer intWrapper = new Integer(i);

float f = 512.32f;
Float floatWrapper = new Float(f);

char c = 's';
Character charWrapper = new Character(c);
// Converting primitive types to Wrapper classes Example
Integer in=new Integer(3); 
int i = in.intValue();

Character ch=new Character('s'); 
char c = ch.charValue();

Double db = new Double(5.99);
double d = db.doubleValue();

In Above Wrapper classes conversion example, we explicitly converted primitive types to Wrapper classes and Wrapper classes to Primitive Type. Java 5 Introduced New feature called AutoBoxing and Unboxing.

AutoBoxing and UnBoxing

,In Java Automatic Conversion of Primitive types into Wrapper Classes is called AutoBoxing. Here user no need to explicitly code to get the primitive value from corresponding Wrapper class In the same way If Java Compiler converts Wrapper classes to their corresponding primitive types, it is called Unboxing.

Let’s have a simple quick example of AutoBoxing and Unboxing in Java

//Blow AutoBxing, Compiler coverts automatically for us
int a = 12;  
Integer intObject = a;

//Blow UnBoxing, Compiler coverts automatically for us
Integer in=new Integer(3); 
int i = in;

Above is brief introduction of Wrapper classes for beginners. Please let me know In comments If you need anything else to be explained or need more details.

Categories
Java Software Testing

Java try catch finally block example | Exception Handling in Java

Before we start to know about try Catch Finally, we should know about Exceptions and its handling in Java.

In Java, according to Oracle’s Java documentation, An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

For example, If a program is trying to read/write a file from a location, and if the file is not found or not accessible then we get FileNotFoundException exception.

Another example where most of the developer face issue in real time is NullPointerException also referred as NPE.One scenario when we get NPE is, when we try to updated an object which is null, then Java will through NPE. That’s why it is recommended to add null checks before updating any Java Object.

These are some of the exceptions which we face in our day to day life. There are many other exceptions available, which are out of the scope for this post. So, the main idea is when a program is being executed and when unintended event happens, Java will through Exception. When the exceptions are thrown, we may get issues like program halts or in Web applications user will see stack trace of an exception, which end users don’r know about.

To avoid these issues, we can handle Exceptions programmatically and if any unexpected event happens, then we can show the meaning full messages to users and log the required details for developer to debug.

This can be done by the trio called “try-Catch-Finally”.

These 3 try, catch and Finally are the building blocks of Exceptions handling. Let us see on by one

Try Block

Try block is the place where we have actual logic implemented. For example, File handling or updating the Objects and so on…

Try block is the place where Exceptions get generated.

When we suspect that particular code may have chance of throwing the Exception we surround that code with try block

Below is the example of try block

Private void printStringLength(String name){
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
}

As we see in above example, first line in try block is trying to get the length of a String. Here if String is not empty, then everything works fine. But what if String is null, User will get unexceptced NPE error.

To avoid this, we need to surround the code where we suspect there is a chance of exception, with try block like below

private void printStringLength(String name){
       try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
     }
}

catch block

catch block are where we handle the Exception thrown from try block. Code written in catch block are executed only when there is an Exception raised in try block, otherwise catch block is skipped.

In General when we developing application, we don’t want to show the user error messages which are not user friendly like “java.lang.NullPointerException” with some stack trace. Instead we want to show some meaningful information like “Given Name is empty” and then log the stack trace for developer to debug.

Above process of displaying meaningfull message to user/client is handled in catch block.

Below example of catch block

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
           System.out.println(“ Exception occurred while getting length“);
        }
}

finally block

Finally block, as the name suggest, is executed after executing try and/or catch blocks.

Usually we use finally if we want to perform some operation irrespective of whether an exception occurred or not.

For example,

We want to close a DB connection after performing some task in try block, but If any exception occurred there is a chance that rest of the code doesn’t execute, in that scenario we want to close connection. To close the connection, we can put the code in finally block.

Finally block make sure whatever code inside is executed 100% whether an exception occurs or not.

private void printStringLength(String name){
        try{
            int n = name.length();
            System.out.println(“String “+name+” length is: “+n);
        }catch(Exception e){
            System.out.println(“Exception occurred while getting length “);
        }finally{
            System.out.println(“In Finally “)
        }
}


Above is just a brief idea on how try catch finally works, still there is a vast amount of information left, which can be found in Oracle java docs and other places.

Categories
Java

‘this’ keyword in Java with Examples and Explanations | Oracle Java

What is ‘this’ keyword in java?

The keyword ‘this’  in java is used to refer to the object that is invoked. It can be used inside any method which refers to the current object. So it acts as the reference to the object on which the method is invoked.

What are the uses of ‘this’ keyword?

‘this’ keyword in Java can be used in following situations.

  • It can be used to invoke current class constructor
  • It can be used to return the current class instance
  • It can be used to refer current class instance variable
  • It can be used to invoke the current class methods

‘this’ keyword with class instance variable in Java

We can use ‘this’ keyword to refer to the Current Object’s instance variables. This is very helpful especially when we have local variables or passed parameters have the same name as instance variable(s).

for example, If a method taking arguments has the same name as instance variables of the class and if we want to refer the local variables, simply we can use the local variable in the code, but If we want to use the Instance variable we can use this.VariableName. using this.variableName, JVM knows that in the method it needs to perform operation based on the value on instance variables instead of the locale variable.

Java’s Plain POJO (Plain Old Java Objects) or Beans in server terminology now a days are the best examples of using ‘this’ keyword. As we know POJO has instance variables and getters and setter methods of these Instance variables in the Class, in these getters and setters we always use this.variablename to set the value or to get the value.

‘this’ keyword in Java with current class method

This keyword is used to invoke the current class constructor when we have many constructors in the class and want to reuse that constructor. For example, If you want to call a constructor from within another constructor, then you can use this.ConstructorName() to invoke the constructor.

 

we can also use this keyword to call current class non static methods.

We cannot use this keyword in java within static blocks because static blocks are per Class not per instance/object.

 

java this() constructor

Categories
Java

Static keyword in Java with Examples and Uses | Oracle Java Wiki

In Java, Static Keyword can be used with variables, methods, nested class and blocks. Static variable or method is same for all the instances of a class.

The static keyword can be used with:

  • Method
  • Variable
  • Nested class
  • Blocks

Static Method in Java

The method which is declared using the static keyword is known as the static method. The static method belongs to the class instead of the object of the class. You can invoke the static keyword without creating an instance of a class. The static method can access the static data member and can change the value of it.

Let us see the example:

public class Student{
	int Rollno;
    String Name;
    static String college = "DU";
    
    Static void change(){
		college = "TRIAS";
    }

    Student(int r, String n){
		Rollno = r;
		Name = n;
    }
    void display (){        
		System.out.println(Rollno+" "+Name+" "+college);
    }

    public static void main(String args[]){
		Student.change();

		Student s1 = new student (1,"abc");
		Student s2 = new student (2,"xyz");

		s1.display();
		s2.display();
    }
}

Where cannot we use static method in Java?

The static method cannot be used with non static data member or call the non static method directly. And also we cannot use this and super keywords in the static context

Static Variable in Java

Variables which are declared using the Static Keyword are known as Static Variables. They can be used to refer the common property of all the objects of a Class. Static Variables In Java are not instantiated per instance or Object, but they are per Class. The memory for the static variable is stored once in the class area at the time of class loading.

What is the advantage of Static Variable in Java?

The main advantage of using the static variable is that it makes our program efficient and save the memory. They can be accessed without Object Creation If made public.

What is the use of using static variable in java?

The static variable is used when we want to store any common property for all the objects of a class, like if we want to store the Name of the College in Student Object. College Name is Same for all the Student So It makes sense to have Single Variable for all the Objects,  when we create a college name as a static variable memory will be allocated only once otherwise It wil be allocated for each and every student.

Let us have a look at the example:

public class Student {
     int Rollno;
     String Name;
     static String college= “IPU”

     Student(int r,String n){
          Rollno =r;
          Name = n;
     }
     void display(){
          System.out.println(Rollno+" "+Name+ " "+college);
     }

     public static void main(String args[]){
     Student s1 = new Student (1,"abc");
     Student s2 = new Student (2,"xyz");
     s1.display();
     s2.display();
     }
}

Static Nested Class in Java

The static nested classes are those classes which are created inside a class. They cannot access the non static data members and method; it can be accessed by the outer class name. They can access the static data members of outer class including the private.

Let us have a look on the example:

public class nested{
  static String name= “abc”;

  static class nested1{
   void display()
     {     System.out.println("The name is: "+name);
     }
  }
 
  public static void main(String args[]){
  nested.nested1 obj=new nested.nested1();
  obj.display();
  }
}

 

Static Blocks in Java

The static block is used to initialize the static data member and it is executed before the main method at the time of class loading.

Let us have a look at the example:

public class Block{

  static
   {       System.out.println("You are in static block");
   }

  public static void main(String args[])
  {
     System.out.println("Hello World…");
  }
}

 

 

Categories
Java

InstanceOf keyword in Java with Examples

What is instanceof keyword?

In Java, the instanceof keyword is used to check that the object is an instance of a class, subclass or interface.

It is also known as type comparison operator because it compares the instance with the type.

instanceof comparison returns either true or false.

public class fruits{}
public class mango extends fruits{//mango inherits fruits
public static void main(String args[]){
mango m=new mango();
System.out.println(m instanceof fruits);// will return true
}
}

Instanceof with Variable having null value

If we use the instanceof operator with any variable which has the null value than it always returns false. in other words, Instanceof Operator always returns false on a null variable.
To understand this let us have a look at the example:

public class mango{
public static void main(String args[]){
mango m=null;
System.out.println(m instanceof mango); //it will return false
}
}
Categories
Java

Java Core Collections Explained |Java Collections Framework

In this Post you will get details about Java’s Core Collection interfaces and more details about Java Core collections.

Collection is an Object which holds data items that form a natural group. Example:- Collection of Names, collection of letters in mail etc…

Java defines some Core Collections which we can use based on the requirement like type of data and many other factors like uniqueness, name-value pair, order and Time taken to do CURD operations.

In Java Collection is the top level interface. All the Collections interfaces (Except Map) extends this Top level Collection .

Below are the Collection interfaces which Extends To Top Level Collection interface

  • Set
  • List
  • Queue
  • DeQueue
  • Map (doesn’t extend Collection interface)

Set Interface

Set is a special Type of Collection Interface which stores Unique items. so When we have a requirement where we don’t want to store duplicate elements then Set can be used to store elements. For Example:- storing the IDs of users created in a website.
Below are the implementations of the Set Interface in Java

  • HashSet
  • TreeSet
  • LinkedHashSet

List Interface

List is a Type of Collection Interface which can store Duplicate items. List is also known as Ordered Collections. Using List one can retrieve elements using Position of the element in the list

Below are the implementations of the List Interface in Java

  • ArrayList
  • LinkedList

Queue Interface

Queue is a Collection for holding elements prior to processing. Queues provide additional insertion, removal, and inspection operations. Queue Typically follows element in FIFO order

DeQueue Interface

Dequeue are similar to Queue, except they can be accessed from both ends. DeQueue are known as double-ended-queue.

Map Interface

Map Interface is a special kind of Collection which doen’t extend Collection interface like other Core Collections. Map Interface is used to store Key Value pairs unlike other collection interfaces. A map cannot contain duplicate keys

Below are the implementations of the Map Interface in Java

  • HashMap
  • TreeMap
  • LinkedHashMap

We will find More details about Collections and their implementations in Next Topics

Categories
Java

How to Override Equals and HashCode methods in java with Step by Step Example

In this Video we are going to see How to Override equals and hashCode methods in java with examples.
We will be using Appache Comman library for the same.

Categories
Java

Final keyword in Java with Examples

In Java, final keyword can be used with member variables, methods, local variables and classes.

In a nutshell the final keyword can be used with:

  • Variable
  • Method
  • Class

Final Variables

A variable which is declared by using final keyword is the final variables. we cannot make any changes to the value of the final variable. The final variables are just like the constants. The final variables which do not have any value are known as the blank final variables or uninitialized final variables. The final keyword can be initialized in constructor only. A static blank final variable can be initialized in static block only.

Let us have a look on the example:

public class Marks{

final int marks=50;//final variable

void run(){

marks = 90;

}

public static void main(String args[]){

Marks o1=new Marks();

o1.run();

}

}//end of class

Final Method

The method which is made final cannot be overridden. Sub class can call the final method of the parent class but it cannot override the final method. The final methods are faster than the non final methods because they are not required to be resolved at runtime and they are joined at the compiled time.

Let us have a look on the example:


public class fruits

{

final void run()

{    System.out.println("in fruit class");

}

}

 

class apple extends fruits

{

void run()

{    System.out.println("apple class");

}

 

public static void main(String args[])

{

apple a= new apple();

a.run();

}

}

Final Class

The class declared using final keyword is known as final class. The final class is complete in nature and cannot be inherited.

Let us have a look at the example:


public class fruits

class apple extends fruits

{

void run()

{    System.out.println("apple class");

}

public static void main(String args[])

{

apple a= new apple();

a.run();

}

}

Some points to remember

  • Constructor cannot be declared as final.
  • The local final variable must be initialized during declaration.
  • The variables which are declared in an interface are by default final.
  • The final method cannot be overridden.
  • The final class cannot be inherited.
Categories
Java

Constructors in Java with Code Example and Usage

What are constructors?

Java Constructors are the block of codes which we use to initialize an object.

Every class has its own constructor. If we don’t declare the constructor for a class then the compiler initialize a default constructor for that class. Constructors looks like a method but it they don’t have any return type like methods do.

What are the rules for creating constructor?

In Java we need to follow below rules to create constructors.

  • The constructor name must be the same as of the class.
  • The constructor does not have a return type like methods have.

Types of Constructor

There are two types of constructor in Java:

  • Default Constructor
  • Parameterized Constructor

Default Constructor

The Default constructor in Java does not contain any parameters. As discussed earlier, if we don’t specify any constructors in class, Compiler creates the Default constructor.

public class fruits{
	fruits( )
	{    
		System.out.println(“fruit class”);
	}
	public static void main(String args[]){
		fruits f = new fruits( );
	}
}

 

Parameterized Constructor

Parameterized Constructors are like Default constructors but takes arguments or parameters . We need to pass the arguments while calling the Parameterized constructors to create an Object.

We can overload the constructors with different data types as its parameters.


public class vehicle{
    int number;
    String model;
    
    vehicle(int n,String m){
		number = n;
		model = m;
    }
    void display(){
		System.out.println(number+" "+model);
	}
 
    public static void main(String args[]){
		vehicle v1 = new vehicle(1,"BMW");
		vehicle v2 = new vehicle(2,"Mercedes");
		v1.display();
		v2.display();
   }
}

Constructor Overloading

In Java, like methods we can overload constructors, The constructor overloading can be achieved in a class by having different types of parameters and the number of parameters.

Example


public class vehicle{
    int number;
    String model;
    int price;
    vehicle(int n,String m){ //Parametrized Constructor with 2 arguments 
		number = n;
		model = m;
    }
    vehicle(int n,String m,int p){ //Parametrized Constructor with 3 arguments
		number = n;
		model = m;
		price=p;
    }
    void display(){
		System.out.println(number+" "+model+" "+price);
	}
 
    public static void main(String args[]){
		vehicle v1 = new vehicle(1,"BMW",900000);
		vehicle v2 = new vehicle(2,"Mercedes");
		v1.display();
		v2.display();
   }
}

Constructor Chaining

In Java Constructor chaining is a process where one constructor is called from another constructor.
Example

public class Test {
     
    public Test(){
        System.out.println("constructor 1...");
    }
    public Test (int i){
        this(); //Default Constructor called from this constructor
        System.out.println("constructor 2...");
    }
    public Test (int i,int j){
        this(j); //Constructor with single argument is called form this constructor
        System.out.println("constructor 3...");
    }
     
    public static void main(String a[]){
        Test t = new Test (10,20);
    }
}

Super Keyword

The super keyword acts like a reference variable that is used to refer the parent class objects. As we create the instance of the subclass the instance of the parent class is created implicitly.

Why we need super keyword?

The super keyword is needed in the following categories:

  1. The super keyword is used to refer the parent class variable. Let us understand this through an example
    public class Fruits{
      String name="mango";
    }
    
    class Banana extends Fruits{
      String name="banana";
        
      void display(){
       System.out.println(super.name);//it will print name of fruits which is a parent class
      }
      public static void main(String args[]){
       Banana f=new Banana();
       f.display();
       
    }
    }           
    

    In the above example there are two classes Fruits is a parent class whereas banana is a child class and in both the classes the name is a common property. So to access the variable of parent class we have use super keyword. If we don’t use the super keyword, then it will print the child class’s variable.

  2. The super keyword is used to invoke the parent class constructor. Let us have a look at the example
    public class Fruits{
    	Fruits()
    	{        
    		System.out.println("In parent class…");
    	}
    }
    class Banana extends Fruits{
    	Banana(){
    		super();//it will invoke parent class constructor
    		System.out.println("In child class…");
    	}
    	public static void main(String args[]){
    		Banana f=new Banana();      
    	}
    }
    
  3. Super keyword can be used to invoke the parent class’s method. Let us have an example to understand this:
    public class fruits{
    	void msg()
    	{     
    		System.out.println("In parent class");
    	}
    }
    class fruit1 extends fruits{
    	void msg() 
    	{      
    		System.out.println("In child class");
    	}
    	void display(){
    		msg();//it will invoke child class msg() method
    		super.msg();//it will invoke parent class msg() method
    	}
    
    public static void main(String args[]){
    	fruit1 f=new fruit1();
    	f.display();
    	}
    }
    
    
Exit mobile version