Core Java interview questions

Core Java interview questions

What is Java?

Java is a platform independent, case sensitive language which is used to create secure and robust applications. It was developed by James Gosling in 1991. Apart from having a C like notation, it was much easier, uniform and simple than C/C++. The first version of Java was released by Sun Microsystems in 1995. It works on a "Write Once Run Anywhere" platform. Java is open source software. The J2 versions of Java were renamed as Java SE, Java EE, and Java ME. Java is an object-oriented programming language. Java is a combination of the features of C and C++. It has inherited its features from C and object-oriented programming feature from C++.

Download Core Java interview questions PDF

Below are the list of Best Core Java interview questions and Answers

In order to load the Java Classes into a virtual environment, Classloader are used. A class loader will load key classes such as java.lang.object and several other codes into the memory. Usually, these classes are loaded only if a demand occurs. Since Java Runtime Environment includes loaders, they need not know about file and file systems. Also, the loaders are responsible for converting the named class into an equivalent binary form.

Call by value: 
A process in which the values of the actual parameters sent by the calling function are copied to the formal parameters of the called function.

Call by reference: 
A process in which the parameters of a calling function are passed to the parameters of the called function using an address.

It is important to understand the difference between JDK, JRE, and JVM in Java.

JVM (Java Virtual Machine):  

Java virtual machine is actually an abstract machine which provides a runtime environment in which the java bytecode gets executed. A JVM performs some main tasks such as- loading, verifying and executing the code. It also provides a runtime environment.

JRE (Java Runtime Environment):

The Java runtime environment is used to provide a runtime environment. It is implemented by JVM. It consists of certain libraries which are used by JVM at runtime.

JDK (Java Development Kit):

The Java development kit consists of JRE and all the development tools which are necessary for compiling a program.

Access specifiers in java are the keywords which define the access scope of the function. It can be used before a class or a method. There are basically 4 types of access specifiers in java: –

  • Public: – class, methods, and fields are accessible from anywhere.
  • Protected: – methods and fields are accessed from the same class to which they belong. Even from the subclass and class from the same package. Any outside class cannot access the methods and fields.
  • Default: – only from the same package, the methods and fields be accessed and not from the outside package.
  • Private: – the methods and fields can be only accessed from the same class to which they belong.
If we want to execute a statement or a block of statements repeatedly in java, then loops are used. And such process is known as looping. There are basically 3 types of looping. They are: –
  • “For loop”: – for executing a statement or a set of statements for a given number of times, for loops are used. It is used when the programmer knows the number of times a statement is to be executed.
  • “While loop”: – in this, a particular statement or set of statements are executed until a particular condition is fulfilled. In this, before the execution of statements, the condition is checked. It is known as an entry controlled loop.
  • “Do While loop”: – there is only one difference between the while and do while loop and that is- in do while loop, the condition is checked after the execution of the block of statements. It is known as an exit controlled loop.

The major features of Java are listed below: –

  • Object-oriented: – Java language is based on object-oriented programming. In this, the class and the methods describe the state and behavior of an object. The programming is done by relating a problem with the real world object.
  • Portable: – the conversion of java program into Java bytecodes take place. This helps in running the program in any environment or platform without any dependency.
  • Platform independent: – java ensures “write once run anywhere” as its programs can be run on multiple platforms like- Windows, Mac, Sun Solaris, Linux, etc.
  • Robust: – java’s strong memory due to no pointer allocations, make it robust. The memory leaks are prohibited with the help of automatic garbage collection in java.
  • Interpreted: – the java code is converted into bytecodes by the java compiler which is then interpreted and executed by the Java interpreter or a just-in-time compiler (JIT).
Java and Python, both the languages hold an important place in today’s IT industry. But in some factors, one is better than the other. Such factors are:
  • Java is easy to use, whereas Python is very good in this case.
  • The speed of coding in Java is average, whereas in Python it is excellent.
  • In Java, the data types are statically typed, whereas in python the data types are dynamically typed.
  • Java is average in the case of data sciences and machine learning applications, whereas data science and machine learning applications are majorly based on python. Python is very good in this case.

An object is a basic entity in an object-oriented programming language that represents the real-life entities. Many objects are created by a java program that interacts with the invoking methods. The state of an object is represented by its attributes and reflects its properties. The behavior of an object is represented by the methods of the object and reflects the relationship of an object with the other objects. The identity of an object is a unique name provided to an object which helps one object to interact with other objects.

In Java, a class is a user-defined data type from which objects are created. It can also be called as a blueprint or prototype. A class is a collection of various methods and variables which represent a set of properties that are common to all the objects of one type. A class includes components such as: –
  • Modifiers: it states that a class can be public or can have a default access.
  • Class name: the name of a class should begin with a letter and should be same as the file name.
  • Body: the class body is surrounded by braces- {}.
