Java Technical Interview Questions

Java Technical Interview Questions

Core Java, Collection, Java 8, Advanced Java

·

19 min read

  1. What is JDK, JRE, JVM and JIT?
    JDK: is Java Development Kit. It is a full-featured software development kit required to develop Java applications and applets. It includes the JRE (Java Runtime Environment), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed for Java development. It’s used by developers for writing and compiling Java programs. (Compiler)
    JRE: is Java Runtime Environment. It provides the libraries, Java Virtual Machine (JVM), and other components to run Java applications. It doesn’t include tools for Java development like compilers. It’s used by end-users who just want to run Java applications.
    JVM: It converts bytecode (compiled Java code) into machine code that your computer's hardware can execute. It allows Java programs to be platform-independent, meaning you can run the same Java program on any device that has a JVM. (Interpreter)
    JIT: is Just In Time compiler. component of the JVM that improves the performance of Java applications. It combines the benefits of both interpretation and compilation, leading to optimized performance. Eg: JIT interprets a method once, if the same method is repeating again, it won’t interpret again. Instead it uses the already interpreted one before, thus saving time.

  2. What are variables? What are its types?

    A variable is a named location in memory that stores a value.(name of a memory address) In Java, variables can be declared and initialized in several ways.

    There are three types of variables in Java:

    1. Local: (defined within a block)

    2. Instance: (defined inside a class, outside a method)

    3. Static: (accessible by all methods of a class)

  3. What is the local variable? What is an instance variable? A local variable is declared inside a method or a block.(temporary variable) It can be used / accessed only within the method or block in which it is declared.(Local variables cannot be unassigned because there is no default value for local variables) An instance variable is declared inside a class but outside of any method. It is accessible to all the methods of the class.

  4. Difference between static and instance variable.

    • A static variable is declared with the static keyword. It is shared by all the instances of the class.

    • Static variables are also known as class variables. We don’t need an object to access static variable.

    • Static variables cannot be declared locally inside the method.

    • Static variables are good for memory management. Static keyword creates/allocates memory during compile time. Static variables can be called inside all static methods, if the methods are within the same class.

    • An instance variable is declared inside a class but outside of any method. It is accessible to all the methods of the class.(for object to object, different variable values in objects)
      Instance variables can be accessed only by creating objects.

    • We initialize instance variables using constructors while creating an object.

    • We may use access specifiers for instance variables. If not used, then it will be default.

  5. What are data types? How many types?
    Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

    • Primitive data type

    • Non-primitive data type

  6. Primitive and non-primitive data types.

    Primitive data types are the eight basic data types in Java: boolean, char, byte, short, int, long, float, and double.

    Non-primitive data types are objects that are created using classes. They include classes, objects, interfaces, arrays, and strings.

    To Calculate range:

    -(2n-1) to +(2n-1-1)

    where ‘n’ is bits

    Java by default takes all numeric values as integers.

  7. What is Java's primitive unsigned integral type?
    char is the only unsigned primitive integral type. Unsigned means it can have only +ve values. Other integral types like byte, short, int and long have -ve values. char ranges from 0 to 65535.

  8. What are conditional statements?
    Conditional statements are used to make decisions in a program. It allows us to execute code based on whether a certain condition is true or false. There are two main types of conditional statements in Java:

    1. if statements (if, if else, if else if ladder, nested if)

    2. switch statements.

  9. Features of Java.

    • Simple & easy to learn syntax (Automatic Garbage Collection)

    • Object Oriented (inheritance, polymorphism, abstraction, encapsulation, class & objects)

    • Platform Independent (run on different OS - Write Once Run Anywhere)

    • Secured (runs inside JVM, others cannot read bytecode)

    • Robust (strong memory mgmt, exception handling & type checking,no pointers)

    • Portable (carry byte code to other platforms OS)

    • High performance (byte code is similar to native code, due to JIT which interprets line by line & not repeat same method again)

    • Multithreaded (shares a common memory area, execute concurrently)

    • Dynamic (dynamic loading of classes, load classes on demand)

    • Distributed applications(RMI & EJB)

    • Architecture-neutral (fixed memory size, support all architectures)

    • Open source

  10. What are classes and objects?

    A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical (don’t have memory). A class encapsulates the data and the methods that operate on that data.

    Class is a combination of state and behavior. It is a keyword. It does not need memory allocation.

    State: variables and values

    Behavior: methods using that variables and values

    Object is a real time entity. It is a combination of state and behavior. It has both a logical and physical view. It has memory allocation.

    A class can contain:

    1. Methods

    2. Constructors

    3. Blocks

    4. Data types / Fields

    5. Interfaces and Nested classes

