Core Java Interview Questions for Beginners

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

Quick Questions about Java

Java is a  Object Oriented Programming Language
Java was designed byJames Gosling (Canadian Computer Scientist)
Java was developed bySun Microsystems
java was initially released on 23 May 1995 (about 27 years ago) 
Java file name extensions are.Java, .class, .jar, & .jmod
Java application areas areGaming, Scientific, Bigdata, Desktop & Mobile Applications
Java features areSimple, Secure,  Platform Independent, & Interpreted

Key Responsibilities of Java Developer

As a java developer, some of the most popular key responsibilities are: 

  • Write clean, efficient, and well-documented code.
  • Design, develop and maintain Java-based applications.
  • Troubleshoot and debug issues in java applications.
  • Participate in Agile development and Scrum meetings.
  • contribute to all the stages of SDLC (software development lifecycle).
  • Stay up-to-date with new technologies and programming languages related to Java development.
  • Participate in code reviews and ensure that all solutions are aligned with industry best practices.
  • Work on and adhere to development schedules and project timelines.
  • Identify and fix bugs or issues with the website, and implement changes to improve its performance.
Download Core Java Interview Questions PDF

Below are the list of Best Core Java Interview Questions and Answers

There are several ways to convert an integer to a string in Java:

  • Using the + operator: int i = 42; String s = "" + i;
  • Using String.format(): int i = 42; String s = String.format("%d", i);
  • sing String.valueOf() method: int i = 42; String s = String.valueOf(i);
  • Using the StringBuilder or StringBuffer class: int i = 42; String s = new StringBuilder().append(i).toString();
  • Using the Integer wrapper class: Integer i = new Integer(42); String s = i.toString();

You can use any of the above methods depending on your requirement.

Java Generics is a feature introduced in Java 5 that allows for type-safe collections and other types. They allow you to write a single class or method that can work with multiple types of data, rather than having to write a separate version of the class or method for each type. This can lead to more reusable and maintainable code.

Here is an example of a simple generic class in Java:

public class Box {
    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

In this example, the class "Box" is parameterized with a type "T". The type "T" is used as a placeholder for an actual type that will be specified when an object of the "Box" class is created. The class can be used to create boxes that can hold any type of object, such as "Box" or "Box".

In Java, 'int' is a primitive data type that represents a 32-bit signed integer. It is a basic data type that is used to store numerical values.

While 'Integer' is a wrapper class for the 'int' primitive data type. It is an object that contains a single field of type 'int'. The 'Integer' class provides additional methods for working with integers, such as converting an 'int' to a 'String' or comparing two 'Integer' objects.

Here are some key differences between 'int' and 'Integer':

  • int is a primitive data type, whereas Integer is a reference data type.
  • int variables are stored in the stack memory, whereas Integer objects are stored in the heap memory.
  • int variables are directly used in arithmetic and comparison operations, whereas Integer objects need to be unwrapped using the intValue() method before they can be used in arithmetic or comparison operations.
  • int variables cannot be null but Integer class objects can be null.
  • int variables are more efficient to work with than Integer objects because they require less memory and have fewer method calls.

An immutable class is a class whose state cannot be modified after it is created. Once an object of an immutable class is created, it cannot be modified in any way.

Here are some popular characteristics of immutable classes:

  • All fields of the class are final and therefore cannot be modified after the object is created.
  • The class has no setter methods, so the values of the fields cannot be changed once they are set in the constructor.
  • The class should not provide any methods that can modify its state.
  • If a class has mutable fields (like collections) it should return a new instance of the collection with the new state, instead of modifying the existing one.
  • The class should be thread-safe since it can be shared among multiple threads without the need for explicit synchronization.

Java is considered to be an object-oriented programming (OOP) language, but it is not a pure OOP language.

It supports many of the key concepts of OOP such as encapsulation, inheritance, and polymorphism. It uses classes and objects to model real-world entities, and it allows for the creation of complex, reusable software by breaking it down into smaller, manageable units.

In Java, a wrapper class is a class that wraps (or "encapsulates") a primitive data type so that it can be used as an object. Java provides a wrapper class for each of the eight primitive data types:

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Character
  • Boolean

For example, the wrapper class for the int primitive data type is Integer, the wrapper class for the char primitive data type is Character, and so on.

Both Iterator and Enumeration are used in Java to iterate over a collection of elements, but they have some important differences.

