JAVA basics Interview Questions And Answers


Are you gearing up for a Java basics interview and want to ace it? We’ve got you covered with a comprehensive guide to help you navigate through common JAVA basics Interview Questions.

Understanding the Basics:

In any Java interview, it’s crucial to have a solid grasp of the fundamentals. Expect questions on data types, variables, and operators. Be prepared to showcase your knowledge of Java’s object-oriented programming principles, including encapsulation, inheritance, and polymorphism.

Memory Management:

Memory management is a critical aspect of Java development. Interviewers often inquire about the garbage collection mechanism. Understand how Java’s automatic garbage collector works, and be ready to discuss the significance of the finalize() method.

Exception Handling:

Exception handling is integral to writing robust Java code. Brush up on the try, catch, and finally blocks. Expect questions on checked and unchecked exceptions, and be ready to explain the importance of the throws clause in method signatures.

Java Collections Framework:

Demonstrate your proficiency in Java’s Collections Framework. Discuss the differences between List, Set, and Map interfaces. Explain when to use ArrayList versus LinkedList and elucidate the importance of the equals() and hashCode() methods when dealing with collections.

Multithreading:

Java’s multithreading capabilities are often a focal point in interviews. Be prepared to discuss the Thread class, synchronization, and the volatile keyword. Showcase your understanding of the wait(), notify(), and notifyAll() methods and their role in managing thread synchronization.

String Handling:

String manipulation is a common task in Java development. Expect questions on the immutability of Strings and delve into the StringBuilder and StringBuffer classes. Be ready to explain the significance of the intern() method and its impact on memory usage.

Java Virtual Machine (JVM):

Understand the role of the Java Virtual Machine in executing Java programs. Be prepared to discuss the differences between the heap and the stack, and explain the purpose of the JVM Garbage Collector.

Networking in Java:

For positions involving network programming, expect questions on Java’s networking capabilities. Be ready to discuss the Socket and ServerSocket classes and understand how to establish a connection between client and server applications.

In conclusion, mastering these JAVA basics interview questions will undoubtedly give you a competitive edge. Remember to not only provide correct answers but also showcase a deep understanding of the underlying concepts. Good luck with your interview! also view this Java coding interview questions

1 . What are the differences between C++ and Java Basics?

  • Concept.

C++ is not platform-independent; the principle behind C++ programming is “write once, compile anywhere.”

In contrast, because the byte code generated by the Java compiler is platform-independent, it can run on any machine, Java programs are written once and run everywhere.

Also Read: Learn C++ Programming

  • Languages Compatibility.

C++ is a programming language that is based on the C programming language. Most other high-level languages are compatible with C++.

Most of the languages of Java are incompatible. Java is comparable to those of C and C++.

  • Interaction with the library.

It can access the native system libraries directly in C++. As a result, it’s better for programming at the system level.

Java’s native libraries do not provide direct call support. You can use Java Native Interface or access the libraries.

  • Characteristics.

C++ distinguishes itself by having features that are similar to procedural and object-oriented languages. The characteristic that sets Java apart is automatic garbage collection. Java doesn’t support destructors at the moment.

  • The semantics of the type.

Primitive and object types in C++ have the same kind of semantics. The primitive and object and classes of Java, on the other hand, are not consistent.

  • In the context of Compiler and Interpreter.

Java refers to a compiled and interpreted language. In contrast, C++ is only a compiled language.

Also, in Java, the source code is the compiled output is a platform-independent byte code.

In C++, you can compile the source program into an object code that further executes to produce an output.

2 . List the features of the Java Basics Programming language?

A few of the significant features of Java Programming Basics Language are:

Easy: Java is a language that is easy to learn. One fundamental concept of OOP Java has a catch to understand.

Secured Feature: Java has a secured feature that helps develop a virus-free and tamper-free system for the users.

OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in Java, you can consider everything an object.

Independent Platform: Java is not compiled into a platform-specific machine; instead, it is compiled into platform-independent bytecode. This code is interpreted by the Virtual Machine on which the platform runs.

