Java Interview Questions and Answers

The  interview questions and answers will help you to prepare and gain more understanding of what you have learnt.  It will help you to prepare for your professional examiations and build your confidence when you want to attend an interview.  You are good to go and good luck.

Q1. What is Java?

A1. Java is an all-purpose high-level, robust, secure, object-oriented programming language, high-performance, Multithreaded, and portable programming language. It was developed by James Gossling in June 1991. Over three billion gadgets run on Java and it is platform-independent.

Q2. How to check the java version?

A2. Execute java -version on a command prompt/terminal.

 

Q3. What are the important Java Editions or Parts of Java?

A3. There are basically three Editions

– Java Standard Edition / Core Java
– Java Enterprise Edition / Advanced Java
– Java Micro Edition

 

Q4. What is a thread in Java?

A4. Threads is a memory management system that allows a program to operate more efficiently by doing multiple things at the same time.

Threads can be used to perform complicated tasks in the background without interrupting the main program.

It can be created by extending the Thread class and overriding its run() method:

Extend Syntax

1

2

3

4

5

public class Child extends Thread {

  public void run() {

    System.out.println(“This code is running in a thread”);

  }

}

 

Q5. How to take input in Java?

A5. “Scanner in = new Scanner(System.in);

      System.out.print(“”Please enter name: “”);

      int name = in.nextInt();

      System.out.print(“”Please enter age: “”);

      int age = in.nextInt();

      System.out.print(“”Please enter hobby 1: “”);

      int hobb1 = in.nextInt();

      System.out.print(“”Please enter hobby 2: “”);

      int hobb2 = in.nextInt();”

 

Q6. What are wrapper classes and what is their role in Java?

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

Q7. What is a transient variable? When will you use it?

A7. Transient variables are not used for Serialization. If you don’t want to make variable serializable, you can make it a transient variable. Serialization is the ​process of converting an object into a byte stream.

 

 

Q8. Explain public static void main(String args[]) in Java.

A8. main() is the entry point for any Java program. It is always written as public static void main(String[] args).

  • public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  • static: It is a keyword in java that identifies it as class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
  • void: It is the return type of the method. Void defines the method which will not return any value.
  • main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  • String args[]: It is the parameter passed to the main method.

 

Q9. What is JVM?

A9. Java Virtual machine (JVM) is the virtual machine that runs the Java bytecodes.
It enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes what is required in a JVM implementation.

 

Q10.  What is JRE?

A10. The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

 

Q11. What is the default value of the local variables?

A11. The local variables are not initialized to any default value, neither primitives nor object references.

 

Q12. What is JDK?

A12. Java Development Kit (JDK) is a superset of the JRE and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.

Q13. Why Java is platform-independent?

A13. Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system or hardware.

 

Q14. How to take input from users in java?

A14. “import java.util.Scanner;

  Scanner console = new Scanner(System.in);

  int num = console.nextInt();

  console.nextLine() // to take in the enter after the nextInt()

  String str = console.nextLine();”

Q!5. Why Java is not hundred percent Object-oriented?

A15. Java is not hundred percent Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.

 

Q16. What are constructors in Java?

A16. Constructor refers to a block of code that is used to initialize 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 an object is created.

There are two types of constructors:

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

Q17. What is a singleton class in Java and how can we make a class singleton?

A17. Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.

 

Q18.  How many types of memory areas are allocated by JVM?

A18. There are five types:

Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.

Heap: It is the runtime data area in which the memory is allocated to the objects

Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack: It contains all the native methods used in the application.

 

Q19. What is a classloader?

A19. Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the superclass of the Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java. util package classes, java.io package classes, java.sql package classes, etc.

 

Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.

 

System/Application ClassLoader: This is the child classloader of the Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using the “-cp” or “-classpath” switch. It is also known as the Application classloader.

Q20. Is Empty .java file name a valid source file name?

A20. Yes, Java allows us to save our java file by .java only, we need to compile it by javac .java and run by java class name Let’s take a simple example:

//save by .java only

class X{

public static void main(String args[]){

System.out.println(“Welcome java”);

}

}

//compile by javac .java

//run by     java X

compile it by javac .java

run it by java X

Q21.  Is delete, next, main, exit or null keyword in java?

No.

Q22. What if I write static public void instead of the public static void?

A22. The program compiles and runs correctly because the order of specifiers doesn’t matter in Java.

Q23.  What is enumeration in Java?

 

