Basically there are three way to convert an primitive value to string so that if we have requirement to use that primitive as a string then we can you this concept and way of conversion but now the point is out of these three way which one is the best and take less time and doesn't have any performance issue.

The three ways of converting primitive into string are :

1. Using Empty string
2. Using valueOf() with String class
3. Using toString() with Wrapper class.

Using Empty String

With the use of an empty string we are creating an new string in the constant string pool and if that string literal is already present in the pool then it will create the object in the heap which points to the pool literal object and return the heap memory address to its original object. For ex-

public class prog {

    public static void main(String[] args) {

 String s=""+10;
 String x1="java10";
 String x2="java"+10;
 System.out.println(x1.equals(x2)); // true
 System.out.println(x1==x2);    // false
 System.out.println(x1.hashCode()==x2.hashCode());//true

    }

}

In the above example ( x2== x1 ) will give false that means s2 and s1 both are different object and which proves that x1 literal get stored in string pool first and then while storing s2 literal it will first check the pool, if present then it will create an new object in the heap memory if we are using new operator that means internally  String is created with the use of ' new ' operator. 

Using valueOf() with String class

Another option for making a primitive value to string value is the use of valueOf( int i ) defined static in the String class, which return string value and take integer value from its integer type parameter. Here i have used only int type but valueOf() can be used with any primitive type. For ex- 

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=String.valueOf(x);
 System.out.println(s1); 
 
     }

}

using valueOf() which it self used Integer.toString( int, int ) internally to convert it into string type value.

Using toString() with Wrapper class

Every wrapper class is having overridden toString() method with parameter as any primitive type. So we have one more option to make a primitive data as string type by using toString( int i ) . Here also i have used int type but toString() is available with any primitive type as argument. For ex-

public class prog {

    public static void main(String[] args) {

 int x=10;
 String s1=Integer.toString(x);
 System.out.println(s1); 
 
     }

}

toString() method internally uses character array concept to create an String. So this is the most efficient way of converting into string value.

So it is recommended to use any of the either valueOf() or toString().

Note: It is not recommended to convert with the use of empty string . 
String is a reference data type and hence string literals are treated as object and get stored in the string constant pool. We must have to define any string within double-quote otherwise it will give compilation error. String can be represented in two form either with using ' new ' operator or without using new operator.

Two way of string representation in java :
1. Without using new operator
2. With using  new operator.

Without using new operator

String can be represented without using new operator that means we are directly assigning string value to its reference. If we are defining like this then first it will search for the string literal whether it is present in the String pool or not. If it is present then simply it returns the reference of the existing object to the current reference. For ex-

public class A {

 public static void main(String[] args) {

    String s = "java";
           String s1= "java";
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 }
}


In the above program with the first statement i.s String s="java", it will search in the string pool whether that string literal is present or not. If it is present in the pool then it will return the reference to the reference variable 's' which also starts pointing to that object.



With the second statement again it will start searching in the string pool , if present then return the reference variable and if not then create the object in the pool and then return the reference. 

Important points regarding Creating string without new operator

1. First search in the string pool whether string literal is present or not.
2. If present in the pool then return the reference.
3. If not present in the pool then crate and object and return the reference of that object.

With using new operator 

With the help of new operator it is definitely going to create an object. First it will search in the string pool that whether that string literal is present or not , if not present then it will create an object in the pool itself and if present then it will create an object in the heap memory and that memory will hold the reference of the already present literal in the pool. So with the above statement its confirm that with the use of new operator it is going to create an object but in heap or in pool it all depends upon the string literal's presence in the pool.
For ex- 

public class A {