3 . What do you get in the Java Basics download file? How do they differ from one another?

We get two major things along with the Java Download file. 

JDK – Java Development Kit

JRE – Java Runtime Environment

JDKJRE
Abbreviation for Java Development KitAbbreviation for Java Runtime Environment
JDK is a dedicated kit for solely software developmentJRE is a set of software and library designed for executing Java Programs
Unlike JVM, JDK is Platform DependentUnlike JVM, JRE is also Platform Dependent
JDK package is a set of tools for debugging and DevelopingJRE Package is one that only supports files and libraries for a runtime environment
JDK package will be provided with an installer fileJRE Package does not get an installer but has only a runtime environment

4 . What is a ClassLoader in Java Basics?

A classloader in Java is a subsystem of Java Virtual Machine, that dedicates to loading class files when a you execute a program; ClassLoader is the first to load the executable file.

Java has Bootstrap, Extension, and Application classloaders.

5 . What are the Memory Allocations available in Java Basics?

Java has five significant types of memory allocations.

  • Class Memory
  • Heap Memory
  • Stack Memory
  • Program Counter-Memory
  • Native Method Stack Memory

6 . What are the differences between Heap and Stack Memory in Java Basics?

Stack memory in data structures is the amount of memory you allocate to each individual programme. It is a fixed memory space. Heap memory, in contrast, is the portion that you do not assign to the Java code. However, it will be available for use by the Java code when you require it, which is generally during the program’s runtime.

7 . Will the program run if we write static public void main?

Yes, the program will successfully execute if written so. Because, in Java, there is no specific rule for the order of specifiers

8 . What is an Association?

You can define an association as a relationship that has no ownership over another. For example, a person can associate with multiple banks, and a bank can be related to various people, but no one can own the other.

9 . What do you mean by aggregation?

The term aggregation refers to the relationship between two classes best described as a “whole/part” and “has-a” relationship. This kind is the most specialised version of an association relationship. It contains the reference to another class and thus has ownership of that class.

10 . Define Copy Constructor in Java Basics

A Copy Constructor in Java is a constructor that initialises an object through another object of the same class.

11 . What is a Marker Interface?

An empty interface in Java is a Marker interface. Serializable and Cloneable are some famous examples of Marker Interface.

12 . What is Object Cloning?

An ability to recreate an object entirely similar to an existing object is popular as Object Cloning in Java. Java provides a clone() method to clone a current object offering the same functionality as the original object.

13 . Can you say Java is the complete object-oriented programming language?

No, Java cannot be treated as a complete object-oriented programming language.

14 . What is an object-oriented paradigm?

A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data that is in the form of fields, and regulation, that is in the form of procedures. The exciting feature of this paradigm is that the object’s procedures can access and often modify the data fields themselves.

15 . Define Wrapper Classes in Java Basics

In Java, when you declare primitive data types, then Wrapper classes are responsible for converting them into objects(Reference types).

16 . What is a singleton class in Java Basics? And How to implement a singleton class?

A class that can possess only one object at a time is a singleton class. To implement a singleton class, follow the given steps:

  1. Make sure that the class has only one object
  2. Give global access to that object

17 . What platforms does the Java Basics programming language support?

Java runs on several platforms. Some of these are Windows, macOS and popular instances of Linux/UNIX. The choice of a running environment may depend on the programming task. For instance, UNIX environments may be suitable when programming UNIX applications.

18 . Is Java architectural-neutral?

Java’s binary is platform independent. Different processors in various systems can run Java applications without having pre-compiled the code themselves. This feature makes the Java system executable in any environment.

19 . What do you consider when creating an exception in Java Basics?

If creating an exception, I consider the parent relationship. This consideration allows me to define each child as a “throwable” exception class. Programmers can handle or declare rules automatically to enforce checked exceptions by extending the exception class. Similarly, to write a runtime exception, programmers can customise the RunTimeException class.

20 . Can you explain encapsulation?

