Java Interview Questions Part 1

What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

What is the output of the following Java program?

  1. class Test   
  2. {  
  3.     public static void main (String args[])   
  4.     {  
  5.         System.out.println(10 + 20 + "Javatpoint");   
  6.         System.out.println("Javatpoint" + 10 + 20);  
  7.     }  
  8. }  

The output of the above code will be

30Javatpoint

Javatpoint1020

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020.

What is the output of the following Java program?

  1. class Test   
  2. {  
  3.     public static void main (String args[])   
  4.     {  
  5.         System.out.println(10 * 20 + "Javatpoint");   
  6.         System.out.println("Javatpoint" + 10 * 20);  
  7.     }  
  8. }  

The output of the above code will be

200Javatpoint

Javatpoint200

Explanation

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint.

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpointto produce the output as Javatpoint200.

What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.


What is the constructor?

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

More Details.


How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

 

What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java Constructor

Java Method

A constructor is used to initialize the state of an object.

A method is used to expose the behavior of an object.

A constructor must not have a return type.

A method must have a return type.

The constructor is invoked implicitly.

The method is invoked explicitly.

The Java compiler provides a default constructor if you don't have any constructor in a class.

The method is not provided by the compiler in any case.

The constructor name must be same as the class name.

The method name may or may not be same as class name.


What is the output of the following Java program?

  1. class Test   
  2. {  
  3.     int i;   
  4. }  
  5. public class Main   
  6. {  
  7.     public static void main (String args[])   
  8.     {  
  9.         Test test = new Test();   
  10. 10.         System.out.println(test.i);  
  11. 11.     }  

12. }  

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

 

What is the output of the following Java program?

  1. class Test   
  2. {  
  3.     int test_a, test_b;  
  4.     Test(int a, int b)   
  5.     {  
  6.     test_a = a;   
  7.     test_b = b;   
  8.     }  
  9.     public static void main (String args[])   
  10. 10.     {  
  11. 11.         Test test = new Test();   
  12. 12.         System.out.println(test.test_a+" "+test.test_b);  
  13. 13.     }  

14. }  

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

  1. class Student3{  
  2. int id;  
  3. String name;  
  4.   
  5. void display(){System.out.println(id+" "+name);}  
  6.   
  7. public static void main(String args[]){  
  8. Student3 s1=new Student3();  
  9. Student3 s2=new Student3();  

10. s1.display();  

11. s2.display();  

12. }  

13. }  

Test it Now

Output:

0 null

0 null

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.


More Details.

What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

  1. //Java program to initialize the values from one object to another  
  2. class Student6{  
  3.     int id;  
  4.     String name;  
  5.     //constructor to initialize integer and string  
  6.     Student6(int i,String n){  
  7.     id = i;  
  8.     name = n;  
  9.     }  
  10. 10.     //constructor to initialize another object  
  11. 11.     Student6(Student6 s){  
  12. 12.     id = s.id;  
  13. 13.     name =s.name;  
  14. 14.     }  
  15. 15.     void display(){System.out.println(id+" "+name);}  
  16. 16.    
  17. 17.     public static void main(String args[]){  
  18. 18.     Student6 s1 = new Student6(111,"Karan");  
  19. 19.     Student6 s2 = new Student6(s1);  
  20. 20.     s1.display();  
  21. 21.     s2.display();  
  22. 22.    }  

23. }  

Test it Now

Output:

111 Karan

111 Karan

 


Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

  1. class Test   
  2. {  
  3.     int i;   
  4.     public Test(int k)  
  5.     {  
  6.         i=k;  
  7.     }  
  8.     public Test(int k, int m)  
  9.     {  
  10. 10.         System.out.println("Hi I am assigning the value max(k, m) to i");  
  11. 11.         if(k>m)  
  12. 12.         {  
  13. 13.             i=k;   
  14. 14.         }  
  15. 15.         else   
  16. 16.         {  
  17. 17.             i=m;  
  18. 18.         }  
  19. 19.     }  

20. }  

21. public class Main   

22. {  

  1. 23.     public static void main (String args[])   
  2. 24.     {  
  3. 25.         Test test1 = new Test(10);  
  4. 26.         Test test2 = new Test(12, 15);  
  5. 27.         System.out.println(test1.i);  
  6. 28.         System.out.println(test2.i);  
  7. 29.     }  

30. }  

  1. 31.       

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

What is the static block?

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

  1. class A2{  
  2.   static{System.out.println("static block is invoked");}  
  3.   public static void main(String args[]){  
  4.    System.out.println("Hello main");  
  5.   }  
  6. }  

Test it Now

Output: static block is invoked

       Hello main

 

 

Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

  1. abstract class Test  
  2. {  
  3.     static int i = 102;  
  4.     static void TestMethod()  
  5.     {  
  6.         System.out.println("hi !! I am good !!");  
  7.     }  
  8. }  
  9. public class TestClass extends Test   

10. {  

  1. 11.     public static void main (String args[])  
  2. 12.     {  
  3. 13.         Test.TestMethod();  
  4. 14.         System.out.println("i = "+Test.i);  
  5. 15.     }  

16. }  

Output

hi !! I am good !!

i = 102

 

Can we make constructors static?

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

What is method overloading?

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • Changing the number of arguments
  • Changing the return type

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