  • Iterator was introduced in JDK 1.2, while Enumeration was available from the initial version of Java.
  • An iterator is a more modern and powerful way of traversing a collection, it has more functionality than Enumeration.
  • Iterator allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics, Enumeration is read-only and does not provide this functionality.
  • Iterator has a remove() method to remove the current element from the collection, Enumeration does not have this method.
  • Iterator is used in the latest collection classes like ArrayList, LinkedList,

The need of Java is that it enforces an object-oriented programming model and can be used to create complete applications that can run on a single computer or be distributed across servers and clients in a network thus it can easily build mobile applications or run on desktop applications that use different operating systems and servers.

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 a 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 the 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 fields and methods. Inheritance takes place with the help of the 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 that inherits the properties of the base class. It is also known as a 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...");}  
}   

In Java programming, a final variable is a variable that can only be assigned a value once. Once a final variable has been assigned a value, it cannot be reassigned or modified. This means that the value of a final variable is constant and cannot be changed throughout the lifetime of the program.

There are two types of final variables in Java:

  • Final instance variables
  • Final static variables

Final variables can be used in a number of ways, such as in defining constants, creating immutable objects, or creating variables that are only set once during the lifetime of a program

Examples:

final int x=10; //final variable
final static double PI=3.14; //final static variable

In Java language, a public static method is a method that can be called without creating an instance of the class in which it is defined. Because these methods are not associated with any specific object, they can be invoked directly using the class name, without the need to create an instance of the class.

There are many reasons available, why we create public static methods in Java:

Utility methods: These are methods that perform some specific task and can be reused across multiple classes. Public static methods are useful for creating utility methods because they can be called from anywhere in the program without the need to create an instance of the class.

Factory methods: These are methods that are used to create and return objects of a particular class. Public static methods are useful for creating factory methods because they can be called directly using the class name.

Main method: The main method of a Java program is a public static method. This method is the entry point of a program and is executed when the program is run.

Performance: Accessing a static method is faster than accessing a non-static method because there is no need to create an instance of the class before calling the method.

An abstract class can be defined by those classes which have at least one method as abstract. The abstract classes in PHP can be declared with a special keyword namely abstract. The main use of the abstract class is that all base classes which implement this class have to option of giving implementation of methods that are abstract already declared in the parent class.

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.

Design patterns can be explained as a general repeatable solution to a problem that is occurring commonly in large numbers during the designing of the software. Design patterns are not considered as a finished design and cannot be directly converted into code. It can be defined as a description or a template that depicts how to solve a problem that is occurring in different situations. It speeds up the development process.

Following code implements bubble sort in JAVA:

// Java program for implementation of Bubble Sort
class BubbleSort
{
    void bubbleSort(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                {
                    // swap temp and arr[i]
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
    }
 
    /* Prints the array */
    void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
 
    // Driver method to test above
    public static void main(String args[])
    {
        BubbleSort ob = new BubbleSort();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        ob.bubbleSort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }
}

JVM stands for Java Virtual Machine. JVM can be explained as an engine that is used by the Java Development Kit to provide a runtime environment to run java code or its applications. The main function of JVM is that it is used for converting Java bytecode into machine language. It is an integral part of the Java Runtime Environment. It works on “Write once, run anywhere” principle and manages the program memory.

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
 }
}

A program to find the greatest among three numbers is as follows:

public class JavaExample{

  public static void main(String[] args) {

      int num1 = 10, num2 = 20, num3 = 7;

      if( num1 >= num2 && num1 >= num3)
          System.out.println(num1+" is the largest Number");

      else if (num2 >= num1 && num2 >= num3)
          System.out.println(num2+" is the largest Number");

      else
          System.out.println(num3+" is the largest Number");
  }
}