A23. Enumeration is a list of named constants In Java. It defines the class type. An Enumeration can have constructors, methods, and instance variables. It is created using the enum keyword. Each enumeration constant is public, static, and final by default. Even though enumeration defines a class type and has constructors, you do not instantiate an enum using new. Enumeration variables are used and declared in much the same way as you do a primitive variable.

 

Q24. What is a string in java?

A24. The string is a sequence of characters, for e.g. “Emma is a boy’. In java, the string is an immutable object which means it is constant and cannot be changed once it has been created.

 

Q25.  What do you mean by Overloading?

Q25.  Overloading is a situation where two or more different methods or operators have the same representation. For example, the + operator adds two integer values but concatenates two strings. Similarly, an overloaded function called Add can be used for two purposes

– To add two integers

– To concatenate two strings

Unlike method overriding, method overloading requires two overloaded methods to have the same name but different arguments. The overloaded functions may or may not have different return types.

 

Q26. What is an abstraction in Java?

A26.  Objects are the building blocks of Object-Oriented Programming which allows only the necessary characteristics to be exposed to the users. An object contains some properties and methods which allow programmers to hide its implementation from the interface so that users can see and interact with the interface. We can also hide them from the outer world through access modifiers. We can provide access only for required functions and properties to the other programs. This is the general procedure to implement abstraction in OOPS.

 

Q27.  What is a collection in java?

A27.  Collections are like containers that group multiple items in a single unit. For example, a box of oranges, a list of names, etc.

 

Q28.  What do you mean by Constructor?

A28.  A constructor is a method that has the same name as that of the class to which it belongs. As soon as a new object is created, a constructor corresponding to the class gets invoked. Although the user can explicitly create a constructor, it is created on its own as soon as a class is created. This is known as the default constructor. Constructors can be overloaded.

 

 

Q29.  What is the platform?

A29.  A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides a software-based platform.

 

Q30.  What gives Java its ‘write once and run anywhere nature?

A30.  The bytecode is not platform-specific and can be executed on any platform. Java compiler converts the Java programs into the class file which is the bytecode an intermediate language between source code and machine code. Therefore, Java can run on any computer.

Q31.  What are the various access specifiers or scopes in Java?

A31.  Access scopes or specifiers are the keywords that are used to define the access scope of the method, class, or variable. In Java, there are four access specifiers given below.

– Public: The classes, methods, or variables which are defined as public, can be accessed by any class or method.

– Protected: Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.

– Default: are accessible within the package only. By default, all the classes,  methods, and variables are of default scope.

– Private: The private class, methods, or variables defined as private can be accessed within the class only.

Q32.  Please explain Local variables and Instance variables in Java.

A32.  A local variable is only accessible to the method or code block in which they are declared. Instance variables, on the other hand, are accessible to all methods in a class. While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method.

Q33.  Please explain Method Overriding in Java?

A33.  Method Overriding in Java allows a subclass to offer a specific implementation of a method that has already been provided by its parent or superclass. Method overriding happens if the subclass method and the Superclass method have:

– The same name

– The same argument

– The same return type

Collections are used in every programming language and when Java arrived, it also came with few Collection classes – Vector, Stack, Hashtable, Array, Hashmap.

Q34.  What is API in java?

Q34.  Java application programming interface (API) is a list of all classes and interfaces that are part of the Java development kit (JDK). It includes all Java packages, classes, and interfaces, along with their methods, fields, and constructors. They are pre-written classes, interfaces, and functionalities to provide a great user experience to the programmer.

Q35.  What are the main differences between the Java platform and other platforms?

A35.  Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.

Java is executed on top of other hardware platforms whereas other platforms can only have the hardware components.

 

Q36.  What is core java?

A36.  “Core Java” is Sun’s term, used to refer to Java SE, the standard edition, and a set of related technologies, libraries, classes, and interfaces. This is mostly to differentiate it from, Java ME and Java EE.

Q37.  If I don’t provide any arguments on the command line, then what will the value stored in the String array passed into the main() method, empty or NULL?

A37.  It is empty, but not null.

Q38.  What’s the purpose of Static methods and static variables?

A38.  The purpose of Static methods is to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keywords to make a method or variable shared for all objects.

 

Q39.  What is encapsulation in java

A39.  The idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data members (instance) of other classes.

However, if we set up public getter and setter methods to update (for example void setName(String Student ))and read (for example String getStudet()) the private data fields then the outside class can access those private data fields via public methods.

Q40.  What is a singleton class?

A40.  A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for situations when there is a need to limit the number of objects for a class.

The best example of singleton usage is where there is a limit of having only one connection to a database due to limited resources as a result of licensing.

