Java Interview Questions Part 2

Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.    
  9.  Public Static void main(String args[]){  
  10. 10.    C obj=new C();  
  11. 11.    obj.msg();//Now which msg() method would be invoked?  

12. }  

13. }  

Test it Now

 Compile Time Error

 

Is delete, next, main, exit or null keyword in java?

No.

What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

  • Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
  • Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
  • Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
  • Private The private class, methods, or variables defined as private can be accessed within the class only.

What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

 

How can constructor chaining be done by using the super keyword?

  1. class Person  
  2. {  
  3.     String name,address;   
  4.     int age;  
  5.     public Person(int age, String name, String address)  
  6.     {  
  7.         this.age = age;  
  8.         this.name = name;  
  9.         this.address = address;  
  10. 10.     }  

11. }  

12. class Employee extends Person   

13. {  

  1. 14.     float salary;  
  2. 15.     public Employee(int age, String name, String address, float salary)  
  3. 16.     {  
  4. 17.         super(age,name,address);  
  5. 18.         this.salary = salary;  
  6. 19.     }  

20. }  

21. public class Test   

22. {  

  1. 23.     public static void main (String args[])  
  2. 24.     {  
  3. 25.         Employee e = new Employee(22, "Mukesh", "Delhi", 90000);  
  4. 26.         System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+" Address: "+e.address);  
  5. 27.     }  

28. }  

Output

Name: Mukesh Salary: 90000.0 Age: 22 Address: Delhi

 

Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

What is the output of the following Java program?

  1. class Base   
  2. {  
  3.     protected final void getInfo()  
  4.     {  
  5.         System.out.println("method of Base class");  
  6.     }  
  7. }  
  8.    
  9. public class Derived extends Base  

10. {  

  1. 11.     protected final void getInfo()  
  2. 12.     {  
  3. 13.         System.out.println("method of Derived class");  
  4. 14.     }  
  5. 15.     public static void main(String[] args)  
  6. 16.     {  
  7. 17.         Base obj = new Base();  
  8. 18.         obj.getInfo();  
  9. 19.     }  

20. }  

Output

        Derived.java:11: error: getInfo() in Derived cannot override getInfo() in Base

    protected final void getInfo()

                         ^

  overridden method is final

1 error

Explanation

The getDetails() method is final; therefore it can not be overridden in the subclass.

What is the final variable?

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

' alt="final keyword in java" v:shapes="_x0000_i1025">

  1. class Bike9{  
  2.  final int speedlimit=90;//final variable  
  3.  void run(){  
  4.   Speed ​​Limit = 400;  
  5.  }  
  6.  public static void main(String args[]){  
  7.  Bike9 obj=new  Bike9();  
  8.  obj.run();  
  9.  }  

10. }//end of class  

Test it Now

Output:Compile Time Error

More Details.

 

What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

What is the output of the following Java program?

  1. class Main {  
  2.  public static void main(String args[]){  
  3.    final int i;  
  4.    i = 20;  
  5.    System.out.println(i);  
  6.  }  
  7. }  

Output

20

Explanation

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

 Can we override the private methods?

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

List the features of Java Programming language.

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.

 

  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.

 

  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.

 

  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.

 

  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.

 

  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.

 

  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.

 

  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.

 

  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).

 

  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.

 

  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.

 

  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

What is the platform?

A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.

How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

  1. public class Employee  
  2. {  
  3.     int id,age;   
  4.     String name, address;  
  5.     public Employee (int age)  
  6.     {  
  7.         this.age = age;  
  8.     }  
  9.     public Employee(int id, int age)  
  10. 10.     {  
  11. 11.         this(age);  
  12. 12.         this.id = id;  
  13. 13.     }  
  14. 14.     public Employee(int id, int age, String name, String address)  
  15. 15.     {  
  16. 16.         this(id, age);  
  17. 17.         this.name = name;   
  18. 18.         this.address = address;   
  19. 19.     }  
  20. 20.     public static void main (String args[])  
  21. 21.     {  
  22. 22.         Employee emp = new Employee(105, 22, "Vikas", "Delhi");  
  23. 23.         System.out.println("ID: "+emp.id+" Name:"+emp.name+" age:"+emp.age+" address: "+emp.address);  
  24. 24.     }  
  25. 25.       

26. }  

Output

ID: 105 Name:Vikas age:22 address: Delhi

 