Hashing is the process of converting a given key to another value by using a hash function that is used to generate the new value according to a mathematical algorithm. The result of a hash function is known as a hash value(hash code) or simply, a hash. Hashing refers to the way that uses some function or algorithm to map object data to some representative integer value. It can be used as a way to narrow down our search when looking for the item on the map.

The difference between call by reference and call by value

ParametersCall by valueCall by reference
DefinitionWhile calling a function, when you pass values by copying variables, it is known as "Call By Values."While calling a function, in programming language instead of copying the values of variables, the address of the variables is used it is known as "Call By References.
ArgumentsA copy of the variable is passed in this method.A variable itself is passed in this method.
Alteration of valueIt does not allow you to make any changes in the actual variables.It allows you to make changes in the values of variables by using function calls.
EffectChanges made in a copy of the variable never modify the value of the variable outside the function.Change in the variable also affects the value of the variable outside the function.
Alteration of valueIt does not allow you to make any changes in the actual variables.It allows you to make changes in the values of variables by using function calls.
Passing of variableValues of variables are passed using a straightforward method.Pointer variables are required to store the address of variables.
Value modificationOriginal value not modified.The original value is modified.
Memory LocationActual and formal arguments will be created in different memory locationActual and formal arguments will be created in the same memory location
SafetyActual arguments remain safe as they cannot be modified accidentally.Actual arguments are not Safe. They can be accidentally modified, so you need to handle arguments operations carefully.

Structs is a framework in Java. The use of this framework is for the development of the Java enterprise edition purpose. It is an open-source framework. This is a very reliable and efficient working framework. In order to introduce the MVC which is known as the model view controller, it makes use of the Java servlet API and also it extends its functions for more results. It later became one of the best frameworks that were designed in the Apache project.

A JAVA program uses the Binary search algorithm to search an element in the given list of elements is as follows:

import java.util.Scanner;
class BinarySearchExample
{
   public static void main(String args[])
   {
      int counter, num, item, array[], first, last, middle;
      //To capture user input
      Scanner input = new Scanner(System.in);
      System.out.println("Enter the number of elements:");
      num = input.nextInt(); 

      //Creating array to store the all the numbers
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      //Loop to store each numbers in array
      for (counter = 0; counter < num; counter++)
          array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last )
      {
         if ( array[middle] < item )
           first = middle + 1;
         else if ( array[middle] == item )
         {
           System.out.println(item + " found at location " + (middle + 1) + ".");
           break;
         }
         else
         {
             last = middle - 1;
         }
         middle = (first + last)/2;
      }
      if ( first > last )
          System.out.println(item + " is not found.\n");
   }
}
Output 1:

Enter the number of elements:
7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

Mutable classes are the classes that are being prepared can change its internal state anytime without any issue. Also, it can change the state even after it has been already developed. The classes here are not the ones that are actually mutable. But the object that consists inside it, they are actually the mutated ones. Until we can prevent it from any change after it has been developed. It also depends strongly on the language that is being used.

Abstraction is basically used to separate the useless data from the essential ones. Only the important things that need to be shown to the users are only being exposed. Here in these issues, the users get to view only the essential data which is actually required. It also helps in differentiating the object from any other similar object just by looking into the classification of features. It is a really efficient process of filtering.

HashMap in Java works on hashing principles. Hashing is a process in which hash functions are used to link key and value in HashMap.

A factorial program using recursion in JAVA is as follows:

class FactorialExample2{  
 static int factorial(int n){    
  if (n == 0)    
    return 1;    
  else    
    return(n * factorial(n-1));    
 }    
 public static void main(String args[]){  
  int i,fact=1;  
  int number=4;//It is the number to calculate factorial    
  fact = factorial(number);   
  System.out.println("Factorial of "+number+" is: "+fact);    
 }  
}

Operator overloading allows doing something extra than what it is expected for. Java only allows arithmetic operations. Operator overloading allows multiple meanings for the same operator which will make things more confusing and messy.