Inheritance in Java is an important concept in any object-oriented programming language. Using inheritance, one class is allowed to inherit the properties and features of another class. The properties and features include the fields and the methods. Inheritance takes place with the help of keyword “extends”. There is a superclass whose features are inherited. It is also known as the base class or parent class. There is a subclass which inherits the properties of the base class. It is also known as derived class, extended class or the child class. Inheritance also supports the concept of “reusability”.

Following are the differences between StringBuffer and StringBuilder in java: –

  • StringBuffer methods are synchronized, whereas StringBuilder methods are non-synchronized.
  • In StringBuffer, a storage area is a heap which can be modified easily, whereas, in StringBuilder, storage is heap which can be modified easily.
  • StringBuffer is threading safe, whereas StringBuilder is not.
  • The performance of StringBuffer is very slow, whereas the performance of StringBuilder is fast.

Following are some of the differences between array list and vectors in JAVA: –

  • An array list is not synchronized, whereas a vector is synchronized.
  • An array list works fast, whereas a vector does not.
  • There is an increase of 50% in the array size whenever any element is inserted inside the array list, whereas vector defaults to doubling the size of its array.
  • The increment size is not defined in an array list, whereas in vector it is defined.
  • Only iterators can be used in an array list for traversing an array, whereas vectors can use both enumeration and iterators for traversing an array.
An abstract class is a class in java which contains the abstract keyword in its declaration. It can have both abstract and non-abstract methods. The abstract class can have the public, private, protected, constant and default variables. This class needs to be extended and we need to implement the methods. This class can’t be instantiated. A class can be declared as an abstract class if it has at least one abstract method. An abstract class has at least one virtual function. Keyword “abstract” is used to make a class abstract.

A constructor in Java is basically a block of code which initializes the objects which are newly created. Although it resembles an instance method in java it is not since it does not return any value or have a return type. People usually refer constructors as special types of methods in java. Constructors and methods are two different things. In java, or in any other object-oriented programming language, a constructor has the same name as that of the class. There are basically 3 types of constructors in java. They are: –

  • Default constructors
  • Parameterized constructors, and
  • Non-parameterized constructors.
In Java, there are basically two ways by which arguments can be passed in any function. They are: –
  • Pass by value- in this, a copy of the value of the arguments is passed in the function. If any changes are made to the parameters of the sub-routine, then there is no effect on the arguments which are used to call it.
  • Pass by reference- In this, the copy of the address of the parameters are passed in the function and if any changes are made to the parameters, then it will have an effect on the arguments used to call the sub-routine.

The super keyword in java is basically related to the parent class. A super keyword can be used for several reasons such as-

  • It can be used to call the superclass or the parent class constructor.
  • It can also be used to access the method of the superclass which has been hidden by a subclass.
  • A super keyword can also be used to call the constructor of the parent class.

When in a program there is more than one method with the same name in a single class but the arguments used in them are different, then such thing is referred to as method overloading.

Overriding concept in java means when there are two methods with the same signature, one is in the parent class and the other one is in the child class. The override annotation can be used in the child class overridden method.

Java use garbage collection which is performed automatically in Java to free the memory space from unused objects automatically. It is used to identify and dispose those objects that are no longer needed for the application. In other languages like C and C++ you must perform garbage collection by yourself to manage the memory, it means Java provides good memory management.

We do expectation handling to handle the errors or problems that arise due to the syntax error or logical error. If these errors are not handled properly then it disturbs the flow of the application and performs abnormal behavior like stops the application.so, these errors need to be handled carefully for smooth and error-free flow.

There are 2 types of exceptions.

  1. Checked Exception
  2. Unchecked Exception

When we have to store a collection of objects which is unordered we prefer the Set interface. The other main reason for using Set is we can ignore duplicate entities and keep our data unique. For example, if we have a Set containing different entities "John", "Smith", "Smith", "John", "Alisha". It will display "John" and "Smith" only one time in output by ignoring the duplicated entities. On the other hand, List is and ordered the collection of objects. So, when we have to keep our entities in ordered form while not caring about the duplication we will prefer List.

The purpose of the final keyword is to make things unchanged in application lifeline. We can make a class, method or variable unchanged by writing "final" keyword before the method, class, and variable. When the final is written before the variable, it remains unchanged (you can’t change it). A function which use final keyword cannot be overridden. On the other hand, if we make a class final we cannot extend it. When we have to make these unchanged conditions, we prefer to use the final keyword.

The process of the connecting function call with function body is called binding. When this binding is done at compile time, it is called early binding. Early binding is static binding it is done when the type of an object is determined at compile time. On the hand, late binding is done at runtime. Late binding is dynamic binding because it is done at runtime by the compiler itself.

The purpose of using multithreading is to make multiple lightweight processes running simultaneously because threads have a plus point, they are lightweight process. Multiple processes not only reserve the memory space but also make the increase the work complication as well. To eliminate the memory space issue and complications we prefer multithreading because they used a shared memory area which saves memory and performs better memory management.