What is the output of the following Java program?

  1. class Base   
  2. {  
  3.     public void baseMethod()  
  4.     {  
  5.         System.out.println("BaseMethod called ...");  
  6.     }  
  7. }  
  8. class Derived extends Base   
  9. {  
  10. 10.     public void baseMethod()  
  11. 11.     {  
  12. 12.         System.out.println("Derived method called ...");  
  13. 13.     }  

14. }  

15. public class Test   

16. {  

  1. 17.     public static void main (String args[])  
  2. 18.     {  
  3. 19.         Base b = new Derived();  
  4. 20.         b.baseMethod();  
  5. 21.     }  

22. }  

Output

Derived method called ...

Explanation

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

Can we execute a program without main() method?

Ans) Yes, one of the ways to execute the program without the main method is using static block. More Details.

Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

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

12. }  

Output

10

 

What is the output of the following Java program?

  1. class OverloadingCalculation3{    
  2.   void sum(int a,long b){System.out.println("a method invoked");}    
  3.   void sum(long a,int b){System.out.println("b method invoked");}    
  4.     
  5.   public static void main(String args[]){    
  6.   OverloadingCalculation3 obj=new OverloadingCalculation3();    
  7.   obj.sum(20,20);//now ambiguity    
  8.   }    
  9. }    

Output

OverloadingCalculation3.java:7: error: reference to sum is ambiguous

obj.sum(20,20);//now ambiguity 

     ^

      both method sum(int,long) in OverloadingCalculation3

      and method sum(long,int) in OverloadingCalculation3 match

1 error

Explanation

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Can we override the overloaded method?

Yes.

Can we override the static methods?

No, we can't override static methods.

Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

What is Java?

Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.

What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.

What is Runtime Polymorphism?

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splendor extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   public static void main(String args[]){  
  7.     Bike b = new Splendor();//upcasting  
  8.     b.run();  
  9.   }  

10. }  

Test it Now

Output:

running safely with 60km.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

More details.

 

 

Can you achieve Runtime Polymorphism by data members?