Q41. What are Loops in Java?

A41.  There are three types of loops. They are used in programming to execute a statement or a block of statement repeatedly:

– For Loops

For loops are used in java to execute statements repeatedly for a specific number of times. For loops are used when the number of times to execute the statements is known to the programmer.

– While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, the condition is checked first before execution of statements.

– Do While Loops

Do While Loop is same as While loop with the only difference that condition is executed once before the condition is checked whether true/false. If the condition is true the program will continue to execute until it becomes false and the program will terminate.

 

Q42.  What is an Infinite Loop? How infinite loop is declared?

A42.  An infinite loop runs without any condition and runs infinitely. It can be broken by defining a breaking logic in the body of the statement.

Infinite loop is declared as follows:

for (;;)

{

// Statements to execute

 

// Add any loop breaking logic

}

Q43.  What is the difference between continuing and break a statement?

A43.  Break and continue are two important keywords used in Loops. When a break keyword is used in a loop, the loop is broken instantly while when the continue keyword is used, the current iteration is broken and the loop continues with next iteration.

In example, Loop is broken when counter reaches 3.

for (counter = 0; counter & lt; 10; counter++)

system.out.println(counter);

 

if (counter == 3) {

 

break;

}

 

}

In the example when counter reaches 3, loop jumps to next iteration and any statements after the continue keyword are skipped for current iteration.

for (counter = 0; counter < 10; counter++)

system.out.println(counter);

 

if (counter == 3) {

 

continue;

}

system.out.println(“This will not get printed when the counter is 3”);

}

Q44.  What is the difference between double and float variables in Java?

A44.  Float is a single-precision floating-point decimal number while Double is a double-precision decimal number.

In java, float takes 4 bytes in memory while Double takes 8 bytes in memory.

 

Q45.  How can you generate random numbers in Java?

A45.  We can generate random numbers in two ways:

– Using Math.random() you can generate random numbers in the range    greater than or equal to 0.1 and less than 1.0

– Using Random class in package java.util

 

Q46.  What role does the final keyword play in Java? What impact does it have on a variable, method, and class?

A46.  The final keyword in Java is a non-access modifier that applies only to a class, method, or variable. It serves a different purpose based on the context where it is used.

– With a class

When a class is declared as final, then it is disabled from being subclassed i.e., no class can extend the final class.

– With a method

Any method accompanying the final keyword is restricted from being overridden by the subclass.

–   With a variable

A variable followed by the final keyword is not able to change the value that it holds during the program execution. So, it behaves like a constant.

Q47.  How to initialize arrays in java?

A47.  “int[] arr = new int[5];         // integer array of size 5 you can also change data type

String[] students = {“”John””, “”Doe””, “”Frank””, “”Andrew””};”

 

Q48. What is an abstract class in java?

A48.  A class that is declared using the “abstract” keyword is known as an abstract class. It can have abstract methods without a body as well as concrete methods with the body. A normal class that is not defined as an abstract or non-abstract class cannot have abstract methods.

 

Q49.  How to enable java in chrome?

A49.  We can enable Java in Chrome by:

– In the Java Control Panel, click the Security tab

– Select the option Enable Java content in the browser

– Click Apply and then OK to confirm the changes

– Restart the browser to enable the changes

Q50.  What is inheritance in Java?

A50.  The process by which one class acquires the properties from one class to another class.  A class can inherit attributes and methods from a parent class using the keyword ‘extends’. The aim of inheritance is to provide the reusability of code so that a class has to write only the unique features and the rest of the common properties and functionalities can be extended from another class.

 

Q51.  What is the JIT compiler?

A51.  Just-In-Time(JIT) compiler:  JIT manages the system performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. It will translate the source code into machine-executable code.

 

Q52.  How to compare two strings in Java?

A52.  “// These two have the same value

new String(“”test””).equals(“”test””) // –> true

 

// … but they are not the same object

new String(“”test””) == “”test”” // –> false

 

// … neither are these

new String(“”test””) == new String(“”test””) // –> false

 

// … but these are because literals are interned by

// the compiler and thus refer to the same object

“”test”” == “”test”” // –> true “

 

Q53.  What is inheritance?

A53. inheritance is an object-oriented programming concept, which allows a derived class to inherit the methods of a base class.

 

Q54.  What is a class in java?

A54.  A class is a building block of an object-oriented language like Java. It is the blueprint or template that describes the data and behaviour associated with instances of that class. When you instantiate a class you create an object that looks and feels like other instances of the same class. The data associated with a class or object is stored in variables; the behaviour associated with a class or object is implemented with methods.

 