 public static void main(String[] args) {

    String s = new String("java");
           String s1= new String("java");
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

In the above for the first statement it will search in the pool whether string literal " java " is present in the pool or not , if not then create the object in the pool itself and if present in the heap memory and return the reference of the already stored object to the reference variable " s ". 

For the second its the string literal " java " is surely present in the pool so JVM will create object in the object in the heap memory and return the reference to that object and that object reference value is returned to the " s1 " reference variable.

Example with and without new operator 

public class A {

 public static void main(String[] args) {

           String s="java";  //without new operator 
           String s1="java";
    String s2 = new String("java"); // with new operator
           String s3= new String("java"); // with new operator
           System.out.println(s==s1);  // true 
           System.out.println(s.hashCode()==s1.hashCode()); // true
 } 
}

From the above example:

String s = "java" ---> Create object in the String pool ( if not present )
String s="java"---> Return the reference of the object present in the pool .
String s1= new String("java") --> Create the String object in the heap.
String s2=new String("java")--> Create the String object in the heap.

Diagram showing how memory is assigned in the heap and string pool.



In the above diagram we can see that s2 and s3 contain the reference of the object created in the heap memory and which itself contains the reference of the string pool object.


But in case of without using new operator, always reference value is returned and it is not going to create any object in the heap memory. This is the major difference between the string object with and without using new operator. 
It is the manually implemented coding for doing cloning. This concept has came to overcome the limitation found with shallow cloning which fails to clone the data member. Through deep cloning we can be able to cover up the problem with the shallow cloning. Now with the help of deep cloning we can able to clone the object members as well but to achieve this we don't have any predefined method, so we need to write our own code. Deep Cloning is just a term to indicate that we are also cloning the object members.

To achieve deep cloning we need to override the clone method and need to create an object of the object member so that we have other object  and need to copy return that object to the clone object.

See the example below then you will be more clear about the above statement written.

Example showing Deep Cloning

class E{
    int y=40;
    String s1="tutorial";
    public E(int y2, String s12) {
 this.y=y2;
 this.s1=s12;
   }
   public E(){}
 }

public class deepCloning implements Cloneable{

    int x= 20;
    String s="java";
    E e;
  
   deepCloning(int x2, String s2, E e1){ //To initialize the property 
 this.x=x2;
 this.s=s2;
 this.e=e1; 
   }
   public deepCloning() {
 e=new E();
   }
   protected Object clone(){   //overridden clone() method 
 deepCloning d2=null;
 E e1= new E(this.e.y,this.e.s1);
 d2=new deepCloning(this.x,this.s,e1);
 return d2;
   }

public static void main(String[] args) {

        deepCloning d = new deepCloning();
 deepCloning d1=null;
 try{
  d1=(deepCloning)d.clone();// Cloning statement 
 }catch(Exception e){
  e.printStackTrace();
 }
 System.out.println(d);
 System.out.println(d1);
 d1.e.y=30;
 System.out.println(d1.e.y);
 System.out.println(d.e.y);

 }  
}

In the above code we can see that clone method is overridden to our class in which we try to create and separate object for the class E and also create and object of the current object to return the class E object so that the clone object will have that reference value for its Object member. 

And all the constructor used in the respective class to initialize the property otherwise there may have chance to throw NullPointerExcpetion
It is a default cloning in java implemented by the Java vendor simply by using one predefined method in the Object class i.e clone().  Using shallow cloning we can only be able to clone the member of the class but fails to clone object members of the class. To clone the object member we need to write our own code which is also called as Deep Cloning.

To achieve shallow Cloning we need to implement Cloneable interface and need to call the clone() method with the object of the class whose object is to be cloned but it returns the Object class object so need to type-cast to its respective class type.

Example showing shallow cloning :

public class deepCloning implements Cloneable {

    int x= 20;
    String s="java";
 
  public static void main(String[] args) {
     deepCloning d = new deepCloning();
     deepCloning d1=null;
      try{
 d1=(deepCloning)d.clone(); // Cloning statement 
      }catch(Exception e){
 e.printStackTrace();
       }
 System.out.println(d);    // Original Object
 System.out.println(d1);   // Cloned Object
        System.out.println(d.x);  // 20 as output
 System.out.println(d1.x); // 20 as output
 d1.x=30;                  // Value changed to 30 by 
                                     cloned object
 System.out.println(d.x);  // 20 as output
 System.out.println(d1.x);//30 as output(not affecting d) 

 }
}

In the above code
d   = Original Object
d1 = Cloned Object
If we try to change the object d will not reflect on object d1 and vice-versa.

What if we are not implemeting the Cloneable interface ?
If we are not implementing Cloneable then it will Runtime error saying CloneNotSupportedException. So its mandatory to implement Cloneable Interface which is marker interface to indicate JVM that the object of that implementing class is to be cloned.

Example showing how shallow Cloning fails to clone Object member

class F{

     int x=30;
     String s="java";
}

   public class deepCloning implements Cloneable{

 int x=40;
 String s1="tutorial";
 F f;

 deepCloning(){
     f = new F();
 }
   public static void main(String[] args) {
 
 deepCloning sc = new deepCloning();
 deepCloning sc1=null;
 try{
      sc1=(deepCloning)sc.clone();//Cloning statement 
 }catch(Exception e){
      e.printStackTrace();
 }
 System.out.println(sc.f.x);  // 30 as output
 System.out.println(sc1.f.x); // 30 as output
 sc.f.x=60;                 // changing the x value of f
 System.out.println(sc.f.x); // 60 as output
 System.out.println(sc1.f.x);// 60 as output
 }

}

In the above code even if i tried to change the value of  instance variable x of class F through deepCloning class object, the value get changed but by accessing with the cloned object it result the changed value which indicated that cloned object's object member f is also pointing to the same object. To avoid this type of problem we have the concept of deep cloning. We can see the last two line of the above program that result of both line even if in the previous line i modified the value of x to 60. 


Diagrammatic representation of the above program

Diagram of Shallow Cloning

                                       ( Above diagram showing the shallow cloning )

What is the problem with the shallow Cloning ?

While Cloning it fails to clone the object member. As we can see in the above example while cloning it simple copies the reference value of the ' f ' to the cloned object which also point the object which was pointing by the original object;s object member. 
Cloning is a concept used to create a new object of the existing object. It means creating another object in the memory same as the existing one by copying the content of it.

For cloning a object java vendor has provided a method i.e clone() method in the Object class which is used to clone the object.

Clone() method is defined as protected in the Object and return the Object class object. Signature of the clone() is :-

protected Object clone() throws CloneNotSupportedException

This method throws one exception i.e java.lnag.CloneNotSupportedException, that means we need to handle this exception while using clone() in our program or we need to define the same exception with the throw keyword in the sub-class. 

We need to implement Cloneable interface to that class whose object we want to clone because by implementing JVM will got to know that this class is to be cloned.Syntax for Cloneable interface :

public interface java.lang.Cloneable{}

Cloneable interface is a marker interface that means without any method or member defined or we can say that empty interface. 

There are two types of cloning possible in java

1. Shallow Cloning ( default Cloning )
2. Deep Cloning ( Manual Cloning ) 

Shallow Cloning 

It is the Default implementation of the clone() method in the Object class. If we are using clone() method then it do shallow cloning. It is used to clone the data members of the existing class but fails to clone any of the member object. To overcome this limitation of the Shallow cloning there is a concept given by the java vendor is deep cloning. 

Deep Cloning 

It is manual implementation which has to be done by user itself. As not predefined method is available so we need to write our own code to do deep cloning and it is used to fulfill the limitations of the shallow cloning as it fails to clone the object member.   

It is a concept in java to achieve the Dynamic / Run-time polymorphism. It is the process of assigning sub-class object in super type reference later if needed that sub-class object can be type-caste into its super type. Dynamic dispatch can be achieved only with the instance member.

Important point regarding dynamic dispatch

1. If we are trying to access instance member with dynamic dispatch concept then it will access sub-class overridden method.

2. If we are trying to access static member with the dynamic dispatch concept then it will access super-class method as because compiler internally replace the super-class reference variable with its class name.

Example showing dynamic dispatch with instance and static method.

class B {

 public static void display(){
  System.out.println("super-class static method");
 }
 public void add(){
  System.out.println("super-class instance method");
 }
}

public class A extends B{
 
 public static void display(){
  System.out.println("sub-class static method");
 }
 public void add(){
  System.out.println("sub-class instance method");
 }
 
 public static void main(String[] args) throws Exception {
  
  B b = new A(); // Dynamic dispatch 
  b.display();  // Calling static method
  b.add();     // Calling instance method
 }

}

In the above code the statement B b = new A() is used to store sub-class in its super-class and tried to access static method " display " which will super-class display() method as because compiler internally convert the b.display() into B.display() but in case of instance it will access with the object only that's why it call the overridden method in sub-class. 

Note : The same will happen with the static and instance variable. With dynamic dispatch concept accessing static variable will access super-class static variable but accessing instance variable will access sub-class instance variable.  

Interface is a keyword in java and also a concept in java to over come the limitation of not supporting multiple inheritance by java. Now with the concept of interface we can have implement multiple interface full filing the concept of a " single class extending more than one class ". In the case of class we can extend only one but with the interface we can implement more than one interface.

Click here to know why java is not supporting multiple inheritance

Syntax to declare an interface :-
interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements interface < interface_name > { }

Syntax to implement an interface :-
class < class_name > implements  interface < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Syntax to extending another interface :-
class < class_name > implements  interface extends < inter_nm1 >, < inter_nm2>......< inter_nmN > { }

Important point regarding interface in java

1. " interface " keyword is used to define any interface in java.

2. We have to use ' implement ' keyword for implementing an interface, extends cannot be used with interface. 

3. Possible to implement more than one interface with single class. 

4.  Interface are fully abstract class. So no need to make an interface as abstract as it is by-default " public abstract ".

5.  An interface can extends another interface but cannot extends/ implements another class. 

6. We cannot declare any instance member inside an interface as it is fully abstract. 

7. Variable declared inside an interface are by default - " public final static " or we can use these modifier explicitly also. 

8. We cannot declare a method as final and static in an interface.

9. We cannot use private , protected , transient and volatile keyword with the variable declared in an interface.

10. We cannot use synchronized and native with the method declared in an interface. 

11. Inner class in an interface are by-default " public static " .

12. We cannot define constructor, instance and static initialization block in an interface. 

13. By-default method declared in an interface are " public abstract " or we can use these keyword explicitly also. 

14. We cannot create an object of an interface as it is fully abstract class.  

15. " .class " file is generated by the compiler for every interfaces. 

Some of the important questions regarding interface with answer

Q1. Why we cannot define instance variable in an interface?
 --> Defining instance variable in an interface is restricted to save memory as because instance variable is inherited in its sub-class.

Now think if we have 3 interfaces(A, B and C)  and 1 class (D).
Interface B and C are extending A and Class D is implementing B and C. That means if declaring instance variable is allowed then for each instance variable as separate copy is also created in the interfaces B and C extending A and those copy are again copied to the class D. So we have many duplicate copies in the sub-classes.

For ex- Now if we have define 100 instance variable then it will create 100 copy in B and 100 in C and finally class D contain total of 100+ 100= 200 unnecessary copy which will obviously take memory as it an instance variable.
So to solve this problem declaring instance variable is restricted instead static is allowed which will create one memory.  

Q2. Why we cannot define variable defined in an interface as private and protected ?
        There are two reason behind it :-

  1. It is because by-default it is using public so we cannot define both public and protected to a single variable. 
  2. As interface doesn't have any instance method implementation and we need to access private member with the help of any method as because we cannot create an object of an interface and with cannot directly access with the sub-class object so need some method implementation which is not possible.   

When we use an abstract modifier before the name of any user-define class then it is called as an abstract class. Abstract class in java has only method signature whose implementation must be in its sub-classes.

Important points regrading Abstract class

1. It cannot be instantiate means we cannot create object of an abstract class.
2. An abstract class can have instance member.
3. Abstract class doesn't have any method implementation instead can have only method declaration.
4. We cannot make an inner class as abstract.
5. We cannot use static method but can use static variable in the abstract class.
6. Extending abstract class means we need to override the abstract methods defined in the abstract class.
7. If we don't want to override abstract in its sub-class then declare that sub-class as abstract.
8. An abstract class may or may not have an abstract method.
9. Constructor of the abstract class will be used to instantiate the abstract class instance variable.
10. Overridden abstract class methods will be accessed by its sub-class object.
11. We can be able to create and reference variable for an abstract class.

Why we cannot instantiate an abstract class?
As because we are not implementing abstract method while declaring it in abstract class. So if an user have any chance to create an instance of abstract class means can able to call abstract method with that object but we don't have any body while declaring it in abstract so no need of calling an empty body method. That's why we are not allowed to create an instance of an abstract class.

If we are not allowed to create and instance of an abstract class then how it can have an instance variable?
We can be able to access instance member of any super-class with its sub-class object therefore we can be able to access the instance member of any abstract class with the object of its sub-class.

Who is responsible to initialize the instance member of abstract class and how?
Its obvious that constructor is always responsible to initialize any instance member of any class. Here by creating its sub-class object will call its constructor and with the super implementation in it, will be able to class its super-class constructor i.e abstract class constructor and finally that constructor is responsible to initialize its instance member.

Why we cannot use static keyword with the abstract method?
By using static keyword with the abstract method will make it eligible to call it with its class name but no need of calling an empty body method. So it is restricted to use static with the abstract method.

Why we need to override abstract method in its sub-class?
It is because an user can be able to call abstract method with its sub-class object so we need to override so that it will call an overridden implemented method.

What will happened if we are extending an abstract class with another abstract class?
Then no need to override the abstract method in its sub-class because sub-class itself is an abstract class.

Why we can create an reference variable of an abstract class?
It is because creating an reference variable doesn't instantiate the member of the abstract class and hence contain null means not referring any object.

Use of an abstract class

1. When we have only static member in our class which can able be accessed with its class name so no need of creating object unnecessarily.So for restricting user to create an object declare that class as abstract.

2. It is used to when the user want to have their own implementation. So declaring a method as abstract will give a chance to an user to have their own implementation for same method name.

An example showing an abstract class with some valid and invalid statement.

abstract class A{

 static int x;                 // valid
 int y;                       // valid
 abstract void add();         // valid
 static abstract void sub(); // invalid as static is not allowed.
}
public class E extends A {

 void add(){}       //Compulsory to override abstract method 
 
 public static void main(String[] args) {
  E e = new E();
  System.out.println(A.x);
  A a = new A();        // Invalid 
 }
}
Abstract is a keyword in java. So its a reserved word in java. general meaning of abstract is to hide the implementation, only show the outer structure. Now in computer science its meaning is that user can have their own implementation with abstract method.

Where we can use abstract keyword ?
Abstract can be used with class and method.

By using abstract with the method a user can able to have their own implementation according to their wish. Its the facility given by the java vendor to the user to have their own implementation.

Abstract with class

Using abstract modifier before the class name can make a class as abstract. Making a class as abstract means we cannot instantiate that class.

Syntax :

abstract  < access_modifier > class < class_name > {  } 

< access_modifier > --> Only public is used with abstract . Private and protected are not used.

To know more about abstract class Click here !

Abstract with method

Declaring abstract modifier with the method name will make that method as abstract. An abstract method cannot have their implementation where it is declared, it must be override in its sub-classes.

Syntax :

abstract  < access_modifier > < return_type > < method_name > {  } 

< access_modifier > --> Only public and protected are used. Private cannot be used with it.


Access Modifiers in java

Like public and private, protected is also a access modifier which has different visibility scope and it is also one of the keyword in java. Its scope are valid to the other packages but it should be within the sub-class. Like private we can be able to use protected scope with the constructor, methods, variables and inner classes. Accessing protected member outside its scope will give compilation error saying " Not Visible ".

Note : We cannot use protected with the class.

What are the possible areas where protected  members can be used ?
It can be used with constructor, methods, variables and inner classes.

Members of the class declared as protected can be accessible outside the package but with the current sub-class object in the other packages. We have two scopes in java:
1. Class Scope

  • Sub-class in the same package        --> Visible 
  • Sub-class in other packages            --> Visible 
  • Another class in the same package --> Visible 
  • Non- subclass in other package      --> Not visible 
2. Package Scope
  • Within the same package ---> Visible 
  • Outside the package         ---> Visible but in the current sub-class. 
Protected with Constructor 
Declaring protected keyword before the name of constructor will make it protected. Protected constructor of a class are visible in another class sub-class which is defined in another package and can only be accessible with that sub-class object. For ex-

D.java in com package 
------------------------------

package com;

public class D {

 protected D(){}  // Protected constructor 
 public static void main(String[] args) {
  
 }
}

E.java in def package
-----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); 
  D d = new D(); // " Visible "  
 }
}