Encapsulation is the practice of wrapping variables and coding logic in certain methods. When encapsulating in Java, the fields in a class become private, providing access only through methods. This process effectively hides data fields from anything outside the class.

21 . What are the features of an interface?

In Java, an interface is an abstract type that specifies the behaviour of a class. Features of an interface include the absence of constructors. All methods within it are blueprints of the class behaviour and are also uninstantiated.

22 . Why would you use a “package” in Java Basics?

Java constructed packages by gathering sub-packages, classes and interfaces. Programmers can use a package to make searching easier, prevent naming conflicts and provide controlled access to similar behaviour. Packages offer a form of encapsulation.

23 . Can you define JAR file and WAR file?

JAR and WAR are archive files. JAR stands for Java Archive File, and WAR stands for Web Archive File. JAR files aggregate Java classes and metadata that programs require to execute Java applications, while WAR contains web application files, such as HTML and JavaScript.

24 . What is a final class?

The final keyword in java finalises the implementation of classes and other variables. This finalisation means the variables are unalterable. In a final class, a method the class implements is constant, meaning it ensures the behaviour and implementation of the class are immutable.

25 . What are constructors in Java?

In Java, constructor refers to a block of code which you use to initialise an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when you create an object.

There are two types of constructors:

  1. Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialise the instance variables with the default values. Also, it is majorly works for object creation. 
  2. Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initialising the instance variables with the provided values. In other words, the constructors which take the arguments are popular as parameterized constructors.

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

Array ListVector
Array List is not synchronized.Vector is synchronized.
Array List is fast as its non-synchronized.Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%.Vector defaults to doubling the size of its array.
Array List does not define the increment size.Vector defines the increment size.
Array List can only use Iterator for traversing an Array List.Vector can use both Enumeration and Iterator for traversing.

27 . When can you use the super keyword?

In Java, the super keyword is a reference variable that refers to an immediate parent class object.

When you create a subclass instance, you’re also creating an instance of the parent class, which is referenced to by the super reference variable.

The uses of the Java super Keyword are- 

  1. To refer to an immediate parent class instance variable, use super.
  2. The keyword super can be used to call the method of an immediate parent class.
  3. Super() can be used to call the constructor of the immediate parent class.

28 . What is the importance of reflection in Java?

Reflection is a runtime API for inspecting and changing the behaviour of methods, classes, and interfaces. Java Reflection is a powerful tool that can be really beneficial. Java Reflection allows you to analyse classes, interfaces, fields, and methods during runtime without knowing what they are called at compile time. Reflection can also be used to create new objects, call methods, and get/set field values. External, user-defined classes can be used by creating instances of extensibility objects with their fully-qualified names. Debuggers can also use reflection to examine private members of classes.

29 . How to not allow serialisation of attributes of a class in Java?

The Non-Serialized attribute can be used to prevent member variables from being serialised.

You should also make an object that potentially contains security-sensitive data non-serializable if possible. Apply the Non-Serialized attribute to certain fields that store sensitive data if the object must be serialized. If you don’t exclude these fields from serialization, the data they store will be visible to any programs with serialization permission.

30 . Explain the term “Double Brace Initialization” in Java?

Double Brace Initialization is a Java term that refers to the combination of two independent processes. There are two braces used in this. The first brace creates an anonymous inner class. The second brace is an initialization block. When these both are used together, it is known as Double Brace Initialization. The inner class has a reference to the enclosing outer class, generally using the ‘this’ pointer. It is used to do both creation and initialization in a single statement. It is generally used to initialise collections. It reduces the code and also makes it more readable.

31 . Why is it said that the length() method of String class doesn’t return accurate results?

The length() method of String class doesn’t return accurate results because

it simply takes into account the number of characters within the String. In other words, code points outside of the BMP (Basic Multilingual Plane), that is, code points having a value of U+10000 or above, will be ignored.

The reason for this is historical. One of Java’s original goals was to consider all text as Unicode; yet Unicode did not define code points outside of the BMP at the time. It was too late to modify char by the time Unicode specified such code points.