Java doesn't support operator overloading due to its simplicity. Every operator has a specific meaning with its arithmetic operation it performs.

    Several ways to avoid memory leaks in Java are as follows:
  1. Release the session when it is no longer needed. Use the HttpSession.invalidate() to do this.
  2. Keep the time-out time low for each session.
  3. Store only the necessary data in your HttpSession.
  4. Avoid using string concatenation. Use StringBuffer’s append() method because the string is an unchangeable object while string concatenation creates a lot of unnecessary objects. A large number of temporary objects will slow down performance.
  5. As much as possible, you should not create HttpSession on your JSP page. You can do this by using the page directive <%@page session=” false”%>.
  6. If you are writing a query that is frequently executed, use the PreparedStatement object rather than using the Statement object. Why? PreparedStatement is precompiled while Statement is compiled every time your SQL statement is transmitted to the database.
  7. When using JDBC code, avoid using “*” when you write your query. Try to use the corresponding column name instead.
  8. If you are going to use stmt = con.prepareStatement(SQL query) within a loop, then be sure to close it inside that particular loop.
  9. Be sure to close the Statement and ResultSet when you need to reuse these.
  10. Close the ResultSet, Connection, PreparedStatement, and Statement in the finally block.
    To create a synchronized collection from a given collection follow detailed Steps:
  • Step 1: Create an ArrayList
  • Step 2: Populate the ArrayList with elements, with add(E e) API method of ArrayList
  • Step 3: Invoke the synchronized list(List list) API method of Collections to get the synchronized list from the provided ArrayList

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.

The differences between The hashCode() method and The equals() method are as follows:

The hashCode() methodThe equals() method
The hashCode() method The hashCode() method returns an integer value, which is referred to as the hash code value of an object. Every Object, at the time of creation assigned with a unique 32-bit, signed int value. This value is the hash code value of that object. The hashCode() method should return the same integer value for the same object for each calling of this method unless the value stored in the object is modified. If two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects. But, it is not necessary that the hashCode() method will return the distinct result for the objects that are not equal (according to equals() method).The equals() method The equals() method of Object class checks the equality of the objects and accordingly it returns true or false. The default implementation, as provided by the Object class, checks the equality of the objects on the basis if both references refer to the same object. It does not check the value or state of the objects. But we can override this method to provide our own implementation to compare the state or value of the objects. For any non-null reference variables a, b and c a.equals(a) should always return true. a.equals(b) should return true if and only if b.equals(a) returns true. If a.equals(b) returns true and b.equals(c) returns true then a.equals(c) should return true. Multiple calling of a.equals(b) should consistently return true or consistently return false If the value of the object is not modified for either object. a.equals(null) should return false.

Dependency injection is way to pass one obeject dependencies to another object.It is a broader form of inversion of control (IOC).

There are basically 3 types of dependency injection:

  • constructor injection
  • setter injection
  • Interface injection

Click Here to Read More 100 Questions on Laravel 5 & 6

The differences between String buffer and String builder are as follows:

No.StringBufferStringBuilder
1)StringBuffer is synchronized.StringBuilder is non-synchronized.
1)StringBuffer is thread-safe.StringBuilder is not thread-safe.
1)Two threads can't call the methods of StringBuffer simultaneously.Two threads can call the methods of StringBuilder simultaneously.
2)StringBuffer is less accomplished than StringBuilder.StringBuilder is more accomplished than StringBuffer.

The four pillars of the OOPs are:

  • Abstraction: Abstraction is basically used to separate unwanted things from the essential ones. Only important properties.
  • Encapsulation: The encapsulation process consists of certain methods and properties of the abstraction process. It also protects these methods from any interference or tampering.
  • Inheritance: Inheritance is of two types basically: single inheritance & multiple inheritances. It is how a class is derived from the other class.
  • Polymorphism: Here in polymorphism, you can name it all the same for the different actions of an object of different data types.

The abstract function or method does not have a body and also it cannot be implemented. The abstract classes cannot be started without the help of the subclasses that help in providing the implementations which are actually for the abstract methods. They actually try developing base classes which help in the custom implementation. The keyword abstract can be used to denote both the abstract methods and also an abstract class.