Protected with variable
Like constructor variable declared as protected are also visible with the sub-class object in another package. For ex-

D.java in com package 
------------------------------

package com;

public class D {

 protected int x=10;  // Protected variable  
 public static void main(String[] args) {
  
 }
}

E.java in def package
-----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); 
  System.out.println(e.x); 
  D d = new D();
  System.out.pritln(d.x); // "Visible"
 }
}


Protected with the method
Like variable method declared as protected can be accessed with the sub-class object defined in another package. For ex-


D.java in com package 
-----------------------------

package com;

public class D {

 protected void display(){
             System.out.println("protected method");
 }                                           // Protected method
 public static void main(String[] args) {
  
 }
}

E.java in def package
----------------------------

package def;
import com.D;

public class E extends D {

 public static void main(String[] args) {

  E e = new E(); // Current class object
  e.display();  
 }
}


Private is the keyword in java and it is also called as the access modifier in java which defines the visibility to the members of the class like methods, constructors, variables etc. Declaring private to the members of the class will limit theirs visibility to that class only. If we are trying to access any private member in another class then compiler will give compilation error as " Member are not visible ".  

Note : We cannot use private with the class as it makes no sense making a class visible because we are accessing member of the class not the class itself. So we can be able to use private with the member of the class member.

Where we can be able to use private access modifier ?
Private access modifier can be used with the constructor, variable and methods.