An object is an instance of a class. It is a variable for a class.

Classes and objects are essential building blocks of object-oriented programming. They allow us to create programs that are more organized, modular(flexible), and maintainable.

  1. Difference between jump and break statements.

    They are used to control the flow of a program. The break statement is used to terminate a loop or a switch statement. Jump or Continue statement is used to skip a section and jump to the end of the loop.

  2. What are methods in Java? What are its types?

    A method is a block of code or collection of statements to perform certain operations or a task when it is called. It provides the reusability of code. The method is executed only when we call or invoke it.

    There are two types of methods in Java:

    1) User defined method: The method written by the programmer is known as a user-defined method. These methods are modified according to the requirement.

    2) Pre-defined method: Methods that are already defined in the Java class libraries are known as predefined methods.

  3. What is method signature?

    A method signature refers to the unique identifier of a method. Method Signature consists of the method name(Name of method) and its parameter list(arguments), return type(int, string, void, etc), access modifiers(public, private, protected), non-access modifiers(static, final, abstract), exceptions(throws IOException).

  4. How to use a method?

    In the case of a user defined method, First we have to define a method to perform a certain operation. Then, to use that method, we have to call that method by passing the parameters or simply calling it using the method name.

  5. What is the difference between a method and a function?

    A method and a function are both blocks of code that are executed when they are called.

    Methods are called using objects. Functions don’t need references to call.

    Methods are used within the class. Functions can be used anywhere.

  6. What is method overloading?

    A class having multiple methods with the same name but different in parameters, it is known as Method Overloading.

  7. What is a constructor? Types of overloading constructors.

    A constructor is a block of codes similar to the method. It is called when an instance of the class is created. It is a special type of method which is used to initialize the object.

    It(JVM) calls a default constructor if there is no constructor available in the class. Java compiler provides a default constructor by default.

    (At the time of calling the constructor, memory for the object is allocated in the memory.)

    There are two types of constructors in Java:

    1. no-arg constructor

    2. parameterized constructor

Rues:

A Java constructor cannot be abstract, static, final, and synchronized

A Constructor does not have a return type

Constructor name must be the same as its class name

Purpose: To initialize objects with default values. To initialize the instance variable of the class. To inform about dependencies. In other words, using the constructor, we can request the user of that class for required dependencies.

  1. What is the ‘this’ keyword?

    this is a reference variable that refers to the current object.

    It is used to refer to the current instance variable.

    It is used in constructors to initialize object properties.

    this can be passed as an argument in the method call.

    this can be used to return the current class instance from the method.

  2. What is inheritance? What are its types?

    A class(sub-class) can acquire the properties and behaviors of its parent(base-class) class.

    We can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and data types of the parent(base) class. Moreover, we can add new methods and data types in our current class also.

    There are 5 types of inheritance:

    1. single inheritance

    2. multilevel inheritance

    3. hierarchical inheritance

    4. hybrid inheritance

    5. multiple inheritance

  3. Why is multiple inheritance not supported in java? Why do we use interface?
    If a class inherits from two classes that have the same method name, there is no way to know which method to call when the inherited method is invoked. It will create confusion/ambiguity.
    Interfaces are used to achieve multiple inheritance in Java. An interface can be implemented by multiple classes, and each class can provide its own implementation of the interface methods. This allows a class to inherit the functionality of multiple interfaces without having to worry about conflicts between the implementations.

  4. What is polymorphism? What are its types?

    We can perform a single action in different ways.

    There are two types of polymorphism in Java:

    1. Compile-time polymorphism

    2. Runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding.

Method overloading is an example of compile-time polymorphism.

Method overriding is an example of runtime polymorphism.

  1. What is method overriding?

    Methods having the same name and same number of parameters but are from different classes is known as method overriding. If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

  2. Why do we use the final keyword?

    The final keyword in java is used to restrict the user. We can use final keywords in:

    1. Variable

    2. Method

    3. Class

We cannot change the value of the final variable once it is initialized.

We cannot override the final method.

We cannot extend (inherit) a final class.

  1. Why do we use super keywords?

    Super keyword in Java is a reference variable which is used to refer to an immediate parent (base) class object. The instance of base class can be accessed in subclass by using super keyword.

  2. What is abstraction? Abstract classes and methods.

    Abstraction is a process of hiding the implementation details and showing only functionality to the user. A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body).

    There are two ways to achieve abstraction:

    1. Abstract class

    2. Interfaces