Q55. What is data encapsulation and what’s its significance?

A55.  Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves a data hiding purposes.

 

 

Q56.  What is a package in java?

A56.  A package in Java is used to group related classes and interfaces. Think of it as a folder in a file directory. We use packages to avoid name conflicts and to write better maintainable code. Packages are divided into two categories:

 

Q57.  How to sort an array in java?

A57.  “import java. util. Arrays;

Arrays. sort(array);”

 

Q58.  Could you draw a comparison between Array and ArrayList?

A58.  An array necessitates giving the size during the time of declaration, while an array list doesn’t necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

 

Q59.  What is a marker interface?

A59.  A Marker interface can be defined as the interface having no data member and member functions. In simpler terms, an empty interface is called the Marker interface. The most common examples of Marker interfaces in Java are Serializable, Cloneable, etc. The marker interface can be declared as follows.

 

Q60.  Why do we use the yield() method?

A60.  Yield() method belongs to the thread class. It transfers the currently running thread to a runnable state and also allows the other threads to execute. In other words, it gives equal priority threads a chance to run. Because yield() is a static method, it does not release any lock.

Q61. What is a constructor overloading in Java?

A61.  In Java, constructor overloading is a technique of adding a number of constructors to a class each having a different parameter list. The compiler uses the number of parameters and their types in the list to differentiate the overloaded constructors.

 

 

 

 

 

 

 

 

 

 

 

 

 

class Test

{

int a;

public Test(int x)

{

a=b;

}

public Test(int x, int y)

{

//body

}

}

 

 

Q62.  Can you explain the thread lifecycle in Java?

A62.  The thread lifecycle has the following states and follows the following order:

  • New – In the very first state of the thread lifecycle, the thread instance is created, and the start() method is yet to be invoked. The thread is considered alive now.
  • Runnable – After invoking the start() method, but before invoking the run() method, a thread is in the runnable state. A thread can also return to the runnable state from the waiting or sleeping state.
  • Running – The thread enters the running state after the run() method is invoked. This is when the thread begins execution.
  • Non-Runnable – Although the thread is alive, it is not able to run. Typically, it returns to the runnable state after some time.
  • Terminated – The thread enters the terminated state once the run() method completes its execution. It is not alive now.

 

Q63. What is static in java?

A63.  A static member is a member of the class.  It is not associated with an instance of a class. Instead, the member belongs to the class itself. As a result, you can access the static member without first creating a class instance.

 

 

Q64.  How to take string input in java?
A64.  Input is taken in Java through a method called ‘Scanner’.

“import java.util.Scanner;  // Import the Scanner class

 

class MyClass {

  public static void main(String[] args) {

    Scanner myObj = new Scanner(System.in);  // Create a Scanner object

    System.out.println(“”Enter studentName””);

 

    String userName = myObj.nextLine();  // Read user input

    System.out.println(“”Studentname is: “” + studentName);  // Output user input

  }

}”

 

Q65.   What is encapsulation in Java?

A65.  Encapsulation is one of the fundamentals of OOP.

It is a mechanism where you bind your variables and methods together as a single unit. Here, the data is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any unnecessary modification. We can achieve encapsulation in Java by:

– Declaring the variables of a class as private.

– Providing public setter and getter methods to modify and view the values of the variables. 

Q66.  What is a composition in Java?

A66.  Composition is again a specialized form of Aggregation and we can call this a “death” relationship. It is a strong type of Aggregation. Child objects does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of a relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically be deleted.

 

Q67. What’s the difference between String, StringBuffer, and StringBuilder?

A67.  The string is an immutable class. In older JDK’s the recommendation when programmatically building a String was to use StringBuffer since this was optimized to concatenate multiple Strings together. However, the methods on StringBuffer were marked as synchronized, which meant that there was a performance penalty, hence StringBuilder was introduced to provide a non-synchronized way to efficiently concatenate and modify Strings.

 

Q68.  What is the difference between final, finalize, and finally?

A68.  Final is a Java keyword used to indicate that either a method can not override in a subclass, or a class can not be extended or a field can not be modified. finalize is a method that gets called on an instance of an Object when it is garbage collected. finally is a Java keyword used in exception handling to indicate a block of code that should always be run whether an exception is thrown or not.

Q69.  What’s the difference between a ClassNotFoundException and NoClassDefFoundError?