No, because method overriding is used to achieve runtime polymorphism and data members cannot be overridden. We can override the member functions but not the data members. Consider the example given below.

  1. class Bike{  
  2.  int speedlimit=90;  
  3. }  
  4. class Honda3 extends Bike{  
  5.  int speedlimit=150;  
  6.  public static void main(String args[]){  
  7.   Bike obj=new Honda3();  
  8.   System.out.println(obj.speedlimit);//90  
  9.    }  

Test it Now

Output:

What is the abstraction?

Abstraction is a process of hiding the implementation details and showing only functionality to the user. It displays just the essential things to the user and hides the internal information, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery. Abstraction enables you to focus on what the object does instead of how it does it. Abstraction lets you focus on what the object does instead of how it does it.

In Java, there are two ways to achieve the abstraction.

  • Abstract Class
  • Interface

More details.

What is the abstract class?

A class that is declared as abstract is known as an abstract class. It needs to be extended and its method implemented. It cannot be instantiated. It can have abstract methods, non-abstract methods, constructors, and static methods. It can also have the final methods which will force the subclass not to change the body of the method. Consider the following example.

  1. abstract class Bike{  
  2.   abstract void run();  
  3. }  
  4. class Honda4 extends Bike{  
  5. void run(){System.out.println("running safely");}  
  6. public static void main(String args[]){  
  7.  Bike obj = new Honda4();  
  8.  obj.run();  
  9. }  

10. }  

Test it Now

Output

running safely

 

What is the difference between abstraction and encapsulation?

Abstraction hides the implementation details whereas encapsulation wraps code and data into a single unit.

Can there be an abstract method without an abstract class?

No, if there is an abstract method in a class, that class must be abstract.

Can you use abstract and final both with a method?

No, because we need to override the abstract method to provide its implementation, whereas we can't override the final method.

Is it possible to instantiate the abstract class?

No, the abstract class can never be instantiated even if it contains a constructor and all of its methods are implemented.

What is the interface?

The interface is a blueprint for a class that has static constants and abstract methods. It can be used to achieve full abstraction and multiple inheritance. It is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. However, we need to implement it to define its methods. Since Java 8, we can have the default, static, and private methods in an interface.

Can the Interface be final?

No, because an interface needs to be implemented by the other class and if it is final, it can't be implemented by any class.

What are the advantages of defining packages in Java?

By defining packages, we can avoid the name conflicts between the same class names defined in different packages. Packages also enable the developer to organize the similar classes more effectively. For example, one can clearly understand that the classes present in java.io package are used to perform io related operations.

What is the package?

A package is a group of similar type of classes, interfaces, and sub-packages. It provides access protection and removes naming collision. The packages in Java can be categorized into two forms, inbuilt package, and user-defined package. There are many built-in packages such as Java, lang, awt, javax, swing, net, io, util, sql, etc. Consider the following example to create a package in Java.

  1. //save as Simple.java  
  2. Package  Mypack;  
  3. public class Simple{  
  4.  public static void main(String args[]){  
  5.     System.out.println("Welcome to package");  
  6.    }  
  7. }  

Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

 

What is the difference between static binding and dynamic binding?

In case of the static binding, the type of the object is determined at compile-time whereas, in the dynamic binding, the type of the object is determined at runtime.

Static Binding

  1. class Dog{  
  2.  private void eat(){System.out.println("dog is eating...");}  
  3.   
  4.  public static void main(String args[]){  
  5.   Dog d1=new Dog();  
  6.   d1.eat();  
  7.  }  
  8. }  

Dynamic Binding

  1. class Animal{  
  2.  void eat(){System.out.println("animal is eating...");}  
  3. }  
  4.   
  5. class Dog extends Animal{  
  6.  void eat(){System.out.println("dog is eating...");}  
  7.   
  8.  public static void main(String args[]){  
  9.   Animal a=new Dog();  
  10. 10.   a.eat();  
  11. 11.  }  

12. }  

 

 

What are the differences between abstract class and interface?

Abstract class

Interface

An abstract class can have a method body (non-abstract methods).

The interface has only abstract methods.

An abstract class can have instance variables.

An interface cannot have instance variables.

An abstract class can have the constructor.

The interface cannot have the constructor.

An abstract class can have static methods.

The interface cannot have static methods.

You can extend one abstract class.

You can implement multiple interfaces.

The abstract class can provide the implementation of the interface.

The Interface can't provide the implementation of the abstract class.

The abstract keyword is used to declare an abstract class.

The interface keyword is used to declare an interface.

An abstract class can extend another Java class and implement multiple Java interfaces.

An interface can extend another Java interface only.

An abstract class can be extended using keyword extends

An interface class can be implemented using keyword implements

A Java abstract class can have class members like private, protected, etc.

Members of a Java interface are public by default.

Example:
public abstract class Shape{
public abstract void draw();
}

Example:
public interface Drawable{
void draw();
}

 

Can we define private and protected modifiers for the members in interfaces?

No, they are implicitly public.

What are the advantages of Encapsulation in Java?

There are the following advantages of Encapsulation in Java?

  • By providing only the setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.
  • It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.
  • It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.
  • The encapsulate class is easy to test. So, it is better for unit testing.
  • The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.

What is the output of the following Java program?

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

19. }  

Output

  Test:print() called

Explanation

It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime. At compile-time, it is checked whether that method is present in the Base class. In this case, it is overridden in the child class, therefore, at runtime the derived class method is called.

What is the difference between JDK, JRE, and JVM?

JVM

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

More Details.

 

What is the difference between compile-time polymorphism and runtime polymorphism?

There are the following differences between compile-time polymorphism and runtime polymorphism.

SN

compile-time polymorphism

Runtime polymorphism

1

In compile-time polymorphism, call to a method is resolved at compile-time.

In runtime polymorphism, call to an overridden method is resolved at runtime.

2

It is also known as static binding, early binding, or overloading.7

It is also known as dynamic binding, late binding, overriding, or dynamic method dispatch.

3

Overloading is a way to achieve compile-time polymorphism in which, we can define multiple methods or constructors with different signatures.

Overriding is a way to achieve runtime polymorphism in which, we can redefine some particular method or variable in the derived class. By using overriding, we can give some specific implementation to the base class properties in the derived class.

4

It provides fast execution because the type of an object is determined at compile-time.

It provides slower execution as compare to compile-time because the type of an object is determined at run-time.

5

Compile-time polymorphism provides less flexibility because all the things are resolved at compile-time.

Run-time polymorphism provides more flexibility because all the things are resolved at runtime.


 

Guess you like

Origin www.cnblogs.com/codingyangmao/p/12669039.html