32 . Why pointers are not used in Java?

Java doesn’t use pointers because they are unsafe and increase the complexity of the program. Since Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.

33 . What is a JIT compiler in Java?

JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.

34 . What are the main concepts of OOPs in Java?

Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

  1. Inheritance: Inheritance is a process where one class acquires the properties of another.
  2. Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
  3. Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. 
  4. Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.

35 . What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor.

this()super()
1. this() represents the current instance of a class1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the same class2. Used to call the default constructor of the parent/base class
3. Used to access methods of the current class3. Used to access methods of the base class
4.  Used for pointing the current class instance4. Used for pointing the superclass instance
5. Must be the first line of a block5. Must be the first line of a block

36 . Difference between String, StringBuilder, and StringBuffer.

FactorStringStringBuilderStringBuffer
Storage AreaConstant String PoolHeap AreaHeap Area
MutabilityImmutableMutableMutable
Thread Safetyyesno yes
Performancefast More efficientLess efficient

37 . What do you understand about an instance variable and a local variable?

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost.

All the objects of the class will have their copy of the variables for utilisation. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Example:

class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilisation of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.

Example:

public void athlete() {
String athleteName;
double athleteSpeed;
int athleteAge;
}

38 . How is an infinite loop declared in Java?

Infinite loops are those loops that run infinitely without any breaking conditions. Some examples of consciously declaring infinite loop is:

  • Using For Loop:
for (;;)
{
   // Business logic
   // Any break logic
}

Using while loop:

while(true){
   // Business logic
   // Any break logic
}

Using do-while loop:

do{
   // Business logic
   // Any break logic
}while(true);

39 . What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects.

  • This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

Using relevant properties highlight the differences between interfaces and abstract classes.

  • Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
  • Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
  • Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
  • Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
  • Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Abstract class example:

public abstract class Athlete {
public abstract void walk();
}
Interface example:
public interface Walkable {
void walk();
}

40 . What is a Comparator in java?

Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. Now if we want to sort this list of employees based on the names of employees. Then that is not possible to sort using the Collections.sort() method. We need to provide something to the sort() function depending on what values we have to perform sorting. Then in that case a comparator is used.

Comparator is the interface in java that contains the compare method. And by overloading the compare method, we can define that on what basis we need to compare the values.

41 . What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronised and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet.

  • Implementation: For a HashSet, the hash table is utilised for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner.
  • Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortised complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet.
  • Methods: hashCode() and equals() are the methods utilised by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilised by TreeSet to facilitate object comparisons.
  • Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects.

42 . Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed.

As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

43 . What is JDBC?

JDBC is an abbreviation for Java Database Connector.

JDBC is an abstraction layer used to establish connectivity between an existing database and a Java application

44 . What are the observer and observable classes?

Objects that inherit the “Observable class” take care of a list of “observers.” 

When an Observable object gets upgraded, it calls the update() method of each of its observers. 

After that, it notifies all the observers that there is a change of state. 

The Observer interface gets implemented by objects that observe Observable objects.

45 . What is Session Management in Java?

A session is essentially defined as the random conversation’s dynamic state between the client and the server. The virtual communication channel includes a string of responses and requests from both sides. The popular way of implementing session management is establishing a session ID in the client’s communicative discourse and the server.

46 . Briefly explain the term Spring Framework.

Spring is essentially defined as an application framework in Java and inversion of control containers for Java. The spring framework creates enterprise applications in Java. Especially useful to keep in mind that the spring framework’s central features are essentially conducive to any Java application.

47 . What is JCA in Java?

Java Cryptography Architecture gives a platform and provides architecture and application programming interfaces that enable decryption and encryption. 

Developers use Java Cryptography Architecture to combine the application with the security applications. Java Cryptography Architecture helps in implementing third party security rules and regulations. 

Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.

48 . Explain JPA in Java.

The Java Persistence API enables us to create the persistence layer for desktop and web applications. Java Persistence deals in the following:

  1. Java Persistence API
  2. Query Language
  3. Java Persistence Criteria API
  4. Object Mapping Metadata