Members of the class declared as private can be accessible within that class only. We have two scope in java program :-
1. Class Scope
  • Sub-class in the same package       --> Private is Not Visible .
  • Sub-class in different package        --> Private is Not Visible.
  • Another class in the same package --> Private is Not Visible.
  • Same class in the same package     --> Private is Visible.
2. Package Scope
  • Within the same package -- > Private is Not Visible. 
  • Outside the package        ---> Private is Not Visible. 
Private with constructor 

To make a constructor as private we have to use private keyword before the constructor. Declaring super-class constructor as private will restrict to create an object of super-class in sub-class as private members are not accessible outside its scope. For ex-

public class prog{

    private prog(){}

}

class A extends prog {

      public static void main(String arg[]){

      prog p= new prog(); //Cannot create object as constructor 
                            is declared as private. 
    }
}

Private with variable

Like private constructor , variable can be declared as private and cannot be accessible in sub-class or any other class expect in the class in which it is declared as private. For ex-

public class prog{

     private int x=10;
}

class A extends prog {

     public static void main(String arg[]){

       prog p= new prog();
       System.out.println(x); //not visible as 'x' is declare 
                                as private.
     }
}

Private with methods

Using private keyword before the name of the constructor makes it a private method and has accessibility limit to that class only and hence accessioning outside the class will give compilation error. For ex-