More Details.


Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

  1. class Adder{  
  2. static int add(int a,int b){return a+b;}  
  3. static double add(int a,int b){return a+b;}  
  4. }  
  5. class TestOverloading3{  
  6. public static void main(String[] args){  
  7. System.out.println(Adder.add(11,11));//ambiguity  
  8. }}  

Test it Now

Output:

Compile Time Error: method add(int, int) is already defined in class Adder

More Details.

 

What is method overriding:

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

More Details.

 

Difference between method Overloading and Overriding.

Method Overloading

Method Overriding

1) Method overloading increases the readability of the program.

Method overriding provides the specific implementation of the method that is already provided by its superclass.

2) Method overloading occurs within the class.

Method overriding occurs in two classes that have IS-A relationship between them.

3) In this case, the parameters must be different.

In this case, the parameters must be the same.


 

What is the output of the following Java program?

  1. class Test   
  2. {  
  3.     public static void main (String args[])   
  4.     {  
  5.         for(int i=0; 0; i++)   
  6.         {  
  7.             System.out.println("Hello Javatpoint");  
  8.         }  
  9.     }  

10. }  

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

 

Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

Is constructor inherited?

No, The constructor is not inherited.


Can you make a constructor final?

No, the constructor can't be final.


What is the static variable?

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

  1. //Program of static variable  
  2.   
  3. class Student8{  
  4.    int rollno;  
  5.    String name;  
  6.    static String college ="ITS";  
  7.      
  8.    Student8(int r,String n){  
  9.    rollno = r;  
  10. 10.    name = n;  
  11. 11.    }  
  12. 12.  void display (){System.out.println(rollno+" "+name+" "+college);}  
  13. 13.   
  14. 14.  public static void main(String args[]){  
  15. 15.  Student8 s1 = new Student8(111,"Karan");  
  16. 16.  Student8 s2 = new Student8(222,"Aryan");  
  17. 17.    
  18. 18.  s1.display();  
  19. 19.  s2.display();  
  20. 20.  }  

21. }  

Test it Now

Output:111 Karan ITS

       222 Aryan ITS


More Details.

;b

 

What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

More Details.


What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.


Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.


What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

  1. class Animal{  
  2. Animal(){System.out.println("animal is created");}  
  3. }  
  4. class Dog extends Animal{  
  5. Dog(){  
  6. System.out.println("dog is created");  
  7. }  
  8. }  
  9. class TestSuper4{  

10. public static void main(String args[]){  

11. Dog d=new Dog();  

12. }  

13. }  

Test it Now

Output:

animal is created

dog is created

More Details.

What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

  1. class Student{  
  2. int id;  
  3. String name;  
  4. final String PAN_CARD_NUMBER;  
  5. ...  
  6. }  

More Details.

Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.


Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.


What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

  1. final class Bike{}  
  2.   
  3. class Honda1 extends Bike{  
  4.   void run(){System.out.println("running safely with 100kmph");}  
  5.     
  6.   public static void main(String args[]){  
  7.   Honda1 honda= new Honda1();  
  8.   honda.run();  
  9.   }  

10. }  

Test it Now

Output:Compile Time Error

More Details.



 Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

  1. public class Test  
  2. {  
  3.     public Test()  
  4.     {  
  5.         this = null;   
  6.         System.out.println("Test class constructor called");  
  7.     }  
  8.     public static void main (String args[])  
  9.     {  
  10. 10.         Test t = new Test();  
  11. 11.     }  

12. }  

Output

Test.java:5: error: cannot assign a value to final variable this

        this = null;

        ^

1 error


 

 What are the main uses of the super keyword?

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.
  •  

 Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

Example:

  1. public class Test{  
  2.     Test()  
  3.      {  
  4.          super();   
  5.          this();  
  6.          System.out.println("Test class object is created");  
  7.      }  
  8.      public static void main(String []args){  
  9.      Test t = new Test();  
  10. 10.      }  

11. }  

Output:

Test.java:5: error: call to this must be first statement in constructor


 


 What is the output of the following Java program?

  1. class Person   
  2. {  
  3.     public Person()   
  4.     {  
  5.         System.out.println("Person class constructor called");  
  6.     }  
  7. }  
  8. public class Employee extends Person   
  9. {  
  10. 10.     public Employee()   
  11. 11.     {  
  12. 12.         System.out.println("Employee class constructor called");  
  13. 13.     }  
  14. 14.     public static void main (String args[])  
  15. 15.     {  
  16. 16.         Employee e = new Employee();  
  17. 17.     }  

18. }  

Output

Person class constructor called

Employee class constructor called

Explanation

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

 Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

 What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  •  
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.


 What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

What is this keyword in java?

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.


More Details.

 

 What is the final method?

If we change any method to a final method, we can't override it. More Details.

  1. class Bike{  
  2.   final void run(){System.out.println("running");}  
  3. }  
  4.      
  5. class Honda extends Bike{  
  6.    void run(){System.out.println("running safely with 100kmph");}  
  7.      
  8.    public static void main(String args[]){  
  9.    Honda honda= new Honda();  
  10. 10.    honda.run();  
  11. 11.    }  

12. }  

Test it Now

Output:Compile Time Error


 

posted @ 2020-04-08 22:32  CodingYM  阅读(680)  评论(0编辑  收藏  举报