Rules: An abstract class must be declared with an abstract keyword. It can have abstract and non-abstract methods. It cannot be instantiated. We cannot create objects for abstract class. It can have constructors and static methods also. It can have final methods which will force the subclass not to change the body of the method.

  1. What is Encapsulation?

    Encapsulation in Java is a process of wrapping code and data together into a single unit. We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

    1. It provides you with control over the data.

    2. It is a way to achieve data hiding in Java because other classes will not be able to access the data through the private data members.

    3. The encapsulated class is easy to test. So, it is better for unit testing.

    4. It can improve the security and reliability of a program by preventing data from being accessed by outside code.

  2. What is Interface?

    The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body.

    1. It is used to achieve abstraction and multiple inheritance in Java.

    2. Java Interface also represents the IS-A relationship.

    3. It cannot be instantiated just like the abstract class.

    4. It can be used to achieve loose coupling.

  3. What are access modifiers?

    Access modifiers specify the accessibility or scope of a variable, method, constructor or class. We can change the access level of a class, variable or method using access modifiers. There are 4 types of access modifiers:

    1. private

    2. protected

    3. public

    4. default

  4. Difference between String and StringBuffer.

    | S No | String | StringBuffer | | --- | --- | --- | | 1) | The String class is immutable. | The StringBuffer class is mutable. | | 2) | String is slow and consumes more memory when we concatenate too many strings because every time it creates a new instance. | StringBuffer is fast and consumes less memory when we concatenate strings. | | 3) | String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. | StringBuffer class doesn't override the equals() method of the Object class. We need to use toString() along with equals to compare. | | 4) | String class is slower while performing concatenation operation. | StringBuffer class is faster while performing concatenation operations. | | 5) | String class uses String constant pool. | StringBuffer uses Heap memory. | | 6) | String is non-synchronized but Thread safe because immutable objects are thread safe. | StringBuffer is synchronized. So, it is Thread safe. |

  5. What is an anonymous array?
    An array without a name is known as an anonymous array. The main purpose of an anonymous array is just for instant use (just for one-time usage). Using an anonymous array, we can pass an array with user values without the referenced variable. An anonymous array is passed as an argument of a method.

  6. What are the types of arrays?

    • Single dimensional array

    • Multi dimensional array

  7. How many ways to clear garbage in java?

    • By Making Reference to object Null

    • By assigning a reference to another

    • By Using an anonymous object

    • finalize() method

    • gc() method

  8. Why are Strings immutable?

    • For security purposes (username, password, email are stored in String format)

    • To save heap space (String pool does not allow duplicates)

    • Thread safe, Multithreading purposes (All immutable objects are thread safe)

  9. What is Garbage collection in java?
    It is the process of reclaiming unused memory by destroying unused objects. If we forget to destroy useless objects, it will lead to memory leaks. After a certain point, memory won't be available to create new objects and the application will terminate due to out-of-memory errors.

  10. What are anonymous objects?
    An object that is created without giving it a name(nameless objects). Anonymous objects are often used in combination with inner classes, anonymous classes, and lambda expressions.

  11. Explain intern() method?
    String Interning is a method of storing only one copy of each distinct String Value, which must be immutable. Applying String.intern() on a couple of strings will ensure that all strings having the same contents share the same memory.

When the intern() method is executed, it checks whether the String equals to this String Object is in the pool. If it is available, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Creating an object is a costly operation in Java. Therefore, to save time, Java developers came up with the concept of String Constant Pool (SCP). The SCP is an area inside the heap memory. It contains unique strings. In order to put the strings in the string pool, one needs to call the intern() method. Before creating an object in the string pool, the JVM checks whether the string is already present in the pool or not. If the string is present, its reference is returned.

  1. What are the 2 types of exceptions?

    • Checked Exceptions (Compile time exceptions)

    • Unchecked exceptions (Runtime exceptions)

  2. What is multithreading?
    Multithreading in Java is a process of executing multiple threads simultaneously. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

    Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such a program is called a thread. So, threads are light-weight processes within a process. Threads can be created by using two mechanisms :

    1. Extending the Thread class

    2. Implementing the Runnable Interface

  3. What is an exception?
    An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.

Creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system attempts to find something to handle it.
The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack

  1. What is exception handling?

    Exception handling is a mechanism to handle errors to regulate the normal flow of the program.
    Compile time errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
    Run time errors like ArithmeticException, NullPointerException, NumberFormatException.

  2. What are the types of exception handling?
    1) Unchecked Exception: Checked ExceptionUnchecked exceptions are called run-time exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
    2) Checked exceptions: are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. For example, ClassNotFoundException, IOException, FileNotFoundException, etc.

  3. Difference between error and exception.
    Exceptions: is an event that occurs during the execution of the program and interrupts the normal flow of program instructions. It can be handled by using the try-catch block and throws keyword.

    NullPointerException: Thrown when a null reference is accessed.

    IOException: Thrown when an I/O operation fails.

    Arithmetic Exception: Exception during arithmetic operations. Errors: cannot be handled or caught. It occurs during runtime of the program. Errors are the problems that are outside the control of the program, such as running out of memory or a system crash.

    OutOfMemoryError: Thrown when the Java Virtual Machine (JVM) runs out of memory.

    StackOverflowError: Thrown when the call stack overflows due to too many method invocations.

    NoClassDefFoundError: Thrown when a required class cannot be found.

  4. Is it possible to declare a try without a catch block?
    Yes, it is possible to declare a try without a catch block. We can use finally or catch block. It is not mandatory that each try block must be followed by a catch block in Java. After a try block, we can use either “catch” block or “finally” block.

  5. In which order multiple catch blocks have to be given?
    All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception. The catch block that catches the exception class of higher-level is to be given at last in the order of catch blocks. If not, all the exceptions of the subclasses will be handled in the higher level catch block making the remaining (catch) blocks unreachable leading to a compile-time exception.

    Eg: Exception is the superclass of all the exception classes, if you place the catch block that catches it earlier to the catch blocks catching any other exceptions, all exceptions are handled in the Exception block itself making the remaining blocks unreachable.

  6. Difference between throw and throws keyword?

    | S No | Throw | Throws | | --- | --- | --- | | 1 | Java throw keyword is used to throw an exception explicitly in the code, inside the function or the block of code. | Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code. | | 2 | Type of exception Using throw keyword, we can only propagate unchecked exceptions i.e., the checked exception cannot be propagated using throw only. | Using throws keyword, we can declare both checked and unchecked exceptions. However, the throws keyword can be used to propagate checked exceptions only. | | 3 | throw is used within the method. | throws is used with the method signature. | | 4 | We are allowed to throw only one exception at a time i.e. we cannot throw multiple exceptions. | We can declare multiple exceptions using throws keyword that can be thrown by the method. |

  7. Difference between final, finally and finalize.

    1) final is an access modifier,used to apply restrictions on a class, method or variable. Final variable becomes constant and cannot be modified. Final method cannot be overridden by subclass. final class cannot be inherited.

    2) finally{ … } is the block in Exception Handling. Finally block is used to execute the important code whether the exception occurs or not. Finally block cleans up all the resources used in try block. Finally block is executed as soon as the try-catch block is executed.

    3) finalize() is the method of object class. Finalize is the method in Java which is used to perform clean up processing just before an object is garbage collected. Finalize method is executed just before the object is destroyed.

  8. What is a null pointer exception?
    NullPointerException is a RuntimeException. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Null is a special value used in Java. It is mainly used to indicate that no value is assigned to a reference variable.

  9. What is a number format exception?
    It is a RuntimeException. The NumberFormatException is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is not appropriate or illegal. By illegal format, it is meant that if you are trying to parse a string to an integer but the String contains a boolean value,(true or false) it is of illegal format.

  10. Why there is no Multiple Inheritance in Java?
    Inheritance is one of the four fundamental OOP concepts. It can be defined as a mechanism, by which one class acquires, all the properties and behaviors of another class. Java being an object oriented language does support inheritance. Though with in inheritance there are several types like-

    • Single inheritance

    • Multi-level inheritance

    • Multiple inheritance

    • Hierarchical inheritance

    • Hybrid inheritance

      → Multiple inheritance as the name suggests means inheriting from multiple sources, it may be classes or interfaces.

      → Out of these two sources Java doesn’t support multiple inheritance through classes. So you are not permitted to extend more than one class in Java. Though you can still implement several interfaces.

One of the reason given for omitting multiple inheritance in Java is to avoid “diamond problem” which is one of the classic multiple inheritance problem.

  1. Difference between a thread and a process.
    A thread is the subset of a process and is also known as the lightweight process.

    • Processes are heavily weighted. A process can have more than one thread, and these threads are managed independently by the thread scheduler.

    • Threads need to be synchronized in order to avoid unexpected scenarios.

    • In Process, a proper synchronization between processes is not required.

    • A thread cannot have its individual existence.

    • A process can exist individually as it contains its own memory and other resources.

    • All the threads within one process are interrelated to each other.

Did you find this article valuable?

Support Dhanush.K by becoming a sponsor. Any amount is appreciated!