Posted in Others

Interface explained with example

Credits:
Naveen reddy (Telusko youtube channel)
http://www.geeksforgeeks.org

Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body).

  • Interfaces specify what a class must do and not how. It is the blueprint of the class.
  • If a class implements an interface and does not provide method bodies for all functions specified in the interface, then class must be declared abstract and the method without body needs to be abstract.
abstract class random implements testInterface{

	public abstract void something(); //No body with abstract
	public void hello() {
		System.out.println("Hello");
	}
}
//Because one method is abstract, the class must also be abstract
  • To declare an interface, use interface keyword.
  • It is used to provide total abstraction. That means all the methods in interface are declared with empty body
  • All fields are public, static and final by default.
  • A class that implement interface must implement all the methods declared in the interface. To implement interface use implements keyword.
  • Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .
  • So the question arises why use interfaces when we have abstract classes?
    The reason is, abstract classes may contain non-final variables, whereas variables in interface are final, public and static.

Important points about interface

  • We can’t create instance(interface can’t be instantiated) of interface but we can make reference of it that refers to the Object of its implementing class.
  • A class can implement more than one interface.
  • An interface can extends another interface or interfaces (more than one interface) .
  • A class that implements interface must implements all the methods in interface.
  • All the methods are public and abstract. And all the fields are public, static, and final.
  • It is used to achieve multiple inheritance.

An example below:

//public class InterfaceDemo extends Pencil { // Extends can happen for only single class, JAVA does not support multiple inheritance
public class InterfaceDemo implements sharpner { // Implements interface now from extending class, implementing sharpner interface which again extends rubber and pencil adv

	public static void main(String[] args) {
		Pen p = new Pen(); // If show method is not static we need to create an object and then we can
							// access pen class
		p.showPen();

		Pencil.showPencil(); // If show method is static , we can access it after extending Pen class

		Pencil pc = new Pencil();
		pc.showPencil(); // Also we can access show by creating object of pencil class
		pc.erase();
		
		Pencil_advance pa=new InterfaceDemo(); // Reference of interface but object of class, to access the methods of interface
		pa.showPencilAdv();
		pa.eraseAdv();
		
		// Since there is already InterfaceDemo() object created, we need to cast for another one
		// Since sharpner interface already extends rubber and pencil advance, we can call all methods from pencil adv, rubber, sharpener
		sharpner sh=new InterfaceDemo();
		sh.sharpen();
		sh.EraseRubber();
		sh.showPencilAdv();
		sh.eraseAdv();
		
	}
	

	public void showPencilAdv() { 				//Method definition is mandatory if implementing interface
	System.out.println("Show Adv pencil");
	}

	public void eraseAdv() { 						///Method definition is mandatory if implementing interface
		System.out.println("Erase adv pencil");
	}


	public void EraseRubber() {
		// TODO Auto-generated method stub
		
	}


	public void sharpen() {
		// TODO Auto-generated method stub
		
	}

}
class Pen {
	void showPen() {
		System.out.println("Pen class_show method");
	}
}
class Pencil {
	static void showPencil() {
		System.out.println("Pencil class_show method");
	}
	void erase() {
		System.out.println("Pencil can erase");
	}
}
//Interfaces with declaration and no definition
interface Pencil_advance { 
	void showPencilAdv();
	void eraseAdv();
}
interface rubber{
	void EraseRubber();
}
interface sharpner extends rubber,Pencil_advance{ //Interface extends interface not implements, interface can extend multiple interface
	void sharpen();
}
Posted in Others

variable-length arguments in Java

Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded method(one for each) and another put the arguments into an array, and then pass this array to the method. Both of them are potentially error-prone and require more code. The varargs feature offers a simpler, better option.

Syntax of varargs :
A variable-length argument is specified by three periods(…). For Example:

public static void fun(int ... a) 
{
   // method body
}

This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here a is implicitly declared as an array of type int[].

// Java program to demonstrate varargs 
class Test1 
{ 
    // A method that takes variable number of intger 
    // arguments. 
    static void fun(int ...a) 
    { 
        System.out.println("Number of arguments: " + a.length); 
  
        // using for each loop to display contents of a 
        for (int i: a) 
            System.out.print(i + " "); 
        System.out.println(); 
    } 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        // Calling the varargs method with different number 
        // of parameters 
        fun(100);         // one parameter 
        fun(1, 2, 3, 4);  // four parameters 
        fun();            // no parameter 
    } 
}

}
Output:

Number of arguments: 1
100 
Number of arguments: 4
1 2 3 4 
Number of arguments: 0
 

Explanation of above program :

  • The … syntax tells the compiler that varargs has been used and these arguments should be stored in the array referred to by a.
  • The variable a is operated on as an array. In this case, we have defined the data type of a as int. So it can take only integer values. The number of arguments can be found out using a.length, the way we find the length of an array in Java.

    Note: A method can have variable length parameters with other parameters too, but one should ensure that there exists only one varargs parameter that should be written last in the parameter list of the method declaration.

    int nums(int a, float b, double … c)

Important points:

  • Vararg Methods can also be overloaded but overloading may lead to ambiguity.
  • Prior to JDK 5, variable length arguments could be handled into two ways : One was using overloading, other was using array argument.
  • There can be only one variable argument in a method.
  • Variable argument (varargs) must be the last argument.

Source: https://www.geeksforgeeks.org/variable-arguments-varargs-in-java/

Posted in Others

JDK, JRE, JVM

JDK
Contains various APIs and libs like
Java.io, javac, java etc
It gives the required packages for java developer to work on JVM and jre

JRE
It is runtime environment, which implements JVM and provides all class libraries and other files that JVM requires at runtime

JVM
It is where the bytecode is executed

Posted in Others

Synchronisation in Java

  • It is a process which keeps all concurrent threads in execution to be in sync while trying to access the same object at the same time.
  • It prevents memory consistency errors caused due to inconsistent view of shared memory.
  • Ex BookMyShow, multiple users try to book tickets at same time but ticket selected by one user is Locked and prevented for other users.
Posted in Others

Process vs thread

  • A process is a running instance of program over OS
  • – A thread is running on top of process
  • – OS, there is multi processing on OS level
  • – Multiple thread, multi threading in process level
  • – Process run on separate memory space
  • – Thread runs on shared memory space
Posted in Others

Wrapper class in Java

– Each of java’s 8 primitive data types has a class dedicated to it. These are known as wrapper class
– They wrap the primitive data type into an object of that class
– Ex- boolean has Boolean, byte has Byte etc
– int is single value container , primitive data type
– Integer iRef = new Integer(i)- it is wrapper class and called and Boxed(constructing object)
– int j=iRef.intValue() – This is Unboxing (Extracting value from object)
– Integer kRef=i; //It is called Autoboxing, no need to write new keyword

Posted in Others

final, finally, finalize

  • Final is used to apply restrictions on class, method,variable
  • Final class can not be inherited, final method can not be over ridden, final variable can not be changed
  • Finally is used mostly with try catch in exception handling
  • it is used to execute the code which needs to be executed irrespective of the exception
  • Ex , closing db connection
  • finalize is used to clean up processing before object is garbage collector