49 . Explain the different authentications in Java Servlets.

Authentication options are available in Servlets: There are four different options for authentication in servlet:

  • Basic Authentication: 

Usernames and passwords are given by the client to authenticate the user.

  • Form-based authentication: 

In this, the login form is made by the programmer by using HTML.

  • Digest Authentication: 

It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula makes digestion more secure.

  • Client certificate Authentication:

It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client Authentication requires the SSL protocol.

50 . Write a program to find the square root of a number

The Square root of a number can be found by using the following program.

import java.util.Scanner;

public class SquareRootCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input: Get the number from the user
        System.out.print("Enter a number to find its square root: ");
        double userInput = scanner.nextDouble();

        // Calculate square root
        double squareRoot = Math.sqrt(userInput);

        // Display the result
        System.out.println("Square root of " + userInput + " is: " + squareRoot);

        // Close the scanner
        scanner.close();
    }
}

51 . Write a program that detects the duplicate characters in a string.

The program that finds the duplicate elements in a string is written below:

package interviewpitchJava;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class FindDuplicate {
public static void main(String args[]) {
printDuplicateCharacters("interviewpitch");
}
public static void printDuplicateCharacters(String word) {
char[] characters = word.toCharArray();
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
for (Character ch : characters) {
if (charMap.containsKey(ch)) {
charMap.put(ch, charMap.get(ch) + 1);
} else {
charMap.put(ch, 1);
}
}
Set<Map.Entry<Character, Integer>> entrySet = charMap.entrySet();
System.out.printf("List of duplicate characters in String '%s' %n", word);
for (Map.Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.printf("%s: %d %n", entry.getKey(), entry.getValue());
}
}
}
}
Expected output:
List of duplicate characters in String 'interviewpitch' 
i: 2 
l: 2

Write a Java program to reverse a given string.

52 . Write a java program to reverse a given string .

public class ReverseString {
    public static void main(String[] args) {
        String original = "Hello, World!";
        
        // Using StringBuilder
        String reversed = reverseWithStringBuilder(original);
        System.out.println("Reversed String (using StringBuilder): " + reversed);
        
        // Using iterative approach
        reversed = reverseIteratively(original);
        System.out.println("Reversed String (iteratively): " + reversed);
    }

    // Using StringBuilder
    private static String reverseWithStringBuilder(String str) {
        return new StringBuilder(str).reverse().toString();
    }

    // Iterative approach
    private static String reverseIteratively(String str) {
        char[] characters = str.toCharArray();
        int start = 0;
        int end = str.length() - 1;

        while (start < end) {
            // Swap characters at start and end indices
            char temp = characters[start];
            characters[start] = characters[end];
            characters[end] = temp;

            // Move indices towards each other
            start++;
            end--;
        }

        return new String(characters);
    }
}

Explanation 

  • The program defines a string original that we want to reverse.
  • Two methods are provided to reverse the string: one using StringBuilder and the other using an iterative approach.
  • The reverseWithStringBuilder method utilizes StringBuilder’s reverse method to efficiently reverse the string.
  • The reverseIteratively method iterates through the characters of the string, swapping characters at the start and end indices until they meet in the middle.

53 . Write a Java program to calculate the factorial of a number.

public class Factorial {
    public static long calculateFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * calculateFactorial(n - 1);
        }
    }

    public static void main(String[] args) {
        int number = 5;
        long factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Write a Java program to find duplicate elements in an array.

54 . Write a java program to find duplicate element in an array.

import java.util.HashSet;
import java.util.Set;

public class FindDuplicates {
    public static void findDuplicates(int[] array) {
        Set<Integer> uniqueElements = new HashSet<>();
        Set<Integer> duplicates = new HashSet<>();

        for (int num : array) {
            if (!uniqueElements.add(num)) {
                duplicates.add(num);
            }
        }

        System.out.println("Duplicate elements: " + duplicates);
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 2, 5, 6, 3};
        findDuplicates(numbers);
    }
}