public class prog{

     private void display(){}

}

class A extends prog {

    public static void main(String arg[]){

      prog p= new prog();
      p.display();   //Compilation error as display()is private. 
   }
}

As its name ' public ' itself indicates that any member of the class declared as public will be visible and accessible ANYWHERE. We have two scope in java programs :
1. Class scope
  • Sub-class in the same package       --> Public is visible .
  • Sub-class in different package        --> Public is visible.
  • Another class in the same package --> Public is visible.
  • Same class in the same package     --> Public is visible.
2. Package Scope
  • Within the same package -- > Public is visible. 
  • Outside the package       ---> Public is visible. 
So public members are visible EVERYWHERE and can be accessible form ANYWHERE.

Where and how we can use public access modifier in java ?
--> Public can be used with class, interface, constructor and variables.

Public with class 
If we are not using any access modifier with the class name then by default it is declared as ' default ' and declaring default will restrict its accessibility to the same package only. So to make any class visible to the another package we have to use public with the class. For ex-

public class prog { }

The above class is now visible to the other packages as well. 

Public with constructor
By default constructor is using default keyword before its name whose visibility will be limited to that package only in which class is been defined. If we want to access that constructor through another class which is defined in another package then we need to define the constructor as public to have its visibility to the other packages as well in which that is been imported. For ex-

Let suppose there are two class A and B in different packages com and def respectively and we import class A using import statement in def package where class B is defined to access the class A constructor by creating the object of class A. Now we came across few cases :

1. EXPLICIT CONSTRUCTOR : - If in com package any explicit constructor is there which is by default ' default ' and then if we try to create class A object in class B then it will compilation error that " constructor is not visible ".

2. NO EXPLICIT CONSTRUCTOR :- If we are not defining any constructor explicitly then JVM will invoke by default constructor and place public keyword before the constructor and hence it won't give any compilation error.

3. PUBLIC EXPLICIT CONSTRUCTOR :-  And if we are declaring constructor explicitly as public then it work fine and won't give and any compilation error.

Public with variable
Like constructor we can also use public keyword with class variable but not with the local variables as their scope will be within the method or constructor block only. Non-public members give compilation error " not visible ". Defining public with the class variables means that it can be accessible in the class which is defined in other package. for ex-

Let suppose there are two class and B in different packages com and def respectively and we import class A using import statement in def package where class B is defined to access the class A variables by creating the object of class A. like -

A.java in com package
------------------------------
package com;

public class A {

public int z=30;   // public variable.
int y=20;         // Be default ' default ' variable. 

 public A(){

  System.out.println(y);
  System.out.println(z);
 }
 public static void main(String sush[]) { }

}

B.java in def package
------------------------------
package def;
import com.A;

public class B{

 public static void main(String sush[]) {

     B b = new B();  // Class B object.
     A a = new A();  // Class A object.

  System.out.println(a.z);  //compiler successfully as it is 
                              declared public in class A.

  System.out.println(a.y);  // As y is not public so 
                              compilation error.
 }
}

Public with interfaces
Using public keyword before the interface will make it visible to any classes in any packages. If we are not using any public then it will not be visible to other packages and hence no class can be able to implement that interface. Without using public to the interface if we try to import that that interface it will give compilation error as " not visible " . for ex-

Let suppose there are two java files and B in different packages com and def respectively where are A.java contain an interface and B.java contain a java class B. We are importing interface A using import statement in def package where class B is defined to implement that interface using implements keyword. for ex-

A.java in com package
------------------------------
package com;

public interface A{

 void display();  // It is By default public and abstract.
}

B.java in def package
------------------------------
package def;
import com.A;  //No compilation error as interface is public

public class B implements A{

 public void display(){
  System.out.println("Display() method");
 }

 public static void main(String sush[]) {

  B b = new B();
  b.display();  
 }
}

The above program compile and execute successfully as because we are importing public interface A.If we are not using any public keyword then it will give compilation error while importing interface as " not visible " .

Note: In a same program we cannot have both public interface and public class as because we are writing java file name as the public class name. So having two public in a single file compiler will instruct to have other public as the java file name.