A69.  A ClassNotFoundException means the class file for a requested class is not on the classpath of the application. A NoClassDefFoundErrormeans that the class file existed at runtime, but for some reason, the class could not be turned into a Class definition. A common cause is an exception being thrown in static initialization blocks.

 

Q70.  Why multiple inheritance is not supported in java?

A70.  Java does not support Multiple inheritances because it leads to a deadly diamond problem.

Java supports multiple inheritances through interfaces only. A class can implement any number of interfaces but can extend only one class.

 

Q71.  What are the important features of Java?

A71.  Important Features of Java are,

– Simple
– Object-Oriented
– Platform independent
– Secured
– Robust,
– Architecture neutral
– Portable
– Interpreted
– Multithreaded

–  Distributed

 

Q72.  What is an association?

A72.  Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of house and room. Multiple rooms can associate with a single house and a single house can associate with multiple rooms but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one, and many to many.

 

Q73.  What is a copy constructor in Java?

The copy constructor is a member function that is used to initialize an object using another object of the same class. Though there is no need for a copy constructor in Java since all objects are passed by reference. Moreover, Java does not even support automatic pass-by-value.

 

Q74.  What are important Java Language Elements?

A74.  Important Language Elements of Java are:

– Data Types
– Modifiers
– Variables
– Operators
– Control Flow Statements
– Methods Etc…

 

 

Q75.  What is Final Keyword in Java? Give an example.

A75.  In java, a constant is declared using the keyword Final. Value can be assigned only once and after the assignment, the value of a constant can’t be changed.

For example, a constant ‘a’ is declared and assigned value:

Private Final int a = 50

When a method is declared as final, it can NOT be overridden by the subclasses. This method is faster than any other method because they are resolved at the complied time.

Q76.  Are constructors inherited? Can a subclass call the parent’s class constructor?

A76.  We cannot inherit a constructor. We create an instance of a subclass using a constructor of one of its superclasses. Because overriding the superclass constructor is not our wish as if we override a superclass constructor, then we will destroy the encapsulation abilities of the language.

 

Q77.  What do you mean by aggregation?

A77.  An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Let’s take an example of room and house. A single room can not belong to multiple houses, but if we delete the room, the house object will not be destroyed. 

 

Q78.  What are the Fundamentals of OOPS?

A78.  Four fundamentals of Object Oriented Programming are,

– Inheritance
– Polymorphism
– Abstraction
– Encapsulation

 

Q79.  How does Garbage Collection prevent a Java application from going out of memory?

A79.  Garbage Collection is a memory management system that simply cleans up unused memory when an object goes out of scope and is no longer needed. However, an application could create a huge number of large objects that cause an OutOfMemoryError.

 

Q80.  What are Java Syntax Rules?

A80.  Rules are:

– Java is a case-sensitive language.

– First letter of the Class name should be in the Upper case.

– Method names should start with lower case letters.

– Java program file name should exactly match with the class name.

– Java program execution starts from the main method, which is mandatory in every Java program.

– Every statement/step should end with a semicolon symbol.

– Code blocks enclosed with {}.

 

Q81.  What is the difference between HashMap and HashSet?

A81.  HashMap implements Map interface which maps keys to value. It is not synchronized and is not thread-safe. Duplicate keys are not allowed and null keys, as well as values, are allowed.

HashSet

HashSet implements a Set interface that does not allow duplicate values. It is not synchronized and is not thread-safe.

 

Q82.  Can we have an abstract class without having any abstract method in it?

A82.  Yes, you can have an abstract class without having any abstract method.

 

 

Q83. What is the difference between JDK, JRE, and JVM?
A83.

– JVM stands for Java Virtual Machine which provides the runtime environment for Java bytecodes to be executed.

 – JRE (Java Runtime Environment) includes the sets of files required by JVM during runtime.

 – JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

 

 

Q84.  What is method overloading?

A84.  When a Java program contains more than one method with the same name but with different properties, then it is called method overloading.

 

Q85.  What is a class in Java?

A85.  Java encapsulates codes in various classes that define new data types. These new data types are used to create objects.

 

Q86.  Why are Strings Immutable

A86.  This question is a very popular interview question at the beginner level. Basically, the interviewer tests your knowledge around the String class, string pool, memory areas, and object creation.

I wrote this post separately because the concept is so much important. In fact, immutability is itself a very important concept in java. Feel the tip of the iceberg.

 

Q87. Define JSON.

A87.  The expansion of JSON is ‘JavaScript Object Notation.’ It is a much lighter and readable alternative to XML. It is independent and easily parseable in all programming languages. It is primarily used for client-server and server-server communication.

 

