Java Interview Questions | 3 | -Interview of Geeks

Core java Interview Questions Interview Questions | 3

101-150 out of 300 Questions

There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

The answers to the Core Java interview questions are short and to the point. The core Java interview questions are categorized in Basics of Java interview questions, OOPs interview questions, String Handling interview questions, Multithreading interview questions, collection interview questions, JDBC interview questions, etc.


Core Java - OOP's Concepts: Polymorphism Interview Questions

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

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

    compile-time polymorphism Runtime polymorphism
    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.
    It is also known as static binding, early binding, or overloading. It is also known as dynamic binding, late binding, overriding, or dynamic method dispatch.
    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.
    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.
    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.

  2. 102. What is Runtime Polymorphism?

    TRuntime 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.


  3. 103. 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.

    class Bike{
    int speedlimit=90;
    }
    class Honda3 extends Bike{
    int speedlimit=150;
    public static void main(String args[]){
    Bike obj=new Honda3();
    System.out.println(obj.speedlimit);//90
    }

    Output

    90
  4. 104. 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

    class Dog{
    private void eat(){System.out.println("dog is eating...");}

    public static void main(String args[]){
    Dog d1=new Dog();
    d1.eat();
    }
    }

    Synamic Binding

    class Animal{
    void eat(){System.out.println("animal is eating...");}
    }

    class Dog extends Animal{
    void eat(){System.out.println("dog is eating...");}

    public static void main(String args[]){
    Animal a=new Dog();
    a.eat();
    }
    }

  5. 105. How can constructor chaining be done using this keyword?
    class BaseTest
    {
    void print()
    {
    System.out.println("BaseTest:print() called");
    }
    }
    public class Test extends BaseTest
    {
    void print()
    {
    System.out.println("Test:print() called");
    }
    public static void main (String args[])
    {
    BaseTest b = new Test();
    b.print();
    }
    }

    Output

    Test:print() called
  6. 106. What is Java instanceOf operator?

    The instanceof in Java is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that has a null value, it returns false. Consider the following example.

    class Simple1{
    public static void main(String args[]){
    Simple1 s=new Simple1();
    System.out.println(s instanceof Simple1);//true
    }
    }

    Output

    true
  7. Core Java - OOP's Concepts: Abstraction Interview Questions

  8. 107. 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

  9. 108. What is the difference between abstraction and encapsulation?

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


  10. 109. 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.

    abstract class Bike{
    abstract void run();
    }
    class Honda4 extends Bike{
    void run(){System.out.println("running safely");}
    public static void main(String args[]){
    Bike obj = new Honda4();
    obj.run();
    }
    }

    Output

    running safely
  11. 110. 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.


  12. 111. Is the following program written correctly? If yes then what will be the output of the program?
    abstract class Calculate
    {
    abstract int multiply(int a, int b);
    }

    public class Main
    {
    public static void main(String[] args)
    {
    int result = new Calculate()
    {
    @Override
    int multiply(int a, int b)
    {
    return a*b;
    } }.multiply(12,32);
    System.out.println("result = "+result);
    }
    }

    Output

    384
  13. 112. 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.


  14. 113. 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.


  15. 114. 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.


  16. 115. Can you declare an interface method static?

    No, because methods of an interface are abstract by default, and we can not use static and abstract together.


  17. 116. 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.


  18. 117. What is a marker interface?

    A Marker interface can be defined as the interface which has no data member and member functions. For example, Serializable, Cloneable are marker interfaces. The marker interface can be declared as follows.

    public interface Serializable{
    }

  19. 118. 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.
    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();
    }

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

    No, they are implicitly public.


  21. 120. When can an object reference be cast to an interface reference?

    An object reference can be cast to an interface reference when the object implements the referenced interface.


  22. 121. How to make a read-only class in Java?

    A class can be made read-only by making all of the fields private. The read-only class will have only getter methods which return the private property of the class to the main method. We cannot modify this property because there is no setter method available in the class. Consider the following example.

    //A Java class which has only getter methods.
    public class Student{
    //private data member
    private String college="AKG";
    //getter method for college
    public String getCollege(){
    return college;
    }
    }

  23. 122. How to make a write-only class in Java?

    A class can be made write-only by making all of the fields private. The write-only class will have only setter methods which set the value passed from the main method to the private fields. We cannot read the properties of the class because there is no getter method in this class. Consider the following example.

    //A Java class which has only setter methods.
    public class Student{
    //private data member
    private String college;
    //getter method for college
    public void setCollege(String college){
    this.college=college;
    }
    }

  24. 123. 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.

  25. Core Java - OOP's Concepts: Package Interview Questions

  26. 124. 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.

    //save as Simple.java
    package mypack;
    public class Simple{
    public static void main(String args[]){
    System.out.println("Welcome to package");
    }
    }


  27. 125. 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.


  28. 126. How to create packages in Java?

    If you are using the programming IDEs like Eclipse, NetBeans, MyEclipse, etc. click on file->new->project and eclipse will ask you to enter the name of the package. It will create the project package containing various directories such as src, etc. If you are using an editor like notepad for java programming, use the following steps to create the package.

    • Define a package package_name. Create the class with the name class_name and save this file with your_class_name.java.

    • Now compile the file by running the following command on the terminal.
      javac -d . your_class_name.java
      The above command creates the package with the name package_name in the present working directory.

    • Now, run the class file by using the absolute class file name, like following.
      java package_name.class_name


  29. 127. How can we access some class in another class in Java?

    There are two ways to access a class in another class.

    • By using the fully qualified name: To access a class in a different package, either we must use the fully qualified name of that class, or we must import the package containing that class.

    • By using the relative path, We can use the path of the class that is related to the package that contains our class. It can be the same or subpackage.

  30. 128. Do I need to import java.lang package any time? Why?

    No. It is by default loaded internally by the JVM.


  31. 129. Can I import same package/class twice? Will the JVM load the package twice at runtime?

    One can import the same package or the same class multiple times. Neither compiler nor JVM complains about it. However, the JVM will internally load the class only once no matter how many times you import the same class.


  32. 130. What is the static import?

    By static import, we can access the static members of a class directly, and there is no to qualify it with the class name.


  33. Java: Exception Handling Interview Questions

  34. 131. How many types of exception can occur in a Java program?

    There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

    • Checked Exception: Checked exceptions are the one which are checked at compile-time. For example, SQLException, ClassNotFoundException, etc.

    • Unchecked Exception: Unchecked exceptions are the one which are handled at runtime because they can not be checked at compile-time. For example, ArithmaticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.

    • Error: Error cause the program to exit since they are not recoverable. For Example, OutOfMemoryError, AssertionError, etc.

  35. 132. What is Exception Handling?

    Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions: checked and unchecked. Here, the error is considered as the unchecked exception.


  36. 133. Explain the hierarchy of Java Exception classes?

    The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:



  37. 134. What is the difference between Checked Exception and Unchecked Exception?
    • Checked Exception
      The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions, e.g., IOException, SQLException, etc. Checked exceptions are checked at compile-time.
    • Unchecked Exception
      The classes that extend RuntimeException are known as unchecked exceptions, e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

  38. 135.What is the base class for Error and Exception?

    The Throwable class is the base class for Error and Exception.


  39. 136. Is it necessary that each try block must be followed by a catch block?

    It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. So whatever exceptions are likely to be thrown should be declared in the throws clause of the method. Consider the following example.

    public class Main{
    public static void main(String []args){
    try{
    int a = 1;
    System.out.println(a/0);
    }
    finally
    {
    System.out.println("rest of the code...");
    }
    }
    }

    The output of the following program is:

    Exception in thread main java.lang.ArithmeticException:/ by zero
    rest of the code...

  40. 137. What is the output of the following Java program?
    public class ExceptionHandlingExample {
    public static void main(String args[])
    {
    try
    {
    int a = 1/0;
    System.out.println("a = "+a);
    }
    catch(Exception e){System.out.println(e);}
    catch(ArithmeticException ex){System.out.println(ex);}
    }
    }

    Output

    ExceptionHandlingExample.java:10: error: exception ArithmeticException has already been caught
    catch(ArithmeticException ex){System.out.println(ex);}
    ^
    1 error

  41. 138. What is finally block?

    The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. In other words, we can say that finally block is the block which is always executed. Finally block follows try or catch block. If you don't handle the exception, before terminating the program, JVM runs finally block, (if any). The finally block is mainly used to place the cleanup code such as closing a file or closing a connection. Here, we must know that for each try block there can be zero or more catch blocks, but only one finally block. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).


  42. 139. Can finally block be used without a catch?

    Yes, According to the definition of finally block, it must be followed by a try or catch block, therefore, we can use try block instead of catch.


  43. 140. Is there any case when finally will not be executed?

    Finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).


  44. 141. What is the difference between throw and throws?
    throw keyword throws keyword
    1) The throw keyword is used to throw an exception explicitly. The throws keyword is used to declare an exception.
    2) The checked exceptions cannot be propagated with throw only. The checked exception can be propagated with throws
    3) The throw keyword is followed by an instance. The throws keyword is followed by class.
    4) The throw keyword is used within the method. The throws keyword is used with the method signature.
    5) You cannot throw multiple exceptions. You can declare multiple exceptions, e.g., public void method()throws IOException, SQLException.

  45. 142. What is the output of the following Java program?
    public class Main{
    public static void main(String []args){
    try
    {
    throw 90;
    }
    catch(int e){
    System.out.println("Caught the exception "+e);
    }
    }
    }

    Output

    Main.java:6: error: incompatible types: int cannot be converted to Throwable
    throw 90;
    ^
    Main.java:8: error: unexpected type
    catch(int e){
    ^
    required: class
    found: int
    2 errors

  46. 143. What is the output of the following Java program?
    class Calculation extends Exception
    {
    public Calculation()
    {
    System.out.println("Calculation class is instantiated");
    }
    public void add(int a, int b)
    {
    System.out.println("The sum is "+(a+b));
    }
    }
    public class Main{
    public static void main(String []args){
    try
    {
    throw new Calculation();
    }
    catch(Calculation c){
    c.add(10,20);
    }
    }
    }

    Output

    Calculation class is instantiated
    The sum is 30

  47. 144. Can an exception be rethrown?

    Yes


  48. 145. Can subclass overriding method declare an exception if parent class method doesn't throw an exception?

    Yes but only unchecked exception not checked.


  49. 146. What is exception propagation?

    An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This procedure is called exception propagation. By default, checked exceptions are not propagated.

    class TestExceptionPropagation1{
    void m(){
    int data=50/0;
    }
    void n(){
    m();
    }
    void p(){
    try{
    n();
    }catch(Exception e){System.out.println("exception handled");}
    }
    public static void main(String args[]){
    TestExceptionPropagation1 obj=new TestExceptionPropagation1();
    obj.p();
    System.out.println("normal flow...");
    }
    }

    Output

    exception handled
    normal flow...

  50. 147. What is the output of the following Java program?
    public class Main
    {
    void a()
    {
    try{
    System.out.println("a(): Main called");
    b();
    }catch(Exception e)
    {
    System.out.println("Exception is caught");
    }
    }
    void b() throws Exception
    {
    try{
    System.out.println("b(): Main called");
    c();
    }catch(Exception e){
    throw new Exception();
    }
    finally
    {
    System.out.println("finally block is called");
    }
    }
    void c() throws Exception
    {
    throw new Exception();
    }

    public static void main (String args[])
    {
    Main m = new Main();
    m.a();
    }
    }
    }

    Output

    a(): Main called
    b(): Main called
    finally block is called
    Exception is caught

  51. 148. What is the output of the following Java program?
    public class Calculation
    {
    int a;
    public Calculation(int a)
    {
    this.a = a;
    }
    public int add()
    {
    a = a+10;
    try
    {
    a = a+10;
    try
    {
    a = a*10;
    throw new Exception();
    }catch(Exception e){
    a = a - 10;
    }
    }catch(Exception e)
    {
    a = a - 10;
    }
    return a;
    }

    public static void main (String args[])
    {
    Calculation c = new Calculation(10);
    int result = c.add();
    System.out.println("result = "+result);
    }
    }

    Output

    result = 290
  52. Java: Java: String Handling Interview Questions

  53. 149. What is String Pool?

    String pool is the space reserved in the heap memory that can be used to store the strings. The main advantage of using the String pool is whenever we create a string literal; the JVM checks the "string constant pool" first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance is created and placed in the pool. Therefore, it saves the memory by avoiding the duplicacy.


  54. 150. What is the meaning of immutable regarding String?

    The simple meaning of immutable is unmodifiable or unchangeable. In Java, String is immutable, i.e., once string object has been created, its value can't be changed. Consider the following example for better understanding.

    class Testimmutablestring{
    public static void main(String args[]){
    String s="Sachin";
    s.concat(" Tendulkar");//concat() method appends the string at the end
    System.out.println(s);//will print Sachin because strings are immutable objects
    }
    }

    Output

    Sachin

Last Updated:


Trending Technologies Interview Questions


@InterviewofGeeks, Some rights reserved.