Core Java Interview Questions

Get Technical Answers for Core Java Interview Questions by Core Java Developers, Advanced Technical Questions for Freshers and Experience Persons. Get Free Practical Tests.

1. What is object-oriented programming? Is Java an object-oriented language?

Ans: Object-oriented programming works based on the concept of objects and the objects are the containers which store the data in the form of fields and code in the form of procedures which implements the logic for performing the operations. Java utilizes eight primitive data types such as boolean, byte, char, int, float, long, short, double and these data types are not the objects, hence java cannot be considered as a 100% object-oriented language.

2. What are wrapper classes in Java?

Ans: Wrapper classes convert the Java primitives into the reference types which are the objects. Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. 

3. What is the difference between an Array list and vector in Java?

Ans: 

Array List:

  • It is not synchronized.
  • It is fast and not it’s non-synchronized.
  • The array size increases to 50% when an element is inserted into an Array List.
  • It doesn’t define any increment size.
  • It uses Iterator for traversing an Array List.

Vector:

  • It is synchronized.
  • It is slow and it is thread-safe.
  • By default, the vectors will double the size of its array.
  • It defines the increment size.
  • It uses Enumeration as well as Iterator for traversing.

4. What is the output of the following Java program?

Ans: 


class Test   

{  

public static void main (String args[])   

{  

System.out.println(10 + 20 + "Java");   

System.out.println("Java" + 10 + 20);  

}  

The program prints the following output.

30Java

Java1020

In the first scenario, 10 and 20 will be treated as numbers and the sum operation is performed which displays 30. Now, this sum 30 is treated as a string and concatenated with a string Java. Hence, the output becomes “30Java”.

In the second scenario, the string Javatpoint is concatenated with 10 as string “Java10” which then again concatenates with 20 as “Java1020”

5. Explain the difference between ‘finally’ and ‘finalize’ in Java?

Ans: 
Finally:

It is used along with a try-catch block, the “finally” block ensures that a particular piece of code is always executed, even if the execution is thrown by the try-catch block.

Finalize:

It is a special method in the object class. The finalize() method is generally overridden to release system resources when garbage value is collected from the object.

6. What are the main uses of “this” keyword?

Ans: There are many uses of this keyword.

  • The keyword “this” can be used for referring to the current class instance variable.
  • The keyword “this” can be used to invoke the current class method (implicitly).
  • The method “this()” can be used to invoke the current class constructor.
  • The keyword “this” can be passed as an argument in the method call.
  • The keyword “this” can be passed as an argument in the constructor call.
  • The keyword “this” can be used to return the current class instance from the method.

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

Ans: It is not possible by changing the return type of the program due to avoid the ambiguity. The following example explains the ambiguity.

class Sum{  

static int addition(int a,int b)

{

return a+b;

}  

static double addition(int a,int b)

{

return a+b;

}  

}  

class TestOverloading3{  

public static void main(String[] args)

{  

System.out.println(Sum.addition(10,10));//ambiguity  

}

}  

Output:

Compile Time Error: method addition(int, int) is already defined in class Sum

8. What is the covariant return type?

Ans: From java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is a subclass type. This is known as a covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

class A{  

A get()

{

return this;

}  

}    

class B1 extends A{  

B1 get()

{

return this;

}  

void message()

{

System.out.println("welcome to covariant return type");

}    

public static void main(String args[])

{  

new B1().get().message();  

}  

}  

Output: 

welcome to covariant return type

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

Ans: No. It’s because “this()” and “super()” has to be the first statement in the class constructor.

Example:

public class Test{  

Test()  

{  

super();   

 this();  

System.out.println("Test class object is created");  

  }  

 public static void main(String []args){  

   Test t = new Test();  

  }  

}  

Output:

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

10. What is super in java?

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

Example:

class Fruit{  

Fruit()

{

System.out.println("fruit is created");

}  

}  

class Apple extends Fruit{  

Apple()

{  

System.out.println("apple is created");  

}  

}  

class TestSuper4{  

public static void main(String args[])

{  

Apple a=new Apple();  

}  

}  

Output:

fruit is created

apple is created

11. What are the differences between method Overloading and Overriding?

Ans:

Method Overloading:

  • It increases the readability of the program.
  • It occurs within a class.
  • In this scenario, the parameters have to be different.

Method Overriding:

  • It provides the specific implementation of the method that is already provided by its superclass.
  • It occurs in two classes that have IS-A relationship between them.
  • In this scenario, the parameters can be the same.

Core Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

 

12. How to achieve encapsulation in Java? Give an example.

Ans: Apply these two steps for achieving encapsulation in java.

Declare the variable of the class as private.
Provide public set() and get() methods to modify the values of variables.
Example:

public class EncapsulationTest 

{

private String empName; 

private String empNum; 

private int empAge; 

public int getEmpAge()



return age; 



public String getEmpName()



return name; 



public String getEmpNum()



return empNum; 



public void setEmpAge(int newAge)



age = newAge; 



public void setEmpName(String newName)



name = newName; 



public void setEmpNum(String newEmpNum)



empNum = newEmpNum; 



}

13. What is runtime polymorphism or dynamic method dispatch?

Ans

  • In Java, 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. 


Example:

class Bike {

void run()

{

System.out.println(“Bike is running”);

}

}

class Pulsar extends Bike {

void run()

{

System.out.println(“Pulsar is running safely with 100km”);

}

public static void main(String args[])

{

Bike b= new Bike(); //upcasting

b.run();

}

}

14. What do you mean by an interface in Java?

Ans: 

  • An interface in Java is a blueprint of a class. 
  • It is a collection of abstract methods and static constants. 
  • Each method in an interface is public and abstract. 
  • Interfaces don’t contain any constructors. 
  • An interface is basically a group of related methods with empty bodies. 


Example:

public interface Switch{

  public void on();

  public void off();

}

15. What are the advantages of Packages in Java?

Ans: There are various advantages of packages in java.

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

16. Why are Java Strings immutable in nature?

Ans: In Java, string objects are immutable which means once if the String object is created then its state cannot be changed. Java creates a new string object whenever you try to update the value of that object instead of updating the values of that particular object. String objects are generally cached in the String pool and hence Java String objects are immutable. Since String literals are usually shared between multiple clients, action from one client might affect the rest. It enhances security, caching, synchronization, and performance of the application. 

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

Ans: Yes. It is possible to change the scope of the overridden method in the subclass. However, it should be noticed that the accessibility of the method cannot be decreased. The following measures 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.

18. Can you modify the throws clause of the superclass method while overriding it in the subclass?

Ans: Yes, it is possible to modify the throws clause of the superclass method while overriding it in the subclass. However, there are certain rules that must be followed while overriding in case of exception handling.

  • If the superclass method doesn’t declare an exception, then the subclass overridden method can’t declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, then the subclass overridden method can declare the same, subclass exception or no exception but it can’t declare parent exception.

19. What is object cloning?

Ans: 

  • The object cloning is used for creating the exact copy of an object. 
  • The “clone()” method of the Object class is used to clone an object. 
  • The “java.lang.Cloneable” interface must be implemented by the class whose object clone has to be created.
  • If the Cloneable interface is not implemented then the clone() method generates “CloneNotSupportedException”.

Example:

protected Object clone() throws CloneNotSupportedException

20. Why is multiple inheritance not supported in java?

Ans: In order to reduce the complexity of the program and simplify the language, the concept of 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 a 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 two classes. So whether you have the same method or different, there will be a compile-time error.

Example:

class A{  

void message()

{

System.out.println("Hello");

}  

}  

class B{  

void message()

{

System.out.println("Welcome");

}  

}  

class C extends A,B

{

//suppose if it were  

    Public Static void main(String args[])

{  

   C obj=new C();  

   obj.message();

//Now which message() method would be invoked?  

}  

}  

Output:

Compile Time Error

Subscribe to our youtube channel to get new updates..!

 

21. What is the difference between abstract classes and interfaces?

Ans: 

Abstract class:

  • An abstract class provides complete, default code and the details that must be overridden.
  • In an abstract class, a class can extend only one abstract class.
  • An abstract class can have non-abstract methods and instance variables.
  • The visibility of an abstract class can be private, public or protected.
  • The abstract class performs fast and it can use the constructors.

Interface:

  • An interface doesn’t provide any code but only the signature.
  • A class can implement several interfaces.
  • All methods of an Interface are abstract and it doesn’t contain instance variables.
  • The visibility of an interface can be either public or none.
  • The interfaces will perform slow and it cannot use the constructors.

22. What are the differences between Checked Exception and Unchecked Exception?

Ans: 

Checked Exception:

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. 
  • These exceptions are checked at compile-time.
    Example: IOException, SQLException etc.

Unchecked Exception:

  • The classes that extend “RuntimeException” are known as unchecked exceptions. 
  • These exceptions are not checked at compile-time.
    Example: ArithmeticException, NullPointerException etc.

23. What are the differences between processes and threads?

Ans: 

Process:

  • The process is an instance execution of a program.
  • It uses inter-process communication to communicate with sibling processes.
  • The changes which are made in the parent process doesn’t affect the child processes.
  • Processes are controlled by the operating systems and it runs in separate memory spaces.

Thread:

  • A thread is a subset of the process.
  • Threads communicate directly with other threads of its process.
  • The changes which are made in the main thread may affect the behaviour of the other threads of the process.
  • Threads are controlled by the programmer in the program and it runs in shared memory spaces.

24. What is synchronization?

Ans: 

  • Synchronization refers to multi-threading. A synchronized block of code is executed only by one thread at a time. 
  • Java supports execution of multiple threads, so two or more threads can access the same fields or objects. 
  • Synchronization is a process which keeps all concurrent threads in execution to be in sync. 
  • Synchronization avoids the memory consistency errors which are caused due to the inconsistent view of shared memory. 
  • When a method is declared as synchronized the thread holds the monitor for that method’s object. If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.

25. What is the difference between an Applet and a Java Application?

Ans: 

Applets:

  • These are executed within a java-enabled browser.
  • It doesn’t require any main method to start the execution.
  • It typically uses a restrictive security policy.

Java Application:

  • As it is a standalone program, it can be executed outside of a browser.
  • It requires a main method with a specific signature to start the execution.
  • It uses more relaxed security policies.

26. Explain the life cycle of an Applet?

Ans: An applet undergoes the following states during execution.

  1. Init: An applet is initialized each time is loaded.
  2. Start: Begin the execution of an applet.
  3. Stop: Stop the execution of an applet.
  4. Destroy: Perform a final cleanup, before unloading the applet.

27. What is the difference between a Choice and a List?

Ans: A Choice is displayed in a compact form. In order to see the list of all available choices, the user must pull down the form. Choice allows only one item to select. A list is displayed in such a way that several List items are visible to the user. A list allows selecting one or more List items.

28. What is the difference between a Scrollbar and a JScrollPane?

Ans: A Scrollbar is a Component, but not a Container whereas the ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Core Java Certification Training

Weekday / Weekend Batches

 

29. What is the advantage of PreparedStatement over Statement?

Ans: The PreparedStatements are precompiled and so its performance is much better. This statement objects can also be reused with different input values to their queries.

30. What is the use of CallableStatement?

Ans: A CallableStatement is used for executing the stored procedures. The stored procedures are stored and offered by a database. It takes the input values from the user and will return a result. The usage of stored procedures is highly recommended because it offers security and modularity. The syntax of a method that prepares a “CallableStatement” is the following:

Syntax:

CallableStament.prepareCall();

Submit an interview question

Categories

Request for more information

John
John
Cloud Technologies & Cyber Security
John is a Post Graduate in Computer Science from Andhra University .She is currently working as an IT developer at hkr trainings.com. And he has great experience includes both IT development and operational roles. Connect with him on LinkedIn and Twitter. Thank you

WhatsApp
To Top