Access Modifier in java defines the scope of accessibility of methods, constructors, variables etc. So to access the different members of the class/interfaces with different scope we have three access modifiers :

1. Public   --> Defines visibility everywhere        
     
2. Private   --> Defines visibility within the current class only    
   
3. Protected  --> Defines visibility within the same package and outside the package with
                          the object of the sub-class extending the class in another package. 

4. default --> Defines the visibility within the package only. 

Note: If we are not using any access modifier then by default the modifier will be " default " and explicitly we cannot use default as default is already a keyword in java.


Difference between access modifiers and modifiers 

Access modifier 
  • It defines the scope of visibility or accessibility of the members of the class.
  • Public, protected, private and default are the access modifiers used in java.
  • Except public and by default "default " modifier is used with the class .
  • We cannot use private and protected with the class.
  • It cab be at class or package level.

Modifiers 
  •  It provides the restriction to the methods and variables about its accessibility at the class level.
  • Static,final,abstract,synchronized, volatile are the modifiers used in java.
  • We cannot use static with the main class and hence can be used with inner class.
  • Final can be used with the class indicates that it cannot be extended by other classes.




Like other classes in java , anonymous is also a type of class but it doesn't have any name like other classes have their own name either defined by the user or pre-defined in the java by the java vendors. So anonymous class is defined as the class without name and it is defined by the user only.
No need of wonder that how a class can exist without any name ?
Its not that it doesn't have any name but generated by the compiler at the run-time. So user cannot guess what compiler will generate the name for an anonymous class. Due of this reason we cannot be define any constructor for the anonymous class. And this is the answer to the answer to the question why we cannot create an constructor of an anonymous class?

An anonymous will be defined dynamically by the { } after the constructor of the current class. Like this,
 new < constructor > { } ;

For every anonymous class a .class file will be generated like this,
< outer_class > $ < int_value > . class

< int_value > --> represents the number of times we are creating the anonymous class for the same outer class.

Anonymous class is always be the sub-class of the class/interface whose name is used while creating the anonymous class.  For ex-

public class prog{

public static void main(String[] args) {

 prog p = new prog(){};

 prog p1 = new prog(){}; 

     }
}

In the above program both the statement is going to create an anonymous class which is the sub-class of class prog. If you need any conformation for the point of sub-class then de-compile the .class generated for the anonymous class where you will find that

class prog$1 extends prog{ } --> For p object

class prog$2 extends prog{ } ---> For p1 object .

So from the above decompiled code we can confirm that anonymous class will act as the sub-class of the class through which it is created.

Important point regarding Anonymous class

1. We cannot create any constructor or reference variable for the anonymous class as we need to know class name for creating a constructor.

2. As it the sub-class of its super type so we can store its object reference to its super class reference.

3. We cannot create multiple object for the an anonymous class as because user doesn't know the name of the anonymous class.

4. Whenever we try to create another object with the new operator the compiler will create another class extending its super type.

5. If we are storing the sub-class reference to its super type reference then we can be able to access the super class inherited members.

6. If we are not storing the anonymous class object reference to its reference then we can be able to access only one member. for ex-

public class prog{

public static void main(String[] args) { 

 new prog(){

 void display() {

        System.out.println("Anonymous class method");
    } 

 }.display();
     }
}  

We can see that we can be able to access display method of the anonymous class, if other methods are defined then we cannot access if we are not storing the object reference to its super type.

7. To access the other member defined in the anonymous class which is the overridden method of its super type so we need to write the method signature to the super type then only we can access the method defined in the anonymous class with the super type object reference storing the anonymous class object reference. For ex-

public class prog{

void show(){}
void display(){}

public static void main(String[] args) {

 prog p = new pro(){

     void display(){
        System.out.println("Anonymous class method");
     }

     void show(){
        System.out.println("By Object Reference");
     }
 };

 p.show();
 p.display();

     }
}

So whenever there is the need of invoking multiple method we need to define the anonymous class method as the overridden method as because we cannot directly call two method with the object of the anonymous class. And we know that we can be able access single method at a time with the single object.  
Local inner class is a class which is define local to the outer class. So it must be defined within the local scope of a class like method, constructor or initialization block . A class within a class in never treated as the local inner class. And most importantly scope of the inner class will be limited to where it is declared, outside of which it is not valid. As local inner class is the local scope to the outer class then we all know that within a local scope we cannot define any static member. So here also in the local inner class we cannot define any static member.

For the local inner class a .class file is generated in the following format :

< outer_class > $ < int_value > < inner class > .class
where as int_value depends on the number of times inner class with the same name is used.

Important points regarding Local inner class

1. We cannot define any static member in a local inner class as because of local scope.

2. But static final variable can be used because of its constant nature.

3.  In the generated class file of local inner class the int value indicate that the local inner class has been used how many times in a single program with the same name.

4. We cannot use the local inner class with the same name in the same method, constructor or initialization block as like we cannot define local variable with the same name within the same block.

5. As we cannot define any static member so it cannot be the starting point of any java program.

6. We cannot create any object of local inner class outside the scope of that class.

Simple example to show the working of the local inner class :

public class prog{

    int x;                // Outer class instance member

prog(){                  //Outer class constructor

    class B {           // Local inner class 

         int x;        // Local inner class instance member

         B(){          // Local inner class constructor

               System.out.println("Local inner class");

           }
      }

     B b = new B();      // Local inner class object 

     class C{}          // Local inner class

   }

public static void main(String[] args) {

prog p = new prog();

     }
}