Q88.  What is a method in java?
A88.  A method is a function, a block of code that runs when it is called. You can pass data, known as parameters, into a method and are used to perform certain actions.

Q89.  What is Enum

A89.  The enum has been a core building block for a long time. They can be seen in the most popular Java libraries. They help you in managing constants in a more object-oriented manner. They look very easy but they hide lots of complexity if you dig deep enough. Some enum questions maybe –

  • Difference between the enum vs. Enum class?
  • Can enum be using with String?
  • Can we extend the enum?
  • Write the syntax of an enum?
  • How to implement reverse-lookup in the enum?
  • What is EnumMap and EnumSet?

Q90.  Serialization and Serializable Interface

A90.  If you are preparing for a Java interview with a Telecom company or any such domain that uses serialization in their application flows, then you will highly benefit from this tutorial. A very good list of dos and dont’s with serialization in java. Possible questions may include –

  • What is serialVersionUID?
  • What are readObject and writeObject?
  • ow, you will serialize and deserialize a class?
  • How you will make changes to a class so that serialization should not break?
  • Can we serialize static fields?

Q91.  What is a Main method in Java

A91.  Ever wondered why main() is public, static, and void? It’s not a very frequently asked interview question in Java interviews but still, I will recommend reading some post to answer these questions:

  • Java main method syntax?
  • Why main method is public?
  • Why main method is static?
  • Why main method is void?
  • What happens internally when you invoke main method?

Q92.  Object Cloning

A92.  Object cloning in Java is not an easy concept. I myself took a long time to understand cloning in java. It really seems simple; use the Cloneable interface and override clone() method. But wait; there is much more to tell and ask in an interview. e.g.

  • How clone() method works?
  • What is a shallow copy in Java?
  • What are copy constructors?
  • What is a deep copy in Java?
  • Different ways to create a deep copy of an object?

 

Check these questions and produce the answer

 

Q93.  What is CounDownLatch?

A93.  Since Java 5, java.uti.concurrent package has lots of useful but complex classes to work on concurrent applications. CountDownLatch is one of those classes which are highly asked in any Java interview big corporates. In this tutorial, CountDownLatch is explained with examples and concepts around it.

 

Q94.  Differentiate overloading with overriding.

A94.  Overloading refers to the case of having two methods of the same name but different properties; whereas, overriding occurs when there are two methods of the same name and properties, but one is in the child class and the other is in the parent class.

 

Q95.  How can you make Java Class Immutable?

A95.  An immutable class is one whose state can not be changed once created. There are certain guidelines to create a class immutable in Java and you must know them to answer this question correctly.

Be aware that immutability is important in many design aspects and is a recommended design pattern by all Java gurus. Learn to make a java class immutable, how it benefits the application design, and be prepared to encounter more software design interview questions on it.

Q96. List some important methods from object class?

A96. Important methods of object classes are:

  • hashcode: It returns the hash value of the object
  • equals: It compares the object references
  • wait: It causes the current thread to wait until notify or notifyAll is not called
  • notify: Wakes up a single thread that is waiting for lock
  • notify: Wakes up all threads which are waiting for lock
  • toString: Provides String representation of the object
  • clone: This method is used to clone the object
  • finalize: This method is called when objects is being garbage collected.

Q97.  Have you heard about the transient variable? When will you use it?

A97.  Transient variables are used for Serialization. If you don’t want to make variable serializable, you can make it a transient variable.

 

Q98.  What’s the creation of a thread-safe singleton in Java using double-checked locking?

A98.  Singleton is created with the double-checked locking as before Java 5 acts as a broker and it’s been possible to have multiple instances of singleton when multiple threads create an instance of the singleton at the same time. Java 5 made it easy to create thread-safe singleton using Enum. Using a volatile variable is essential for the same.

 

Q99.  What are the advantages of JSON over XML?

A99.  The advantages of JSON over XML are:

–  JSON is lighter and faster than XML.

– It is easily understandable.

– It is easy to parse and convert to objects for information consumption.

– JSON supports multiple data types—string, number, array, or Boolean—but XML data are all strings.

 

Q100.  What is object cloning in Java?

A100.  Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability to create an object with a similar state as the original object. To achieve this, Java provides a method clone() to make use of this functionality. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a protected method, thus you need to override it.

 

Q101.  What is an exception in java?

A101.  An exception is an event, which occurs during the execution of a Java program, that interrupts the normal flow of the program’s instructions such as error.
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.