Thread scheduler maintains threading states by using primitive and time slicing scheduling. It schedules the tasks by setting priority and time. Only one thread can run at a time in a single process by thread scheduler. When the highest priority is set to a process, the first process at highest priority gets starts before coming into dead or waiting state, after that the next process in the waiting state comes and make it task done and so on. This is how the thread scheduler schedules the task.

Deadlock is a situation that occurs when the same resource is required by two processes. This situation occurs in multithreading when one thread holds a resource which is required by the second thread and second thread holds a resource which is required by the first thread. To identify the deadlock, we can use the jConsole/VisualVM, it will show exactly which threads are getting locked and on which object.

It is not possible in java to write the definition of a function inside another function. It is like we are creating confusion for the compiler in making a decision for which function definition part to terminate and which is not. It is not recommended and not professional. For this purpose, we can use Lambda expression.

Note: Lambda expression is introduced in Java 8 which can be created without belonging to any class.

After creating the object JVM internally calls the toString method to generate the indirect address of the object. To string method is present inside object class, which is defined as non-static. So that object class makes it as a superclass for every class in java.

Differences between overloading and overriding

OverloadingOverriding
Overloading is performed at compilation time.Overriding is performed at runtime
Overloading is also called static binding.Overriding is also called dynamic binding.
Overloading is done within the class.Overriding occurs in between two classes that have an IS-A (inheritance) relationship.
It is an example of compile-time polymorphism.It is an example of run time polymorphism.

Overloading Example:

class ExampleClass{  
static int sum(int a,int b){return a+b;}  
static int sum(int a,int b,int c){return a+b+c;}  
}  

Overriding Example:

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

Difference between Class and object In JAVA:

  • Class - A class is like a blueprint. It is the class with the help of which objects are created. The class holds together data and methods in one single unit. And the class needs to be declared only a single time.
  • Object - This is an instance of the class. It is with the help of an object that data and methods that exist within a class can be used. Objects can be called upon several times as and when required.

A number that is divisible by 1 or itself is a Prime Number. 2, 3, 5, 7, 11, 13, 17 are examples of some Prime numbers.

Please Note: 0 and 1 are not a prime number.

Below is a simple Prime number Program in Java to check a number is Prime or Not.

import java.util.Scanner;
public class PrimeExample {
 public static void main(String args[]) {
  int i, m = 0, flag = 0;
  Scanner scan = new Scanner(System.in);
  System.out.print("Enter any number: ");
  // This method reads the number provided using keyboard
  int num = scan.nextInt();
  // Closing Scanner after the use
  scan.close();
  m = num / 2;
  if (num == 0 || num == 1) {
   System.out.println(num + " is not prime number");
  } else {
   for (i = 2; i <= m; i++) {
    if (num % i == 0) {
     System.out.println(num + " is not prime number");
     flag = 1;
     break;
    }
   }
   if (flag == 0) {
    System.out.println(num + " is prime number");
   }
  } //end of else
 }
}

Singleton design pattern is a creational pattern that is used whenever only one instance an object is needed to be created. In this pattern, you can't initialize the class.

A custom exception is also known as a user-defined exception are derived classes of Java Exception classes. In order to create your Custom exception in Java following point must be taken care of.

  • All exceptions must be a child of Throwable.
  • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  • If you want to write a runtime exception, you need to extend the RuntimeException class.

Custom exception example in Java

class InvalidAgeException extends Exception{  
 InvalidAgeException(String s){  
  super(s);  
 }  
}  

class CustomExceptionTest{  
  
   static void validate(int age)throws InvalidAgeException{  
     if(age<18)  
      throw new InvalidAgeException("not valid");  
     else  
      System.out.println("welcome to vote");  
   }  
     
   public static void main(String args[]){  
      try{  
      validate(13);  
      }catch(Exception m){System.out.println("Exception occured: "+m);}  
  
      System.out.println("rest of the code...");  
  }  
} 

Above is an example of a custom exception in Java that checks the age of voter. If age is less than 18 years than it throws an InvalidAgeException.

Whenever an exception is generated in Java it is either type of a checked or unchecked exception. Below are the few differences between checked and unchecked exceptions in Java.

Checked ExceptionUnchecked Exception
Checked exceptions are checked at compile-time.Unchecked exceptions are not checked at compile time
Interrupted Exception, file not found, Class Not Found are few Checked exceptions.Empty Stack Exception, Arithmetic Exception, Null Pointer Exception, Array Index Out of Bounds Exception are few Unchecked exceptions

Checked Vs Unchecked Exceptions in Java

Meta annotations are annotations that are used to annotate other annotation types.In Java java.lang.annotation package contain four annotation types they are @Documented, @Inherited, @Repeatable, @Target.