Like Instance inner class we have also static inner class. Static instance class is loaded at the time of loading the outer class as it is declared as static that means it will act as the static member of the outer class and hence we can be able to define static member as it get initialized at the time of loading the outer class.

Important point regarding Static inner class

1. We can be able to define static and instance both in the static inner class.

2. We can have main() method which will make static inner class possible to have starting point for any java program.

3.  It can be accessed from both static and instance scope of outer class.

4. ' this ' will always refer to the outer class member , to access inner class member we need to create inner class object.

5. As it a static class then we can be able to access the static member with the class name itself. Object will be needed to access instance member.

6. Inner class is extending Object class that means we cannot use outer class member with the help of inner class object.

Example showing the working of an static inner class

public class A{

   int x;        // instance member of outer class

static class B{     // inner static class

   B(){           // inner class constructor 

        System.out.println("Inner class constructor");
}

   int x;      // inner class instance member

   static int z=40;   // inner class static member

}


A(){                    // outer class constructor

    A.B a = new A.B();   // inner class object 

    a.x=30;

   System.out.println(a.x); 

   System.out.println(this.x);

   System.out.println(A.B.z); // Accessing inner class static 
                                with class name 

}

public static void main(String[] args) {

A p = new A();

A.B b = new A.B();     // inner class in static method 

Class c = b.getClass(); //getting class name of inner class

System.out.println(c.getName());

c=c.getSuperclass();  //getting superclass name of inner class

System.out.println(c.getName());

     }
}

As the name itself indicates that inner class with non-static scope that means a member of outer class which is of instance scope called as instance inner class. Instance inner class is itself a class but we cannot use any static member.

Why we cannot use any static member in instance inner class ?
--> It is first treated as the member of outer class. Because of this if it is declared as non-static that means JVM is not going to load the class while loading the outer class even if inner class is a class. So as the non-static member of outer class, at the time of class loading JVM will not be able to load the instance member and hence if JVM will not load it then no static member can be able to initialized at the class loading time and hence we cannot use any static member inside an instance inner class.

But can be able to define an static final variable as because it will be treated as constant. And there is no memory concern of final static variable hence we can use it uses directly the value instead through any variable.

We can define an instance member as it will be used when we are creating any object for instance inner class and hence there is no risk of declaring as instance memory for instance variable is not created at the time of class loading.

Important points regarding inner class.

1. To access inner class member we need to create an object of it as we cannot access it through outer class object.

2. Member of outer class cannot be accessed with the inner class object.

3. outer class member can be accessed directly with its name as internally this will be used to indicate current class object.

4. We cannot use any static member in the instance inner class.

5. Instance inner class cannot use be the starting point of any java program as we cannot use main() which is declared as static.

6. But we can be able to use static final member as it is always treated as constant an also it does not require any memory for its value storage.

What will happen if we try to use main() in instance inner class?
--> While compiling the java program it will gibe an compilation error as " inner class cannot have any static declarations ".

Is it possible to use instance inner class as the starting point of our program ?
--> No , as because we can't be able to use any static method inside instance inner class.

An example to show how to access to create an object and how to access the member of it .

public class A{

   int x;

class B{                           // instance inner class

    int x;                        // instance member of instance inner class.

   static final int z= 30;        // final static member

}

A(){                              // outer class constructor

   A.B a = new A.B();            // inner class object creation .

   a.x=30;                       // inner class instance member 
                                     initialization

   System.out.println(a.x);

   System.out.println(this.x);   // this refer to the outer 
                                    class instance member.

   System.out.println(a.z);     // accessing the static final 
                                   instance member.

}

public static void main(String[] args) {

 A p = new A();

     }
}

Inner class in a class defined as a class inside another class. So it is itself a class but first it will act as a member of that class. As we know that we cannot make a class as static but inner class can be made as static which proves that it is first a member of a class in which it is defined . We can execute our class with its name but to execute a inner class we need to take help of outer class that proves that an inner class has identity with its outer class.

Important points regarding Inner Class :

1. A .class file is generated  for inner class but the file name will be as follows :
    < outer_class_name > $ < inner_class_name > . class 

2. We can be able to create a reference of inner class within the scope of an outer class simply as a normal reference definition.

3. To create a reference of inner class outside the scope of an outer class then we need to indicate to write the inner class name followed by outer class name, like this
     < outer_class_name > . < inner_class_name > . < ref_value > = null ;

4. As inner class itself is a member of a outer class then it the other members won't be the member of the inner class.

5. We can have a class inside an inner class which is defined as the inner class of inner class.So like this we can have infinite number of inner class / nested classes.

6. Inner class is generally used for abstraction.

Example of an inner class :- 