There are basically four types of storage classes in Java:

  • Automatic storage class: When a variable that is used in the coding is defined within a function and that also with the auto specifier then it simply belongs to this storage class.
  • Register storage class: Those variables in the coding which are declared by the register specifier then it belongs to this storage class.
  • Static storage class: It has a function to declare the variable with the help of the static specifier and that is how it belongs to the static storage class.
  • External storage class: The main objective with this is that the variable which is being declared consists of external linkage.

A JAVA program to generate Fibonacci series is as follows:

import java.util.Scanner;
public class Fibonacci 
{
    public static void main(String[] args) 
    {
        int n, a = 0, b = 0, c = 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the value of n: ");
        n = s.nextInt();
        System.out.print("Fibonacci Series: ");
        for(int i = 1; i <= n; i++)
        {
            a = b;
            b = c;
            c = a + b;
            System.out.print(a+" ");
        }
    }
}
Compile: $ javac Fibonacci.java
Run: $ java Fibonacci
Output:
Enter the value of n: 5
Fibonacci Series: 0 1 1 2 3

Garbage collection is the process of automatically managing memory in java. It is helpful to finds the unused objects that are no longer used by the program and deletes or remove them to free up the memory. The internal structure of the garbage collection mechanism uses several GC algorithms. It works with the most popular algorithm such as Mark and Sweep. Garbage collection is controlled by a thread known as Garbage Collector.

In Java, System.gc() and Runtime.gc() are two methods that sends requests to the JVM for garbage collection. It totally depends on the JVM. If the Heap Memory is full, the JVM will not allow creating a new object and shows an error java.lang.OutOfMemoryError. When the garbage collector removes the object from the memory, first, the garbage collector thread calls the finalize() method of that object and then remove it.

Difference between throw and throws are:

ThrowThrows
It is basically used inside the function. It is used when it needs to insert the exception.It is basically present in the function signature. Here if the functions have the same statements then it can result in certain exceptions.
It is used to basically use the exception. It can throw only a single exception at ones.Here multiple exceptions can be thrown and then whichever matches are thrown automatically.
The exception which is been thrown cannot be checked here.Here for the propagation purpose, the throws can use the throw keyword. Here it can use the specific exception class.

C program to Check String is Palindrome without using a loop is as follows:

/*
 * C program to find the length of a string without using the
 * built-in function also check whether it is a palindrome
 */
#include <stdio.h>
#include <conio.h>
 
void main()
{
    char string[25], reverse_string[25] = {'\0'};
    int i, length = 0, flag = 0;
 
    printf("Enter a string: ");
    gets(string);
    /*  keep going through each character of the string till its end */
    for (i = 0; string[i] != '\0'; i++)
    {
        length++;
    }
    printf("The length of the string '%s' = %d\n", string, length);
    for (i = length - 1; i >= 0 ; i--)
    {
        reverse_string[length - i - 1] = string[i];
    }
   /*  Check if the string is a Palindrome */
 
    for (flag = 1, i = 0; i < length ; i++)
    {
        if (reverse_string[i] != string[i])
            flag = 0;
    }
    if (flag == 1)
       printf ("%s is a palindrome \n", string);
    else
       printf("%s is not a palindrome \n", string);
}

Output:
Enter a string: how  are you
The length of the string 'how  are you' = 12
how  are you is not a palindrome
 
Enter a string: madam
The length of the string 'madam' = 5
madam is a palindrome
 
Enter a string: mam
The length of the string 'mam' = 3
mam is a palindrome

The static keyword indicates that the particular member belongs to a type itself, rather than to an instance of that type in the Java programming language.

The differences between JAVA and C are as follows:

S. N.CJava
1C is a Procedural Programming Language.Java is an Object-Oriented language.
2C was developed by Dennis M. Ritchie in 1972.Java language was developed by James Gosling in 1995.
3It is a middle-level language as it is binding the gaps between machine level and high-level languages.It is a high-level language because the translation of code is taken place into machine language, which uses a compiler or interpreter.
4The C declaration variable is declared at the beginning of the block.In Java, you can declare a variable anywhere.
5Free is a variable used for freeing the memory in C.A compiler will free up the memory by calling the garbage collector.
6C generally breaks down to functions.Java breaks down to Objects.
7C support pointers.Java does not support pointers.
8Memory allocation can be done by malloc.Memory allocation can be done by a new keyword.
9The garbage collector needs to manage manually.In Java, it is automatically managed by a garbage collector
10C does not have a feature of overloading functionality.Java supports method overloading.
11C support for call by value and call by reference.Java only supports a call by value.
12C is a platform-dependent language.Java is a platform-independent language.
13C does not support Multithreading.Java supports the concept of Multithreading.
14It is not portable.It is portable.
15Exception handling cannot be directly achieved in C.Exception Handling is supported in Java.

StringBuffer is better than string because StringBuffer is faster than String when performing simple concatenations.

Exception chaining is also known as exception wrapping. It is an object-oriented programming technique for handling exceptions by re-throwing a caught exception after wrapping it inside a new exception. The original exception is saved as property such as the cause of the new exception. In an application, Chained Exception helps to identify a situation in which one exception causes another Exception. For instance, Consider the I/O error: A method that throws an ArithmeticException because of an attempt to divide by zero but that caused the divisor to be zero.

OutOfMemoryError is an exception that is a runtime error thrown in the JAVA programming application when there is insufficient space to allocate an object in the Java heap.

The differences between the final and finally are as follows:

S. N.finalfinally
1A final method can't be overridden.It ensures that the code inside that block is executed no matter what happens in try and catch blocks. 
2The final variable value can't be changed.Only “System.exit()” can stop finally from being executed.
3The final class can't be inherited,finally is an optional block that is used together with try-catch blocks.
4The final keyword is used to apply restrictions on class, method, and variable. Finally is used to place important code, it will be executed whether an exception is handled or not.

Exception in Java is basically an event that takes place all of a sudden. This is really unexpected and also unwanted. Mostly it happens when the program is ready to execute and during the runtime, it can break the normal and easy flow of the program. These exceptions can be also called errors. At a time when the error occurs the method which is present there sets an object which is then sent to the runtime process.

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.

Like Iterator and ListIterator, Spliterator is also a Java Iterator, which is used to iterate elements one-by-one from a List implemented object. Java Spliterator is one of the four iterators among Enumeration, Iterator, ListIterator, and Spliterator. Java Spliterator is an interface in Java Collection API. Spliterator is introduced in Java 8 release in java. util package and it supports Parallel Programming functionality.

Iterators in java provide us the fluency to traverse over the collection objects. Iterators restored by the collection in nature are fail-fast or fail-safe. Fail-Fast iterators promptly throw ConcurrentModificationException if a collection is adjusted while iterating over it.

Bytecode is a computer program code that has passed through compilation from source code to machine code. The code produced after it is compiled is easily recognized by the microprocessor. There are different types of byte code such as Java byte code and these byte codes make use of distinct syntax. A virtual machine like the JVM in full, Java Virtual Machine has the capability of executing a byte code. It is on this machine that a java byte code can run on.

In Java, semaphore manages access to a shared resource by the use of a counter and if the counter is bigger than zero, then access is granted else if it is zero, then access is refused. What the limiter is counting are permits that allow access to the shared resource. Thus, to obtain the resource, a thread must be granted a permit from the semaphore. Technically, to use a semaphore, the thread that needs access to the shared resource attempts to acquire a permit.

The string is Immutable in Java language for certain reasons. One of the reasons for doing so is due to the fact that every string object is cached in the String pool. There is a risk associated because of multi-sharing of string literals among many clients as an action of a particular client affect other clients. To reduce this risk of compromising string class and to optimize performance, a string has to be immuted in java. Because of the importance and popularity of strings just like the HashMap, it is vital for the strings to be immutable as a mutable string can give two distinct hash codes.

If a class has no modifier (the default, also known as package-private), it is visible only within its own package.