class prog {    // main class 

int x;

class A {      // Inner class of prog 

int x ;
String name ;

public static void main( String sush[] ) {

System.out.println(" Inner class " ) ;
A a = new A();     // Object of an inner class 
  }

}

In the above example class A is an inner class of prog class which is also called as the instance class.

Types of Inner class :

There are four (4) types of inner class :

1. Instance inner class.  -->     Click here to know more about instance inner class
2. Static inner class.      -->     Click here to know more about Static inner class
3. Local Inner class       -->    Click here to know more about Local inner class
4. Anonymous inner class.


Like this in java one more most important keyword is there i.e super. super in Java has a wide use and it is mainly used to call the super class constructor explicitly by the user and implicitly used by the JVM to initialize the super class property.
Have you ever wondered that how super class members get instantiated by creating subclass object ?
Let suppose we have two class A and B following inheritance relation where B is extending A that means B is a sub-class and A is a super-class. Here if we create a sub-class object which is going to invoke the constructor of sub-class and then compiler will implicitly place super() to invoke the super-class constructor which is used to instantiate the super-class members.

Important points regarding super in java

1. If there are no constructor then a default constructor is invoke by the JVM to place a super() which will call the super-class constructor.

2. If we have any constructor with some implementation then also compiler will place one super() to call super-class constructor.

3. If we have a parameterized constructor and in which first statement is this( value ) , then it will recursively call the sub-class constructor and hence there will no chance to call super-class constructor. In this case compiler will give compilation error.

4. Always make sure that if a class in inheriting another class then there must  be a super() call through sub-class constructor either explicitly by the user or implicitly by the JVM to initialize the super-class property , otherwise compiler will give compilation error.

Important uses of super

1. It is used to initialize the super-class property by invoking super-class constructor from sub-class constructor.

2. Inherited members are accessible with the help of super.

3. If we have member defined in the sub-class and super-class with the same name then super is used to refer the super-class member where as this is used to refer current class member.

4. It is used to refer the member of current object which is inherited from super-class.

5. In a inheritance hierarchy at last super() is calling to object class constructor which indicates the end of calling super-class constructor.

An example to show how super is working

class A{

int x;   //super-class instance member

}

public class B extends A {

int x;       // sub-class instance member

B(int x){    //local variable x as an argument in constructor

System.out.println(x);     //x indicate local variable

System.out.println(this.x);  //this.x indicate current class 
                                instance member x

System.out.println(super.x); //super.x indicate current object 
                                having inherited member x .

}

public static void main(String sush[]) {

 B b = new B(10);

 }
}

In the above program every variable is having same name so in this case ,
1. If we write simply x then JVM will prefer local variable.
2. If we write this.x then JVM will search for any instance variable in the current class.
3. So to access the super class instance variable x we have to use super.

What if in the above program class A extends another class X then it will also have an instance variable x then how will access that member as super will only refer to its immediate super-class ?
--> To access the instance member x of class X we have to use the method which will return the value of x from class X. Using statement like super.super.x is invalid . for ex-

class X{

int x;           // instance member of class X

int value(){    // method returning x value of class X

this.x=40;     // initializing x to 40. 
return x;
    }
}

class A extends X{

int x;       // instance member of class A

}

public class B extends A {

int x;

B(int x){

System.out.println(x);

System.out.println(this.x);

System.out.println(super.x);

System.out.println(value());

}

public static void main(String[] args) {

 B b = new B(10);

 }
}



this is one of the most important keyword in java which refers to the current class object. Like we are creating an object for our class similarly internally a object is there called as this which points to the current class object unless we create an Object.We can say that  'this ' is not an actual object but it points to the current class object. Accessibility of ' this ' refers to the current object that means if we have more than one object in our class then this will refer to that object in which context area it is been used. 

Important points regarding this keyword 

1. It is a scope of instance context so it can only be used from the non-static context. 
2. It is an alias for the current object.
3. We can be able to assign this into other reference of the current or super class type. 
4. We cannot assign any other current class or its super class object in this as because it is defined as a final variable so content cannot be modified . 
5. ' this ' is a final variable so we cannot assign any reference. 

Some of the uses of this keyword 

1. this can be use to initialize the instance we have both local and instance member with same name.
2. this can be used to access the member from the current object.
3. this can be used while using constructor chaining i.e constructor overloading to pass the value from one overloaded constructor to another but it should be the first statement.
4. Also used to distinguish between the local variable and instance variable in any instance method . 

What if we try to access this from any static context ?
It will give an compilation error that " non-static variable this cannot be referenced from a static context " .

Why such type error occur and why we cannot access this in any static context ?
It is because static context is not a part of object and unless we create and object ' this ' cannot be used and hence we cannot guarantee that used will surely create an object in their program. That is why it is a compilation error as because compiler is very much unsure about the creation of object by the user.

Give an example showing the initializing the instance variable if local variable is of same name as of instance variable ?

public class prog {

int x ;           // Instance variable.

prog(int x) {    // In constructor parameter x is local.

this.x = x ;    //this.x is used to initialize instance var 
                 with local x. 
}
public static void main(String sush[]) {

 prog p = new prog(10);  // 10 is passed to x in constructor. 

 }
}

Give an example to show how it is been used in constructor chaining ?

public class prog {

int x ;          // instance variable.
int y ;          // Instance variable.

prog(int x){
this.x = x ;   //this.x is used to initialize instance var with 
                 local x i.e 30
}

prog(int x, int y) { 
this(30);       //30 is passed to one parameter overloaded 
                  constructor.

this.x = x ;   //this.x is used to initialize instance var 
                with local x i.e 10 
this.y = y ;   //this.y is used to initialize instance var 
                 with local y i.e 20
}

public static void main(String sush[]) {

 prog p = new prog(10,20);  // 10 is passed to x in constructor. 

 }
}

What will happen if we assign any other reference variable to ' this ' ?

If we try to assign any other current class reference or any super class reference to this variable then it will give compilation error that " cannot assign a value to final variable this " . It means it is a final variable we cannot modify the content of it. For ex -

public class prog {

int x ;           // Instance variable.

prog(int x) {  
prog p1 = new prog(); // Local object creation. 
this = p1;           // Assigning p1 to this "compilation error"
this.x = x ;        //this.x is used to initialize instance
                      var with local x. 
}
public static void main(String sush[]) {

 prog p = new prog(10);  // 10 is passed to x in constructor. 

 }
}

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic