• Java Course
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Java Interview Questions and Answers

Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance.

In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience. Here, we cover everything, including core Java concepts, Object-Oriented Programming (OOP), multithreading, exception handling, design patterns, Java Collections, and more, that will surely help you to crack Java interviews. Along with these interview questions you can also try Java course to enhance your Java concepts.

Table of Content

Java Interview questions for Freshers

Java intermediate interview questions, java interview questions for experienced, java difference interview questions, 1. is java platform independent if then how.

Yes, Java is a Platform Independent language. Unlike many programming languages javac compiles the program to form a bytecode or .class file. This file is independent of the software or hardware running but needs a JVM(Java Virtual Machine) file preinstalled in the operating system for further execution of the bytecode.

Although JVM is platform dependent , the bytecode can be created on any System and can be executed in any other system despite hardware or software being used which makes Java platform independent.

2. What are the top Java Features?

Java is one the most famous and most used language in the real world, there are many features in Java that makes it better than any other language some of them are mentioned below:

Features-of-Java-768

  • Simple : Java is quite simple to understand and the syntax
  • Platform Independent: Java is platform independent means we can run the same program in any software and hardware and will get the same result.
  • Interpreted : Java is interpreted as well as a compiler-based language. 
  • Robust : features like Garbage collection, exception handling, etc that make the language robust.
  • Object-Oriented : Java is an object-oriented language that supports the concepts of class,  objects, four pillars of OOPS, etc. 
  • Secured : As we can directly share an application with the user without sharing the actual program makes Java a secure language. 
  • High Performance:  faster than other traditional interpreted programming languages.
  • Dynamic : supports dynamic loading of classes and interfaces.
  • Distributed : feature of Java makes us able to access files by calling the methods from any machine connected.
  • Multithreaded : deal with multiple tasks at once by defining multiple threads
  • Architecture Neutral : it is not dependent on the architecture.

3. What is JVM?

JVM-768

JVM stands for Java Virtual Machine it is a Java interpreter. It is responsible for loading, verifying, and executing the bytecode created in Java.

Although it is platform dependent which means the software of JVM is different for different Operating Systems it plays a vital role in making Java platform Independent.

To know more about the topic refer to JVM in Java .

4. What is JIT?

JIT-768

JIT stands for (Just-in-Time) compiler is a part of JRE(Java Runtime Environment), it is used for better performance of the Java applications during run-time. The use of JIT is mentioned in step by step process mentioned below:

  • Source code is compiled with javac to form bytecode
  • Bytecode is further passed on to JVM 
  • JIT is a part of JVM, JIT is responsible for compiling bytecode into native machine code at run time.
  • The JIT compiler is enabled throughout, while it gets activated when a method is invoked. For a compiled method, the JVM directly calls the compiled code, instead of interpreting it.
  • As JVM calls the compiled code that increases the performance and speed of the execution.

To know more about the topic refer to JIT in Java .

5. What are Memory storages available with JVM?

JVM-Areas-768

JVM consists of a few memory storages as mentioned below:

  • Class(Method) Area: stores class-level data of every class such as the runtime constant pool, field, and method data, and the code for methods.
  • Heap: Objects are created or objects are stored. It is used to allocate memory to objects during run time.
  • Stack: stores data and partial results which will be needed while returning value for method and performing dynamic linking
  • Program Counter Register: stores the address of the Java virtual machine instruction currently being executed.
  • Native Method Stack: stores all the native methods used in the application.

To know more about the topic refer to JVM Memory Storages .

6. What is a classloader?

Classloader is the part of JRE(Java Runtime Environment), during the execution of the bytecode or created .class file classloader is responsible for dynamically loading the java classes and interfaces to JVM(Java Virtual Machine). Because of classloaders Java run time system does not need to know about files and file systems.

To know more about the topic refer to ClassLoader in Java.

7. Difference between JVM, JRE, and JDK.

JVM : JVM also known as Java Virtual Machine is a part of JRE. JVM is a type of interpreter responsible for converting bytecode into machine-readable code. JVM itself is platform dependent but it interprets the bytecode which is the platform-independent reason why Java is platform-independent. 

JRE : JRE stands for Java Runtime Environment, it is an installation package that provides an environment to run the Java program or application on any machine.

JDK : JDK stands for Java Development Kit which provides the environment to develop and execute Java programs. JDK is a package that includes two things Development Tools to provide an environment to develop your Java programs and, JRE to execute Java programs or applications.

To know more about the topic refer to the Differences between JVM, JRE, and JDK .

8. What are the differences between Java and C++?

Basis

C++

Java

Platform                   

C++ is Platform Dependent

Java is Platform Independent

Application

C++ is mainly used for System Programming

Java is Mainly used for Application Programming

Hardware

C++ is nearer to hardware

Java is not so interactive with hardware

Global Scope

C++ supports global and namespace scope.

Java doesn’t support global scope.

Not Supporting                  

Functionality supported in Java but not in C++ are:

Functionality supported in C++ but not in Java are:

OOPS

C++ is an object-oriented language. It is not a single root hierarchy .

Java is also an object-oriented language. It is a single root hierarchy as everything gets derived from a single class (java.lang.Object).

Inheritance Tree

C++ always creates a new inheritance tree.

Java uses a Single inheritance tree as classes in Java are the child of object classes in Java.

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

Main_function

Unlike any other programming language like C, C++, etc. In Java, we declared the main function as a public static void main (String args[]). The meanings of the terms are mentioned below:

  • public : the public is the access modifier responsible for mentioning who can access the element or the method and what is the limit.  It is responsible for making the main function globally available. It is made public so that JVM can invoke it from outside the class as it is not present in the current class.
  • static : static is a keyword used so that we can use the element without initiating the class so to avoid the unnecessary allocation of the memory. 
  • void : void is a keyword and is used to specify that a method doesn’t return anything. As the main function doesn’t return anything we use void.
  • main : main represents that the function declared is the main function. It helps JVM to identify that the declared function is the main function.
  • String args[] : It stores Java command-line arguments and is an array of type java.lang.String class.

10. What is Java String Pool?

A Java String Pool is a place in heap memory where all the strings defined in the program are stored. A separate place in a stack is there where the variable storing the string is stored. Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created.

Java-String-Pool-768

11. What will happen if we declare don’t declare the main as static?

We can declare the main method without using static and without getting any errors. But, the main method will not be treated as the entry point to the application or the program.

12. What are Packages in Java?

Packages in Java can be defined as the grouping of related types of classes, interfaces, etc providing access to protection and namespace management.

13. Why Packages are used?

Packages are used in Java in order to prevent naming conflicts, control access, and make searching/locating and usage of classes, interfaces, etc easier.

14. What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and are used by the package.
  • It is easier to locate the related classes.

15. How many types of packages are there in Java?

There are two types of packages in Java

  • User-defined packages
  • Build In packages

16. Explain different data types in Java.

There are 2 types of data types in Java as mentioned below:

  • Primitive Data Type
  • Non-Primitive Data Type or Object Data type

Primitive Data Type: Primitive data are single values with no special capabilities. There are 8 primitive data types:

  • boolean : stores value true or false
  • byte : stores an 8-bit signed two’s complement integer
  • char : stores a single 16-bit Unicode character
  • short : stores a 16-bit signed two’s complement integer
  • int : stores a 32-bit signed two’s complement integer
  • long : stores a 64-bit two’s complement integer
  • float : stores a single-precision 32-bit IEEE 754 floating-point
  • double : stores a double-precision 64-bit IEEE 754 floating-point

Non-Primitive Data Type: Reference Data types will contain a memory address of the variable’s values because it is not able to directly store the values in the memory. Types of Non-Primitive are mentioned below:

17. When a byte datatype is used?

A byte is an 8-bit signed two-complement integer. The minimum value supported by bytes is -128 and 127 is the maximum value. It is used in conditions where we need to save memory and the limit of numbers needed is between -128 to 127.

18. Can we declare Pointer in Java?

No, Java doesn’t provide the support of Pointer. As Java needed to be more secure because which feature of the pointer is not provided in Java.

19. What is the default value of byte datatype in Java?

The default value of the byte datatype in Java is 0.

20. What is the default value of float and double datatype in Java?

The default value of the float is 0.0f and of double is 0.0d in Java.

21. What is the Wrapper class in Java?

Wrapper, in general, is referred to a larger entity that encapsulates a smaller entity. Here in Java, the wrapper class is an object class that encapsulates the primitive data types. 

The primitive data types are the ones from which further data types could be created. For example, integers can further lead to the construction of long, byte, short, etc. On the other hand, the string cannot, hence it is not primitive. 

Getting back to the wrapper class, Java contains 8 wrapper classes. They are Boolean, Byte, Short, Integer, Character, Long, Float, and Double. Further, custom wrapper classes can also be created in Java which is similar to the concept of Structure in the C programming language. We create our own wrapper class with the required data types.

22. Why do we need wrapper classes?

The wrapper class is an object class that encapsulates the primitive data types, and we need them for the following reasons:

  • Wrapper classes are final and immutable
  • Provides methods like valueOf(), parseInt(), etc.
  • It provides the feature of autoboxing and unboxing.

23. Differentiate between instance and local variables.

Instance Variable

Local Variable

Declared outside the method, directly invoked by the method.

Declared within the method.                                                              

Has a default value.

No default value

It can be used throughout the class.

The scope is limited to the method.

24. What are the default values assigned to variables and instances in Java?

In Java When we haven’t initialized the instance variables then the compiler initializes them with default values. The default values for instances and variables depend on their data types. Some common types of default data types are:

  • The default value for numeric types (byte, short, int, long, float, and double) is 0.
  • The default value for the boolean type is false.
  • The default value for object types (classes, interfaces, and arrays) is null.
  • The null character, “u0000, ” is the default value for the char type.

25. What is a Class Variable?

In Java, a class variable (also known as a static variable) is a variable that is declared within a class but outside of any method, constructor, or block. Class variables are declared with the static keyword, and they are shared by all instances (objects) of the class as well as by the class itself. No matter how many objects are derived from a class, each class variable would only exist once.

26. What is the default value stored in Local Variables?

There is no default value stored with local variables. Also, primitive variables and objects don’t have any default values.

27. Explain the difference between instance variable and a class variable.

Instance Variable: A class variable without a static modifier known as an instance variable is typically shared by all instances of the class. These variables can have distinct values among several objects. The contents of an instance variable are completely independent of one object instance from another because they are related to a specific object instance of the class.

Class Variable:  Class Variable variable can be declared anywhere at the class level using the keyword static. These variables can only have one value when applied to various objects. These variables can be shared by all class members since they are not connected to any specific object of the class.  

28. What is a static variable?

The static keyword is used to share the same variable or method of a given class. Static variables are the variables that once declared then a single copy of the variable is created and shared among all objects at the class level.

29. What is the difference between System.out, System.err, and System.in?

System.out – It is a PrintStream that is used for writing characters or can be said it can output the data we want to write on the Command Line Interface console/terminal. 

System.err – It is used to display error messages.

Although, System.err have many similarities both of them have quite a lot of difference also, let us check them.

It will print to the standard out of the system.

It will print to the standard error.

It is mostly used to display results on the console.

It is mostly used to output error texts.

It gives output on the console with the default(black) color.

It also gives output on the console but most of the IDEs give it a red color to differentiate.

System.in – It is an InputStream used to read input from the terminal Window. We can’t use the System.in directly so we use Scanner class for taking input with the system.in.

30. What do you understand by an IO stream?

2-768

Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These streams support all types of objects, data types, characters, files, etc to fully execute the I/O operations.

31. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The key difference between them is that byte stream data is read and written by input/output stream classes. Characters are handled by the Reader and Writer classes. In contrast to Reader/Writer classes, which accept character arrays as parameters, input/output stream class methods accept byte arrays. In comparison to input/output streams, the Reader/Writer classes are more efficient, handle all Unicode characters, and are useful for internalization. Use Reader/Writer classes instead of binary data, such as pictures, unless you do so.

32. What are the super most classes for all the streams?

All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes. The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output stream classes is java.io.OutPutStream. Similarly, for all the reader classes, the super-most class is java.io.Reader, and for all the writer classes, it is java.io.Writer.

33. What are the FileInputStream and FileOutputStream?

To read and write data, Java offers I/O Streams. A Stream represents an input source or an output destination, which could be a file, an i/o device, another program, etc. FileInputStream in Java is used to read data from a file as a stream of bytes. It is mostly used for reading binary data such as images, audio files, or serialized objects. 

In Java, the FileOutputStream function is used to write data byte by byte into a given file or file descriptor. Usually, raw byte data, such as pictures, is written into a file using FileOutputStream.

34. What is the purpose of using BufferedInputStream and BufferedOutputStream classes?

When we are working with the files or stream then to increase the Input/Output performance of the program we need to use the BufferedInputStream and BufferedOutputStream classes. These both classes provide the capability of buffering which means that the data will be stored in a buffer before writing to a file or reading it from a stream. It also reduces the number of times our OS needs to interact with the network or the disk. Buffering allows programs to write a big amount of data instead of writing it in small chunks. This also reduces the overhead of accessing the network or the disk. 

35. What are FilterStreams?

Stream filter or Filter Streams returns a stream consisting of the elements of this stream that match the given predicate. While working filter() it doesn’t actually perform filtering but instead creates a new stream that, when traversed, contains the elements of initial streams that match the given predicate.

36. What is an I/O filter?

An I/O filter also defined as an Input Output filter is an object that reads from one stream and writes data to input and output sources. It used java.io package to use this filter.

37. How many ways you can take input from the console?

There are two methods to take input from the console in Java mentioned below:

  • Using Command line argument
  • Using Buffered Reader Class
  • Using Console Class
  • Using Scanner Class

The program demonstrating the use of each method is given below.

38. Difference in the use of print, println, and printf.

print, println, and printf all are used for printing the elements but print prints all the elements and the cursor remains in the same line. println shifts the cursor to next line. And with printf we can use format identifiers too.

39. What are operators? 

Operators are the special types of symbols used for performing some operations over variables and values.

40. How many types of operators are available in Java? 

All types of operators in Java are mentioned below:

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators
  • instance of operator

Postfix operators are considered as the highest precedence according to Java operator precedence.

41. Explain the difference between >> and >>> operators.

Operators like >> and >>> seem to be the same but act a bit differently. >> operator shifts the sign bits and the >>> operator is used in shifting out the zero-filled bits.

42. Which Java operator is right associative?

There is only one operator which is right associative which is = operator.

43. What is dot operator?

The Dot operator in Java is used to access the instance variables and methods of class objects. It is also used to access classes and sub-packages from the package.

44. What is covariant return type?

The covariant return type specifies that the return type may vary in the same direction as the subclass. It’s possible to have different return types for an overriding method in the child class, but the child’s return type should be a subtype of the parent’s return type and because of that overriding method becomes variant with respect to the return type.

We use covariant return type because of the following reasons:

  • Avoids confusing type casts present in the class hierarchy and makes the code readable, usable, and maintainable.
  • Gives liberty to have more specific return types when overriding methods.
  • Help in preventing run-time ClassCastExceptions on returns.

45. What is the transient keyword?

The transient keyword is used at the time of serialization if we don’t want to save the value of a particular variable in a file. When JVM comes across a transient keyword, it ignores the original value of the variable and saves the default value of that variable data type.

46. What’s the difference between the methods sleep() and wait()?

Sleep()

Wait()

The sleep() method belongs to the thread class.

Wait() method belongs to the object class.

Sleep does not release the lock that the current thread holds.

wait() release the lock which allows other threads to acquire it.

This method is a static method.

This method is not a static method.

Sleep() does not throw an InterruptedException.InterruptedException is shown if the thread is interrupted while waiting.

Mainly used to delay a thread for some specific time duration.

Mainly used to pause a thread until notified by another thread.

Sleep() Has Two Overloaded Methods:

Wait() Has Three Overloaded Methods:

47. What are the differences between String and StringBuffer?

String

StringBuffer

Store of a sequence of characters.            Provides functionality to work with the strings.
It is immutable.It is mutable (can be modified and other string operations could be performed on them.)
No thread operations in a string.                                                           It is thread-safe (two threads can’t call the methods of StringBuffer simultaneously) 

48. What are the differences between StringBuffer and StringBuilder?

StringBuffer provides functionality to work with the strings.StringBuilder is a class used to build a mutable string.
It is thread-safe (two threads can’t call the methods of StringBuffer simultaneously)It is not thread-safe (two threads can call the methods concurrently)
Comparatively slow as it is synchronized.Being non-synchronized, implementation is faster

49. Which among String or String Buffer should be preferred when there are a lot of updates required to be done in the data?

The string is preferred over StringBuffer as StringBuilder is faster than StringBuffer, but StringBuffer objects are the preferred over as it provides more thread safety.

50. Why is StringBuffer called mutable?

StringBuffer class in Java is used to represent a changeable string of characters. It offers an alternative to the immutable String class by enabling you to change a string’s contents without constantly creating new objects. Mutable (modifiable) strings are created with the help of the StringBuffer class. The StringBuffer class in Java is identical to the String class except that it is changeable.

51. How is the creation of a String using new() different from that of a literal?

String using new() is different from the literal as when we declare string it stores the elements inside the stack memory whereas when it is declared using new() it allocates a dynamic memory in the heap memory. The object gets created in the heap memory even if the same content object is present.

3-768

52. What is an array in Java?

An Array in Java is a data structure that is used to store a fixed-size sequence of elements of the same type. Elements of an array can be accessed by their index, which starts from 0 and goes up to a length of minus 1. Array declaration in Java is done with the help of square brackets and size is also specified during the declaration. 

53. On which memory arrays are created in Java?

Arrays in Java are created in heap memory. When an array is created with the help of a new keyword, memory is allocated in the heap to store the elements of the array. In Java, the heap memory is managed by the Java Virtual Machine(JVM) and it is also shared between all threads of the Java Program. The memory which is no longer in use by the program, JVM uses a garbage collector to reclaim the memory. Arrays in Java are created dynamically which means the size of the array is determined during the runtime of the program. The size of the array is specified during the declaration of the array and it cannot be changed once the array is created.

54. What are the types of an array?

There are two types of arrays i.e., Primitive arrays and References Arrays.

  • Single-Dimensional Arrays: Arrays that have only one dimension i.e., an array of integers or an array of strings are known as single-dimensional arrays.

4-768

  • Multi-Dimensional Arrays: Arrays that have two or more dimensions such as two-dimensional or three-dimensional arrays. 

55. Why does the Java array index start with 0?

The index of an array signifies the distance from the start of the array. So, the first element has 0 distance therefore the starting index is 0.

56. What is the difference between int array[] and int[] array?

Both int array[] and int[] array are used to declare an array of integers in java. The only difference between them is on their syntax no functionality difference is present between them.

However, it is generally recommended to use Java-style syntax to declare an Array. As it is easy to read and understand also it is more consistent with other Java language constructs.

57. How to copy an array in Java?

In Java there are multiple ways to copy an Array based on the requirements. 

  • clone() method in Java: This method in Java is used to create a shallow copy of the given array which means that the new array will share the same memory as the original array.
  • arraycopy() method: To create a deep copy of the array we can use this method which creates a new array with the same values as the original array.
  • copyOf() method: This method is used to create a new array with a specific length and copies the contents of the original array to the new array.
  • copyOfRange() method: This method is very similar to the copyOf() method in Java, but this method also allows us to specify the range of the elements to copy from the original array.

58. What do you understand by the jagged array?

A jagged Array in Java is just a two-dimensional array in which each row of the array can have a different length. Since all the rows in a 2-d Array have the same length but a jagged array allows more flexibility in the size of each row. This feature is very useful in conditions where the data has varying lengths or when memory usage needs to be optimized.   

59. Is it possible to make an array volatile?

In Java, it is not possible to make a volatile. Volatile keywords in Java can only be applied to individual variables but not to arrays or collections. The value of the Variable is always read from and written to the main memory when it is defined as volatile rather than being cached in a thread’s local memory. This makes it easier to make sure that all threads that access the variable can see changes made to it.

60. What are the advantages and disadvantages of an array?

5-768

The advantages of Arrays are:

  • Direct and effective access to any element in the collection is made possible by arrays. An array’s elements can be accessed using an O(1) operation, which means that the amount of time needed to do so is constant and independent of the array’s size.
  • Data can be stored effectively in memory using arrays. The size of an array is known at compile time since its elements are stored in contiguous memory regions.
  • Due to the fact that the data is stored in contiguous memory areas, arrays provide quick data retrieval.
  • Arrays are easy to implement and understand, making them an ideal choice for beginners learning computer programming.

Disadvantages of Arrays are:

  • Arrays are created with a predetermined size that is chosen at that moment. This means that if the array’s size needs to be extended, a new array will need to be made, and the data will need to be copied from the old array to the new array, which can take a lot of time and memory.
  • There may be unused memory space in an array’s memory space if the array is not completely occupied. If you have poor recall, this can be a problem.
  • Compared to other data structures like linked lists and trees, arrays might be rigid due to their fixed size and limited support for sophisticated data types.
  • Because an array’s elements must all be of the same data type, it does not support complex data types like objects and structures.

61. What is an object-oriented paradigm?

Paradigm literally means a pattern or a method. Programming paradigms are the methods to solve a program that is of four types namely, Imperative, logical, functional, and object-oriented. When objects are used as base entities upon which the methods are applied, encapsulation or inheritance functionalities are performed, it is known as an object-oriented paradigm.

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

The main concepts of OOPs in Java are mentioned below:

  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation 

63. What is the difference between an object-oriented programming language and an object-based programming language?

Object-Oriented Programming Language

Object-Based Programming Language

Object-oriented programming language covers larger concepts like inheritance, polymorphism, abstraction, etc.The scope of object-based programming is limited to the usage of objects and encapsulation.
It supports all the built-in objectsIt doesn’t support all the built-in objects
Examples: Java, C#, etc.Examples: Java script, visual basics, etc.

64. How is the ‘new’ operator different from the ‘newInstance()’ operator in Java?

the new operator is used to create objects, but if we want to decide the type of object to be created at runtime, there is no way we can use the new operator. In this case, we have to use the newInstance() method .

65. What are Classes in Java? 

In Java, Classes are the collection of objects sharing similar characteristics and attributes. Classes represent the blueprint or template from which objects are created.  Classes are not real-world entities but help us to create objects which are real-world entities. 

66. What is the difference between static (class) method and instance method?

Static(Class) method

Instance method

Static method is associated with a class rather than an object.

The instance method is associated with an object rather than a class.

Static methods can be called using the class name only without creating an instance of a class.

The instance methods can be called on a specific instance of a class using the object reference.

Static methods do not have access to keyword

Instance methods have access to keyword

Static methods can access only static members of the class.

Instance methods can access both static and non-static methods of the class.

Static methods cannot be overridden because they are resolved at compile time, not at run time. This means that the compiler decides which method to call based on the reference type, not on the object type.

Instance methods can be overridden because they are resolved at run time, not at compile time. This means that the compiler decides which method to call based on the object type, not on the reference type.

67. What is this keyword in Java?

6

‘this’ is a keyword used to reference a variable that refers to the current object.

68. What are Brief Access Specifiers and Types of Access Specifiers?

Access_modifiers_in_java-768

Access Specifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of Access Specifiers in Java mentioned below:

69. What will be the initial value of an object reference which is defined as an instance variable?

The initial value of an object reference which is defined as an instance variable is a NULL value.

70. What is an object?

The object is a real-life entity that has certain properties and methods associated with it. The object is also defined as the instance of a class. An object can be declared using a new keyword.

71. What are the different ways to create objects in Java?

Methods to create objects in Java are mentioned below:

  • Using new keyword
  • Using new instance
  • Using clone() method
  • Using deserialization
  • Using the newInstance() method of the Constructor class

To know more about methods to create objects in Java refer to this article .

72. What are the advantages and disadvantages of object cloning?

There are many advantages and disadvantages of using object cloning as mentioned below:

Advantages:

  • In Java, the ‘=’ assignment operator cannot be used for cloning as it simply creates a copy of reference variables. To overcome such discrepancy the clone() method of Object class can be used over the assignment operator.
  • The clone() method is a protected method of class Object which means that only the Employee class can clone Employee objects. This means no class other than Employee can clone Employee objects since it does not know the Employee class’ attributes.
  • Code size decreases as repetition decreases. 
  • Allows replication (kind of like prototype pattern) manually initilizing each field creates large code if object is complex, its faster with cloning.

Disadvantages:

  • As the Object.clone() method is protected, so need to provide our own clone() and indirectly call Object.clone() from it.
  • If we don’t have any methods then we need to provide a Cloneable interface as we need to provide JVM information so that we can perform a clone() on our object.if not, we cant clone clone does shallow copy of fields if we just return super.clone() from clone method that can be problematic.

73. What are the advantages of passing this into a method instead of the current class object itself?

There are a few advantages of passing this into a method instead of the current class object itself these are:

  • this is the final variable because of which this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

74. What is the constructor?

Constructor is a special method that is used to initialize objects. Constructor is called when a object is created. The name of constructor is same as of the class.

75. What happens if you don’t provide a constructor in a class?

If you don’t provide a constructor in a class in Java, the compiler automatically generates a default constructor with no arguments and no operation which is a default constructor.

76. How many types of constructors are used in Java?

There are two types of constructors in Java as mentioned below:

  • Default Constructor
  • Parameterized Constructor

Default Constructor: It is the type that does not accept any parameter value. It is used to set initial values for object attributes.

Parameterized Constructor: It is the type of constructor that accepts parameters as arguments. These are used to assign values to instance variables during the initialization of objects.

77. What is the purpose of a default constructor?

Constructors help to create instances of a class or can be said to create objects of a class. Constructor is called during the initialization of objects. A default constructor is a type of constructor which do not accept any parameter, So whatever value is assigned to properties of the objects are considered default values.

78. What do you understand by copy constructor in Java?

The copy constructor is the type of constructor in which we pass another object as a parameter because which properties of both objects seem the same, that is why it seems as if constructors create a copy of an object.

79. Where and how can you use a private constructor?

A private constructor is used if you don’t want any other class to instantiate the object to avoid subclassing. The use private constructor can be seen as implemented in the example.

80. What are the differences between the constructors and methods?

Java constructors are used for initializing objects. During creation, constructors are called to set attributes for objects apart from this few basic differences between them are:

  • Constructors are only called when the object is created but other methods can be called multiple times during the life of an object.
  • Constructors do not have a return type, whereas methods have a return type, which can be void or any other type.
  • Constructors are used to setting up the initial state but methods are used to perform specific actions.

81. What is an Interface?

An interface in Java is a collection of static final variables and abstract methods that define the contract or agreement for a set of linked classes. Any class that implements an interface is required to implement a specific set of methods. It specifies the behavior that a class must exhibit but not the specifics of how it should be implemented.

82. Give some features of the Interface.

An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods.

Features of the Interface are mentioned below:

  • The interface can help to achieve total abstraction.
  • Allows us to use multiple inheritances in Java.
  • Any class can implement multiple interfaces even when one class can extend only one class.
  • It is also used to achieve loose coupling.

83. What is a marker interface?

An Interface is recognized as an empty interface (no field or methods) it is called a marker interface. Examples of marker interfaces are Serializable, Cloneable, and Remote interfaces. 

84. What are the differences between abstract class and interface?

Abstract-class-and-interface-768

Abstract Class

Interface Class

Both abstract and non-abstract methods may be found in an abstract class.

The interface contains only abstract methods.

Abstract Class supports Final methods.

The interface class does not support Final methods.

Multiple inheritance is not supported by the Abstract class.

Multiple inheritances is supported by Interface Class.

Abstract Keyword is used to declare Abstract class.

Interface Keyword is used to declare the interface class.

keyword is used to extend an Abstract Class. keyword is used to implement the interface.

Abstract Class has members like protected, private, etc.

All class members are public by default.

85. What do you mean by data encapsulation?

Encapsulation-in-Java-300

Data Encapsulation is the concept of OOPS properties and characteristics of the classes that The interface is binded together. Basically, it bundles data and methods that operate on that data within a single unit. Encapsulation is achieved by declaring the instance variables of a class as private, which means they can only be accessed within the class.

86. What are the advantages of Encapsulation in Java?

The advantages of Encapsulation in Java are mentioned below:

  • Data Hiding:  it is a way of restricting the access of our data members by hiding the implementation details. Encapsulation also provides a way for data hiding. The user will have no idea about the inner implementation of the class. 
  • Increased Flexibility: We can make the variables of the class read-only or write-only depending on our requirements. 
  • Reusability: Encapsulation also improves the re-usability and is easy to change with new requirements.
  • Testing code is easy: Code is made easy to test for unit testing.

87. What is the primary benefit of Encapsulation? 

The main advantage of Encapsulation in Java is its ability to protect the internal state of an object from external modification or access. It is the is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class. The main benefit is of providing a way to control and manage the state and the behavior of an object and also protecting it from modification and unauthorized access at the same time. 

88. What do you mean by aggregation?

Aggregation-in-Java

Aggregation is a term related to the relationship between two classes best described as a “has-a” relationship. This kind is the most specialized version of association. It is a unidirectional association means it is a one-way relationship. It contains the reference to another class and is said to have ownership of that class.

89. What is the ‘IS-A ‘ relationship in OOPs Java?

‘IS-A’ is a type of relationship in OOPs Java where one class inherits another class.

90. Define Inheritance.

When an object that belongs to a subclass acquires all the properties and behavior of a parent object that is from the superclass, it is known as inheritance.  A class within a class is called the subclass and the latter is referred to as the superclass. Sub class or the child class is said to be specific whereas the superclass or the parent class is generic. Inheritance provides code reusability.

91. What are the different types of inheritance in Java?

Inheritance is the method by which the Child class can inherit the features of the Super or Parent class. In Java, Inheritance is of four types:

  • Single Inheritance: When a child or subclass extends only one superclass, it is known to be single inheritance. Single-parent class properties are passed down to the child class. 
  • Multilevel Inheritance: When a child or subclass extends any other subclass a hierarchy of inheritance is created which is known as multilevel inheritance. In other words, one subclass becomes the parent class of another.
  • Hierarchical Inheritance: When multiple subclasses derive from the same parent class is known as Hierarchical Inheritance. In other words, a class that has a single parent has many subclasses.
  • Multiple Inheritance: When a child class inherits from multiple parent classes is known as Multiple Inheritance. In Java, it only supports multiple inheritance of interfaces, not classes.

92. What is multiple inheritance? Is it supported by Java?

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from many parent classes. When methods with the same signature are present in both superclasses and subclasses, an issue arises. The method’s caller cannot specify to the compiler which class method should be called or even which class method should be given precedence. 

Note: Java doesn’t support Multiple Inheritance

93. How is inheritance in C++ different from Java?

C++ lets the user to inherit multiple classes.Java doesn’t support multiple inheritances.
When a class is created in C++, it doesn’t inherit from the object class, instead exists on its own.Java is always said to have a single inheritance as all the classes inherit in one or the other way from the object class.

94. Is there any limitation to using Inheritance?

Yes, there is a limitation of using Inheritance in Java, as because of inheritance one can inherit everything from super class and interface because of which subclass is too clustered and sometimes error-prone when dynamic overriding or dynamic overloading is done in certain situations.

95. Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance is a popular concept of Object-Oriented Programming (OOP), in which a class can inherit the properties and methods from any other class, which is referred to as a Parent or superclass. On the other hand in Composition, a class can contain an instance of another class as a member variable which is often referred to as part or a component. Below are some reasons why composition is more advantageous than inheritance:

  • Tight Coupling: Whenever any changes are made to the superclass, these changes can affect the behavior of all its child or Subclasses. This problem makes code less flexible and also creates issues during maintenance. This problem also leads to the Tight coupling between the classes.
  • Fragile Base Class Problem: When the changes to the base class can break the functionality of its derived classes. This problem can make it difficult to add new features or modify the existing ones. This problem is known as the Fragile Base class problem.
  • Limited Reuse: Inheritance in Java can lead to limited code reuse and also code duplication. As a subclass inherits all the properties and methods of its superclass, sometimes it may end up with unnecessary code which is not needed. This leads to a less maintainable codebase.

96. What is an association?

The association is a relation between two separate classes established through their Objects. It represents Has-A’s relationship.

97. What do you mean by aggregation?

Composition is a restricted form of Aggregation in which two entities are highly dependent on each other. It represents part-of the relationship.

98. What is the composition of Java?

Composition implies a relationship where the child cannot exist independently of the parent. For example Human heart, the heart doesn’t exist separately from a Human.

99. State the difference between Composition and Aggregation.

Aggregation

Composition

It defines a “has a” relationship between the objects

It represents the part-of relationship

Objects are independent of each other.

Objects are dependent on each other.

Represent it by using the filled diamond.

Represent it by using the empty diamond.

Child objects don’t have a lifetime.

Child objects have a lifetime.

100. Can the constructor be inherited?

No, we can’t inherit a constructor.

101. What is Polymorphism?

Polymorphism is defined as the ability to take more than one form It is of two types namely, Compile time polymorphism or method overloading- a function called during compile time. For instance, take a class ‘area’. Based on the number of parameters it may calculate the area of a square, triangle, or circle. Run time polymorphism or method overriding- links during run time.  The method inside a class overrides the method of the parent class.

102. What is runtime polymorphism or dynamic method dispatch?

Dynamic method dispatch is a resolving mechanism for method overriding during the run time. Method overriding is the one where the method in a subclass has the same name, parameters, and return type as a method in the superclass. When the over-ridden method is called through a superclass reference, java determines which version (superclass or subclass) of that method is to be executed based upon the type of an object being referred to at the time the call occurs. Thus the decision is made at run time. This is referred to as dynamic method dispatch.

103. What is method overriding?

Method overriding, also known as run time polymorphism is one where the child class contains the same method as the parent class. For instance, we have a method named ‘gfg()’ in the parent class. A method gfg() is again defined in the sub-class. Thus when gfg() is called in the subclass, the method within the class id executed. Here, gfg() within the class overridden the method outside.

Overloading-in-Java-768

Method overriding is a method to achieve Run-time polymorphism in Java. Method overriding is a feature that allows a child class to provide a specific implementation of a method that is already provided by one of its parent classes. When a method in a child class has the same name, the same parameters or signature, and the same return type(or sub-type) as a method in its parent class, then the method in the subclass is said to override the method in the superclass.

104. What is method overloading?

In Java, Method Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters, or a mixture of both.

Method overloading in Java is also known as   Compile-time Polymorphism , Static Polymorphism, or   Early binding . In Method overloading compared to the parent argument, the child argument will get the highest priority.

105. Can we override the static method?

No, as static methods are part of the class rather than the object so we can’t override them.

106. Can we override the overloaded method?

Yes, since the overloaded method is a completely different method in the eyes of the compiler. Overriding isn’t the same thing at all. The decision as to which method to call is deferred to runtime.

107. Can we overload the main() method?

Yes in Java we can overload the main method to call the main method with the help of its predefined calling method. 

108. What are method overloading and method overriding?

Method Overloading: It is also known as Compile Time Polymorphism. In method overloading two or more methods are shared in the same class with a different signature. 

Method Overriding: Method Overriding occurs when a subclass can provide the implementation of a method which is already defined in the parent class or superclass. The return type, name and arguments must be similar to the methods in superclass.

Method Overloading

Method Overriding

When two or multiple methods are in the same class with different parameters but the same name.

When a subclass provides its own implementation of a method that is already defined in the parent class.

Method overloading can only happen in the same class or between a subclass or parent class.

Method overriding can only happen in Subclass.

When an error occurs it is caught at the compile time of the program.

When an error occurs it is caught at Runtime of the program.

Example of Compile Time Polymorphism.

Example of Run Time Polymorphism.

Method Overloading may or may not require Inheritance.

Method overriding always needs Inheritance.

It occurs within the class.

It is performed in two classes with an inheritance relationship.

109. Can we override the private methods?

It is not possible to override the private methods in Java. Method overriding is where the method in the subclass is implemented instead of the method from the parent class. The private methods are accessible only within the class in which it is declared. Since this method is not visible to other classes and cannot be accessed, it cannot be overridden. 

110. Can we change the scope of the overridden method in the subclass?

In Java, it is not possible to modify the overridden method’s scope. The subclass method’s scope must be equal to or wider than the Superclass method’s overridden method’s scope. The overridden method in the subclass, for instance, can have a public scope or a more accessible scope like protected or default if the overridden method in the superclass has a public scope. It cannot, however, have a more exclusive scope like private.

111. Can we modify the throws clause of the superclass method while overriding it in the subclass?

We can modify the throws clause of the Superclass method with some limitations, we can change the throws clause of the superclass method while overriding it in the subclass. The subclass overridden method can only specify unchecked exceptions if the superclass method does not declare any exceptions. If the superclass method declares an exception, the subclass method can declare the same exception, a subclass exception, or no exception at all. However, the subclass method cannot declare a parent exception that is broader than the ones declared in the superclass method.

112. Can you have virtual functions in Java?

Yes, Java supports virtual functions. Functions are by default virtual and can be made non-virtual using the final keyword.

113. What is Abstraction?

Abstraction refers to the act of representing essential features without including background details. The detailed information or the implementation is hidden. The most common example of abstraction is a car, we know how to turn on the engine, accelerate and move, however, the way engine works, and its internal components are complex logic hidden from the general users. This is usually done to handle the complexity.

114. What is Abstract class?

A class declared as abstract, cannot be instantiated i.e., the object cannot be created. It may or may not contain abstract methods but if a class has at least one abstract method, it must be declared abstract.

Example of an abstract class with abstract method:

115. When Abstract methods are used?

An abstract method is used when we want to use a method but want to child classes to decide the implementation in that case we use Abstract methods with the parent classes.

116. How can you avoid serialization in the child class if the base class is implementing the Serializable interface?

Serialization in the child class if the base class is implementing the Serializable interface then we can avoid it by defining the writeObject() method and throwing NotSerializableException().

117. What is Collection Framework in Java?

Collections are units of objects in Java. The collection framework is a set of interfaces and classes in Java that are used to represent and manipulate collections of objects in a variety of ways. The collection framework contains classes(ArrayList, Vector, LinkedList, PriorityQueue, TreeSet) and multiple interfaces (Set, List, Queue, Deque) where every interface is used to store a specific type of data.

118. Explain various interfaces used in the Collection framework.

Collection framework implements

  • Collection Interface
  • List Interface
  • Set Interface
  • Queue Interface
  • Deque Interface
  • Map Interface

Collection interface: Collection is the primary interface available that can be imported using java.util.Collection.

119. How can you synchronize an ArrayList in Java?

An ArrayList can be synchronized using two methods mentioned below:

  • Using Collections.synchronizedList()
  • Using CopyOnWriteArrayList

Using Collections.synchronizedList():

Using CopyOnWriteArrayList:

  • Create an empty List.
  • It implements the List interface
  • It is a thread-safe variant of ArrayList
  • T represents generic

120. Why do we need a synchronized ArrayList when we have Vectors (which are synchronized) in Java?

ArrayList is in need even when we have Vectors because of certain reasons:

  • ArrayList is faster than Vectors.
  • ArrayList supports multithreading whereas Vectors only supports single-thread use.
  • ArrayList is safer to use, as Vectors supports single threads and individual operations are less safe and take longer to synchronize.
  • Vectors are considered outdated in Java because of their synchronized nature.

121. Why can’t we create a generic array?

Generic arrays can’t be created because an array carries type information of its elements at runtime because of which during runtime it throw ‘ArrayStoreException’ if the elements’ type is not similar. Since generics type information gets erased at compile time by Type Erasure, the array store check would have been passed where it should have failed.

122. Can you explain how elements are stored in memory for both regular arrays and ArrayLists in Java? . Explain.

The elements of a regular array in Java are stored in contiguous memory locations, meaning that each element is stored in a sequential block of memory. This allows easy access to any element by its index because the address can be calculated using the base address of the array and the size of each element

In contrast, the ArrayList class implements a dynamic array, which means that its size can change as elements are added or removed. ArrayList elements are also stored in contiguous memory locations, similar to arrays. However, when an ArrayList reaches its capacity and more elements need to be added, a new, larger underlying array is created. The elements from the old array are then copied to the new one. This process ensures that the ArrayList can grow dynamically while keeping the elements in contiguous memory locations.

123. Explain the method to convert ArrayList to Array and Array to ArrayList.

Conversion of list to arraylist.

There are multiple methods to convert List into ArrayList

Convert-Array-into-ArrayList-768

Programmers can convert an Array to ArrayList using asList() method of the Arrays class. It is a static method of the Arrays class that accepts the List object.

Conversion of ArrayList to Array

Convert-ArrayList-to-Array-768

Java programmers can convert ArrayList to

124. How does the size of ArrayList grow dynamically? And also state how it is implemented internally.

Due to ArrayLists array-based nature, it grows dynamically in size ensuring that there is always enough room for elements. When an ArrayList element is first created, the default capacity is around 10-16 elements which basically depends on the Java version. ArrayList elements are copied over from the original array to the new array when the capacity of the original array is full. As the ArrayList size increases dynamically, the class creates a new array of bigger sizes and it copies all the elements from the old array to the new array. Now, the reference of the new array is used internally. This process of dynamically growing an array is known as resizing. 

125. What is a Vector in Java?

Vectors in Java are similar and can store multiple elements inside them. Vectors follow certain rules mentioned below:

  • Vector can be imported using Java.util.Vector.
  • Vector is implemented using a dynamic array as the size of the vector increases and decreases depending upon the elements inserted in it. 
  • Elements of the Vector using index numbers.
  • Vectors are synchronized in nature means they only used a single thread ( only one process is performed at a particular time ).
  • The vector contains many methods that are not part of the collections framework.

126. How to make Java ArrayList Read-Only?

An ArrayList can be made ready only using the method provided by Collections using the Collections.unmodifiableList() method. 

127. What is a priority queue in Java?

Priority-Queue-768

A priority queue is an abstract data type similar to a regular queue or stack data structure. Elements stored in elements are depending upon the priority defined from low to high. The PriorityQueue is based on the priority heap.

128. Explain the LinkedList class.

LinkedList class is Java that uses a doubly linked list to store elements. It inherits the AbstractList class and implements List and Deque interfaces. Properties of the LinkedList Class are mentioned below:

  • LinkedList classes are non-synchronized.
  • Maintains insertion order.
  • It can be used as a list, stack, or queue.

129. What is the Stack class in Java and what are the various methods provided by it?

A Stack class in Java is a LIFO data structure that implements the Last In First Out data structure. It is derived from a Vector class but has functions specific to stacks. The Stack class in java provides the following methods:

  • peek(): returns the top item from the stack without removing it
  • empty(): returns true if the stack is empty and false otherwise
  • push(): pushes an item onto the top of the stack
  • pop(): removes and returns the top item from the stack
  • search(): returns the 1, based position of the object from the top of the stack. If the object is not in the stack, it returns -1

130. What is Set in the Java Collections framework and list down its various implementations?

Sets are collections that don’t store duplicate elements. They don’t keep any order of the elements. The Java Collections framework provides several implementations of the Set interface, including:

  • HashSet: HashSet in Java, stores the elements in a has table which provides faster lookups and faster insertion. HashSet is not ordered.
  • LinkedHashSet: LinkedHashSet is an implementation of HashSet which maintains the insertion order of the elements.
  • TreeSet: TreeSet stores the elements in a sorted order that is determined by the natural ordering of the elements or by a custom comparator provided at the time of creation.

131. What is the HashSet class in Java and how does it store elements?

The HashSet class implements the Set interface in the Java Collections Framework and is a member of the HashSet class. Unlike duplicate values, it stores a collection of distinct elements. In this implementation, each element is mapped to an index in an array using a hash function, and the index is used to quickly access the element. It produces an index for the element in the array where it is stored based on the input element. Assuming the hash function distributes the elements among the buckets appropriately, the HashSet class provides constant-time performance for basic operations (add, remove, contain, and size).

132. What is LinkedHashSet in Java Collections Framework?

The LinkedHashSet is an ordered version of Hashset maintained by a doubly-linked List across all the elements. It is very helpful when iteration order is needed. During Iteration in LinkedHashSet, elements are returned in the same order they are inserted.

133. What is a Map interface in Java?

Map-Interface-in-Java-660

The map interface is present in the Java collection and can be used with Java.util package. A map interface is used for mapping values in the form of a key-value form. The map contains all unique keys. Also, it provides methods associated with it like containsKey(), contains value (), etc. 

There are multiple types of maps in the map interface as mentioned below:

  • LinkedHashMap

134. Explain Treemap in Java

TreeMap is a type of map that stores data in the form of key-value pair. It is implemented using the red-black tree. Features of TreeMap are :

  • It contains only unique elements.
  • It cannot have a NULL key 
  • It can have multiple NULL values.
  • It is non-synchronized.
  • It maintains ascending order.

135. What is EnumSet?

EnumSet is a specialized implementation of the Set interface for use with enumeration type. A few features of EnumSet are:

  • Faster than HashSet.
  • All of the elements in an EnumSet must come from a single enumeration type.
  • It doesn’t allow null Objects and throws NullPointerException for exceptions.
  • It uses a fail-safe iterator.

Parameter: E specifies the elements.

136. What is BlockingQueue?

BlockingQueue-768

A blocking queue is a Queue that supports the operations that wait for the queue to become non-empty while retrieving and removing the element, and wait for space to become available in the queue while adding the element.

Parameters: E is the type of elements stored in the Collection

137. What is the ConcurrentHashMap in Java and do you implement it?

ConcurrentHashMap is implemented using Hashtable.

Parameters : K is the key Object type and V is the value Object type

138. Can you use any class as a Map key?

Yes, we can use any class as a Map Key if it follows certain predefined rules mentioned below:

  • The class overriding the equals() method must also override the hashCode() method
  • The concurrentHashMap class is thread-safe.
  • The default concurrency level of ConcurrentHashMap is 16.
  • Inserting null objects in ConcurrentHashMap is not possible as a key or as value.

139. What is an Iterator?

Iterator-in-Java-768

The Iterator interface provides methods to iterate over any Collection in Java. Iterator is the replacement of Enumeration in the Java Collections Framework. It can get an iterator instance from a Collection using the _iterator()_ method.  It also allows the caller to remove elements from the underlying collection during the iteration.

140. What is an enumeration?

Enumeration is a user-defined data type. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. The main objective of the enum is to define user-defined data types.

141. What is the difference between Collection and Collections?

Collection

Collections

The Collection is an Interface.

Collections is a class.

It provides the standard functionality of data structure.

It is to sort and synchronize the collection elements.

It provides the methods that can be used for the data structure.

It provides static methods that can be used for various operations.

142. Differentiate between Array and ArrayList in Java.

Single-dimensional or multidimensional 

Single-dimensional 

For and for each used for iteration

Here iterator is used to traverse riverArrayList 

length keyword returns the size of the array. 

size() method is used to compute the size of ArrayList.

The array has Fixed-size.

ArrayList size is dynamic and can be increased or decreased in size when required.

It is faster as above we see it of fixed size

It is relatively slower because of its dynamic nature 

Primitive data types can be stored directly in unlikely objects.

Primitive data types are not directly added to unlikely arrays, they are added indirectly with help of autoboxing and unboxing

They can not be added here hence the type is in the unsafe.

They can be added here hence makingArrayList type-safe. 

The assignment operator only serves the purpose

Here a special method is used known as add() method  

143. What is the difference between Array and Collection in Java?

Array

Collections

Array in Java has a fixed size.                                        

Collections in Java have dynamic sizes.

In an Array, Elements are stored in contiguous memory locations. 

In Collections, Elements are not necessarily stored in contiguous memory locations.

Objects and primitive data types can be stored in an array.

We can only store objects in collections.

Manual manipulation is required for resizing the array.

Resizing in collections is handled automatically.

The array has basic methods for manipulation.

Collections have advanced methods for manipulation and iteration.

The array is available since the beginning of Java.

Collections were introduced in Java 1.2.

144. Difference between ArrayList and LinkedList.

ArrayList

LinkedList

ArrayList is Implemented as an expandable Array.

LinkedList is Implemented as a doubly-linked list.

In ArrayList, Elements are stored in contiguous memory locations 

LinkedList Elements are stored in non-contiguous memory locations as each element has a reference to the next and previous elements.

ArrayLists are faster for random access.

LinkedLists are faster for insertion and deletion operations

ArrayLists are more memory efficient. 

LinkedList is less memory efficient

ArrayLists Use more memory due to maintaining the array size.              

LinkedList Uses less memory as it only has references to elements

The search operation is faster in ArrayList.

The search operation is slower in LinkedList

145. Differentiate between ArrayList and Vector in Java.

ArrayList

Vector

is mplemented as a resizable array.

is mplemented as a synchronized, resizable array.

ArrayList is not synchronized. 

The vector is synchronized.

ArrayLists are Faster for non-concurrent operations.

Vector is Slower for non-concurrent operations due to added overhead of synchronization.

ArrayLists were Introduced in Java 1.2.

Vector was Introduced in JDK 1.0.

Recommended for use in a single-threaded environment.

Vectors are Recommended for use in a multi-threaded environment.

The default initial capacity of ArrayLists is 10.

In Vectors, the default initial capacity is 10 but the default increment is twice the size.

ArrayList performance is high.

Vector performance is low.

146. What is the difference between Iterator and ListIterator?

Iterator

ListIterator

Can traverse elements present in Collection only in the forward direction.                                          

Can traverse elements present in Collection both in forward and backward directions.

Used to traverse Map, List, and Set.

Can only traverse List and not the other two.

Indexes can’t be obtained using Iterator

It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing the List.

Can’t modify or replace elements present in Collection

Can modify or replace elements with the help of set(E e)

Can’t add elements, and also throws ConcurrentModificationException.

Can easily add elements to a collection at any time.

Certain methods of Iterator are next(), remove(), and hasNext().

Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e).

147. Differentiate between HashMap and HashTable.

HashMap

HashTable

HashMap is not synchronized

HashTable is synchronized

One key can be a NULL value

NULL values not allowed

The iterator is used to traverse HashMap.

Both Iterator and Enumertar can be used

HashMap is faster.

HashTable is slower as compared to HashMap.

148. What is the difference between Iterator and Enumeration?

Iterator

Enumeration

The Iterator can traverse both legacies as well as non-legacy elements.

Enumeration can traverse only legacy elements.

The Iterator is fail-fast.

Enumeration is not fail-fast.

The Iterators are slower.

Enumeration is faster.

The Iterator can perform a remove operation while traversing the collection.

The Enumeration can perform only traverse operations on the collection.

149. What is the difference between Comparable and Comparator?

Comparable

Comparator

The interface is present in java.lang package.

The Interface is present in java.util package.

Provides compareTo() method to sort elements.

Provides compare() method to sort elements.

It provides single sorting sequences.

It provides multiple sorting sequences.

The logic of sorting must be in the same class whose object you are going to sort.

The logic of sorting should be in a separate class to write different sorting based on different attributes of objects.

Method sorts the data according to fixed sorting order.

Method sorts the data according to the customized sorting order.

It affects the original class.

It doesn’t affect the original class.

Implemented frequently in the API by Calendar, Wrapper classes, Date, and String.

It is implemented to sort instances of third-party classes.

150. What is the difference between Set and Map?

Set

Map

The Set interface is implemented using java.util package.

The map is implemented using java.util package.

It can extend the collection interface.

It does not extend the collection interface.

It does not allow duplicate values.

It allows duplicate values.

The set can sort only one null value.

The map can sort multiple null values.

151. Explain the FailFast iterator and FailSafe iterator along with examples for each.

A FailFast iterator is an iterator that throws a ConcurrentModificationException if it detects that the underlying collection has been modified while the iterator is being used. This is the default behavior of iterators in the Java Collections Framework. For example, the iterator for a HashMap is FailFast.

A FailSafe iterator does not throw a ConcurrentModificationException if the underlying collection is modified while the iterator is being used. Alternatively, it creates a snapshot of the collection at the time the iterator is created and iterates over the snapshot. For example, the iterator for a ConcurrentHashMap is FailSafe.

152. What is Exception Handling?

An Exception is an Event that interrupts the normal flow of the program and requires special processing. During the execution of a program, errors and unplanned occurrences can be dealt with by using the Java Exception Handling mechanism. Below are some reasons why Exceptions occur in Java:

  • Device failure
  • Loss of Network Connection
  • Code Errors
  • Opening an Unavailable file
  • Invalid User Input
  • Physical Limitations (out of disk memory)

153. How many types of exceptions can occur in a Java program?

Types-of-Exception-in-Java-660

There are generally two types of exceptions in Java:

  • ArrayIndexOutOfBoundsExceptions
  • ClassNotFoundException
  • FileNotFoundException
  • IOException
  • NullPointerException
  • ArithmeticException
  • InterruptedException
  • RuntimeException
  • User-Defined Exceptions: User-defined exceptions are defined by the programmers themselves to handle some specific situations or errors which are not covered by built-in exceptions. To define user-defined exceptions a new class that extends the appropriate exception class must be defined. User-defined Exceptions in Java are used when the built-in exceptions are in Java.

154. Difference between an Error and an Exception.

Recovering from Errors is not possible.                            

Recover from exceptions by either using a try-catch block or throwing exceptions back to the caller.

Errors are all unchecked types in Java.

It includes both checked as well as unchecked types that occur.

Errors are mostly caused by the environment in which the program is running.

The program is mostly responsible for causing exceptions.

Errors can occur at compile time as well as run time. Compile Time: Syntax Error, Run Time: Logical Error.

All exceptions occur at runtime but checked exceptions are known to the compiler while unchecked are not.

They are defined in java.lang.Error package.

They are defined in java.lang.Exception package

: java.lang.StackOverflowError, java.lang.OutOfMemoryError

: Checked Exceptions: SQLException, IOException Unchecked Exceptions: ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.

155. Explain the hierarchy of Java Exception classes.

Exception-Handling-768

All exception and error types in Java are subclasses of the class throwable, which is the base class of the hierarchy. This class is then used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, error is used by the Java run-time system to indicate errors having to do with the JRE. StackOverflowError is an example of one of such error.

156. Explain Runtime Exceptions.

Runtime Exceptions are exceptions that occur during the execution of a code, as opposed to compile-time exceptions that occur during compilation. Runtime exceptions are unchecked exceptions, as they aren’t accounted for by the JVM.

Examples of runtime exceptions in Java include:

  • NullPointerException: This occurs when an application attempts to use a null object reference.
  • ArrayIndexOutOfBoundsException: This occurs when an application attempts to access an array index that is out of bounds.
  • ArithmeticException: This occurs when an application attempts to divide by zero.
  • IllegalArgumentException: This occurs when a method is passed on an illegal or inappropriate argument.

Unlike checked exceptions, runtime exceptions do not require a declaration in the throws clause or capture in a try-catch block. However, handling runtime exceptions is advisable in order to provide meaningful error messages and prevent a system crash. Because runtime exceptions provide more specific information about the problem than checked exceptions, they enable developers to detect and correct programming errors more easily and quickly.

157. What is NullPointerException?

It is a type of run-time exception that is thrown when the program attempts to use an object reference that has a null value. The main use of NullPointerException is to indicate that no value is assigned to a reference variable, also it is used for implementing data structures like linked lists and trees. 

158. When is the ArrayStoreException thrown?

ArrayStoreException is thrown when an attempt is made to store the wrong type of object in an array of objects.

159. What is the difference between Checked Exception and Unchecked Exception?

Checked exception:.

Checked Exceptions are the exceptions that are checked during compile time of a program. In a program, if some code within a method throws a checked exception, then the method must either handle the exception or must specify the exception using the throws keyword. 

Checked exceptions are of two types: 

  • Fully checked exceptions: all its child classes are also checked, like IOException, and InterruptedException.
  • Partially checked exceptions: some of its child classes are unchecked, like an Exception. 

Unchecked Exception:

Unchecked are the exceptions that are not checked at compile time of a program. Exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. 

160. What is the base class for Error and Exception?

Error is an illegal operation performed by the user which causes abnormality in the program. Exceptions are the unexpected events or conditions that comes while running the program, exception disrupts the normal flow of the program’s instructions.

Errors and Exceptions both have a common parent class which is java.lang.Throwable class.

161. Is it necessary that each try block must be followed by a catch block?

No, It is not necessary to use catch block after try block in Java as we can create another combination with finally block. Finally is the block which runs despite the fact that the exception is thrown or not.

162. What is exception propagation?

Exception propagation is a process in which the exception is dropped from to the top to the bottom of the stack. If not caught once, the exception again drops down to the previous method, and so on until it gets caught or until it reaches the very bottom of the call stack.

163. What will happen if you put System.exit(0) on the try or catch block? Will finally block execute?

System.exit(int) has the capability to throw SecurityException. So, if in case of security, the exception is thrown then finally block will be executed otherwise JVM will be closed while calling System. exit(0) because of which finally block will not be executed.

164. What do you understand by Object Cloning and how do you achieve it in Java?

It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is:

Protected Object clone() throws CloneNotSupportedException{ return (Object)super.clone();}In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

165. How do exceptions affect the program if it doesn’t handle them?

Exceptions are responsible for abruptly terminating the running of the program while executing and the code written after the exception occurs is not executed.

166. What is the use of the final keyword?

The final keyword is used to make functions non-virtual. By default, all the functions are virtual so to make it non-virtual we use the final keyword.

167. What purpose do the keywords final, finally, and finalize fulfill?

final is a keyword is used with the variable, method, or class so that they can’t be overridden. 

ii). finally

finally is a block of code used with “try-catch” in exception handling. Code written in finally block runs despite the fact exception is thrown or not.

iii). finalize

It is a method that is called just before deleting/destructing the objects which are eligible for Garbage collection to perform clean-up activity.

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

this( )

super( )

It represents the current instance of the class.

It represents the current instance of the parent class.

Calls the default constructor of the same class.

Calls the default constructor of the base class.

Access the methods of the same class.

Access the methods of the parent class.

Points current class instance.

Points the superclass instance.

169. What is multitasking?

Multitasking in Java refers to a program’s capacity to carry out several tasks at once. Threads, which are quick operations contained within a single program, can do this. Executing numerous things at once is known as multitasking.

170. What do you mean by a Multithreaded program?

Multithreaded programs in Java contain threads that run concurrently instead of running sequentially. A computer can use its resources more efficiently by combining multiple tasks at once. Any program with multithreading allows more than one user to simultaneously use the program without running multiple copies. A multithreaded program is designed to run multiple processes at the same time which can improve the performance of a program and allows the program to utilize multiple processors and improves the overall throughput.

171. What are the advantages of multithreading?

There are multiple advantages of using multithreading which are as follows:

  • Responsiveness: User Responsiveness increases because multithreading interactive application allows running code even when the section is blocked or executes a lengthy process.
  • Resource Sharing: The process can perform message passing and shared memory because of multithreading.
  • Economy: We are able to share memory because of which the processes are economical.
  • Scalability: Multithreading on multiple CPU machines increases parallelism.
  • Better Communication: Thread synchronization functions improves inter-process communication.
  • Utilization of multiprocessor architecture
  • Minimized system resource use

172. What are the two ways in which Thread can be created?

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of the CPU. In general, threads are small, lightweight processes with separate paths of execution. These threads use shared memory, but they act independently, thus if any one thread fails it does not affect the other threads. There are two ways to create a thread:

By extending the Thread class

  • By implementing a Runnable interface.

We create a class that extends the java.lang.Thread class . This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. 

By implementing the Runnable interface

We create a new class that implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call the start() method on this object. 

173. What is a thread?

Threads in Java are subprocess with lightweight with the smallest unit of processes and also has separate paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that do not affect the working of other threads despite them sharing the same memory. A thread has its own program counter, execution stack, and local variables, but it shares the same memory space with other threads in the same process. Java provides built-in support for multithreading through the Runnable interface and the Thread class .

174. Differentiate between process and thread?

A process and a thread are both units of execution in a computer system, but they are different in several ways:

Process

Thread

A process is a program in execution.

A thread is a single sequence of instructions within a process.

The process takes more time to terminate.

The thread takes less time to terminate.

The process takes more time for context switching.

The thread takes less time for context switching.

The process is less efficient in terms of communication.

Thread is more efficient in terms of communication.

The process is isolated.

Threads share memory.

The process has its own Process Control Block, Stack, and Address Space.                   

Thread has Parents’ PCB, its own Thread Control Block, and Stack and common Address space.

The process does not share data with each other.

Threads share data with each other.

175. Describe the life cycle of the thread?

Cycle-of-thread-768

A thread in Java at any point in time exists in any one of the following states. A thread lies only in one of the shown states at any instant: 

  • New: The thread has been created but has not yet started.
  • Runnable: The thread is running, executing its task, or is ready to run if there are no other higher-priority threads.
  • Blocked: The thread is temporarily suspended, waiting for a resource or an event.
  • Waiting: The thread is waiting for another thread to perform a task or for a specified amount of time to elapse.
  • Terminated: The thread has completed its task or been terminated by another thread.

176. Explain suspend() method under the Thread class.

The suspend() method of the Thread class in Java temporarily suspends the execution of a thread. When a thread is suspended it goes into a blocked state and it would not be scheduled by the operating system which means that it will not be able to execute its task until it is resumed. There are more safer and flexible alternatives to the suspend() methods in the modern java programming language. This method does not return any value.

177. Explain the main thread under Thread class execution.

Java provides built-in support for multithreaded programming. The main thread is considered the parent thread of all the other threads that are created during the program execution. The main thread is automatically created when the program starts running. This thread executes the main method of the program. It is responsible for executing the main logic of the Java program as well as handling the user input operations. The main thread serves as the base thread from which all other child threads are spawned. 

Thread-Class-Execution-768

178. What is a daemon thread?

A daemon thread in Java is a low-priority thread that is used to perform background operations or tasks which are used to perform continuously. such as Garbage collection, Signal dispatches, Action listeners, etc. Daemon threads in Java have lower priority than user threads, which means they can only execute when no user threads are running. Daemon threads in Java are useful features that are required for background tasks that do not require explicit shutdown or finalization. It allows more efficient use of system resource and are used to simplify resources and can simplify long-running tasks.

179. What are the ways in which a thread can enter the waiting state?

Thread is a lightweight process that runs concurrently with the other thread inside a single process. Each thread can execute a different task and share the resources within a single process. Thread in Java can enter the waiting state in many different ways:

  • Sleep() method Call: The sleep () method is used to pause the execution of the thread for a specific amount of time. While the thread is paused it goes into the waiting state.
  • Wait() method: This method is used to wait a thread until the other thread signals it to wake up. Thread goes into the waiting state until it receives a notification from another thread.
  • Join() method: Join() method can be used to wait for thread to finish the execution. Calling thread goes into the waiting state until the target thread is completed.
  • Waiting for I/O operations: If the thread is waiting for Input/Output operation to complete, it goes into the waiting state until the operation is finished.
  • Synchronization Issues: If there are any synchronization issues in a multi-threaded application, threads may go into the waiting state until the synchronization issues are resolved.

180. How does multi-threading take place on a computer with a single CPU?

Java uses a technique called time-sharing, commonly referred to as time-slicing, to implement multi-threading on computers with a single CPU. The appearance of parallel execution is created by the CPU switching between active threads. The operating system is in charge of allocating CPU time to each thread sequentially and scheduling the threads.

In order to stop threads from interacting with one another and creating race situations or other issues, Java has a number of ways to govern the behavior of threads, including synchronization and locking. It is feasible to create multi-threaded programmers that operate correctly and effectively on a machine with a single CPU by regulating the interaction between threads and making sure that crucial code parts are synchronized. In contrast to running the same program on a computer with multiple CPUs or cores, multi-threading on a single CPU can only give the appearance of parallelism, and actual performance gains may be modest. The operating system divides the CPU time that is available when numerous threads are running on a single CPU into small time slices and gives each thread a time slice to execute. Rapid switching between the threads by the operating system creates the appearance of parallel execution. The switching between threads appears to be immediate because the time slices are often very tiny, on the order of milliseconds or microseconds.

181. What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

Priorities in threads is a concept where every thread is having a priority which in layman’s language one can say every object is having priority here which is represented by numbers ranging from 1 to 10. There are different types of thread properties in Java mentioned below:

  • MIN_PRIORITY
  • MAX_PRIORITY
  • NORM_PRIORITY 

By default, the thread is assigned NORM_PRIORITY.

182. Why Garbage Collection is necessary in Java?

For Java, Garbage collection is necessary to avoid memory leaks which can cause the program to crash and become unstable. There is no way to avoid garbage collection in Java. Unlike C++, Garbage collection in Java helps programmers to focus on the development of the application instead of managing memory resources and worrying about memory leakage. Java Virtual Machine (JVM) automatically manages the memory periodically by running a garbage collector which frees up the unused memory in the application. Garbage collection makes Java memory efficient because it removes unreferenced objects from the heap memory.

183. What is the drawback of Garbage Collection?

Apart from many advantages, Garbage Collector has certain drawbacks mentioned below:

  • The main drawback to Garbage collection is that it can cause pauses in an application’s execution as it works to clear the memory which slows down the performance of the application. 
  • The Process of Garbage collection is non-deterministic which makes it difficult to predict when garbage collection occurs which causes unpredictable behavior in applications. For Example, if we write any program then it is hard for programmers to decide if the issue is caused by garbage collection or by any other factors in the program. 
  • Garbage collection can also increase memory usage if the program creates and discards a lot of short-lived objects.

184. Explain the difference between a minor, major, and full garbage collection.

The Java Virtual Machine (JVM) removes objects that are no longer in use using a garbage collector which periodically checks and removes these objects. There are different types of garbage collection in the JVM, each with different characteristics and performance implications. The main types of garbage collection are:

  • Minor garbage collection: Also known as young generation garbage collection, this type of garbage collection is used to collect and reclaim memory that is used by short-lived objects (objects that are quickly created and discarded). 
  • Major garbage collection: Also known as old-generation garbage collection, this type of garbage collection is used to collect and reclaim memory that is used by long-lived objects (objects that survive multiple minor garbage collections and are promoted to the old generation).
  • Full garbage collection: During full garbage collection, memories from all generations are collected and reclaimed, including memories of young and old. A full garbage collection normally takes longer to complete than a minor or major garbage collection which causes that app to pause temporarily.

185. How will you identify major and minor garbage collections in Java?

Major garbage collection works on the survivor space and Minor garbage collection works on the Eden space to perform a mark-and-sweep routine. And we can identify both of them based on the output where the minor collection prints “GC”, whereas the major collection prints “Full GC” for the case where the garbage collection logging is enabled with “-XX:PrintGCDetails” or “verbose:gc”.

186. What is a memory leak, and how does it affect garbage collection?

In Java Memory leaks can be caused by a variety of factors, such as not closing resources properly, holding onto object references longer than necessary, or creating too many objects unnecessarily. There are situations in which garbage collector does not collect objects because there is a reference to those objects. In these situations where the application creates lots of objects and does not use them and every object has some valid references, a Garbage collector in Java cannot destroy the objects. These useless objects which do not provide any value to the program are known as Memory leaks. Memory leaks can impact garbage collection negatively by preventing the garbage collector from reclaiming unused memory. This behavior will lead to slow performance or sometimes system failure. In a program, it is important to avoid memory leaks by managing resources and object references properly. 

187. Name some classes present in java.util.regex package.

Regular Expressions or Regex in Java is an API used for searching and manipulating of strings in Java. It creates String patterns that can extract the data needed from the strings or can generalize a pattern.

There are 3 Classes present in java.util.regex mentioned below:

  • Pattern Class: Can define patterns
  • Matcher Class: Can perform match operations on text using patterns
  • PatternSyntaxException Class: Can indicate a syntax error in a regular expression pattern.

Also, apart from the 3 classes package consists of a single interface MatchResult Interface which can be used for representing the result of a match operation.

188. Write a regular expression to validate a password. A password must start with an alphabet and followed by alphanumeric characters; Its length must be in between 8 to 20.

Explanation:

  • ^ used for starting character of the string.
  • (?=.*[0-9]) used for a digit must occur at least once.
  • (?=.*[a-z]) used for a lowercase alphabet must occur at least once.
  • (?=.*[A-Z]) used for an upper case alphabet that must occur at least once in the substring.
  • (?=.*[@#$%^&-+=()] used for a special character that must occur at least once.
  • (?=\\S+$) white spaces don’t allow in the entire string.
  • .{8, 20} used for at least 8 characters and at most 20 characters.
  • $ used for the end of the string.

189. What is JDBC?

JDBC standard API is used to link Java applications and relational databases. It provides a collection of classes and interfaces that let programmers to use the Java programming language to communicate with the database. The classes and interface of JDBC allow the application to send requests which are made by users to the specified database. There are generally four components of JDBC by which it interacts with the database:

  • JDBC Driver manager
  • JDBC Test Suite
  • JDBC-ODBC Bridge Drivers

JDBC-768

190. What is JDBC Driver?

JDBC Driver is a software component that is used to enable a Java application to interact with the database. JDBC provides the implementation of the JDBC API for a specific database management system, which allows it to connect the database, execute SQL statements and retrieve data. There are four types of JDBC drivers:

  • JDBC-ODBC Bridge driver
  • Native-API driver
  • Network Protocol driver
  • Thin driver

JDBC-Driver-660

191. What are the steps to connect to the database in Java?

There are certain steps to connect the database and Java Program as mentioned below:

  • Import the Packages
  • Load the drivers using the forName() method 
  • Register the drivers using DriverManager 
  • Establish a connection using the Connection class object
  • Create a statement
  • Execute the query
  • Close the connections

192. What are the JDBC API components?

JDBC API components provide various methods and interfaces for easy communication with the databases also it provides packages like java Se and java EE which provides the capability of write once run anywhere (WORA).

193. What is JDBC Connection interface?

Java database connectivity interface (JDBC) is a software component that allows Java applications to interact with databases. To enhance the connection, JDBC requires drivers for each database.

194. What does the JDBC ResultSet interface?

JDBC ResultSet interface is used to store the data from the database and use it in our Java Program. We can also use ResultSet to update the data using updateXXX() methods. ResultSet object points the cursor before the first row of the result data. Using the next() method, we can iterate through the ResultSet.

195. What is the JDBC Rowset?

A JDBC RowSet provides a way to store the data in tabular form. RowSet is an interface in java that can be used within the java.sql package. The connection between the RowSet object and the data source is maintained throughout its life cycle. RowSets are classified into five categories based on implementation mentioned below:

  • CachedRowSet
  • FilteredRowSet

196. What is the role of the JDBC DriverManager class?

JDBC DriverManager class acts as an interface for users and Drivers. It is used in many ways as mentioned below: 

  • It is used to create a connection between a Java application and the database. 
  • Helps to keep track of the drivers that are available.
  • It can help to establish a connection between a database and the appropriate drivers.
  • It contains all the methods that can register and deregister the database driver classes.
  • DriverManager.registerDriver() method can maintain the list of Driver classes that have registered themselves.

197. Differentiate between Iterable and Iterator.

Iterable

Iterator

Iterable provides a way to iterate over a sequence of elements.

Iterator helps in iterating over a collection of elements sequentially.

method returns an Iterator. and methods are required.
method is optional. method is required in the iterator.

Examples are

Examples are

198. Differentiate between List and Set.

List

Set

Ordered

Unordered

List allows duplicates.

Set does not allow duplicate values.

List is accessed by index.

Set is accessed by hashcode.

Multiple null elements can be stored.

Null element can store only once.

Examples are ArrayList, LinkedList, etc.

Examples are HashSet and TreeSet. LinkedHashSet etc.

199. Differentiate between List and Map.

List

Map

List interface allows duplicate elements.

Map does not allow duplicate elements.

List maintains insertion order.

Map do not maintain insertion order.

Multiple null elements can be stored.

The map allows a single null key at most and any number of null values.

The list provides get() method to get the element at a specified index.

The map does not provide a get method to get the elements at a specified index.

List is Implemented by ArrayList, etc.

Map is Implemented by HashMap, TreeMap, LinkedHashMap

200. Differentiate between Queue and Stack.

Queue

Stack

Queue data structure is used to store elements, and is used to perform operations like enqueue, dequeue from back or end of the queue.

Stack data structure is used to store elements, and is used to perform operations like push, pop from top of the stack.

Queue data structure Implements FIFO order.

Stack data structure Implements LIFO order.

Insertion and deletion in queues take place from the opposite ends of the list. Deletion takes place from the front of the list and insertion takes place at the rear of the list.

Insertion and deletion in stacks take place only from one end of the list called the top.

Insert operation is called enqueue operation.

Insert operation is called Push operation.

Queue is generally used to solve problems related to sequential processing.

Stack is generally used to solve problems related to recursion.

201. Differentiate between PriorityQueue and TreeSet.

Priority Queue

TreeSet

It uses Queue as an underlying data structure.

It uses a Set as an underlying data structure.

This data structure allows duplicate elements

This data structure does not allow duplicate elements

Priority Queue is Implemented by PriorityQueue class.

TreeSet is implemented by TreeSet class.

PriorityQueue comes in JDK 1.5. 

TreeSet comes in JDK 1.4.

PriorityQueue<Integer> pq = new PriorityQueue<>();

reeSet<Integer> ts = new TreeSet<>();

202. Differentiate between the Singly Linked List and Doubly Linked List.

Singly Linked List

Doubly Linked List

Singly Linked List contain only two segments i.e, Data and Link.

Doubly Linked List contains three segments i.e, Data, and two pointers.

Traversal in a singly linked list is possible in only a forward direction.

Traversal in a doubly linked list is only possible in both directions forward as well as backward.

It uses less memory as every single node has only one pointer.

It requires more memory than a singly linked list as each node has two pointers.

Easy to use and insert nodes at the beginning of the list.

Slightly more complex to use and easy to insert at the end of the list.

The time complexity of insertion and deletion is O(n).

The time complexity of insertion and deletion is O(1).

203. Differentiate between Failfast and Failsafe.

FailFast

FailSafe

Failsfast fails immediately when it detects concurrent modification during the time of iteration.

Failsafe continues to iterate over the original collection and also creates a copy to modify.

Failfast is generally used in single-threaded environments.

Failsafe is used in multithreaded environments.

Failfast does not allow any modification while iteration.

Failsafe allows modification during the time of iteration.

Failfast is fast compared to failsafe as it does not involve the copying of the collection.

Failsafe is generally slow compared to failfast.

FailFast throws if the collection is modified during iteration.


FailSafe does not throws any exception but instead, it creates a copy of the collection to iterate.

204. Differentiate between HashMap and TreeMap.

HashMap

TreeMap

Hasmap uses a hashtable in order to store key-value pairs.

Treemap uses Red-black trees to store key-value pair.

Hashmap does not maintain any specific order for key-value pairs.

Treemap maintains a natural ordering based on the keys.

Order of iteration is not guaranteed in the hashmap.

Iteration is of sorted order based on keys.

Hashmaps are faster for retrieval compared to Treemap.

Retrieval in Treemap is slower as it uses tree traversal to find keys.

Hashmap is implemented by using an Array of linked list.

TreeMap is implemented using a Red-black Tree.

Hashmap uses the equals() method of the Object class to compare keys.

TreeMap uses compareTo() method to compare keys.

205. Differentiate between Queue and Deque.

Queue

Deque

The queue is a linear Data structure that is used to store a collection of elements.

Deque also known as a Double-ended queue is also a linear data structure that stores a collection of elements with operations to remove and add from both ends.

Elements in the queue can only be inserted at the end of the data structure.

Elements can be inserted from both ends of the data structure.

Queue can be implemented using Array or Linked List.

Dequeue can be implemented using Circular Array or Doubly Linked List.

Queues are generally used to implement a waiting list or task queue.

Deque is used to implement a stack or dequeuing elements from both ends.

206. Differentiate between HashSet and TreeSet.

HashSet

TreeSet

HashSet is unordered.

TreeSet is based on natural ordering.

HashSet allows null elements.

TreeSet does not allow null elements.

HashSet is Implemented by the HashSet class.

TreeSet is Implemented by TreeSet class.

HashSet<String> hs = new HashSet<>();

TreeSet<String> ts = new TreeSet<>();

Core-Java-Interview-Questions

Java Interview Questions – FAQs

Q1. what is a java developer’s salary in india.

According to various resources, The average salary of a Java Backend Developer is more than 14 lakhs per annum which is 30% higher than any other developer role . Here you can also check our latest course on Java Backend Development !

Q2. What does Java Developer do?

A Java developer writes code, designs software solutions, and builds applications using the Java programming language. They collaborate with teams, solve problems, and ensure code quality for efficient and reliable software development.

Q3. What are the essential skills required for a Java developer?

A Java developer should have a strong understanding of core Java concepts such as object-oriented programming, data types, control structures, and exception handling. Additionally, knowledge of frameworks like Spring, Hibernate, and web development technologies like Servlets and JSP is beneficial. Other than Technical Skills Problem-solving, debugging, and critical thinking skills are also highly valued.

Q4. How can I prepare for a Java interview?

To prepare for a Java interview, start by reviewing fundamental Java concepts and practice coding exercises. Study common interview questions related to core Java, data structures, algorithms, and multithreading from GeeksforGeeks Interview Section . Additionally, brush up on design patterns, database connectivity, and web development frameworks. Practising coding challenges on platforms like GeekforGeeks Practice Portal can also be helpful.

Q5. How can I stand out in a Java interview?

To stand out in a Java interview, demonstrate a deep understanding of Java concepts and practical applications. Showcase your problem-solving skills by explaining your approach to complex scenarios and providing efficient solutions. Additionally, highlight any relevant projects or contributions you’ve made to the Java community. Showing enthusiasm, good communication, and a willingness to learn can also leave a positive impression.

Please Login to comment...

Similar reads.

  • Interview Questions
  • interview-preparation
  • interview-questions
  • Java-Interview

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javarevisited

Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions

Topics and Categories

  • collections
  • multithreading
  • design patterns
  • interview questions
  • data structure
  • Java Certifications
  • jsp-servlet
  • online resources
  • jvm-internals

Monday, July 1, 2024

  • Top 50 Java Programs from Coding Interviews

Big O Notation cheat sheet

  • 50+ Data Structure and Algorithms Interview Questions
  • 20+ Basic Algorithms Questions from Interviews
  • 20 System Design Interview Questions 
  • How to Crack System Design Interview [The Ultimate Guide]
  • 10 Dynamic Programming Interview Questions
  • 10 Matrix based Coding Problems for Interviews
  • 100+ System Design Interview Questions
  • 25 Recursion based Coding Interview Questions and Answers

31 comments :

Nice collection of interview question

Good Programmas

Good collection

Do you know any other books recommended for coding interviews?

I used: "Cracking the Coding Interview" by Gayle Laakmann McDowell "TOP 30 Java Interview Coding Tasks" by Matthew Urban "Elements of Programming Interviews in Java" by Adnan Aziz, Tsung-Hsien Lee, Amit Prakash "Coding Interview Questions" by Narasimha Karumanchi

nice collection of questions. Thank you.

Really helpful ! Thanks !

String palindrome is found with error.unable to view it

Hello @Unknown, can you give more details? you mean you can't see the solution?

Ah got it, the link is incorrect, I'll correct it.

perfect ...thank you,Guys!

Thanks! for help,guys.

Very nice.. But I need a differential and integral problems in java If any one think about it reply me... We'll discuss about it😊😊😊

Nice thank you

It's very much benificial for us

My problem with this type of question is that most of them do not reflect the types of problems you encounter on the job. A good java programmer knows how to perform task needed by the job. A DB centric application will manipulate many data results efficiently. That might mean knowing lists, iterations, or using lombok. A realtime application will be more focused on things like concurrency. I've used Java professionally since it was in beta nad have never had to shift bits.

Hello Bill, interview and real work is always different. It's part of the culture we have. I think asking these kind of question is to check if people have good fundamental knowledge or not. This is important for engineering a solution rather than just coding. For example, if you know about paging, swap memory, virtual memory you will be better equipped to solve memory related problems of Java application. Just my 2 cent.

Can u plzz help me in solving the below pattern-: 55555 54444 54333 54322 54321

@Unknown, I can give you an hint, use two for loop and a combination of system.out.println() and system.print() to print this pattern

@Unknown public static void main(String[] s) { int i=55555; int r=1111; System.out.println(i); for(int j=0;j<4;j++) { i=i-r; System.out.println(i); r=r/10; }

@Unknown public static void main(String []args){ String num = ""; for(int i = 5; i>=1; i--){ num += i; //System.out.print(i); for(int j = 1; j<=i; j++){ System.out.print(i); } if(i != 1){ System.out.print("\n"+num); } } }

what are the modifiers applicable in java main method

5432 is the answer of program

Very helpful this kind of coding to pass in coding test

Num value is 5

*** * ** ** * *** Please slove this program

Reverse String ..... public class Reve { public static void main(String [] args) { String s="hello java"; String s1=" "; for(int i=s.length()-1;i>=0;i--) { s1=s1+s.CharAt(); } System.out.println("Original String : "+s); System.out.println("Reverse String : "+s1); } }

Can you please add Dynamic Programming Interview questions on this list?

1st non Repeating character and Binary Search were asked.

Any newsletter would you recommend for coding interview preparation?

Post a Comment

Preparing for java and spring boot interview.

  • Join My Newsletter .. Its FREE
  • Everything Bundle (Java + Spring Boot + SQL Interview) for a discount
  • Grokking the Java Interview
  • Grokking the Spring Boot Interview
  • Spring Framework Practice Questions
  • Grokking the SQL Interview
  • Grokking the Java Interview Part 2
  • Grokking the Java SE 17 Developer Certification (1Z0-829 Exam)
  • Spring Professional Certification Practice Test
  • Java SE 11 Certification Practice Test
  • Azure Fundamentals AZ-900 Practice Test
  • Java EE Developer Exam Practice Test
  • Java Foundations 1Z0-811 Exam Practice Test
  • AWS Cloud Practitioner CLF-C02 Exam Practice Test
  • Java SE 17 1Z0-829 Exam Practice Test
  • Azure AI-900 Exam Practice Test
  • 1Z0-829 Java Certification Topic wise Practice Test

My Newsletter articles

  • How to grow financially as Software Engineer?
  • Difference between Microservices and Monolithic Architecture
  • What is Rate Limiter? How does it work
  • Difference between @Component vs @Bean annotations in Spring Framework?
  • Top 10 Software Design Concepts Every Developer should know
  • How does SSO Single Sign On Authentication Works?

Search This Blog

Interview Questions

  • core java interview question (183)
  • interview questions (103)
  • data structure and algorithm (91)
  • Coding Interview Question (81)
  • spring interview questions (52)
  • design patterns (47)
  • object oriented programming (38)
  • SQL Interview Questions (36)
  • thread interview questions (30)
  • collections interview questions (26)
  • database interview questions (16)
  • servlet interview questions (15)
  • hibernate interview questions (10)
  • Programming interview question (6)

Java Tutorials

  • date and time tutorial (25)
  • FIX protocol tutorial (16)
  • Java Certification OCPJP SCJP (30)
  • java collection tutorial (92)
  • java IO tutorial (30)
  • Java JSON tutorial (21)
  • Java multithreading Tutorials (63)
  • Java Programming Tutorials (21)
  • Java xml tutorial (16)
  • jsp-servlet (37)
  • online resources (205)

Get New Blog Posts on Your Email

Get new posts by email:.

  • courses (253)
  • database (50)
  • Eclipse (35)
  • JVM Internals (27)
  • JQuery (23)
  • Testing (21)
  • general (15)

Blog Archive

  • ►  August (2)
  • What is the delegating filter proxy in Spring Secu...
  • 5 Ways to Loop or Iterate over ArrayList in Java?
  • How to get the selected radio button on click usin...
  • 10 Example of Hashtable in Java – Java Hashtable T...
  • How to sort a Map by keys in Java 8 - Example Tuto...
  • Top 30 Array Interview Questions and Answers for P...
  • What is WeakHashMap in Java? When to use it? Examp...
  • 17 SQL Query Best Practices Every Developer Should...
  • How to declare and initialize two dimensional Arra...
  • What is lazy loading in Hibernate? Lazy vs Eager l...
  • Difference between @Secured vs @RolesAllowed vs @P...
  • How to reverse an ArrayList in place in Java? Exam...
  • How to Remove Duplicates from Array without Using ...
  • 12 Apache HTTP Server Interview Questions Answers ...
  • 17 Scenario Based Debugging Interview Questions fo...
  • 10 Singleton Pattern Interview Questions in Java -...
  • 14 Multicasting Interview Questions and Answers
  • Top 20 Algorithms Interview Problems for Programme...
  • How HashMap works in Java?
  • Top 12 SQL Query Problems for Coding Interviews (w...
  • 42 Programming Interview Questions for 1 to 3 Year...
  • ►  June (9)
  • ►  May (45)
  • ►  April (53)
  • ►  March (12)
  • ►  February (4)
  • ►  January (60)
  • ►  December (30)
  • ►  November (7)
  • ►  October (13)
  • ►  September (176)
  • ►  August (55)
  • ►  July (50)
  • ►  June (4)
  • ►  May (206)
  • ►  April (136)
  • ►  March (35)
  • ►  February (11)
  • ►  January (11)
  • ►  December (6)
  • ►  November (1)
  • ►  September (1)
  • ►  August (25)
  • ►  July (44)
  • ►  June (33)
  • ►  May (15)
  • ►  April (37)
  • ►  March (7)
  • ►  February (17)
  • ►  January (23)
  • ►  December (69)
  • ►  November (37)
  • ►  October (23)
  • ►  September (46)
  • ►  August (153)
  • ►  July (238)
  • ►  June (2)
  • ►  May (1)
  • ►  April (3)
  • ►  March (6)
  • ►  February (2)
  • ►  January (2)
  • ►  December (1)
  • ►  October (1)
  • ►  August (1)
  • ►  June (1)
  • ►  May (5)
  • ►  April (13)
  • ►  March (5)
  • ►  February (3)
  • ►  November (4)
  • ►  July (2)
  • ►  April (1)
  • ►  July (1)
  • Privacy Policy
  • Terms and Conditions

Welcome to Java! Easy Max Score: 3 Success Rate: 97.04%

Java stdin and stdout i easy java (basic) max score: 5 success rate: 96.83%, java if-else easy java (basic) max score: 10 success rate: 91.38%, java stdin and stdout ii easy java (basic) max score: 10 success rate: 92.78%, java output formatting easy java (basic) max score: 10 success rate: 96.54%, java loops i easy java (basic) max score: 10 success rate: 97.66%, java loops ii easy java (basic) max score: 10 success rate: 97.32%, java datatypes easy java (basic) max score: 10 success rate: 93.70%, java end-of-file easy java (basic) max score: 10 success rate: 97.91%, java static initializer block easy java (basic) max score: 10 success rate: 96.12%, cookie support is required to access hackerrank.

Seems like cookies are disabled on this browser, please enable them to open this website

Java Coding Practice

java problem solving questions and answers

What kind of Java practice exercises are there?

How to solve these java coding challenges, why codegym is the best platform for your java code practice.

  • Tons of versatile Java coding tasks for learners with any background: from Java Syntax and Core Java topics to Multithreading and Java Collections
  • The support from the CodeGym team and the global community of learners (“Help” section, programming forum, and chat)
  • The modern tool for coding practice: with an automatic check of your solutions, hints on resolving the tasks, and advice on how to improve your coding style

java problem solving questions and answers

Click on any topic to practice Java online right away

Practice java code online with codegym.

In Java programming, commands are essential instructions that tell the computer what to do. These commands are written in a specific way so the computer can understand and execute them. Every program in Java is a set of commands. At the beginning of your Java programming practice , it’s good to know a few basic principles:

  • In Java, each command ends with a semicolon;
  • A command can't exist on its own: it’s a part of a method, and method is part of a class;
  • Method (procedure, function) is a sequence of commands. Methods define the behavior of an object.

Here is an example of the command:

The command System.out.println("Hello, World!"); tells the computer to display the text inside the quotation marks.

If you want to display a number and not text, then you do not need to put quotation marks. You can simply write the number. Or an arithmetic operation. For example:

Command to display the number 1.

A command in which two numbers are summed and their sum (10) is displayed.

As we discussed in the basic rules, a command cannot exist on its own in Java. It must be within a method, and a method must be within a class. Here is the simplest program that prints the string "Hello, World!".

We have a class called HelloWorld , a method called main() , and the command System.out.println("Hello, World!") . You may not understand everything in the code yet, but that's okay! You'll learn more about it later. The good news is that you can already write your first program with the knowledge you've gained.

Attention! You can add comments in your code. Comments in Java are lines of code that are ignored by the compiler, but you can mark with them your code to make it clear for you and other programmers.

Single-line comments start with two forward slashes (//) and end at the end of the line. In example above we have a comment //here we print the text out

You can read the theory on this topic here , here , and here . But try practicing first!

Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program.

java problem solving questions and answers

The two main types in Java are String and int. We store strings/text in String, and integers (whole numbers) in int. We have already used strings and integers in previous examples without explicit declaration, by specifying them directly in the System.out.println() operator.

In the first case “I am a string” is a String in the second case 5 is an integer of type int. However, most often, in order to manipulate data, variables must be declared before being used in the program. To do this, you need to specify the type of the variable and its name. You can also set a variable to a specific value, or you can do this later. Example:

Here we declared a variable called a but didn't give it any value, declared a variable b and gave it the value 5 , declared a string called s and gave it the value Hello, World!

Attention! In Java, the = sign is not an equals sign, but an assignment operator. That is, the variable (you can imagine it as an empty box) is assigned the value that is on the right (you can imagine that this value was put in the empty box).

We created an integer variable named a with the first command and assigned it the value 5 with the second command.

Before moving on to practice, let's look at an example program where we will declare variables and assign values to them:

In the program, we first declared an int variable named a but did not immediately assign it a value. Then we declared an int variable named b and "put" the value 5 in it. Then we declared a string named s and assigned it the value "Hello, World!" After that, we assigned the value 2 to the variable a that we declared earlier, and then we printed the variable a, the sum of the variables a and b, and the variable s to the screen

This program will display the following:

We already know how to print to the console, but how do we read from it? For this, we use the Scanner class. To use Scanner, we first need to create an instance of the class. We can do this with the following code:

Once we have created an instance of Scanner, we can use the next() method to read input from the console or nextInt() if we should read an integer.

The following code reads a number from the console and prints it to the console:

Here we first import a library scanner, then ask a user to enter a number. Later we created a scanner to read the user's input and print the input out.

This code will print the following output in case of user’s input is 5:

More information about the topic you could read here , here , and here .

See the exercises on Types and keyboard input to practice Java coding:

Conditions and If statements in Java allow your program to make decisions. For example, you can use them to check if a user has entered a valid password, or to determine whether a number is even or odd. For this purpose, there’s an 'if/else statement' in Java.

The syntax for an if statement is as follows:

Here could be one or more conditions in if and zero or one condition in else.

Here's a simple example:

In this example, we check if the variable "age" is greater than or equal to 18. If it is, we print "You are an adult." If not, we print "You are a minor."

Here are some Java practice exercises to understand Conditions and If statements:

In Java, a "boolean" is a data type that can have one of two values: true or false. Here's a simple example:

The output of this program is here:

In addition to representing true or false values, booleans in Java can be combined using logical operators. Here, we introduce the logical AND (&&) and logical OR (||) operators.

  • && (AND) returns true if both operands are true. In our example, isBothFunAndEasy is true because Java is fun (isJavaFun is true) and coding is not easy (isCodingEasy is false).
  • || (OR) returns true if at least one operand is true. In our example, isEitherFunOrEasy is true because Java is fun (isJavaFun is true), even though coding is not easy (isCodingEasy is false).
  • The NOT operator (!) is unary, meaning it operates on a single boolean value. It negates the value, so !isCodingEasy is true because it reverses the false value of isCodingEasy.

So the output of this program is:

More information about the topic you could read here , and here .

Here are some Java exercises to practice booleans:

With loops, you can execute any command or a block of commands multiple times. The construction of the while loop is:

Loops are essential in programming to execute a block of code repeatedly. Java provides two commonly used loops: while and for.

1. while Loop: The while loop continues executing a block of code as long as a specified condition is true. Firstly, the condition is checked. While it’s true, the body of the loop (commands) is executed. If the condition is always true, the loop will repeat infinitely, and if the condition is false, the commands in a loop will never be executed.

In this example, the code inside the while loop will run repeatedly as long as count is less than or equal to 5.

2. for Loop: The for loop is used for iterating a specific number of times.

In this for loop, we initialize i to 1, specify the condition i <= 5, and increment i by 1 in each iteration. It will print "Count: 1" to "Count: 5."

Here are some Java coding challenges to practice the loops:

An array in Java is a data structure that allows you to store multiple values of the same type under a single variable name. It acts as a container for elements that can be accessed using an index.

What you should know about arrays in Java:

  • Indexing: Elements in an array are indexed, starting from 0. You can access elements by specifying their index in square brackets after the array name, like myArray[0] to access the first element.
  • Initialization: To use an array, you must declare and initialize it. You specify the array's type and its length. For example, to create an integer array that can hold five values: int[] myArray = new int[5];
  • Populating: After initialization, you can populate the array by assigning values to its elements. All elements should be of the same data type. For instance, myArray[0] = 10; myArray[1] = 20;.
  • Default Values: Arrays are initialized with default values. For objects, this is null, and for primitive types (int, double, boolean, etc.), it's typically 0, 0.0, or false.

In this example, we create an integer array, assign values to its elements, and access an element using indexing.

In Java, methods are like mini-programs within your main program. They are used to perform specific tasks, making your code more organized and manageable. Methods take a set of instructions and encapsulate them under a single name for easy reuse. Here's how you declare a method:

  • public is an access modifier that defines who can use the method. In this case, public means the method can be accessed from anywhere in your program.Read more about modifiers here .
  • static means the method belongs to the class itself, rather than an instance of the class. It's used for the main method, allowing it to run without creating an object.
  • void indicates that the method doesn't return any value. If it did, you would replace void with the data type of the returned value.

In this example, we have a main method (the entry point of the program) and a customMethod that we've defined. The main method calls customMethod, which prints a message. This illustrates how methods help organize and reuse code in Java, making it more efficient and readable.

In this example, we have a main method that calls the add method with two numbers (5 and 3). The add method calculates the sum and returns it. The result is then printed in the main method.

All composite types in Java consist of simpler ones, up until we end up with primitive types. An example of a primitive type is int, while String is a composite type that stores its data as a table of characters (primitive type char). Here are some examples of primitive types in Java:

  • int: Used for storing whole numbers (integers). Example: int age = 25;
  • double: Used for storing numbers with a decimal point. Example: double price = 19.99;
  • char: Used for storing single characters. Example: char grade = 'A';
  • boolean: Used for storing true or false values. Example: boolean isJavaFun = true;
  • String: Used for storing text (a sequence of characters). Example: String greeting = "Hello, World!";

Simple types are grouped into composite types, that are called classes. Example:

We declared a composite type Person and stored the data in a String (name) and int variable for an age of a person. Since composite types include many primitive types, they take up more memory than variables of the primitive types.

See the exercises for a coding practice in Java data types:

String is the most popular class in Java programs. Its objects are stored in a memory in a special way. The structure of this class is rather simple: there’s a character array (char array) inside, that stores all the characters of the string.

String class also has many helper classes to simplify working with strings in Java, and a lot of methods. Here’s what you can do while working with strings: compare them, search for substrings, and create new substrings.

Example of comparing strings using the equals() method.

Also you can check if a string contains a substring using the contains() method.

You can create a new substring from an existing string using the substring() method.

More information about the topic you could read here , here , here , here , and here .

Here are some Java programming exercises to practice the strings:

In Java, objects are instances of classes that you can create to represent and work with real-world entities or concepts. Here's how you can create objects:

First, you need to define a class that describes the properties and behaviors of your object. You can then create an object of that class using the new keyword like this:

It invokes the constructor of a class.If the constructor takes arguments, you can pass them within the parentheses. For example, to create an object of class Person with the name "Jane" and age 25, you would write:

Suppose you want to create a simple Person class with a name property and a sayHello method. Here's how you do it:

In this example, we defined a Person class with a name property and a sayHello method. We then created two Person objects (person1 and person2) and used them to represent individuals with different names.

Here are some coding challenges in Java object creation:

Static classes and methods in Java are used to create members that belong to the class itself, rather than to instances of the class. They can be accessed without creating an object of the class.

Static methods and classes are useful when you want to define utility methods or encapsulate related classes within a larger class without requiring an instance of the outer class. They are often used in various Java libraries and frameworks for organizing and providing utility functions.

You declare them with the static modifier.

Static Methods

A static method is a method that belongs to the class rather than any specific instance. You can call a static method using the class name, without creating an object of that class.

In this example, the add method is static. You can directly call it using Calculator.add(5, 3)

Static Classes

In Java, you can also have static nested classes, which are classes defined within another class and marked as static. These static nested classes can be accessed using the outer class's name.

In this example, Student is a static nested class within the School class. You can access it using School.Student.

More information about the topic you could read here , here , here , and here .

See below the exercises on Static classes and methods in our Java coding practice for beginners:

The Java Interview Prep Handbook – 50 Questions Solved + Code Examples

Vahe Aslanyan

If you're trying to get a job in big tech or you want to refine your skills in software development, a strong grasp of Java is indispensable.

Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level.

This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring you're well-prepared for the challenges ahead.

This guide serves as a comprehensive Java review tutorial, bridging the gap between foundational Java knowledge and the sophisticated expertise sought by industry leaders like Google. And it'll help you deepen your understanding and practical application of Java, preparing you for professional success in the tech industry.

Table of Contents

  • What is Java?
  • What's the difference between the JDK, JRE, and JVM?
  • How does the 'public static void main(String[] args)' method work?
  • What is bytecode in Java?
  • Differentiate between overloading and overriding
  • What is the Java ClassLoader?
  • Can we override static methods in Java?
  • How does the 'finally' block differ from the 'finalize' method in Java?
  • What is the difference between an abstract class and an interface?
  • Explain the concept of Java packages
  • What are Java annotations?
  • How does multi-threading work in Java?
  • Use throw to raise an exception
  • Use throws to declare exceptions
  • What is the significance of the transient keyword?
  • How do you ensure thread safety in Java?
  • Explain the Singleton pattern
  • What are Java Streams?
  • What are the primary differences between ArrayList and LinkedList?
  • How do HashSet, LinkedHashSet, and TreeSet differ?
  • Differentiate between HashMap and ConcurrentHashMap
  • Describe the contract between hashCode() and equals() methods
  • What is Java reflection?
  • How do you create a custom exception in Java?
  • What is the difference between a checked and unchecked exception?
  • What are generics? Why are they used?
  • Explain the concept of Java Lambda Expressions
  • What is the diamond problem in inheritance?
  • Describe the difference between fail-fast and fail-safe iterators
  • What is type erasure in Java generics?
  • Describe the differences between StringBuilder and StringBuffer
  • What is the volatile keyword in Java?
  • Explain the Java memory model
  • What is the purpose of the default keyword in interfaces?
  • How does switch differ in Java 7 and Java 8?
  • Explain the concept of Autoboxing and Unboxing
  • Describe the @FunctionalInterface annotation
  • How can you achieve immutability in Java?
  • What is the decorator pattern?
  • Explain the Java I/O streams
  • How does the garbage collector work in Java?
  • What are the benefits of using Java NIO?
  • Explain the Observer pattern
  • What is the purpose of Java's Optional?
  • Explain Java's try-with-resources
  • Explain the difference between C++ and Java
  • What is polymorphism? Provide an example
  • How can you avoid memory leaks in Java?
  • Explain the purpose of Java's synchronized block
  • Explain the concept of modules in Java

1. What is Java?

Java is a high-level, object-oriented programming language known for its platform independence. It allows developers to write code once and run it anywhere using the Java Virtual Machine (JVM).

2. What's the Difference between the JDK, JRE, and JVM?

  • JDK (Java Development Kit): This is a software package that provides developers with the tools and utilities necessary to develop, compile, and run Java applications.
  • JRE (Java Runtime Environment): A subset of the JDK, the JRE contains the essential components, including the JVM, to run Java applications but not to develop them.
  • JVM (Java Virtual Machine): An abstract computing machine, the JVM enables Java bytecode to be executed, providing the platform independence Java is known for.

3. How Does the public static void main(String[] args) Method Work?

This method is the entry point for Java applications. The public modifier means it's accessible from other classes, static denotes it's a class-level method, and void indicates it doesn't return any value. The argument String[] args allows command-line arguments to be passed to the application.

4. What is bytecode in Java?

Bytecode is an intermediate, platform-independent code that Java source code is compiled into. It is executed by the JVM, enabling the "write once, run anywhere" capability.

5. Differentiate between overloading and overriding

  • Overloading: This occurs when two or more methods in the same class share the same name but have different parameters. It's a compile-time concept.
  • Overriding: In this case, a subclass provides a specific implementation for a method already defined in its superclass. It's a runtime concept.

6. What is the Java ClassLoader?

The Java ClassLoader is a part of the JRE that dynamically loads Java classes into the JVM during runtime. It plays a crucial role in Java's runtime environment by extending the core Java classes.

7. Can We Override Static Methods in Java?

No, we cannot override static methods. While a subclass can declare a method with the same name as a static method in its superclass, this is considered method hiding, not overriding.

8. How Does the finally Block Differ from the finalize Method in Java?

Understanding the distinction between the finally block and the finalize method in Java is crucial for effective resource management and exception handling in your programs.

Finally Block:

  • Purpose and Usage: The finally block is a key component of Java's exception handling mechanism. It is used in conjunction with try-catch blocks.
  • Execution Guarantee: Regardless of whether an exception is thrown or caught within the try or catch blocks, the code within the finally block is always executed. This ensures that it runs even if there’s a return statement in the try or catch block.
  • Common Uses: It is typically utilized for cleaning up resources, such as closing file streams, database connections, or releasing any system resources that were acquired in the try block. This helps in preventing resource leaks.

Finalize Method:

  • Definition: The finalize method is a protected method of the Object class in Java. It acts as a final resort for objects garbage collection.
  • Garbage Collector Call: It is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object. However, its execution is not guaranteed, and it's generally unpredictable when, or even if, the finalize method will be invoked.
  • Resource Release: The finalize method is designed to allow an object to clean up its resources before it is collected by the garbage collector. For example, it might be used to ensure that an open file owned by an object is closed.
  • Caution in Use: It's important to note that relying on finalize for resource cleanup is generally not recommended due to its unpredictability and potential impact on performance.

Access Modifiers in Java:

  • Private: This modifier makes a member accessible only within its own class. Other classes cannot access private members of a different class.
  • Default (no modifier): When no access modifier is specified, the member has package-level access. This means it is accessible to all classes within the same package.
  • Protected: A protected member is accessible within its own package and also in subclasses. This is often used in inheritance.
  • Public: Public members are accessible from any class in the Java program. It provides the widest level of access.

Understanding these distinctions and access levels is vital for effective Java programming, ensuring resource management, security, and encapsulation are handled appropriately in your software development endeavors.

9. What is the Difference between an Abstract Class and an Interface?

An abstract class in Java is used as a base for other classes. It can contain both abstract methods (without an implementation) and concrete methods (with an implementation).

Abstract classes can have member variables that can be inherited by subclasses. A class can extend only one abstract class due to Java's single inheritance property.

Example of an Abstract Class:

An interface in Java, on the other hand, is a completely "abstract class" that is used to group related methods with empty bodies.

From Java 8 onwards, interfaces can have default and static methods with a body. A class can implement any number of interfaces.

Example of an Interface:

Both abstract classes and interfaces are foundational concepts in Java, used for achieving abstraction and supporting design patterns like Strategy and Adapter. The use of these concepts depends on the specific requirements and design considerations of your software project.

10. Explain the Concept of Java Packages

Java packages are a way of organizing and structuring classes and interfaces in Java applications. They provide a means to group related code together. Packages help prevent naming conflicts, enhance code readability, and facilitate code reusability.

For example, consider a banking application. You might have packages like com.bank.accounts , com.bank.customers , and com.bank.transactions . These packages contain classes and interfaces specific to their respective functionalities.

In essence, Java packages are like directories or folders in a file system, organizing code and making it more manageable.

11. What are Java Annotations?

Java annotations are metadata that can be added to Java source code. They provide information about the code to the compiler or runtime environment. Annotations do not directly affect the program's functionality – instead, they convey instructions to tools or frameworks.

A common use of annotations is for marking classes or methods as belonging to a specific framework or for providing additional information to tools like code analyzers, build tools, or even custom code generators.

For example, the @Override annotation indicates that a method is intended to override a method from a superclass, helping catch coding errors during compilation. Another example is @Deprecated , which indicates that a method or class is no longer recommended for use.

12. How Does Multi-threading Work in Java?

Multi-threading in Java allows a program to execute multiple threads concurrently. Threads are lightweight processes within a program that can run independently. Java provides a rich set of APIs and built-in support for multi-threading.

Threads in Java are typically created by either extending the Thread class or implementing the Runnable interface. Once created, threads can be started using the start() method, causing them to run concurrently.

Java's multi-threading model ensures that threads share resources like memory and CPU time efficiently while providing mechanisms like synchronization and locks to control access to shared data.

Multi-threading is useful for tasks such as improving application responsiveness, utilizing multi-core processors, and handling concurrent operations, as often seen in server applications.

13. Use throw to Raise an Exception

In Java programming, the throw keyword is crucial for handling exceptions deliberately and responsively. This approach to exception management allows developers to enforce specific conditions in their code and maintain control over the program flow.

In this example, an IllegalArgumentException is thrown if the age parameter is less than 18. This method of raising an exception ensures that the program behaves predictably under defined conditions, enhancing both the security and reliability of the code.

14. Use throws to Declare Exceptions

The throws keyword in Java serves to declare that a method may cause an exception to be thrown. It signals to the method's caller that certain exceptions might arise, which should be either caught or further declared.

In this scenario, the readDocument method declares that it might throw a FileNotFoundException . This declaration requires the caller of this method to handle this exception, ensuring that appropriate measures are in place to deal with potential errors, and thus improving the robustness of the application.

Both throw and throws are integral to managing exceptions in Java. throw is used for actively raising an exception in the code, while throws declares possible exceptions that a method might produce, thereby mandating their handling by the caller. This distinction is essential for writing error-resistant and well-structured Java programs.

15. What is the Significance of the transient Keyword?

The transient keyword in Java is used to indicate that a field should not be serialized when an object of a class is converted to a byte stream (for example, when using Java Object Serialization).

This is significant when you have fields in a class that you do not want to include in the serialized form, perhaps because they are temporary, derived, or contain sensitive information.

16. How Do You Ensure Thread Safety in Java?

Thread safety in Java is achieved by synchronizing access to shared resources, ensuring that multiple threads can't simultaneously modify data in a way that leads to inconsistencies or errors.

You can ensure thread safety through synchronization mechanisms like synchronized blocks, using thread-safe data structures, or utilizing concurrent utilities from the java.util.concurrent package.

In the code above, we have a SharedCounter class with a synchronized increment method, ensuring that only one thread can increment the count variable at a time. This synchronization mechanism prevents data inconsistencies when multiple threads access and modify the shared count variable.

We create two threads ( thread1 and thread2 ) that concurrently increment the counter. By using synchronized methods or blocks, we guarantee thread safety, and the final count will be accurate, regardless of thread interleaving.

17. Explain the Singleton Pattern

The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. It is achieved by making the constructor of the class private, creating a static method to provide a single point of access to the instance, and lazily initializing the instance when needed.

Implementation without Singleton:

Let's imagine a scenario where you want to establish a database connection. Without the Singleton pattern, every time you'd need a connection, you might end up creating a new one.

Now, imagine initializing this connection multiple times in different parts of your application:

For the above code, "Establishing a new database connection..." would be printed twice, implying two separate connections were created. This is redundant and can be resource-intensive.

Implementation with Singleton:

With the Singleton pattern, even if you attempt to get the connection multiple times, you'd be working with the same instance.

Initializing this connection multiple times:

For the above code, "Establishing a single database connection..." would be printed just once, even though we've called getInstance() twice.

18. What are Java Streams?

Java Streams are a powerful abstraction for processing sequences of elements, such as collections, arrays, or I/O channels, in a functional and declarative style. They provide methods for filtering, mapping, reducing, and performing various transformations on data.

Streams can significantly simplify code and improve readability when working with data collections.

19. What Are the Primary Differences between ArrayList and LinkedList?

ArrayList and LinkedList are both implementations of the List interface. The primary differences between them lie in their internal data structures.

ArrayList uses a dynamic array to store elements, offering fast random access but slower insertions and deletions. LinkedList uses a doubly-linked list, which provides efficient insertions and deletions but slower random access.

20. How do HashSet , LinkedHashSet , and TreeSet Differ?

  • HashSet stores elements in an unordered manner, offering constant-time complexity for basic operations.
  • LinkedHashSet maintains the order of insertion, providing ordered iteration of elements.
  • TreeSet stores elements in a sorted order (natural or custom), offering log(n) time complexity for basic operations.

In this code, we add a large number of elements to each type of set ( HashSet , LinkedHashSet , and TreeSet ) and measure the time it takes to perform this operation. This demonstrates the performance characteristics of each set type.

Typically, you will observe that HashSet performs the fastest for adding elements since it doesn't maintain any specific order, followed by LinkedHashSet , and TreeSet , which maintains a sorted order.

This output demonstrates the time taken (in nanoseconds) to add one million elements to each of the three sets: HashSet , LinkedHashSet , and TreeSet . As you can see, HashSet is the fastest, followed by LinkedHashSet , and TreeSet is the slowest due to its need to maintain elements in sorted order.

21. Differentiate between HashMap and ConcurrentHashMap

HashMap is not thread-safe and is suitable for single-threaded applications. ConcurrentHashMap , on the other hand, is designed for concurrent access and supports multiple threads without external synchronization. It provides high concurrency and performance for read and write operations.

22. Describe the Contract between the hashCode() and equals() Methods

The contract between hashCode() and equals() methods states that if two objects are equal ( equals() returns true), their hash codes ( hashCode() ) must also be equal.

However, the reverse is not necessarily true: objects with equal hash codes may not be equal. Adhering to this contract is crucial when using objects as keys in hash-based collections like HashMap .

23. What is Java Reflection?

Java reflection is a feature that allows you to inspect and manipulate the metadata of classes, methods, fields, and other program elements at runtime. It enables you to perform tasks such as dynamically creating objects, invoking methods, and accessing fields, even for classes that were not known at compile time.

24. How Do You Create a Custom Exception in Java?

You can create a custom exception in Java by extending the Exception class or one of its subclasses. By doing so, you can define your exception with specific attributes and behaviors tailored to your application's needs.

25. What is the Difference between a Checked and Unchecked Exception?

Checked exceptions are exceptions that must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked exceptions (usually subclasses of RuntimeException ) do not require such handling.

Checked exceptions are typically used for recoverable errors, while unchecked exceptions represent programming errors or runtime issues.

Here is a code example to illustrate checked and unchecked exceptions.

In this code, we attempt to read a file using FileReader, which may throw a checked exception called IOException .

To handle this exception, we enclose the file reading code in a try-catch block specifically catching IOException . This is an example of how you handle checked exceptions, which are typically used for recoverable errors like file not found or I/O issues.

Now, let's take a look at an example of an unchecked exception:

In this code, we attempt to divide an integer by zero, which leads to an unchecked exception called ArithmeticException . Unchecked exceptions do not require explicit handling using a try-catch block. However, it's good practice to catch and handle them when you anticipate such issues. These exceptions often represent programming errors or runtime issues.

26. What Are Generics? Why Are They Used?

Generics in Java are a powerful feature that allows you to create classes, interfaces, and methods that operate on types. They provide a way to define classes or methods with a placeholder for the data type that will be used when an instance of the class is created or when a method is called.

Generics are used to make your code more reusable, type-safe, and less error-prone by allowing you to write generic algorithms that work with different data types. They help eliminate the need for typecasting and enable compile-time type checking.

For example, consider the use of a generic class to create a List of integers:

Generics ensure that you can only add integers to the list and that you don't need to perform explicit typecasting when retrieving elements from the list.

27. Explain the Concept of Java Lambda Expressions

Lambda expressions in Java are a concise way to express instances of single-method interfaces (functional interfaces) using a more compact syntax. They facilitate functional programming by allowing you to treat functions as first-class citizens.

Lambda expressions consist of a parameter list, an arrow (->), and a body. They provide a way to define and use anonymous functions.

For example, consider a functional interface Runnable that represents a task to be executed. With a lambda expression, you can define and execute a runnable task as follows:

We will talk about a more practical example later down the post.

28. What is the Diamond Problem in Inheritance?

The diamond problem in inheritance is a common issue in object-oriented programming languages that support multiple inheritance. It occurs when a class inherits from two classes that have a common ancestor class, resulting in ambiguity about which superclass's method or attribute to use.

Java solves the diamond problem by not supporting multiple inheritance of classes (that is, a class cannot inherit from more than one class).

But Java allows multiple inheritance of interfaces, which doesn't lead to the diamond problem because interfaces only declare method signatures, and the implementing class must provide concrete implementations. In case of method conflicts, the implementing class must explicitly choose which method to use.

Here's a simplified example to illustrate the diamond problem (even though Java doesn't directly encounter it):

In Java, the diamond problem is avoided through interface implementation and explicit method choice when conflicts arise.

29. Describe the Difference between Fail-fast and Fail-safe Iterators

In Java, fail-fast and fail-safe are two strategies for handling concurrent modification of collections during iteration.

Fail-fast iterators throw a ConcurrentModificationException if a collection is modified while being iterated. Fail-safe iterators, on the other hand, do not throw exceptions and allow safe iteration even if the collection is modified concurrently.

Fail-Fast Iterator Example:

In this example, when we attempt to remove an element from the list while iterating, it leads to a ConcurrentModificationException , which is characteristic of fail-fast behavior. Fail-fast iterators immediately detect and throw an exception when they detect that the collection has been modified during iteration.

Fail-Safe Iterator Example:

In this example, a ConcurrentHashMap is used, which supports fail-safe iterators. Even if we modify the map concurrently while iterating, there is no ConcurrentModificationException thrown. Fail-safe iterators continue iterating over the original elements and do not reflect changes made after the iterator is created.

30. What is Type Erasure in Java Generics?

Type erasure is a process in Java where type parameters in generic classes or methods are replaced with their upper bound or Object during compilation. This erasure ensures backward compatibility with pre-generic Java code. But it means that the type information is not available at runtime, which can lead to issues in some cases.

31. Describe the Differences between StringBuilder and StringBuffer

Thread safety:.

StringBuffer is thread-safe. This means it is synchronized, so it ensures that only one thread can modify it at a time. This is crucial in a multithreaded environment where you have multiple threads modifying the same string buffer.

StringBuilder , on the other hand, is not thread-safe. It does not guarantee synchronization, making it unsuitable for use in scenarios where a string is accessed and modified by multiple threads concurrently. But this lack of synchronization typically leads to better performance under single-threaded conditions.

Performance:

Because StringBuffer operations are synchronized, they involve a certain overhead that can impact performance negatively when high-speed string manipulation is required.

StringBuilder is faster than StringBuffer because it avoids the overhead of synchronization. It's an excellent choice for string manipulation in a single-threaded environment.

Use Case Scenarios:

Use StringBuffer when you need to manipulate strings in a multithreaded environment. Its thread-safe nature makes it the appropriate choice in this scenario.

Use StringBuilder in single-threaded situations, such as local method scope or within a block synchronized externally, where thread safety is not a concern. Its performance benefits shine in these cases.

API Similarity:

Both StringBuilder and StringBuffer have almost identical APIs. They provide similar methods for manipulating strings, such as append() , insert() , delete() , reverse() , and so on.

This similarity means that switching from one to the other in your code is generally straightforward.

Memory Efficiency:

Both classes are more memory efficient compared to using String for concatenation. Since String is immutable in Java, concatenation with String creates multiple objects, whereas StringBuilder and StringBuffer modify the string in place.

Introduced Versions:

StringBuffer has been a part of Java since version 1.0, whereas StringBuilder was introduced later in Java 5. This introduction was primarily to offer a non-synchronized alternative to StringBuffer for improved performance in single-threaded applications.

You should make the choice between StringBuilder and StringBuffer based on the specific requirements of your application, particularly regarding thread safety and performance needs.

While StringBuffer provides safety in a multithreaded environment, StringBuilder offers speed and efficiency in single-threaded or externally synchronized scenarios.

32. What is the volatile Keyword in Java?

Basic Definition: The volatile keyword is used to modify the value of a variable by different threads. It ensures that the value of the volatile variable will always be read from the main memory and not from the thread's local cache.

Visibility Guarantee: In a multithreading environment, threads can cache variables. Without volatile, there's no guarantee that one thread's changes to a variable will be visible to another. The volatile keyword guarantees visibility of changes to variables across threads.

Happens-Before Relationship: volatile establishes a happens-before relationship in Java. This means that all the writes to the volatile variable are visible to subsequent reads of that variable, ensuring a consistent view of the variable across threads.

Usage Scenarios: volatile is used for variables that may be updated by multiple threads. It's often used for flags or status variables. For example, a volatile boolean running variable can be used to stop a thread.

Limitations: Volatile cannot be used with class or instance variables. It's only applicable to fields. It doesn't provide atomicity.

For instance, volatile int i; i++; is not an atomic operation. For atomicity, you might need to resort to AtomicInteger or synchronized methods or blocks. It's not a substitute for synchronization in every case, especially when multiple operations on the volatile variable need to be atomic.

Avoiding Common Misconceptions: A common misconception is that volatile makes the whole block of statements atomic, which is not true. It only ensures the visibility and ordering of the writes to the volatile variable.

Another misconception is that volatile variables are slow. But while they might have a slight overhead compared to non-volatile variables, they are generally faster than using synchronized methods or blocks.

Performance Considerations: volatile can be a more lightweight alternative to synchronization in cases where only visibility concerns are present. It doesn't incur the locking overhead that synchronized methods or blocks do.

Best Practices: Use volatile sparingly and only when necessary. Overusing it can lead to memory visibility issues that are harder to detect and debug. Always assess whether your use case requires atomicity, in which case other concurrent utilities or synchronization might be more appropriate.

volatile use case:

We will create a simple program where one thread modifies a volatile boolean flag, and another thread reads this flag. This flag will be used to control the execution of the second thread.

Code Example:

Key points in the comments:.

  • Visibility of volatile variable: The most crucial aspect of using volatile here is ensuring that the update to the running variable in one thread (main thread) is immediately visible to another thread ( thread1 ). This is what allows thread1 to stop gracefully when running is set to false .
  • Use in a Simple Flag Scenario: The example demonstrates a common scenario for using volatile , that is as a simple flag to control the execution flow in a multithreaded environment.
  • Absence of Compound Operations: Note that we are not performing any compound operations (like incrementing) on the running variable. If we were, additional synchronization would be needed because volatile alone does not guarantee atomicity of compound actions.
  • Choice of volatile Over Synchronization: The choice to use volatile over other synchronization mechanisms (like synchronized blocks or Locks ) is due to its lightweight nature when dealing with the visibility of a single variable. It avoids the overhead associated with acquiring and releasing locks.

33. Explain the Java Memory Model

The JMM defines how Java threads interact through memory. Essentially, it describes the relationship between variables and the actions of threads (reads and writes), ensuring consistency and predictability in concurrent programming.

Happens-Before Relationship:

At the heart of the JMM is the 'happens-before' relationship. This principle ensures memory visibility, guaranteeing that if one action happens-before another, then the first is visible to and affects the second.

For example, changes to a variable made by one thread are guaranteed to be visible to other threads only if a happens-before relationship is established.

Memory Visibility:

Without the JMM, threads might cache variables, and changes made by one thread might not be visible to others. The JMM ensures that changes made to a shared variable by one thread will eventually be visible to other threads.

Synchronization:

The JMM utilizes synchronization to establish happens-before relationships. When a variable is accessed within synchronized blocks, any write operation in one synchronized block is visible to any subsequent read operation in another synchronized block.

Additionally, the JMM governs the behavior of volatile variables, ensuring visibility of updates to these variables across threads without synchronization.

Thread Interleaving and Atomicity:

The JMM defines how operations can interleave when executed by multiple threads. This can lead to complex states if not managed correctly.

Atomicity refers to operations that are indivisible and uninterrupted. In Java, operations on most primitive types (except long and double ) are atomic. However, compound operations (like incrementing a variable) are not automatically atomic.

Reordering:

The JMM allows compilers to reorder instructions for performance optimization as long as happens-before guarantees are maintained. However, this can lead to subtle bugs if not properly understood.

Use of Volatile Keyword:

The volatile keyword plays a significant role in the JMM. It ensures that any write to a volatile variable establishes a happens-before relationship with subsequent reads of that variable, thus ensuring memory visibility without the overhead of synchronization.

Locking Mechanisms:

Locks in Java (implicit via synchronized blocks/methods or explicit via ReentrantLock or others) also adhere to the JMM, ensuring that memory visibility is maintained across threads entering and exiting locks.

Safe Publication:

The JMM also addresses the concept of safe publication, ensuring that objects are fully constructed and visible to other threads after their creation.

High-Level Implications:

Understanding the JMM is critical for writing correct and efficient multi-threaded Java applications. It helps developers reason about how shared memory is handled, especially in complex applications where multiple threads interact and modify shared data.

Best Practices:

  • Always use the appropriate synchronization mechanism to ensure memory visibility and atomicity.
  • Be cautious about memory visibility issues; even simple operations can lead to visibility problems in a multi-threaded context.
  • Understand the cost of synchronization and use volatile variables where appropriate.

34. What is the Purpose of the default Keyword in Interfaces?

The default keyword in Java interfaces, introduced in Java 8, marks a significant evolution in the Java language, especially in how interfaces are used and implemented. It serves several key purposes:

Adding Method Implementations in Interfaces:

Prior to Java 8, interfaces in Java could only contain method signatures (abstract methods) without any implementation.

The default keyword allows you to provide a default implementation for a method within an interface. This feature bridges a gap between full abstraction (interfaces) and concrete implementations (classes).

Enhancing Interface Evolution:

One of the primary motivations for introducing the default keyword was to enhance the evolution of interfaces.

Before Java 8, adding a new method to an interface meant breaking all its existing implementations. With default methods, you can add new methods to interfaces with default implementations without breaking the existing implementations.

This is particularly useful for library designers, ensuring backward compatibility when interfaces need to be expanded.

Facilitating Functional Programming:

\The introduction of default methods played a crucial role in enabling functional programming features in Java, such as Lambda expressions. It allowed for richer interfaces (like java.util.stream.Stream ) which are fundamental to functional-style operations in Java.

Multiple Inheritance of Behavior:

While Java does not allow multiple inheritance of state (that is, you cannot inherit from multiple classes), the default keyword enables multiple inheritance of behavior.

A class can implement multiple interfaces, and each interface can provide a default implementation of methods, which the class inherits.

Reducing Boilerplate Code:

default methods can be used to reduce the amount of boilerplate code by providing a general implementation that can be shared across multiple implementing classes, while still allowing individual classes to override the default implementation if a more specific behavior is required.

Example Usage:

In this example, any class implementing the Vehicle interface must provide an implementation for cleanVehicle , but it's optional for startEngine . The default implementation of startEngine can be used as is, or overridden by the implementing class.

Best Practices and Considerations:

  • Use Sparingly: Default methods should be used judiciously. They are best suited for gradually evolving interfaces or for methods that have a common implementation across most implementing classes.
  • Design With Care: When designing interfaces with default methods, consider how they might be used or overridden. It's important to document the expected behavior and interactions between default methods and other abstract methods in the interface.
  • Overriding Default Methods: Just like any inherited method, default methods can be overridden in the implementing class. This should be done to provide a specific behavior different from the default implementation.

35. How Does switch Differ in Java 7 and Java 8?

Limited Case Types: In Java 7, the switch statement supports limited types for the case labels, namely byte , short , char , int , and their corresponding Wrapper classes, along with enum types and, as of Java 7, String .

Traditional Structure: The structure of the switch statement in Java 7 follows the conventional C-style format, with a series of case statements and an optional default case. Each case falls through to the next unless it ends with a break statement or other control flow statements like return .

No Lambda Expressions: Java 7 does not support lambda expressions, and thus, they cannot be used within a switch statement or case labels.

Lambda Expressions: While the basic syntax and supported types for the switch statement itself did not change in Java 8, the introduction of lambda expressions in this version brought a new paradigm in handling conditional logic.

This doesn’t directly change how switch works, but it offers alternative patterns for achieving similar outcomes, especially when used in conjunction with functional interfaces.

Functional Programming Approach: Java 8 promotes a more functional programming style, encouraging the use of streams, lambda expressions, and method references. This can lead to alternatives for traditional switch statements, like using Map of lambdas for conditional logic, which can be more readable and concise.

Enhanced Readability and Maintainability: Although not a direct change to the switch statement, the use of lambda expressions and functional programming practices in Java 8 can lead to more readable and maintainable code structures that might otherwise use complex switch or nested if-else statements.

Practical Considerations:

  • When to Use switch in Java 8: Despite the advancements in Java 8, the switch statement remains a viable and efficient method for controlling complex conditional logic. It is particularly useful when dealing with a known set of possible values, such as enum constants or strings.
  • Combining switch with Lambdas: While you cannot use lambdas directly in a switch statement, Java 8 allows for more elegant ways to handle complex conditional logic that might traditionally have been a use case for switch . For example, using a Map with lambdas or method references can sometimes replace a complex switch statement.
  • Performance Considerations: The performance of a switch statement is generally better than a series of if-else statements, especially when dealing with a large number of cases, due to its internal implementation using jump tables or binary search.

36. Explain the Concept of Autoboxing and Unboxing

What is autoboxing.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer , a double to a Double , and so on.

When to use autoboxing

This feature is commonly used when working with collections, like ArrayList or HashMap , which can only store objects and not primitive types.

It simplifies the code by allowing direct assignment of a primitive value to a variable of the corresponding wrapper class.

Behind the Scenes:

When autoboxing, the compiler essentially uses the valueOf method of the respective wrapper class to convert the primitive to its wrapper type.

For example, Integer.valueOf(int) is used for converting int to Integer .

Performance Considerations:

  • While convenient, autoboxing can introduce performance overhead, especially in scenarios with extensive boxing and unboxing in tight loops, due to the creation of additional objects.

What is unboxing?

Unboxing is the reverse process, where the Java compiler automatically converts an object of a wrapper type to its corresponding primitive type.

When to use unboxing

It is often used when performing arithmetic operations or comparisons on objects of wrapper classes, where primitive types are required.

During unboxing, the compiler uses the corresponding wrapper class's method to extract the primitive value. For instance, it uses Integer.intValue() to get the int from an Integer .

Null Pointer Exception:

A crucial point to consider is that unboxing a null object reference will throw a NullPointerException . This is a common bug in code that relies heavily on autoboxing and unboxing.

  • Be Aware of Implicit Conversions: It's important to be aware that these conversions are happening, as they can sometimes lead to unexpected behavior, especially with regards to NullPointerExceptions during unboxing of null references.
  • Consider Performance: In performance-sensitive applications, prefer using primitives to avoid the overhead of autoboxing and unboxing.
  • Null Safety: Always check for null before unboxing, to avoid potential NullPointerExceptions .
  • Readability vs Efficiency: While autoboxing and unboxing significantly improve code readability and reduce boilerplate, be mindful of their impact on performance and choose wisely based on the application's context.

37. Describe the @FunctionalInterface Annotation

The @FunctionalInterface annotation in Java is a key feature that dovetails with the language's embrace of functional programming concepts, particularly since Java 8. It serves a specific purpose in defining and enforcing certain coding patterns, making it a vital tool for developers focusing on functional-style programming.

Definition and Purpose

@FunctionalInterface is an annotation that marks an interface as a functional interface.

A functional interface in Java is an interface that contains exactly one abstract method. This restriction makes it eligible to be used in lambda expressions and method references, which are core components of Java's functional programming capabilities.

Enforcing Single Abstract Method

The primary role of @FunctionalInterface is to signal the compiler to enforce the rule of a single abstract method. If the annotated interface does not adhere to this rule, the compiler throws an error, ensuring the interface's contract is not accidentally broken by adding additional abstract methods.

Usage and Implications:

  • Lambda Expressions: Functional interfaces provide target types for lambda expressions and method references. For example, Java's standard java.util.function package contains several functional interfaces like Function<T,R> , Predicate<T> , Consumer<T> , which are widely used in stream operations and other functional programming scenarios.
  • Optional but Recommended: While the @FunctionalInterface annotation is not mandatory for an interface to be considered a functional interface by the Java compiler, using it is considered best practice. It makes the developer's intention clear and ensures the contract of the functional interface is not inadvertently broken.
  • Existing Interfaces: Many existing interfaces from earlier versions of Java naturally fit the definition of a functional interface. For example, java.lang.Runnable and java.util.concurrent.Callable are both functional interfaces as they have only one abstract method.

In this example, SimpleFunction is a functional interface with one abstract method execute() . The @FunctionalInterface annotation ensures that no additional abstract methods are inadvertently added.

  • Clarity and Documentation: Use @FunctionalInterface to communicate your intention clearly both to the compiler and to other developers. It serves as a form of documentation.
  • Design with Care: When designing a functional interface, consider its general utility and how it fits into the broader application architecture, especially if it's intended to be used across different parts of the application.
  • Avoid Overuse: While functional programming in Java can lead to more elegant and concise code, be cautious of overusing lambdas and functional interfaces, as they can make the code harder to read and debug if used excessively or inappropriately.
  • Compatibility with Older Java Versions: Be aware that @FunctionalInterface is a Java 8 feature. If you're working on applications that need to be compatible with earlier Java versions, you won’t be able to use this feature.

38. How Can You Achieve Immutability in Java?

Achieving immutability in Java is a fundamental practice, particularly useful for creating robust, thread-safe applications.

An immutable object is one whose state cannot be modified after it is created. Here's a detailed and precise explanation of how to achieve immutability in Java:

Core Principles of Immutability:

  • No Setters: Immutable objects do not expose any methods to modify their state after construction. This typically means not providing any setter methods.
  • Final Class: The class should be declared as final to prevent subclassing. Subclasses could add mutable state, undermining the immutability of the parent class.
  • Final Fields: All fields should be final , ensuring they are assigned only once, typically within the constructor, and cannot be re-assigned.
  • Private Fields: Fields should be private to prevent external modification and to encapsulate the data.

No Direct Access to Mutable Objects:

If your class has fields that are references to mutable objects (like arrays or collections), ensure these fields are not directly exposed or modified:

  • Do not provide methods that modify mutable objects.
  • Do not share references to the mutable objects. Provide copies of mutable objects when needed.

How to Create an Immutable Class:

  • Defensive Copies: When dealing with mutable objects passed to the constructor or returned by methods, create defensive copies. This practice prevents external code from modifying the internal state of the immutable object.
  • Immutable Collections: Utilize immutable collections (like those provided in Java 9 and later) to simplify the creation of classes with immutable collection fields.
  • Performance Considerations: Be mindful of the performance implications of creating defensive copies, especially in performance-critical applications.
  • Use in Multi-threaded Environments: Immutable objects are inherently thread-safe, making them ideal for use in multi-threaded environments.
  • String and Wrapper Types: Leverage the immutability of String and wrapper types (Integer, Long, and so on) as part of your immutable objects.
  • Design Strategy: Consider immutability as a design strategy, especially for objects representing values that are not expected to change, such as configuration data, constants, or natural data types.

Advantages of Immutability:

  • Simplicity and Clarity: Immutable objects are easier to understand and use. There's no need to track changes in state, reducing cognitive load.
  • Thread Safety: Immutability eliminates issues related to concurrency and synchronization, as immutable objects can be freely shared between threads without synchronization.
  • Caching and Reuse: Immutable objects can be cached and reused, as they are guaranteed not to change, reducing the overhead of object creation.
  • Hashcode Caching: Immutable objects are great candidates for caching their hashcode, which can be beneficial in collections like HashMaps and HashSets .

39. What is the Decorator Pattern?

The Decorator Pattern is a structural design pattern used in object-oriented programming, and it's particularly useful for extending the functionality of objects at runtime. It is a robust alternative to subclassing, providing a more flexible approach to add responsibilities to objects without modifying their underlying classes.

Purpose of decorator pattern

The Decorator Pattern allows you to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The pattern involves a set of decorator classes that are used to wrap concrete components. Each decorator class has a reference to a component object and adds its own behavior either before or after delegating the task to the component object.

How to implement the decorator pattern

It typically involves an abstract decorator class that implements or extends the same interface or superclass as the objects it will dynamically add functionality to. Concrete decorators then extend the abstract decorator.

Key Components:

  • Component: An interface or abstract class defining the operations that can be altered by decorators.
  • Concrete Component: A class implementing or extending the Component, defining an object to which additional responsibilities can be attached.
  • Decorator: An abstract class that extends or implements the Component interface and has a reference to a Component.
  • Concrete Decorator: A class that extends the Decorator and adds functionalities to the Component it decorates.

Decorator example in Java:

Usage and advantages:.

  • Flexibility: The Decorator Pattern provides a more flexible way to add responsibilities to objects compared to subclassing. New functionalities can be added at runtime.
  • Avoid Class Explosion: It helps in avoiding an extensive hierarchy of subclasses when you need multiple combinations of functionalities.
  • Single Responsibility Principle: Decorators allow functionalities to be divided into simple classes with single responsibilities.

Considerations:

  • Complexity: Overuse of the decorator pattern can lead to complexity, making the code harder to understand and maintain.
  • Instantiation Management: Managing the instantiation of decorated objects can be challenging, especially when dealing with multiple layers of decoration.

The Decorator Pattern is a powerful tool in a software developer's toolkit, offering a dynamic and flexible solution for extending object functionality. Understanding and applying this pattern can greatly enhance the design of software, particularly in situations where adding responsibilities to objects at runtime is necessary.

This pattern is highly valued in software development, as it showcases an ability to effectively manage and extend object functionalities without altering existing codebases, aligning with principles of maintainability and scalability.

40. Explain Java I/O Streams

Java I/O (Input/Output) streams are a fundamental part of the Java I/O API, providing a robust framework for handling input and output operations in Java. Understanding these streams is crucial for efficient data handling in Java applications.

Overview of Java I/O Streams

I/O streams in Java are used to read data from an input source and to write data to an output destination. The Java I/O API is rich and provides various classes to handle different types of data, like bytes, characters, objects, etc.

Stream Types:

Java I/O streams are broadly categorized into two types:

  • Byte Streams: Handle I/O of raw binary data.
  • Character Streams: Handle I/O of character data, automatically handling character encoding and decoding.

Byte Streams:

  • Classes: InputStream and OutputStream are abstract classes at the hierarchy's root for byte streams.
  • Usage: They are used for reading and writing binary data, such as image or video files.
  • Example Classes: FileInputStream , FileOutputStream , BufferedInputStream , BufferedOutputStream , etc.

Character Streams:

  • Classes: Reader and Writer are abstract classes for character streams.
  • Usage: Suitable for handling textual data, ensuring correct interpretation of characters according to the default character encoding.
  • Example Classes: FileReader , FileWriter , BufferedReader , BufferedWriter , etc.

Key Features of Java I/O Streams:

  • Stream Hierarchy: Java uses a hierarchy of classes to manage different types of I/O operations, allowing for flexibility and reusability of code.
  • Decorators: Java I/O uses decorators, where one stream wraps another and adds additional capabilities, like buffering, data conversion, and so on.
  • Buffering: Buffering is a common practice in I/O streams to enhance I/O efficiency, allowing for the temporary storage of data in memory before it's written to or read from the actual I/O source.
  • Exception Handling: I/O operations in Java are prone to errors like file not found, access denied, etc. Hence, most I/O operations throw IOException , which must be properly handled using try-catch blocks or thrown further.
  • Use Buffered Streams: Always use buffered streams ( BufferedInputStream , BufferedOutputStream , BufferedReader , BufferedWriter ) for efficient I/O operations, as they reduce the number of actual I/O operations by buffering chunks of data.
  • Close Streams: Ensure streams are closed after their operation is complete to free up system resources. This is typically done in a finally block or using try-with-resources introduced in Java 7.
  • Error Handling: Implement robust error handling. I/O operations are susceptible to many issues, so proper exception handling is crucial.
  • Character Encoding: Be mindful of character encoding while using character streams. Incorrect handling of encoding can lead to data corruption.

Practical Example:

In this example, BufferedReader and BufferedWriter are used for reading from and writing to a text file, demonstrating the use of character streams with buffering for efficiency.

Java I/O streams form the backbone of data handling in Java applications. Understanding the distinction between byte and character streams, along with the proper use of buffering and exception handling, is essential for writing efficient, robust, and maintainable Java code.

This knowledge is vital for Java developers and is often a subject of interest in technical interviews, showcasing one's capability to handle data proficiently in Java applications.

41. How Does the Garbage Collector Work in Java?

In Java, garbage collection (GC) is a critical process of automatically freeing memory by reclaiming space from objects that are no longer in use, ensuring efficient memory management.

Understanding how the garbage collector works in Java is essential for writing high-performance applications and is a key area of knowledge in professional Java development.

Overview of Garbage Collection in Java

The primary function of garbage collection in Java is to identify and discard objects that are no longer needed by a program. This prevents memory leaks and optimizes memory usage.

Automatic Memory Management

Unlike languages where memory management is manual (like C/C++), Java provides automatic memory management through its garbage collector, which runs in the background.

How the Garbage Collector Works

Object creation and heap storage:.

In Java, objects are created in a heap memory area. This heap is divided into several parts – Young Generation, Old Generation (or Tenured Generation), and Permanent Generation (replaced by Metaspace in Java 8).

  • Young Generation: Newly created objects reside in the Young Generation, which is further divided into three parts: one Eden space and two Survivor spaces (S0 and S1). Most objects die young. When the Eden space fills up, a minor GC is triggered, moving surviving objects to one of the Survivor spaces (S0 or S1) and clearing Eden.
  • Aging of Objects: As objects survive more garbage collection cycles, they age. After surviving certain cycles, they are moved to the Old Generation.
  • Old Generation: The Old Generation stores long-living objects. A more comprehensive form of GC, known as major GC, occurs here, which is generally more time-consuming.
  • Metaspace (Java 8 and above): Metaspace stores metadata of classes. Unlike the PermGen (Permanent Generation) space in earlier Java versions, Metaspace uses native memory, and its size is not fixed but can be configured.

Types of Garbage Collectors in Java:

  • Serial GC: Suitable for single-threaded environments. It freezes all application threads during garbage collection.
  • Parallel GC: Also known as Throughput Collector, it uses multiple threads for young generation garbage collection but stops all application threads during major GC.
  • Concurrent Mark Sweep (CMS) GC: Minimizes pauses by doing most of its work concurrently with application threads but requires more CPU resources.
  • G1 Garbage Collector: Designed for large heap memory areas, it divides the heap into regions and prioritizes GC on regions with the most garbage first.

Garbage Collection Processes

The process starts by marking all reachable objects. Reachable objects are those that are accessible directly or indirectly through references from root objects (like local variables, static fields, etc.).

Unreachable objects (those not marked as reachable) are considered for deletion .

To prevent fragmentation and optimize memory usage, some garbage collectors perform compaction , moving surviving objects closer together.

  • Avoid Memory Leaks: Despite automatic garbage collection, memory leaks can still occur (for example, through static references). It's crucial to be mindful of object references and their lifecycles.
  • GC Tuning: For high-performance applications, GC tuning can be essential. Understanding different garbage collector types and their configuration parameters allows for optimal tuning according to application needs.
  • Monitoring and Profiling: Regular monitoring of garbage collection and memory usage is important, especially for applications with high throughput or large heaps.

Garbage collection in Java is a sophisticated system designed to efficiently manage memory in the Java Virtual Machine (JVM). An in-depth understanding of how garbage collection works, its types, and its impact on application performance is essential for Java developers, particularly those working on large-scale, high-performance applications.

This knowledge not only helps in writing efficient and robust applications but also is a valuable skill in troubleshooting and performance tuning, aspects highly regarded in the field of software development.

42. What Are the Benefits of Using Java NIO?

Java NIO (New Input/Output), introduced in JDK 1.4, marks a substantial advancement in Java's approach to I/O operations. It was developed to address the constraints of traditional I/O methods, leading to improved scalability and efficiency.

This makes Java NIO particularly advantageous in scenarios demanding high throughput and concurrent access.

Let’s discuss the key benefits of using Java NIO in detail.

1. Channels and Buffers: Enhanced Data Handling

  • Channels : These are bi-directional conduits allowing both reading and writing operations. Unlike traditional unidirectional streams, channels simplify I/O patterns, especially for network sockets, by enabling two-way communication within a single channel.
  • Buffers : Acting as fixed-size data containers, buffers allow batch processing of data. This is more efficient compared to the byte-by-byte processing in traditional I/O, as it enables handling data in larger, more manageable blocks.

2. Non-blocking and Asynchronous I/O

Java NIO supports non-blocking and asynchronous I/O operations, a stark contrast to the blocking nature of traditional I/O where a thread remains idle until an operation completes.

This feature of NIO means a thread can initiate an I/O operation and continue performing other tasks without waiting for the I/O process to finish. This capability significantly enhances the scalability and responsiveness of applications, making them more efficient in handling multiple concurrent I/O requests.

3. Practical Applications

Java NIO is particularly effective in environments that require high-performance and low latency, such as:

  • Web and Application Servers : Managing high-volume network traffic efficiently.
  • Real-time Systems : Like trading platforms where quick data processing is critical.
  • Big Data Applications : Benefiting from efficient handling of large datasets.
  • File-based Database Systems : Where efficient file I/O operations are crucial.

4. Channels: The Foundation of NIO’s Architecture

Channels serve as the backbone of NIO, providing a more unified and simplified interface for various I/O operations. They come in different types, each catering to specific needs:

  • FileChannel : For file operations.
  • SocketChannel and ServerSocketChannel : For TCP network communications.
  • DatagramChannel : For UDP operations.
  • Pipes : For inter-thread communication. Particularly in network operations, the ability of channels to operate in a non-blocking mode allows a single thread to handle multiple connections, enhancing the application’s scalability.

5. Buffers: Central to NIO’s Data Transfer

Buffers in NIO are essential for data transfer, acting as temporary storage for data during I/O operations. Their key operations include:

  • Put and Get : For writing and reading data.
  • Flip : To switch modes between reading and writing.
  • Clear and Compact : Preparing the buffer for new data. Different buffer types (like ByteBuffer, CharBuffer, IntBuffer) cater to various data primitives, enhancing the flexibility and efficiency of data handling. Notably, direct buffers, which are allocated outside of the JVM heap, can provide faster I/O operations, though they come with higher allocation and deallocation costs.

6. Selectors: Streamlining Scalable I/O Operations

Selectors are a unique NIO feature enabling a single thread to monitor multiple channels for readiness, thus efficiently managing numerous I/O operations. This reduces the need for multiple threads, cutting down on resource usage and context switching, which is particularly advantageous in high-performance environments.

7. Improved Performance and Scalability

The amalgamation of channels, buffers, and selectors provides a substantial performance boost. The non-blocking nature of NIO minimizes idle thread time, and managing multiple channels with a single thread significantly improves the scalability. This is pivotal in server environments dealing with numerous simultaneous connections.

Java NIO offers a robust, scalable, and efficient framework for handling I/O operations, addressing many of the limitations of traditional I/O. Its design is particularly advantageous for high-throughput and concurrent-processing systems.

While the complexity of NIO might be higher compared to traditional I/O, the performance and scalability benefits it provides make it an indispensable tool for developers working on large-scale, I/O-intensive Java applications.

43. Explain the Observer Pattern

The Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

It's particularly useful in the scenario where a single object needs to notify an array of objects about a change in its state. In the context of a newsletter system, the Observer pattern can be effectively used to notify subscribers whenever a new post is available.

How to Implement the Observer Pattern for a Newsletter System

Let's break down the implementation using the Observer pattern in the context of a newsletter system:

  • Subject (Newsletter) : This is the entity being observed. It will notify all attached observers when a new post is available.
  • Observer (Subscriber) : These are the observers who wish to be notified about new posts in the newsletter.
  • Client : This will use both the Subject and Observers.

Step 1: Create the Subject Class (Newsletter)

Step 2: create the observer abstract class (subscriber), step 3: create concrete observer classes.

EmailSubscriber.java

SMSSubscriber.java

Step 4: Use the Newsletter and Concrete Subscriber Objects

Step 5: output verification.

When running NewsletterSystemDemo , the output will be something like:

This output indicates that both the email and SMS subscribers are notified whenever the newsletter has a new post.

The Observer pattern provides a clean and straightforward way to implement a subscription mechanism in a newsletter system, ensuring that all subscribers are automatically updated with the latest posts.

This pattern enhances modularity and separation of concerns, making the system easier to understand, maintain, and extend.

44. Explain the Purpose of the this Keyword.

The this keyword in Java serves a very specific and useful purpose. It refers to the current instance of the class in which it is used. This is particularly valuable in scenarios where you need to distinguish between class fields (instance variables) and parameters or variables within a method that have the same name. Let's break it down:

Reference to Instance Variables: When a class’s field is shadowed by a method or constructor parameter, this can be used for referencing the class's field. For instance, in a setter method, this helps differentiate between the instance variable and the parameter passed to the method.

Calling One Constructor from Another: In a class with overloaded constructors, this can be used to call one constructor from another, avoiding code duplication.

Returning the Current Instance: Methods can return this to return the current class instance. This is often used in method chaining.

Passing the Current Instance to Another Method: this can be passed as an argument in the method call or constructor call. This is common in event handling.

Disambiguation: It eliminates ambiguity when instance variables and parameters or local variables share the same name.

45. Explain Java's try-with-resources.

Java's try-with-resources, introduced in Java 7, is a mechanism that ensures more efficient handling of resources, like files or sockets, in Java. Its primary purpose is to simplify the cleanup of resources which must be closed after their operations are completed.

Key Characteristics:

Automatic Resource Management: In try-with-resources, resources declared within the try clause are automatically closed at the end of the statement, even if exceptions are thrown. This reduces boilerplate code significantly as compared to traditional try-catch-finally blocks.

Syntax: The resources that implement java.lang.AutoCloseable or java.io.Closeable are declared and initialized within parentheses just after the try keyword.

  • Here, the BufferedReader instance is automatically closed when the try block exits, regardless of whether it exits normally or due to an exception.
  • Exception Handling: Any exception thrown by the automatic closure of resources is suppressed if an exception is thrown in the try block. These suppressed exceptions can be retrieved using Throwable.getSuppressed() method.
  • Improved Readability and Reliability: This structure enhances code readability and reliability. It reduces the risk of resource leaks, as the closing of resources is handled automatically.
  • Use in Custom Resources: Custom classes can also utilize this mechanism by implementing the AutoCloseable interface and overriding the close method.

Practical Implications:

In real-world applications, try-with-resources ensures that resources like file streams, database connections, or network sockets are closed properly, preventing resource leaks which could lead to performance issues and other bugs. It is especially valuable in large-scale applications where resource management is critical for efficiency and reliability.

46. Explain the Difference between C++ and Java.

When distinguishing between C++ and Java, it's important to understand that both are powerful programming languages with their unique characteristics and use cases.

They share some similarities, as both are object-oriented and have similar syntax (being influenced by C), but there are key differences that set them apart.

Language Nature and Design Philosophy:

C++ is a multi-paradigm language that supports both procedural and object-oriented programming. It's often chosen for system-level programming due to its efficiency and fine-grained control over memory management.

Java , on the other hand, is primarily object-oriented and designed with a simpler approach to avoid common programming errors (like pointer errors in C++). Java's design principle "Write Once, Run Anywhere" (WORA) emphasizes portability, which is achieved through the Java Virtual Machine (JVM).

Memory Management:

In C++ , memory management is manual. Programmers have direct control over memory allocation and deallocation using operators like new and delete .

Java abstracts away the complexity of direct memory management through its Automatic Garbage Collection, which periodically frees memory that's no longer in use, reducing the likelihood of memory leaks but at the cost of less control and potential overhead.

Platform Dependency and Portability:

C++ is platform-dependent. A C++ program needs to be compiled for each specific platform it's intended to run on, which can lead to more work when targeting multiple platforms.

Java is platform-independent at the source level. Java programs are compiled into bytecode, which can run on any device equipped with a JVM, making it highly portable.

Runtime and Performance:

C++ generally offers higher performance than Java. It compiles directly to machine code, which the CPU executes, resulting in faster execution suitable for performance-critical applications.

Java may have slower performance due to the added abstraction layer of the JVM. But improvements in Just-In-Time (JIT) compilers within the JVM have significantly narrowed this performance gap.

Pointers and Memory Safety:

C++ supports both pointers and references, allowing for powerful, albeit potentially risky, memory manipulation.

Java has references but does not support pointers (at least not in the traditional sense), reducing the risk of memory access errors, thereby increasing program safety.

Exception Handling:

C++ supports exception handling but does not enforce error handling (uncaught exceptions can lead to undefined behavior).

Java has a robust exception handling mechanism, requiring checked exceptions to be caught or declared in the method signature, promoting better error management practices.

Multi-Threading:

C++ has more complex approaches to multi-threading and requires careful management to ensure thread safety.

Java provides built-in support for multi-threading with synchronized methods and blocks, making concurrent programming more manageable.

Standard Template Library (STL) vs. Java Standard Library:

C++ 's STL is a powerful library that offers containers, algorithms, iterators, and so on for efficient data manipulation.

Java 's Standard Library provides a rich set of APIs, including collections, streams, networking, and so on with a focus on ease of use.

Legacy and Use Cases:

C++ is often chosen for system/software development, game development, and applications where hardware access and performance are critical.

Java is widely used in enterprise environments, web services, and Android app development due to its portability and robust libraries.

Both C++ and Java have their strengths and are chosen based on the requirements of the project.

C++ is preferred for scenarios where performance and memory control are crucial, while Java is ideal for applications where portability and ease of use are more important.

Understanding these differences is key in selecting the right language for a particular task or project, and adapting to the strengths of each can lead to more efficient and effective programming practices.

47. What is Polymorphism? Provide an Example.

Polymorphism, a fundamental concept in object-oriented programming, allows objects to be treated as instances of their parent class or interface. It’s a Greek word meaning “many shapes” and in programming, it refers to the ability of a single function or method to work in different ways based on the object it is acting upon.

There are two primary types of polymorphism: compile-time (or static) polymorphism and runtime (or dynamic) polymorphism.

Compile-Time Polymorphism : This is achieved through method overloading and operator overloading. It’s called compile-time polymorphism because the decision about which method to call is made by the compiler.

Method Overloading involves having multiple methods in the same scope, with the same name but different parameters.

In this example, the operate method is overloaded with different parameter types, allowing it to behave differently based on the type of arguments passed.

Runtime Polymorphism : This is mostly achieved through method overriding, which is a feature of inheritance in object-oriented programming. In runtime polymorphism, the method to be executed is determined at runtime.

Method Overriding involves defining a method in a subclass that has the same name, return type, and parameters as a method in its superclass.

In this example, the speak method in the subclass Dog overrides the speak method in its superclass Animal . When the speak method is called on an object of type Dog , the overridden method in the Dog class is executed, demonstrating runtime polymorphism.

Why Polymorphism is Important

  • Flexibility and Extensibility : Polymorphism allows for flexible and extensible code. You can create a more generalized code that works on the superclass type, and it automatically adapts to the specific subclass types.
  • Code Reusability : It enables the reuse of code through inheritance and the ability to override or overload methods.
  • Loose Coupling : By using polymorphic behavior, components can be designed loosely coupled, which means a change in one part of the system causes minimal or no effect on other parts of the system.
  • Simplifies Code Maintenance : With polymorphism, developers can write more maintainable and manageable code, as changes to a superclass are inherited by all subclasses, reducing the need for changes across multiple classes.

Polymorphism is a cornerstone in the world of object-oriented programming, enabling more dynamic and flexible code. It allows objects to interact in a more abstract manner, focusing on the shared behavior rather than the specific types.

Understanding and effectively using polymorphism can lead to more robust and maintainable code, a crucial aspect for any software developer looking to excel in their field.

48. How Can You Avoid Memory Leaks in Java?

Avoiding memory leaks in Java, despite its automated garbage collection mechanism, requires a deep understanding of how memory allocation and release work in Java, alongside meticulous coding practices and effective use of analysis tools.

Let’s delve into some advanced and specific strategies for preventing memory leaks in Java applications:

Understand Object Lifecycle and Scope:

  • Scope Management : Ensure objects are scoped as narrowly as possible. For instance, use local variables within methods rather than class-level variables if the data does not need to persist beyond the method’s execution context.
  • Reference Management : Be cautious with static references. Static fields can keep objects alive for the lifetime of the class, potentially leading to memory leaks.

Efficient Use of Collections:

  • WeakHashMap : For cache implementations, consider using WeakHashMap . It uses weak references for keys, which allows keys (and their associated values) to be garbage-collected when no longer in use.
  • Data Structure Choice : Be mindful of the choice of data structure. For example, use ArrayList over LinkedList for large lists of data where frequent access is required, as LinkedList can consume more memory due to the storage of additional node references.

Leveraging WeakReferences and SoftReferences :

  • SoftReferences for Caches : Use SoftReference for memory-sensitive caches. The garbage collector will only remove soft-referenced objects if it needs memory, making them more persistent than weak references.
  • WeakReferences for Listeners : Utilize WeakReference for listener patterns where listeners might not be explicitly removed.

Managing Resources and I/O:

  • AutoCloseable and Try-with-Resources : For resources like streams, files, and connections, use try-with-resources for automatic closure. Ensure that objects implementing AutoCloseable are closed properly to release resources.

Inner Classes Handling:

  • Static Inner Classes : Prefer static inner classes over non-static to avoid the implicit reference to the outer class instance, which can prevent the outer instance from being garbage-collected.

Profiling and Leak Detection:

  • Heap Dump Analysis : Regularly analyze heap dumps in tools like Eclipse Memory Analyzer (MAT) to detect large objects and potential memory leaks.
  • Java Flight Recorder : Use Java Flight Recorder for runtime analysis and monitoring, which can help identify memory leaks.

ThreadLocal Variables Management:

  • Explicit Removal : Always remove ThreadLocal variables after use, particularly in thread-pooled environments like servlet containers or application servers.

ClassLoader Leaks:

  • ClassLoader Lifecycle : In environments with dynamic class loading/unloading (for example, web servers), ensure that class loaders are garbage collected when not needed. This involves ensuring that classes loaded by these class loaders are no longer referenced.

Garbage Collection Tuning:

  • GC Analysis : Analyze GC logs to understand the garbage collection behavior and identify potential memory leaks.
  • GC Algorithm Choice : Choose an appropriate garbage collection algorithm based on application needs, which can be tuned with JVM options for optimal performance.

String Interning:

  • Selective Interning : Be cautious with the String.intern() method. Unnecessary interning of strings can lead to a bloated String pool.

Static Analysis Tools:

Utilize tools like SonarQube, FindBugs, or PMD to statically analyze code for patterns that could lead to memory leaks.

Developer Training and Code Reviews:

Regularly train developers on best practices in memory management and conduct thorough code reviews with a focus on potential memory leak patterns.

Memory leak prevention in Java is a sophisticated practice that involves a thorough understanding of Java memory management, careful coding, diligent use of analysis tools, and regular monitoring.

By adopting these advanced practices, developers can significantly mitigate the risk of memory leaks, leading to more robust, efficient, and scalable Java applications.

49. Explain the Purpose of Java's Synchronized Block

The purpose of Java's synchronized block is to ensure thread safety in concurrent programming by controlling access to a shared resource among multiple threads.

In a multithreaded environment, where multiple threads operate on the same object, there's a risk of data inconsistency if the threads simultaneously modify the object. A synchronized block in Java is used to lock an object for exclusive access by a single thread.

Thread Safety and Data Consistency:

When different threads access and modify shared data, it can lead to unpredictable data states and inconsistencies. The synchronized block ensures that only one thread can execute a particular block of code at a time, thus maintaining data integrity.

Lock Mechanism:

In Java, each object has an intrinsic lock or monitor lock. When a thread enters a synchronized block, it acquires the lock on the specified object. Other threads attempting to enter the synchronized block on the same object are blocked until the thread inside the synchronized block exits, thereby releasing the lock.

Syntax and Usage:

The synchronized block is defined within a method, and you must specify the object that provides the lock:

The lockObject is a reference to the object whose lock the synchronized block acquires. It can be this to lock the current object, a class object for class-level locks, or any other object.

Advantages Over Synchronized Methods:

Compared to synchronized methods, synchronized blocks provide finer control over the scope and duration of the lock.

While a synchronized method locks the entire method, a synchronized block can lock only the part of the method that needs synchronization, potentially improving performance.

Avoiding Deadlocks:

Take care to avoid deadlocks, a situation where two or more threads are blocked forever, each waiting for the other's lock. This usually occurs when multiple synchronized blocks are locking objects in an inconsistent order.

Synchronized blocks also solve memory visibility problems. Changes made by one thread in a synchronized block are visible to other threads entering subsequent synchronized blocks on the same object.

Best Practices

  • Minimize Lock Contention : Keep the synchronized sections as short as possible to minimize lock contention and avoid performance bottlenecks.
  • Consistent Locking Order : Always acquire locks in a consistent order to prevent deadlocks.
  • Avoid Locking on Public Objects : Locking on public objects can lead to accidental and uncontrolled access to the lock, increasing the deadlock risk. Prefer private objects as lock targets.
  • Complement with Other Concurrency Tools : In some cases, using higher-level concurrency tools like ReentrantLock , Semaphore , or concurrent collections from java.util.concurrent package might be more appropriate.

Java's synchronized block is a critical tool for achieving thread safety in concurrent applications. Its proper use ensures data integrity and consistency by controlling access to shared resources. But, it requires careful consideration to avoid common pitfalls like deadlocks and performance issues due to excessive lock contention.

Understanding and applying these concepts is essential for developers working in a multithreaded environment to create robust and efficient Java applications.

50. Explain the Concept of Modules in Java

Modules in Java, introduced in Java 9 with the Java Platform Module System (JPMS), represent a fundamental shift in organizing Java applications and their dependencies.

Understanding modules is essential for modern Java development, as they offer improved encapsulation, reliable configuration, and scalable system architectures.

What are Java modules?

A module in Java is a self-contained unit of code and data, with well-defined interfaces for communicating with other modules. Each module explicitly declares its dependencies on other modules.

Modules enable better encapsulation by allowing a module to expose only those parts of its API which should be accessible to other modules, while keeping the rest of its codebase hidden. This reduces the risk of unintended usage of internal APIs.

Key Components of modules:

module-info.java : Each module must have a module-info.java file at its root, which declares the module's name, its required dependencies, and the packages it exports.

  • Here, com.example.myapp is the module name, java.sql is a required module, and com.example.myapp.api is the exported package.
  • Exports and Requires: The exports keyword specifies which packages are accessible to other modules, while requires lists the modules on which the current module depends.
  • Improved Application Structure: Modules encourage a cleaner, more organized code structure, helping in maintaining large codebases and improving code quality.
  • Reduced Memory Footprint: By only loading the required modules, applications can reduce their memory footprint and start-up time, enhancing performance.
  • Enhanced Security and Maintenance: Modules reduce the surface area for potential security vulnerabilities. They also simplify dependency management, making it easier to update and maintain libraries without affecting the entire system.

Consider a scenario where you are developing a large-scale application with various functionalities like user management, data processing, and reporting. By organizing these functionalities into separate modules (like usermodule , dataprocessmodule , reportmodule ), you can maintain them independently, avoiding the complexities of a monolithic application structure.

Modules in Java are a powerful feature for building scalable, maintainable, and efficient applications. They offer clear boundaries and contracts between different parts of a system, facilitating better design and architecture.

For developers and teams aiming to build robust Java applications, understanding and leveraging modules is not just a technical skill but a strategic approach to software development.

This modular architecture aligns with modern development practices, enabling Java applications to be more scalable and easier to manage in the long term.

As we wrap up this roundup of Java interview questions, I want to take a moment to thank the freeCodeCamp team. This platform is a fantastic resource for people learning to code, and it's great to have such a supportive community in the tech world.

I also want to thank the editorial team for their help in making this guide possible. Working together has been a great experience, and it's been rewarding to combine our efforts to help others learn Java.

It's important to reflect on the journey we've undertaken together. Java's robustness in Object-Oriented Programming (OOP) is a critical asset for developers at all levels, especially those aspiring to join top-tier tech firms. This handbook has aimed to provide a clear pathway to mastering Java interviews, focusing on the insights and techniques that matter most in the competitive landscape of big tech.

From the fundamentals to the more complex aspects of Java, I've sought to bridge the gap between basic Java knowledge and the sophisticated expertise that industry leaders like Google value. This resource is crafted not just for those new to Java, but also for those revisiting key concepts, offering a comprehensive understanding of the language in a practical context.

As you continue to explore the depths of Java, remember that mastering this language is not just about enhancing coding skills, but also about expanding your professional horizons. Java's significant role in IoT and its presence in billions of devices worldwide make it a language that can truly shape your career.

In closing, I hope this handbook has provided you with valuable insights and a strong foundation for your future endeavors in Java programming and beyond. Whether you're preparing for a big tech interview or simply looking to refine your software development skills, this guide is a stepping stone towards achieving those goals.

If you're keen on furthering your Java knowledge, here's a guide to help you conquer Java and launch your coding career . It's perfect for those interested in AI and machine learning, focusing on effective use of data structures in coding. This comprehensive program covers essential data structures, algorithms, and includes mentorship and career support.

Additionally, for more practice in data structures, you can explore these resources:

  • Java Data Structures Mastery - Ace the Coding Interview : A free eBook to advance your Java skills, focusing on data structures for enhancing interview and professional skills.
  • Foundations of Java Data Structures - Your Coding Catalyst : Another free eBook, diving into Java essentials, object-oriented programming, and AI applications.

Visit LunarTech's website for these resources and more information on the bootcamp .

Connect with Me:

  • Follow me on LinkedIn for a ton of Free Resources in CS, ML and AI
  • Visit my Personal Website
  • Subscribe to my The Data Science and AI Newsletter

About the Author

I'm Vahe Aslanyan, deeply engaged in the intersecting worlds of computer science, data science, and AI. I invite you to explore my portfolio at vaheaslanyan.com, where I showcase my journey in these fields. My work focuses on blending full-stack development with AI product optimization, all fueled by a passion for innovative problem-solving.

I've had the privilege of contributing to the launch of a well-regarded data science bootcamp and collaborating with some of the best minds in the industry. My goal has always been to raise the bar in tech education, making it accessible and standard for everyone.

As we conclude our journey here, I want to thank you for your time and engagement. Sharing my professional and academic experiences in this book has been a rewarding experience. I appreciate your involvement and look forward to seeing how it helps you advance in the tech world.

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java exercises.

You can test your Java skills with W3Schools' Exercises.

We have gathered a variety of Java exercises (with answers) for each Java Chapter.

Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start Java Exercises

Start Java Exercises ❯

If you don't know Java, we suggest that you read our Java Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Java Programming Exercises

  • All Exercises
  • Java 8 - Lambdas & Streams
  • Binary Tree

I created this website to help developers improve their programming skills by practising simple coding exercises. The target audience is Software Engineers, Test Automation Engineers, or anyone curious about computer programming. The primary programming language is Java, as it is mature and easy to learn, but you can practice the same problems in any other language (Kotlin, Python, Javascript, etc.).

  • Binary Tree problems are common at Google, Amazon and Facebook coding interviews.
  • Sharpen your lambda and streams skills with Java 8 coding practice problems .
  • Check our Berlin Clock solution , a commonly used code exercise.
  • We have videos too! Check out the FizzBuzz solution , a problem widely used on phone screenings.

How does it work ?

1. Choose difficulty

Easy, moderate or challenging.

2. Choose the exercise

From a list of coding exercises commonly found in interviews.

3. Type in your code

No IDE, no auto-correct... just like the whiteboard interview question.

4. Check results

Typically 3-5 unit tests that verify your code.

[email protected]

Email

{{ activeMenu.name }}

  • Python Courses
  • JavaScript Courses
  • Artificial Intelligence Courses
  • Data Science Courses
  • React Courses
  • Ethical Hacking Courses
  • View All Courses

Fresh Articles

TripleTen Data Science Bootcamp: Insider Review

  • Python Projects
  • JavaScript Projects
  • Java Projects
  • HTML Projects
  • C++ Projects
  • PHP Projects
  • View All Projects

How to Build an Age Calculator in Python

  • Python Certifications
  • JavaScript Certifications
  • Linux Certifications
  • Data Science Certifications
  • Data Analytics Certifications
  • Cybersecurity Certifications
  • View All Certifications

DataCamp’s Certifications To Get You Job-Ready: Insider Review

  • IDEs & Editors
  • Web Development
  • Frameworks & Libraries
  • View All Programming
  • View All Development

The Best Computer for Android Development: Minimum and Recommended Specs

  • App Development
  • Game Development
  • Courses, Books, & Certifications
  • Data Science
  • Data Analytics
  • Artificial Intelligence (AI)
  • Machine Learning (ML)
  • View All Data, Analysis, & AI

Insider Review of DataCamp’s AI-Powered DataLab Tool

  • Networking & Security
  • Cloud, DevOps, & Systems
  • Recommendations
  • Crypto, Web3, & Blockchain
  • User-Submitted Tutorials
  • View All Blog Content

Last Mile Education Fund helps students cover costs while learning cybersecurity

  • Python Online Compiler
  • JavaScript Online Compiler
  • HTML & CSS Online Compiler
  • Certifications
  • Programming
  • Development
  • Data, Analysis, & AI
  • Online Python Compiler
  • Online JavaScript Compiler
  • Online HTML Compiler

Don't have an account? Sign up

Forgot your password?

Already have an account? Login

Have you read our submission guidelines?

Go back to Sign In

java problem solving questions and answers

Top 80 Java Interview Questions and Answers [2024]

To land the job, it helps to review common and challenging Java interview questions. After all, the class-based, general-purpose, object-oriented programming language is one of the most widely used programming languages in the world .

We prepared these Java interview questions with answers from experts. Expect to cover the basics with beginner-friendly topics and much more advanced challenges with specific code to help professional Software Developers and Android Applications Developers. 

Remember that, with a plethora of great features , the programming language is preferred not only by seasoned experts but also by those new to the programming world. Our interview questions start with basic Java concepts and progress to much more difficult challenges.

Whether you're seeking a new gig or hiring to expand your team, read on to review the best Java interview questions for 2024.

  • Top Java Interview Questions and Answers

We also recommend you brush up on your Java skills with this Java Cheat Sheet before starting your Java interview preparation. 

We have divided these interview questions into several sections. Check the breakdown below to review basic, advanced, OOPs, exception handling, and programming Java interview questions. We also have specific examples of code. Review the coding Java interview questions section for reference.

Basic Java Interview Questions

1. what is java.

Java is an object-oriented, high-level, general-purpose programming language originally designed by James Gosling and further developed by the Oracle Corporation. It is one of the most popular programming languages in the world . 

2. What is the Java Virtual Machine? 

Java Virtual Machine

JVM is a program that interprets the intermediate Java byte code and generates the desired output. It is because of bytecode and JVM that programs written in Java are highly portable. 

3. What are the features of Java?

The following are the various features of the Java programming language:

  • High Performance: Using a JIT (Just-In-Time) compiler allows high performance in Java. The JIT compiler converts the Java bytecode into machine language code, which then gets executed by the JVM.
  • Multi-threading: A thread is a flow of execution. The JVM creates a thread which is called the main thread. Java allows the creation of several threads using either extending the thread class or implementing the Runnable interface.
  • OOPs Concepts: Java follows various OOPs concepts , namely abstraction, encapsulation, inheritance, object-oriented, and polymorphism
  • Platform Independency: Java makes use of the Java Virtual Machine or JVM, which allows a single Java program to operate on multiple platforms without any modifications.

You may want to check out detailed explanations of Java features here . 

4. How does Java enable high performance?

In Just-in-Time compilation, the required code is executed at run time. Typically, it involves translating bytecode into machine code and then executing it directly. It allows for high performance. The JIT compiler is enabled by default in Java and gets activated as soon as a method is called. 

It then compiles the bytecode of the Java method into native machine code. 

After that, the JVM calls the compiled code directly instead of interpreting it.

5. What are the differences between JVM, JRE, and JDK?

Java Virtual Machine

Java Runtime Environment

Java Development Kit

It provides a runtime environment to execute Java bytecode. 

It is a set of software tools used for developing Java applications. 

It is a software development environment used to develop Java applications. 

It is a runtime instance created when we run a Java class. 

It exists physically.

It exists physically.

Its implementation is known as JRE 

It is the implementation of JVM 

It is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform

Enterprise Edition Java Platform

Micro Edition Java Platform

6. What is the JIT compiler?

JIT compiler runs after the program is executed and compiles the code into a faster form, hosting the CPU's native instructing set. JIT can access dynamic runtime information, whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. 

7. What are Java IDEs?

A Java IDE is a software that allows Java developers to easily write as well as debug Java programs. It is basically a collection of various programming tools, accessible via a single interface, and several helpful features, such as code completion and syntax highlighting. 

Codenvy, Eclipse, and NetBeans are some of the most popular Java IDEs .

8. Java is a platform-independent language. Why?

Java does not depend on any particular hardware or software because it is compiled by the compiler and then converted into byte code. Byte code is platform-independent and can run on multiple systems. The only requirement is that Java needs a runtime environment, i.e., JRE, which is a set of tools used for developing Java applications.

9. Explain Typecasting.

The concept of assigning a variable of one data type to a variable of another data type. This is not possible for the boolean data type. There are two types: implicit and explicit.

10. What are the different types of typecasting?

types of typecasting

The different types of typecasting are:

  • Implicit: Storing values from a smaller data type to the larger data type. It is automatically done by the compiler.
  • Explicit: Storing the value of a larger data type into a smaller data type. This results in information loss:
  • Truncation: While converting a value from a larger data type to a smaller data type, the extra data will be truncated. This code example explains it : 

After execution, the variable i will contain only 3 and not the decimal portion. 

  • Out of Range: Typecasting does not allow assigning value more than its range; if that happens then the data is lost in such cases. This code example explains it: 

long l = 123456789;

byte b = ( byte ) l; // byte is of not the same range as long so there will be loss of data.

11. Explain access modifiers in Java.

Access modifiers are predefined keywords in Java that are used to restrict the access of a class, method, constructor, and data member in another class. Java supports four access modifiers:

Same class

yes

yes

yes

yes

Same package subclass

yes

no

yes

yes

Same package non-subclass

yes

no

yes

yes

Different package subclass

no

no

yes

yes

Different package non-subclass

no

no

no

yes

12. What are the default values for local variables?

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

OOPs Java Interview Questions

13. what is object-oriented programming .

OOPs is a programming paradigm centered around objects rather than functions. It is not a tool or a programming language, it is a paradigm that was designed to overcome the flaws of procedural programming . 

There are many languages that follow OOPs concepts — some popular ones are Java, Python, and Ruby. Some frameworks also follow OOPs concepts, such as Angular.

14. Explain the OOPs concepts.

The following are the various OOPS Concepts:

  • Abstraction: Representing essential features without the need to give out background details. The technique is used for creating a new suitable data type for some specific application.
  • Aggregation: All objects have their separate lifecycle, but ownership is present. No child object can belong to some other object except for the parent object.
  • Association: The relationship between two objects, where each object has its separate lifecycle. There is no ownership.
  • Class: A group of similar entities.
  • Composition: Also called the death relationship, it is a specialized form of aggregation. Child objects don't have a lifecycle. As such, they automatically get deleted if the associated parent object is deleted.
  • Encapsulation: Refers to the wrapping up of data and code into a single entity. This allows the variables of a class to be only accessible by the parent class and no other classes.
  • Inheritance: When an object acquires the properties of some other object, it is called inheritance. It results in the formation of a parent-child relationship amongst classes involved. This offers a robust and natural mechanism of organizing and structuring software.
  • Object: Denotes an instance of a class. Any class can have multiple instances. An object contains the data as well as the method that will operate on the data
  • Polymorphism: Refers to the ability of a method, object, or variable to assume several forms.

Decision Making Java Interview Questions

15. Differentiate between break and continue.

Used with both loop and switch statement.

Used with only loop statements.

It terminates the loop or switch block.

It does not terminate but skips to the next iteration.

Classes, Objects, and Methods Java Interview Questions

16. what is an object.

An instance of a Java class is known as an object. Two important properties of a Java object are behavior and state . An object is created as soon as the JVM comes across the new keyword.

17. Define classes in Java. 

A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

Example of Class:

18. What are static methods and variables?

A class has two sections: one declares variables, and the other declares methods. These are called instance variables and instance methods, respectively. They are termed so because every time a class is instantiated, a new copy of each of them is created. 

Variables and methods can be created that are common to all objects and accessed without using a particular object by declaring them static. Static members are also available to be used by other classes and methods. 

19. What do you mean by Constructor?

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.

If an explicitly-created constructor has a parameter, then it is necessary to create another constructor without a parameter.

20. What are local variables and instance variables?

Variables that are only accessible to the method or code block in which they are declared are known as local variables. 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. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn't the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

21. What is Method Overriding?

Method Overriding

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

22. What is Overloading?

Overloading is the phenomenon when two or more different methods (method overloading) or operators (operator overloading) 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.

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

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.

Arrays, Strings and Vectors Java Interview Questions

24. draw a comparison between array and arraylist..

An array necessitates stating 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.

25. What are the differences between String, Stringbuilder, and Stringbuffer?

String variables are stored in a constant string pool. With the change in the string reference, it becomes impossible to delete the old value. For example, if a string has stored a value "Old," then adding the new value "New" will not delete the old value. It will still be there, however, in a dormant state. In a Stringbuffer, values are stored in a stack. With the change in the string reference, the new value replaces the older value. The Stringbuffer is synchronized (and therefore, thread-safe) and offers slower performance than the StringBuilder, which is also a Stringbuffer but is not synchronized. Hence, performance is faster in Stringbuilder than the Stringbuffer.

26. What is the String Pool?

The string pool is a collection of strings stored in the heap memory refers to. Whenever a new object is created, it is checked if it is already present in the string pool. If it is already present, then the same reference is returned to the variable, otherwise a new object is created in the string pool, and the respective reference is returned.

  • Advanced Java Interview Questions

Interfaces and Abstract Classes Java Interview Questions

27. what do you know about interfaces.

A Java interface is a template that has only method declarations and not method implementations. It is a workaround for achieving multiple inheritances in Java. Some worth remembering important points regarding Java interfaces are:

  • A class that implements the interface must provide an implementation for all methods declared in the interface.
  • All methods in an interface are internally public abstract void.
  • All variables in an interface are internally public static final.
  • Classes do not extend but implement interfaces.

28. How is an Abstract class different from an Interface?

There are several differences between an Abstract class and an Interface in Java, summed up as follows:

  • Constituents: An abstract class contains instance variables, whereas an interface can contain only constants.
  • Constructor and Instantiation: While an interface has neither a constructor nor it can be instantiated, an abstract class can have a default constructor that is called whenever the concrete subclass is instantiated.
  • Implementation of Methods – All classes that implement the interface need to provide an implementation for all the methods contained by it. A class that extends the abstract class, however, doesn't require implementing all the methods contained in it. Only abstract methods need to be implemented in the concrete subclass.
  • Type of Methods: Any abstract class has both abstract as well as non-abstract methods. Interface, on the other hand, has only a single abstract method.

29. Please explain Abstract class and Abstract method.

An abstract class in Java is a class that can't be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. 

To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

30. What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

If a subclass or child class has two parent classes, that means it inherits the properties from two base classes; it has multiple inheritances. Java does not have multiple inheritances as in case the parent classes have the same method names. Then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

Packages Java Interview Questions

31. what are packages in java state some advantages..

packages in Java

Packages are Java's way of grouping a variety of classes and/or interfaces together. The functionality of the objects decides how they are grouped. Packagers act as "containers" for classes.

Enlisted below are the advantages of Packages:

  • Classes of other programs can be reused.
  • Two classes with the same can exist in two different packages.
  • Packages can hide classes, thus denying access to certain programs and classes meant for internal use only.
  • They also separate design from coding.

Multithreading Java Interview Questions

32. how do you make a thread in java give examples..

To make a thread in Java, there are two options:

  • Extend the Thread Class : The thread is available in the java.lang.Thread class. To make a thread, you need to extend a thread class and override the run method. For example,

A disadvantage of using the thread class is that it becomes impossible to extend any other classes.

Nonetheless, it is possible to overload the run() method in the class

  • Implement Runnable Interface: Another way of making a thread in Java is by implementing a runnable interface. For doing so, there is the need to provide the implementation for the run() method that is defined as follows:

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

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

34. Explain the thread lifecycle in Java.

thread lifecycle in Java.

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 waiting or sleeping.
  • 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.

35. When is the Runnable interface preferred over thread class and vice-versa?

In Java, it is possible to extend only one class. Hence, the thread class is only extended when no other class needs to be extended. If it is required for a class to extend some other class than the thread class, then we need to use the Runnable interface.

36. Draw a comparison between notify() and notifyAll() methods.

The notify() method is used for sending a signal to wake up a single thread in the waiting pool. Contrarily, the notifyAll() method is used for sending a signal to wake up all threads in a waiting pool.

37. How will you distinguish processes from threads?

There are several fundamental differences between a process and a thread, stated as follows:

  • Definition: A process is an executing instance of a program whereas, a thread is a subset of a process.
  • Changes: A change made to the parent process doesn't affect child processes. However, a change in the main thread can yield changes in the behavior of other threads of the same process.
  • Communication – While processes require inter-process communication for communicating with sibling processes, threads can directly communicate with other threads belonging to the same process.
  • Control: Processes are controlled by the operating system and can control only child processes. On the contrary, threads are controlled by the programmer and are capable of exercising control over threads of the same process to which they belong.
  • Dependence: Processes are independent entities while threads are dependent entities
  • Memory: Threads run in shared memory spaces, but processes run in separate memory spaces.

38. What is the join() method? Give an example.

We use the join() method for joining one thread with the end of the currently running thread. It is a non-static method and has an overloaded version. Consider the example below:

The main thread starts execution in the example mentioned above. As soon as the execution reaches the code t.start(), then the thread t starts its stack for execution. The JVM switches between the main thread and the thread there. Once the execution reaches the t.join(), then the thread t alone is executed and allowed to complete its task. Afterwards, the main thread resumes execution.

39. How do you make a thread stop in Java?

There are three methods in Java to stop the execution of a thread:

  • Blocking: This method is used to put the thread in a blocked state. The execution resumes as soon as the condition of the blocking is met. For instance, the ServerSocket.accept() is a blocking method that listens for incoming socket connections and resumes the blocked thread only when a connection is made.
  • Sleeping: This method is used for delaying the execution of the thread for some time. A thread upon which the sleep() method is used is said to enter the sleep state. It enters the runnable state as soon as it wakes up i.e., the sleep state is finished. The time for which the thread needs to enter the sleep state is mentioned inside the braces of the sleep() method. It is a static method.
  • Waiting: Although it can be called on any Java object, the wait() method can only be called from a synchronized block.

Exception Handling Java Interview Questions

40. what are the various types of exceptions how do you handle them.

Java has provision for two types of exceptions:

  • Checked Exceptions: Classes that extend the Throwable class, except Runtime exception and Error, are called checked exceptions. Such exceptions are checked by the compiler during the compile time. These types of exceptions must either have appropriate try/catch blocks or be declared using the throws keyword. ClassNotFoundException is a checked exception.
  • Unchecked Exceptions: Such exceptions aren't checked by the compiler during the compile time. As such, the compiler doesn't necessitate handling unchecked exceptions. Arithmetic Exception and ArrayIndexOutOfBounds Exception are unchecked exceptions.

Exceptions in Java are handled in two ways:

Declaring the throws keyword: We can declare the exception using throws keyword at the end of the method. For example:

Using try/catch: Any code segment that is expected to yield an exception is surrounded by the try block. Upon the occurrence of the exception, it is caught by the catch block that follows the try block. For example:

41. Draw the Java Exception Hierarchy.

Java Exception Hierarchy

42. Is it possible to write multiple catch blocks under a single try block?

Yes, it is possible to write several catch blocks under a single try block. However, the approach needs to be from specific to general. The following example demonstrates it:

43. How does the throw keyword differ from the throws keyword?

While the throws keyword allows declaring an exception, the throw keyword is used to explicitly throw an exception. 

Checked exceptions can't be propagated with throw only, but throws allow doing so without the need for anything else. 

The throws keyword is followed by a class, whereas the throw keyword is followed by an instance. The throw keyword is used within the method, but the throws keyword is used with the method signature. 

Furthermore, it is not possible to throw multiple exceptions, but it is possible to declare multiple exceptions.

44. Explain various exceptions handling keywords in Java.

There are two crucial exception handling keywords in Java, followed by the third keyword final, which may or may not be used after handling exceptions.

If and when a code segment has chances of having an abnormality or an error, it is placed within a try block. When the exception is raised, it is handled and caught by the catch block.

The try block must have a catch() or a final() or both blocks after it.

When an exception is raised in the try block, it is handled in the catch block.

This block is executed regardless of the exception. It can be placed either after try{} or catch {} block.

45. Explain exception propagation.

The method at the top of the stack throws an exception if it is not caught. It moves to the next method and goes on until caught.

The stack of the above code is:

If an exception occurred in the add() method is not caught, then it moves to the method addition(). It is then moved to the main() method, where the flow of execution stops. It is called Exception Propagation.

File Handling Java Interview Questions

46. is an empty file name with .java extension a valid file name.

Yes, Java permits us to save our java file by .java only. It is compiled by javac and run by the java class name. Here’s an example:

To compile: javac.java

To run: Java Any

Collections Java Interview Questions

47. what are collections what are their constituents.

A group of objects in Java is known as collections. Java.util package contains, along with date and time facilities, internationalization, legacy collection classes, etc., the various classes and interfaces for collecting. Alternatively, collections can be considered as a framework designed for storing the objects and manipulating the design in which the objects are stored. You can use collections to perform the following operations on objects:

  • Manipulation

Following are the various constituents of the collections framework:

  • Classes: Array List, Linked List, Lists, and Vector
  • Interfaces: Collection, List, Map, Queue, Set, Sorted Map, and Sorted Set
  • Maps: HashMap, HashTable, LinkedHashMap, and TreeMap
  • Queues: Priority Queue
  • Sets: Hash Set, Linked Hash Set, and Tree Set

48. How do you differentiate HashMap and HashTable?

HashMap in Java is a map-based collection class, used for storing key & value pairs. It is denoted as HashMap<Key, Value> or HashMap<K, V> HashTable is an array of a list, where each list is called a bucket. 

Values contained in a HashTable are unique and depend on the key. Methods are not synchronized in HashMap, while key methods are synchronized in HashTable. 

However, HashMap doesn't have thread safety, while HashTable has the same. 

For iterating values, HashMap uses an iterator and HashTable uses an enumerator. HashTable doesn't allow anything that is null, while HashMap allows one null key and several null values. 

In terms of performance, HashTable is slow. Comparatively, HashMap is faster.

49. What is a Map and what are the types?

A Java Map is an object that maps keys to values. It can't contain duplicate keys, and each key can map to only one value. In order to determine whether two keys are the same or distinct, Map makes use of the equals() method. There are 4 types of Map in Java, described as follows:

  • HashMap: It is an unordered and unsorted map and hence, is a good choice when there is no emphasis on the order. A HashMap allows one null key and multiple null values and doesn't maintain any insertion order.
  • HashTable: Doesn't allow anything null and has methods that are synchronized. As it allows for thread safety, the performance is slow.
  • LinkedHashMap: Slower than a HashMap but maintains insertion order and has a faster iteration.
  • TreeMap: A sorted Map providing support for constructing a sort order using a constructor.

50. What is a Priority Queue?

A priority queue, like a regular queue, is an abstract data type, but it has a priority associated with each element contained by it. 

The element with the high priority is served before the element with low priority in a priority queue. Elements in a priority queue are ordered either according to the comparator or naturally. The order of the elements in a priority queue represents their relative priority.

51. What is a Set? Explain the types in Java Collections.

In Java, a set is a collection of unique objects. It uses the equals() method to determine whether two objects are the same or not. The various types of set in Java Collections are:

  • Hash Set: An unordered and unsorted set that uses the hash code of the object for adding values. Used when the order of the collection isn't important
  • Linked Hash Set: This is an ordered version of the hash set that maintains a doubly-linked list of all the elements. Used when iteration order is mandatory. Insertion order is the same as that of how elements are added to the Set.
  • Tree Set: One of the two sorted collections in Java, it uses Read-Black tree structure and ensures that the elements are present in the ascending order.

52. What is ordered and sorted when it comes to collections?

  • Ordered: Values are stored in a collection in a specific order, but the order is independent of the value. Example: List
  • Sorted: The collection has an order which is dependent on the value of an element. Example: SortedSet

Miscellaneous Java Interview Questions 

53. what are the various types of garbage collectors in java.

The Java programming language has four types of garbage collectors:

  • Serial Garbage Collector: Using only a single thread for garbage collection, the serial garbage collector works by holding all the application threads. It is designed especially for single-threaded environments. Because serial garbage collector freezes all application threads while performing garbage collection, it is most suitable for command-line programs only. For using the serial garbage collector, one needs to turn on the -XX:+UseSerialGC JVM argument.
  • Parallel Garbage Collector: Also known as the throughput collector, the parallel garbage collector is the default garbage collector of the JVM. It uses multiple threads for garbage collection, and like a serial garbage collector freezes all application threads during garbage collection.
  • CMS Garbage Collector: Short for Concurrent Mark Sweep, CMS garbage collector uses multiple threads for scanning the heap memory for marking instances for eviction, followed by sweeping the marked instances. There are only two scenarios when the CMS garbage collector holds all the application threads:
  • When marking the referenced objects in the tenured generation space.
  • If there is a change in the heap memory while performing the garbage collection, CMS garbage collector ensures better application throughput over parallel garbage collectors by using more CPU resources. For using the CMS garbage collector, the XX:+USeParNewGC JVM argument needs to be turned on.
  • G1 Garbage Collector: Used for large heap memory areas, G1 garbage collector works by separating the heap memory into multiple regions and then executing garbage collection in them in parallel. Unlike the CMS garbage collector that compacts the memory on STW (Stop The World) situations , G1 garbage collector compacts the free heap space right after reclaiming the memory. Also, the G1 garbage collector prioritizes the region with the most garbage. Turning on the –XX:+UseG1GC JVM argument is required for using the G1 garbage collector.

54. What do you understand by synchronization? What is its most significant disadvantage?

If several threads try to access a single block of code, then there is an increased chance of producing inaccurate results. Synchronization is used to prevent this. Using the synchronization keyword makes a thread need a key to access the synchronized code. Simply, synchronization allows only one thread to access a block of code at a time. Each Java object has a lock, and every lock has only one key. A thread can access a synchronized method only if it can get the key to the lock of the object. The following example demonstrates synchronization:

Note : It is recommended to avoid implementing synchronization for all methods. This is because when only one thread can access the synchronized code, the next thread needs to wait. Consequently, it results in slower performance of the program.

55. What is the difference between execute(), executeQuery(), and executeUpdate()?

  • execute(): Used for executing an SQL query. It returns TRUE if the result is a ResultSet, like running Select queries, and FALSE if the result is not a ResultSet, such as running an Insert or an Update query.
  • executeQuery(): Used for executing Select queries. It returns the ResultSet, which is not null, even if no records are matching the query. The executeQuery() method must be used when executing select queries so that it throws the java.sql.SQLException with the 'executeQuery method cannot be used for update' message when someone tries to execute an Insert or Update statement.
  • executeUpdate(): Used for executing Delete/Insert/Update statements or DDL statements that return nothing. The output varies depending on whether the statements are Data Manipulation Language (DML) statements or Data Definition Language (DDL) statements. The output is an integer and equals the total row count for the former case, and 0 for the latter case.

Note : The execute() method needs to be used only in a scenario when there is no certainty about the type of statement. In all other cases, either use executeQuery() or executeUpdate() method.

56. Provide an example of the Hibernate architecture.

Hibernate architecture

57. Could you demonstrate how to delete a cookie in JSP with a code example?

The following code demonstrates deleting a cookie in JSP:

58. Write suitable code examples to demonstrate the use of final, final, and finalize.

Final:  The final keyword is used for restricting a class, method, and variable. A final class can't be inherited, a final method is disabled from overriding, and a final variable becomes a constant i.e., its value can't be changed.

Finally: Any code inside the final block will be executed, irrespective of whether an exception is handled or not.

Finalize: The finalize method performs the clean up just before the object is garbage collected.

59. What purpose does the Volatile variable serve?

The value stored in a volatile variable is not read from the thread's cache memory but from the main memory. Volatile variables are primarily used during synchronization.

60. Please compare serialization and deserialization.

Serialization is the process by which Java objects are converted into the byte stream. 

Deserialization is the exact opposite process of serialization where Java objects are retrieved from the byte stream.

 A Java object is serialized by writing it to an ObjectOutputStream and deserialized by reading it from an ObjectInputStream.

61. What is OutOfMemoryError?

Typically, the OutOfMemoryError exception is thrown when the JVM is not able to allocate an object due to running out of memory. In such a situation, no memory could be reclaimed by the garbage collector. 

There can be several reasons that result in the OutOfMemoryError exception, of which the most notable ones are:

  • Holding objects for too long
  • Trying to process too much data at the same time
  • Using a third-party library that caches strings
  • Using an application server that doesn't perform a memory cleanup post the deployment
  • When a native allocation can't be satisfied

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

The execution Java program starts with public static void main(String args[ ]), also called the main() method.

  • public: It is an access modifier defining the accessibility of the class or method. Any class can access the main() method defined public in the program.
  • static: The keyword indicates the variable, or the method is a class method. The method main() is made static so that it can be accessed without creating the instance of the class. When the method main() is not made static, the compiler throws an error because the 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 that does not return any type of value.
  • main: JVM searches this method when starting the execution of any program, with the particular signature only.
  • String args[]: The parameter passed to the main method.

Java Programming Masterclass Updated to Java 17

63. What are wrapper classes in Java?

Wrapper classes are responsible for converting the Java primitives into the reference types (objects). A class is dedicated to every primitive data type. They are known as wrapper classes because they wrap the primitive data type into an object of that class. It is present in the Java.lang package. The table below displays the different primitive types and wrapper classes.

boolean

Boolean

char

Character

double

Double

float

Float

int

Integer

long

Long

64. Explain the concept of boxing, unboxing, autoboxing, and auto unboxing.

  • Boxing: The concept of putting a primitive value inside an object is called boxing.
  • Unboxing: Getting the primitive value from the object.
  • Autoboxing: Assigning a value directly to an integer object.
  • Auto unboxing: Getting the primitive value directly into the integer object.

65. Define the Singleton class. How can a class be made Singleton?

A Singleton class allows only one instance of the class to be created. A class can be made singleton with the following steps:

  • Creating a static instance of the class with the class.
  • By not allowing the user to create an instance with default constructor by defining a private constructor.
  • Create a static method to return the object of an instance of A.

66. What if the public static void is replaced by static public void, will the program still run?

Yes, the program would compile and run without any errors as the order of the specifiers doesn't matter.

67. What is the difference between == and equals()?

It is a method of String class

It is an operator

Content comparison

Address comparison

68. Why don't we use pointers in Java?

Pointers are considered to be unsafe, and increase the complexity of the program, adding the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.

69. What is the difference between this() and super()?

Represents the current instance of the class

Represents the current instance of the parent/base class

It is used to call the default constructor of the same class

It is used to call the default constructor of the parent/base class.

Accesses method of the current class

Accesses method of the base class

Points current class instance

Points to the superclass instance.

Must be the first line of the block

It must be the first line of the block.

Java Coding Interview Questions 

Apart from having good knowledge about concepts of Java programming, you are also tested for your skills in coding in Java programming language. The following are Java coding interview questions that are relevant for freshers and are quite popular amongst Java programming interviews.

70. Take a look at the two code snippets below. What is the important difference between the two?

Code snippet i. is an example of method overloading while the code snippet ii. demonstrates method overriding.

71. Write a program for string reversal without using an inbuilt function.

72. write a program to delete duplicates from an array., 73. write a program to reverse a number., 74. write a program that implements binary search., 75. write a program to check if a number is prime., 76. write a program to print fibonacci series., 77. write a program to check if the given string is a palindrome., 78. write a program to print the following pattern., 79. write a program to swap two numbers., 80. write a program to check if the given number is an armstrong number..

These core Java Interview Questions and Java Programming Interview Questions are a great way to prepare you for the interview. Review the answers, including the coding examples, and put your best foot forward.

Please note that we also provided a PDF for your preparation so that you can download and learn and prepare on the go: 

Download Java Interview Questions PDF

Prefer on-demand videos? Check out this course for further reading and preparation for a Java-based interview: Java Interview Guides: 200+ Interview Question and Answer

Otherwise, we recommend this book to help you succeed in your future Java interviews: Elements of Programming Interviews in Java: The insider guide second edition

  • Frequently Asked Questions

1. What are the basic Java questions asked in an interview?

There are several basic Java interview questions that can appear in an interview. Look at the ones we’ve listed above to get a sense of them.

2. How should I prepare for a Java interview?

You should prepare for a Java interview by learning both the theory and practicing coding. There are several related questions above.

3. What are the advanced Java interview questions?

Advanced Java interview questions can be of many kinds, including both theory and coding-based questions. Check out the list of Java programming questions above to see what they are like.

People are also reading:

  • Best Java Courses
  • Top 10 Java Certifications
  • Best Java Books
  • Best Java Projects
  • Programming Interview Questions
  • Core Java Cheatsheet - Introduction to Programming in Java
  • Difference between Java vs Javascript
  • Top 10 Java Frameworks
  • Best Way to Learn Java
  • Constructor in Java 
  • Prime Number Program in Java

java problem solving questions and answers

Simran works at Hackr as a technical writer. The graduate in MS Computer Science from the well known CS hub, aka Silicon Valley, is also an editor of the website. She enjoys writing about any tech topic, including programming, algorithms, cloud, data science, and AI. Traveling, sketching, and gardening are the hobbies that interest her.

Subscribe to our Newsletter for Articles, News, & Jobs.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

  • Top 48 Networking Interview Questions and Answers in 2024 Computer Networks Career Development Interview Questions
  • Top 20 REST API Interview Questions & Answers [2024] Web Development Career Development Interview Questions
  • How to Extract a Java Substring [with Code Examples] Java

Please login to leave comments

Always be in the loop.

Get news once a week, and don't worry — no spam.

{{ errors }}

{{ message }}

  • Help center
  • We ❤️ Feedback
  • Advertise / Partner
  • Write for us
  • Privacy Policy
  • Cookie Policy
  • Change Privacy Settings
  • Disclosure Policy
  • Terms and Conditions
  • Refund Policy

Disclosure: This page may contain affliate links, meaning when you click the links and make a purchase, we receive a commission.

Devglan Logo

  • Java Interview Programming Questions and Answers

java-programs thumbnail

Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995.

During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving capabilities. To test these, all the interviewers start interview from core programming problems and most of these programming problems are from core java concepts. Here, in this article, I have tried to put some initial level of Java programming questions to get through an interview process. These programs are helpful to both freshers and experienced Java professionals.

Keep an eye on this page as I will be regularly adding and updating more and more interview questions.

Write a Java program to find the largest sum of the contiguous subarray in a given Array

Write a Java program to find the largest sum of the contiguous subarray in a given Array. The given array might contain negative elements too and hence we need to find out a contiguous sub-array whose sum would be maximum....

Write a Java program to rotate a matrix

Given a 2D matrix of N X N. Write a Java program to rotate the matrix in a clockwise direction by 90 degrees. The 0th row of the given matrix will be transformed to the nth column, the 1st row will be transformed to the n-1 column, and so on. Below is its representation....

Writing a Java program to rotate an array by d elements.

For any given array of length n, rotating it by elements d means moving its first d elements either at the end of the array or moving the last d elements to the beginning of the array....

Java Program to Find Union and Intersection of Arrays in Java

Writing a Java program to find first non-repeated character in a String is a common programming interview question to test the usage of Set interface provided in Java collection framework....

Java Program to Find First non Repeated Character in a String

Writing a Java program to find first non-repeated character in a String is a common programming interview question. For example, the first non-repeated character in the String 'devglan for developers' is 'g'....

Write a Java Program to Find missing Number in an Array

Write a java program to find a missing number in an Array of length N-1 containing elements from 1 to N. The trick to find the missing number is using the mathematical formula of Sum of Series....

Write a Java Program to Compare Files in Java

When you are learning Java, network programming can be a great source of practicing Java. In this program, we will see how we can compare two different files in Java. Comparing files in java also can help you to differentiate between the local and the remote files. You can quickly identify the duplicate lines, which allows you to remove the file entirely. First, we will be comparing the files using BufferedReader but this way of comparing files is not memory efficient and requires more execution time. Hence, we will be using a highly advanced technique called memory mapping using RandomAccessFile from java.io package....

Write a Java Program to Print 1 To 10 Without Using Loop

Write a java program to print 1 to 10 without using any loop.This can be achieved by using recursion in Java.Following is the sample code....

Write a Java Program to Reverse an Array in Place Without Using Any Second Array

Write a java program to reverse an array in place without using any second array.Here, we can loop till the middle index of the array and swap the first element with last element, swap the second element with second last element until we reach the middle of the array....

Write a Java Program to Find the Longest Palindrome Present in a Given String

A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as madam. Write a java program to find the longest palindrome present in a given string. For example, in the string abcba , the longest palindrome is abcba and similarly in abcmadamcbamadam , the longest palindrome is abcmadamcba ....

Write a Java Program to Find the Second Largest Number in an Array

Write a java program to find the second largest number in an array.There are multiple ways to achieve this. We can sort any given array in a descending order and pick the second index element.The main concept here is to sort the given array.This can be achieved via Arrays.sort() or Collection.sort() and once the given array is sorted the second largest number can be easily found....

Write a Java Program to Remove Common Characters From Given Strings

In many java interviews, it is asked this question to compare two strings and remove the common character from the given strings to check the programming aptitude.For example, suppose there are two string, s1 = "abcfgh" and s2 = "aasdf" and after removal of common character the value of s1 and s2 becomes bcgh and sd respectivly. Following is the java program to remove the common characters from any given strings....

Java Program To Check If A Given Number is A Perfect Number

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.Write a java program to check if a given number is a perfect number or not....

Check Given String is Rotation of Another String

Given two string s1 and s2 then write a java program to check if s1 is the rotation of another string s2.Here rotation means, each character of s2 must be the same character of s1 but only thing is that the character in s2 can be present at any random position. Following is the java program to check if a given string is a rotation of another string....

Java Program to Find LCM of a Two Given Number

Write a Java program to find LCM of a given two numbers.LCM stands for Lowest Common Multiple. LCM of a two given number a and b is the smallest positive integer that is divisible by both a and b.For example the LCM of 4 and 6 is 12. Following is the java program to find LCM using while and for loop....

Write a Java Program to Test Given Words are Anagram or Not

Two words are said to be anagrams, if both the words contain same set of characters with all original letters exactly once. For example, the word program can be re-arranged as grampor and these both words form an anagram. Following is a java program to check if a string is anagram or not. There are two ways for this test - One is using equals() method provided in Arrays class and another by comparing each character of he words....

Write a Java Program to Add Two 2D Matrix

A matrix is a rectangular array of numbers or expressions arranged in rows and columns.Below is the java program to add two 2D matrices.We can change the dimension variables accordingly for 3D and 4D matrix....

Write a Java Program to Perform Binary Search in a Sorted Array

Binary search is one of the famous and fundamental algorithm in computer science which solves a large number of problems in developing applications and APIs. It uses divide and conquer approach to find out the element.Here, we will be writing a sample program in java that implements binary search.The given array is a sorted array of n elements and we have to search the position a given element inside the array....

Write a Java Program to find Factorial of a Given Number

Write a program to find factorial of a given number is a common java program asked in any interview to freshers.The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example factorial of 4 is 4*3*2 = 24.There are 2 ways to find a factorial of a given number - One by using for loop and the other using recursion.Following java program uses for loop to find factorial of a given number....

Java Program to Reverse a Given String without using Predefined Functions

Write a java program to reverse a given string using recursion without using any predefined function.This program checks the understanding of recursion in programming language and also checks the programming sense.Here, the method reverseString() is called recursively to revrse a given string.Following is the complete program....

Java program to Find Permutations of a Given String

Write a java program to find all the permutations of any given string.Permutation is the each of several possible ways in which a set or number of things can be ordered or arranged.Order matters in case of Permutation.For example, the permutation of ab will be ab and ba.Following is the java program to find permutation of a given string....

Java program to reverse a given number

Write a java program to reverse a given number by using only numeric operators.Suppose, if you are given an input of 4567 then the output should be 7654.In the program below, we have only used the modulus or remainder and / operator.Following is the complete program....

Java program to find sum of prime numbers which are less than a given number

Write a java program to find the sum of all the prime numbers less than a given natural number N. The main purpose of this interview question is to check the programming sense and capabilities to check how good you are to convert existing logic into code. The question is mostly asked to freshers.The only main logic in this program is to find the prime numbers.Prime number is a number that is greater than 1 and divided by 1 or itself.For reminder, 2 is also a prime number....

Java program to find max repeated words from a file

In java interview, this program can be asked in a multiple ways such as write program to find max repeated words or duplicate words or the count of each duplicate words.Whatever the question, the main programming concept is the same to count the occurrence of each word in a .txt file. To solve this programmatically, we can use Map implementation in Java that does not allow any duplicate key and at the end of iteration we can find out the count.Following is the complete program.Here, we are using java 8 Lambda operator during sorting....

Java Program to find max two numbers in an array

In many java interviews especially for freshers, it is asked to write program to find max two numbers from a given array.This kind of program is good to check the programming sense as this program does not use any inbuilt java sorting functions or predefined data structures or collections.It simply uses java iterations and programming sense to swap in between the numbers and find the solution.Following is the implementation....

Java Program to Find line with max character length in Descending Order

This java interview program is about finding lines with max character from a file in descending order.In this case, we will be using buffered reader to read a file and use java provided data structure TreeSet to hold the line and it's character length as it automatically maintains ascending order.Following is the program to find two lines with max characters in descending order....

Java Program to Find middle index of array where both ends sum is equal

In the java interview, you will be asked to find the middle index or position of a given array where sum of numbers preceding the index is equals to sum of numbers succeeding the index.There are two ways to solve this problem.One is to use 2 for loops - one starting from the last index to the middle index and another starting from start index to middle index. Another way to solve it by using while loop - the while loop should stop when the start index crosses the end index. Following is the program to achieve this using while loop....

Java Program to Find Duplicate Character from a String and Count of repetition

While dealing with string, many of the time it is required to find or remove duplicate character from a string.Following is the java program to find duplicate or repeated characters from a given string.The program also results the count of the duplicate characters....

Java Program to Find Distinct Word List From a File

Java program to find distinct words from file is a very common question in java interview.In the following program, we will be using BufferedReader to read a file and then retain distinct words from it. To achieve this, we will be using Set to store all the words from a file and since, set dos not allow duplicates, we can easily find the distinct words.Following is the complete java program for this....

Java Program to test if a given number is Fibonacci or not

Fibonacci numbers are the numbers in which each number is the sum of the two preceding numbers.For example 1, 1, 2, 3, 5, 8, 13, 21, 34, ...The first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence.In most of the java interview, itapos;s a common programming question to check a given number is fibonacci number or not....

Java Program to test if a given number is Armstrong Number or not

Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits.For example 371 is an Armstrong number as 3^3+7^3+1^3 = 371. It is also sometimes called as narcissistic number or pluperfect digital invariant (PPDI). Following is the java program to test if a given number is an armstrong number or not....

Guru99

100+ Java Interview Questions and Answers (2024)

James Hartman

Java Programming Interview Questions and Answers for freshers

1) what is the difference between an inner class and a sub-class.

An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

👉 Free PDF Download: Java Interview Interview Questions & Answers >>

2) What are the various access specifiers for Java classes?

In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:

1) Public: Class,Method,Field is accessible from anywhere.

2) Protected: Method,Field can be accessed from the same class to which they belong or from the sub-classes, and from the class of same package, but not from outside.

3) Default: Method,Field,class can be accessed only from the same package and not from outside of it’s native package.

3) What’s the purpose of Static methods and static variables?

When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.

4) What is data encapsulation and what’s its significance?

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 data hiding purpose.

5) What is a singleton class? Give a practical example of its usage.

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 the situations when there is a need to limit the number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.

6) What are Loops in Java? What are three types of loops?

Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java :

1) For Loops

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

2) While Loops

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

3) Do While Loops

7) What is an infinite Loop? How infinite loop is declared?

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

Infinite loop is declared as follows:

8) What is the difference between continue and break statement?

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

In below example, Loop is broken when counter reaches 4.

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

9) What is the difference between double and float variables in Java?

In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is single precision floating point decimal number while Double is double precision decimal number.

10) What is Final Keyword in Java? Give an example.

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

In below example, a constant with the name const_val is declared and assigned avalue:

Private Final int const_val=100

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

When a class is declares as final, it cannot be subclassed. Example String, Integer and other wrapper classes.

11) What is ternary operator? Give an example.

Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?

In the below example, if rank is 1, status is assigned a value of “Done” else “Pending”.

12) How can you generate random numbers in Java?

  • 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

13) What is default switch case? Give example.

In a switch statement , default case is executed when no other switch condition matches. Default case is an optional case .It can be declared only once all other switch cases have been coded.

In the below example, when score is not 1 or 2, default case is used.

14) What’s the base class in Java from which all classes are derived?

java.lang.object

15) Can main() method in Java can return any data?

In java, main() method can’t return any data and hence, it’s always declared with a void return type.

16) What are Java Packages? What’s the significance of packages?

In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper re-use. Once code has been packaged in Packages, it can be imported in other classes and used.

17) Can we declare a class as Abstract without having any abstract method?

Yes we can create an abstract class by using abstract keyword before class name even if it doesn’t have any abstract method. However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.

18) What’s the difference between an Abstract Class and Interface in Java?

The primary difference between an abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its super class.

19) What are the performance implications of Interfaces over abstract classes?

Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. Another key factor for developers to take into consideration is that any class can extend only one abstract class while a class can implement many interfaces.

Use of interfaces also puts an extra burden on the developers as any time an interface is implemented in a class; developer is forced to implement each and every method of interface.

20) Does Importing a package imports its sub-packages as well in Java?

In java, when a package is imported, its sub-packages aren’t imported and developer needs to import them separately if required.

For example, if a developer imports a package university.*, all classes in the package named university are loaded but no classes from the sub-package are loaded. To load the classes from its sub-package (say department), developer has to import it explicitly as follows:

Import university.department.*

21) Can we declare the main method of our class as private?

In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won’t get any compilation error however, it will not get executed and will give a runtime error.

22) How can we pass argument to a function by reference instead of pass by value?

In java, we can pass argument to a function only by value and not by reference.

23) How an object is serialized in java?

In java, to convert an object into byte stream by serialization, an interface with the name Serializable is implemented by the class. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream.

24) When we should use serialization?

Serialization is used when data needs to be transmitted over the network. Using serialization, object’s state is saved and converted into byte stream .The byte stream is transferred over the network and the object is re-created at destination.

25) Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception handling?

Try block needs to be followed by either Catch block or Finally block or both. Any exception thrown from try block needs to be either caught in the catch block or else any specific tasks to be performed before code abortion are put in the Finally block.

Java Interview Questions and Answers for Experienced

26) is there any way to skip finally block of exception even if some exception occurs in the exception block.

If an exception is raised in Try block, control passes to catch block if it exists otherwise to finally block. Finally block is always executed when an exception occurs and the only way to avoid execution of any statements in Finally block is by aborting the code forcibly by writing following line of code at the end of try block:

27) When the constructor of a class is invoked?

The constructor of a class is invoked every time an object is created with new keyword.

For example, in the following class two objects are created using new keyword and hence, constructor is invoked two times.

28) Can a class have multiple constructors?

29) can we override static methods of a class.

We cannot override static methods. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime).Even if we try to override static method, we will not get an complitaion error,nor the impact of overriding when running the code.

30) In the below example, what will be the output?

Ans : Output will be:

Displaying from subClass

Printing from superclass

31) Is String a data type in java?

String is not a primitive data type in java. When a string is created in java, it’s actually an object of Java.Lang.String class that gets created. After creation of this string object, all built-in methods of String class can be used on the string object.

32) In the below example, how many String Objects are created?

In the above example, two objects of Java.Lang.String class are created. s1 and s3 are references to same object.

33) Why Strings in Java are called as Immutable?

In java, string objects are called immutable as once value has been assigned to a string, it can’t be changed and if changed, a new object is created.

In below example, reference str refers to a string object having value “Value one”.

When a new value is assigned to it, a new String object gets created and the reference is moved to the new object.

34) What’s the difference between an array and Vector?

An array groups data of same primitive type and is static in nature while vectors are dynamic in nature and can hold data of different data types.

35) What is multi-threading?

Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It helps in performance improvement of any program.

36) Why Runnable Interface is used in Java?

Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.

37) What are the two ways of implementing multi-threading in Java?

Multi threaded applications can be developed in Java by using any of the following two methodologies:

1) By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented.

2) By writing a class that extend Java.Lang.Thread class.

38) When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer?

Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it’s always a good choice to use StringBuffer when data is being changed too much. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.

39) What’s the purpose of using Break in each case of Switch Statement?

Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.

If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.

40) How garbage collection is done in Java?

In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() method or Runtime.gc() method.

41) How we can execute any code even before main method?

If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

42) Can a class be a super class and a sub-class at the same time? Give example.

If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.

In the example below, continent class is sub-class of world class and it’s super class of country class.

43) How objects of a class are created if no constructor is defined in the class?

Even if no explicit constructor is defined in a java class, objects get created successfully as a default constructor is implicitly used for object creation. This constructor has no parameters.

44) In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. Using synchronized keyword , we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it has become free from the other one using it.

45) Can we call the constructor of a class more than once for an object?

Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.

46) There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB?

Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.

47) Can we have two methods in a class with the same name?

We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.

For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:

48) How can we make copy of a java object?

We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

49) What’s the benefit of using inheritance?

Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.

50) What’s the default access specifier for variables and methods of a class?

Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package, not outside the package.

51) Give an example of use of Pointers in Java class.

There are no pointers in Java. So we can’t use concept of pointers in Java.

52) How can we restrict inheritance for a class so that no class can be inherited from it?

If we want a class not to be extended further by any class, we can use the keyword Final with the class name.

In the following example, Stone class is Final and can’t be extend

53) What’s the access scope of Protected Access specifier?

When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class, any other class of the same package as well as a sub-class.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

54) What’s difference between Stack and Queue?

Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.

55) In java, how we can disallow serialization of variables?

If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:

56) How can we use primitive data types as objects?

Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.

57) Which types of exceptions are caught at compile time?

Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.

58) Describe different states of a thread.

A thread in Java can be in either of the following states:

  • Ready: When a thread is created, it’s in Ready state.
  • Running: A thread currently being executed is in running state.
  • Waiting: A thread waiting for another thread to free certain resources is in waiting state.
  • Dead: A thread which has gone dead after execution is in dead state.

59) Can we use a default constructor of a class even if an explicit constructor is defined?

Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.

60) Can we override a method by using same method name and arguments but different return types?

The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden. Hence using a different return type doesn’t override a method.

61) What will be the output of following piece of code?

In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.

61) A person says that he compiled a java class successfully without even having a main method in it? Is it possible?

main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.

62) Can we call a non-static method from inside a static method?

Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked.

63) What are the two environment variables that must be set in order to run any Java programs?

Java programs can be executed in a machine only once following two environment variables have been properly set:

  • PATH variable
  • CLASSPATH variable

64) Can variables be used in Java without initialization?

In Java, if a variable is used in a code without prior initialization by a valid value, program doesn’t compile and gives an error as no default value is assigned to variables in Java.

65) Can a class in Java be inherited from more than one class?

In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritances is not supported by Java.

66) Can a constructor have different name than a Class name in Java?

Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method.

67) What will be the output of Round(3.7) and Ceil(3.7)?

Round(3.7) returns 4 and Ceil(3.7) returns 4.

68) Can we use goto in Java to go to a particular line?

In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.

69) Can a dead thread be started again?

In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.

70) Is the following class declaration correct?

Ans: The above class declaration is incorrect as an abstract class can’t be declared as Final.

71) Is JDK required on each machine to run a Java program?

JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.

72) What’s the difference between comparison done by equals method and == operator?

In Java, equals() method is used to compare the contents of two string objects and returns true if the two have same value while == operator compares the references of two string objects.

In the following example, equals() returns true as the two string objects have same values. However == operator returns false as both string objects are referencing to different objects:

73) Is it possible to define a method in Java class but provide it’s implementation in the code of another language like C?

Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.

74) How are destructors defined in Java?

In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.

Java Interview Questions and Answers for 5+ Years Experience

75) can a variable be local and static at the same time.

No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error.

76) Can we have static methods in an Interface?

Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.

77) In a class implementing an interface, can we change the value of any variable defined in the interface?

No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later.

78) Is it correct to say that due to garbage collection feature in Java, a java program never goes out of memory?

Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources.

So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that.

79) Can we have any other return type than void for main method?

No, Java class main method can have only void return type for the program to get successfully executed.

Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status)

80) I want to re-reach and use an object once it has been garbage collected. How it’s possible?

Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.

81) In Java thread programming, which method is a must implementation for all threads?

Run() is a method of Runnable interface that must be implemented by all threads.

82) I want to control database connections in my program and want that only one thread should be able to make database connection at a time. How can I implement this logic?

Ans: This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time.

83) How can an exception be thrown manually by a programmer?

In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.

84) I want my class to be developed in such a way that no other class (even derived class) can create its objects. How can I do so?

If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.

85) How objects are stored in Java?

In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.

86) How can we find the actual size of an object on the heap?

In java, there is no way to find out the exact size of an object on the heap.

87) Which of the following classes will have more memory allocated?

Class A: Three methods, four variables, no object

Class B: Five methods, three variables, no object

Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.

88) What happens if an exception is not handled in a program?

If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing.

89) I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?

If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this() .

90) What’s meant by anonymous class?

An anonymous class is a class defined without any name in a single line of code using new keyword.

For example, in below code we have defined an anonymous class in one line of code:

91) Is there a way to increase the size of an array after its declaration?

Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size (no of items), we should prefer vector over array.

92) If an application has multiple classes in it, is it okay to have a main method in more than one class?

If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only.

93) I want to persist data of objects for later use. What’s the best approach to do so?

The best way to persist data for future use is to use the concept of serialization.

94) What is a Local class in Java?

In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined.

95) String and StringBuffer both represent String objects. Can we compare String and StringBuffer in Java?

Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error.

96) Which API is provided by Java for operations on set of objects?

Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

97) Can we cast any other type to Boolean Type with type casting?

No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.

98) Can we use different return types for methods when overridden?

The basic requirement of method overriding in Java is that the overridden method should have same name, and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.

For example , method is returning a reference type.

99) What’s the base class of all exception classes?

In Java, Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.

100) What’s the order of call of constructors in inheritance?

In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.

Prep Up For your Job Interview!!! Go through Java Tutorial to be better prepared.

This detailed Java Mock Test Quiz will help you to clear the doubts about Java interview questions and will also help you to crack the interview.

These Java and Java 8 interview questions will also help in your viva(orals)

  • Java Program to Check Prime Number
  • How to Reverse a String in Java using Recursion
  • Palindrome Number Program in Java Using while & for Loop
  • Bubble Sort Algorithm in Java: Array Sorting Program & Example
  • Insertion Sort Algorithm in Java with Program Example
  • Selection Sorting in Java Program with Example
  • Abstract Class vs Interface in Java – Difference Between Them
  • JAVA Tutorial PDF: Basics for Beginners (Download Now)

Javatpoint Logo

All Interview

Company interview, technical interview, web interview, php interview, .net interview, java interview, database interview.



There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers.

The answers to the Core Java interview questions are short and to the point. The core Java interview questions are categorized in Basics of Java interview questions, OOPs interview questions, String Handling interview questions, Multithreading interview questions, collection interview questions, JDBC interview questions, etc.

is the high-level, , robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by in June 1991. It can also be known as the platform as it provides its own JRE and API.

The differences between and Java are given in the following table.

Comparison Index C++Java
C++ is platform-dependent.Java is platform-independent.
C++ is mainly used for system programming.Java is mainly used for application programming. It is widely used in window, web-based, enterprise and mobile applications.
C++ was designed for systems and applications programming. It was an extension of .Java was designed and created as an interpreter for printing systems but later extended as a support network computing. It was designed with a goal of being easy to use and accessible to a broader audience.
C++ supports the statement.Java doesn't support the goto statement.
C++ supports multiple inheritance.Java doesn't support multiple inheritance through class. It can be achieved by .
C++ supports .Java doesn't support operator overloading.
C++ supports . You can write pointer program in C++.Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in Java.
C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent. Java uses compiler and interpreter both. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform independent.
C++ supports both call by value and call by reference.Java supports call by value only. There is no call by reference in java.
C++ supports structures and unions.Java doesn't support structures and unions.
C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support.Java has built-in support.
C++ doesn't support documentation comment.Java supports documentation comment (/** ... */) to create documentation for java source code.
C++ supports virtual keyword so that we can decide whether or not override a function.Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default.
C++ doesn't support >>> operator.Java supports unsigned right shift >>> operator that fills zero at the top for the negative numbers. For positive numbers, it works same like >> operator.
C++ creates a new inheritance tree always.Java uses a single inheritance tree always because all classes are the child of Object class in java. The object class is the root of the tree in java.
C++ is nearer to hardware.Java is not so interactive with hardware.
C++ is an object-oriented language. However, in C language, single root hierarchy is not possible.Java is also an language. However, everything (except fundamental types) is an object in Java. It is a single root hierarchy as everything gets derived from java.lang.Object.

3) List the features of Java Programming language.

There are the following features in Java Programming Language.

  • Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
  • Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
  • Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
  • Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
  • Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
  • Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
  • Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
  • Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
  • High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
  • Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
  • Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
  • Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.

4) What do you understand by Java virtual machine?

Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.

5) What is the difference between JDK, JRE, and JVM?

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

  • Standard Edition Java Platform
  • Enterprise Edition Java Platform
  • Micro Edition Java Platform

6) How many types of memory areas are allocated by JVM?

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

7) What is JIT compiler?

Just-In-Time(JIT) compiler: It is used to improve the 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. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

8) What is the platform?

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 the software-based platform.

9) What are the main differences between the Java platform and other platforms?

There are the following differences between the Java platform and other platforms.

  • Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
  • Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.

10) What gives Java its 'write once and run anywhere' nature?

The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.

11) What is classloader?

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 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 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 "-cp" or "-classpath" switch. It is also known as Application classloader.

12) Is Empty .java file name a valid source file name?

Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:

compile it by javac .java

run it by java A

13) Is delete, next, main, exit or null keyword in java?

14) 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.

It is empty, but not null.

15) What if I write static public void instead of public static void?

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

16) What is the default value of the local variables?

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

17) What are the various access specifiers in Java?

In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a 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 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.

18) What is the purpose of static methods and variables?

The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static .

19) What are the advantages of Packages in Java?

There are various advantages of defining packages in Java.

  • Packages avoid the name clashes.
  • The Package provides easier access control.
  • We can also have the hidden classes that are not visible outside and used by the package.
  • It is easier to locate the related classes.

20) What is the output of the following Java program?

The output of the above code will be

Explanation

In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint . Therefore, the output will be 30Javatpoint .

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020 .

21) What is the output of the following Java program?

In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint .

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpoint to produce the output as Javatpoint200 .

22) What is the output of the following Java program?

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.

Core Java - OOPs Concepts: Initial OOPs Interview Questions

There is given more than 50 OOPs (Object-Oriented Programming and System) interview questions. However, they have been categorized in many sections such as constructor interview questions, static interview questions, Inheritance Interview questions, Abstraction interview question, Polymorphism interview questions, etc. for better understanding.

23) What is object-oriented paradigm?

It is a programming paradigm based on objects having data and methods defined in the class to which it belongs. Object-oriented paradigm aims to incorporate the advantages of modularity and reusability. Objects are the instances of classes which interacts with one another to design applications and programs. There are the following features of the object-oriented paradigm.

  • Follows the bottom-up approach in program design.
  • Focus on data with methods to operate upon the object's data
  • Includes the concept like Encapsulation and abstraction which hides the complexities from the user and show only functionality.
  • Implements the real-time approach like inheritance, abstraction, etc.
  • The examples of the object-oriented paradigm are C++, Simula, Smalltalk, Python, C#, etc.

24) What is an object?

The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

25) What is the difference between an object-oriented programming language and object-based programming language?

There are the following basic differences between the object-oriented language and object-based language.

  • Object-oriented languages follow all the concepts of OOPs whereas, the object-based language doesn't follow all the concepts of OOPs like inheritance and polymorphism.
  • Object-oriented languages do not have the inbuilt objects whereas Object-based languages have the inbuilt objects, for example, JavaScript has window object.
  • Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the examples of object-based languages are JavaScript, VBScript, etc.

26) What will be the initial value of an object reference which is defined as an instance variable?

All object references are initialized to null in Java.

Core Java - OOPs Concepts: Constructor Interview Questions

27) what is the constructor.

The constructor can be defined as the special type of method that is used to initialize the state of an object. It is invoked when the class is instantiated, and the memory is allocated for the object. Every time, an object is created using the new keyword, the default constructor of the class is called. The name of the constructor must be similar to the class name. The constructor must not have an explicit return type.

28) How many types of constructors are used in Java?

Based on the parameters passed in the constructors, there are two types of constructors in Java.

  • Default Constructor: default constructor is the one which does not accept any value. The default constructor is mainly used to initialize the instance variable with the default values. It can also be used for performing some useful task on object creation. A default constructor is invoked implicitly by the compiler if there is no constructor defined in the class.
  • Parameterized Constructor: The parameterized constructor is the one which can initialize the instance variables with the given values. In other words, we can say that the constructors which can accept the arguments are called parameterized constructors.

Java Constructors

29) What is the purpose of a default constructor?

The purpose of the default constructor is to assign the default value to the objects. The java compiler creates a default constructor implicitly if there is no constructor in the class.

Explanation: In the above class, you are not creating any constructor, so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.

Java default constructor

30) Does constructor return any value?

Ans: yes, The constructor implicitly returns the current instance of the class (You can't use an explicit return type with the constructor). More Details.

31)Is constructor inherited?

No, The constructor is not inherited.

32) Can you make a constructor final?

No, the constructor can't be final.

33) Can we overload the constructors?

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

34) What do you understand by copy constructor in Java?

There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

  • By constructor
  • By assigning the values of one object into another
  • By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

35) What are the differences between the constructors and methods?

There are many differences between constructors and methods. They are given below.

Java ConstructorJava Method
A constructor is used to initialize the state of an object.A method is used to expose the behavior of an object.
A constructor must not have a return type.A method must have a return type.
The constructor is invoked implicitly.The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class.The method is not provided by the compiler in any case.
The constructor name must be same as the class name. The method name may or may not be same as class name.

Java Constructors vs Methods

36) What is the output of the following Java program?

The output of the following program is:

Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first parameterized constructor with the two integer parameters is called.

37) What is the output of the following Java program?

The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no constructor in the class.

38) What is the output of the following Java program?

There is a compiler error in the program because there is a call to the default constructor in the main method which is not present in the class. However, there is only one parameterized constructor in the class Test. Therefore, no default constructor is invoked by the constructor implicitly.

Core Java - OOPs Concepts: static keyword Interview Questions

39) what is the static variable.

The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.

Static Variable

40) What is the static method?

  • A static method belongs to the class rather than the object.
  • There is no need to create the object to call the static methods.
  • A static method can access and change the value of the static variable.

41) What are the restrictions that are applied to the Java static methods?

Two main restrictions are applied to the static methods.

  • The static method can not use non-static data member or call the non-static method directly.
  • this and super cannot be used in static context as they are non-static.

42) Why is the main method static?

Because the object is not required to call the static method. If we make the main method non-static, JVM will have to create its object first and then call main() method which will lead to the extra memory allocation. More Details.

43) Can we override the static methods?

44) what is the static block.

Static block is used to initialize the static data member. It is executed before the main method, at the time of classloading.

45) Can we execute a program without main() method?

Ans) No, It was possible before JDK 1.7 using the static block. Since JDK 1.7, it is not possible. More Details.

46) What if the static modifier is removed from the signature of the main method?

Program compiles. However, at runtime, It throws an error "NoSuchMethodError."

47) What is the difference between static (class) method and instance method?

static or class methodinstance method
1)A method that is declared as static is known as the static method. A method that is not declared as static is known as the instance method.
2)We don't need to create the objects to call the static methods.The object is required to call the instance methods.
3)Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly.Static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;}For example: public void msg(){...}.

48) Can we make constructors static?

As we know that the static context (method, block, or variable) belongs to the class, not the object. Since Constructors are invoked only when the object is created, there is no sense to make the constructors static. However, if you try to do so, the compiler will show the compiler error.

49) Can we make the abstract methods static in Java?

In Java, if we make the abstract methods static, It will become the part of the class, and we can directly call it which is unnecessary. Calling an undefined method is completely useless therefore it is not allowed.

50) Can we declare the static variables and methods in an abstract class?

Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to make the object to access the static context, therefore, we can access the static context declared inside the abstract class by using the name of the abstract class. Consider the following example.

Core Java - OOPs Concepts: Inheritance Interview Questions

51) what is this keyword in java.

The this keyword is a reference variable that refers to the current object. There are the various uses of this keyword in Java. It can be used to refer to current class properties such as instance methods, variable, constructors, etc. It can also be passed as an argument into the methods or constructors. It can also be returned from the method as the current class instance.

java this keyword

52) What are the main uses of this keyword?

There are the following uses of this keyword.

  • this can be used to refer to the current class instance variable.
  • this can be used to invoke current class method (implicitly)
  • this() can be used to invoke the current class constructor.
  • this can be passed as an argument in the method call.
  • this can be passed as an argument in the constructor call.
  • this can be used to return the current class instance from the method.

53) Can we assign the reference to this variable?

No, this cannot be assigned to any value because it always points to the current class object and this is the final reference in Java. However, if we try to do so, the compiler error will be shown. Consider the following example.

54) Can this keyword be used to refer static members?

Yes, It is possible to use this keyword to refer static members because this is just a reference variable which refers to the current class object. However, as we know that, it is unnecessary to access static variables through objects, therefore, it is not the best practice to use this to refer static members. Consider the following example.

55) How can constructor chaining be done using this keyword?

Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.

56) What are the advantages of passing this into a method instead of the current class object itself?

As we know, that this refers to the current class object, therefore, it must be similar to the current class object. However, there can be two main advantages of passing this into a method instead of the current class object.

  • this is a final variable. Therefore, this cannot be assigned to any new value whereas the current class object might not be final and can be changed.
  • this can be used in the synchronized block.

57) What is the Inheritance?

Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

There are five types of inheritance in Java.

  • Single-level inheritance
  • Multi-level inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

Multiple inheritance is not supported in Java through class.

58) Why is Inheritance used in Java?

There are various advantages of using inheritance in Java that is given below.

  • Inheritance provides code reusability. The derived class does not need to redefine the method of base class unless it needs to provide the specific implementation of the method.
  • Runtime polymorphism cannot be achieved without using inheritance.
  • We can simulate the inheritance of classes with the real-time objects which makes OOPs more realistic.
  • Inheritance provides data hiding. The base class can hide some data from the derived class by making it private.
  • Method overriding cannot be achieved without inheritance. By method overriding, we can give a specific implementation of some basic method contained by the base class.

59) Which class is the superclass for all the classes?

The object class is the superclass of all other classes in Java.

60) Why is multiple inheritance not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class.

Since the compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have the same method or different, there will be a compile time error.

61) What is aggregation?

Aggregation can be defined as the relationship between two classes where the aggregate class contains a reference to the class it owns. Aggregation is best described as a has-a relationship. For example, The aggregate class Employee having various fields such as age, name, and salary also contains an object of Address class having various fields such as Address-Line 1, City, State, and pin-code. In other words, we can say that Employee (class) has an object of Address class. Consider the following example.

Address.java

Employee.java

62) What is composition?

Holding the reference of a class within some other class is known as composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. In other words, we can say that composition is the particular case of aggregation which represents a stronger relationship between two objects. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

63) What is the difference between aggregation and composition?

Aggregation represents the weak relationship whereas composition represents the strong relationship. For example, the bike has an indicator (aggregation), but the bike has an engine (composition).

64) Why does Java not support pointers?

The pointer is a variable that refers to the memory address. They are not used in Java because they are unsafe(unsecured) and complex to understand.

65) What is super in java?

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Whenever you create the instance of the subclass, an instance of the parent class is created implicitly which is referred by super reference variable. The super() is called in the class constructor implicitly by the compiler if there is no super or this.

66) How can constructor chaining be done by using the super keyword?

67) what are the main uses of the super keyword.

There are the following uses of super keyword.

  • super can be used to refer to the immediate parent class instance variable.
  • super can be used to invoke the immediate parent class method.
  • super() can be used to invoke immediate parent class constructor.

68) What are the differences between this and super keyword?

There are the following differences between this and super keyword.

  • The super keyword always points to the parent class contexts whereas this keyword always points to the current class context.
  • The super keyword is primarily used for initializing the base class variables within the derived class constructor whereas this keyword primarily used to differentiate between local and instance variables when passed in the class constructor.
  • The super and this must be the first statement inside constructor otherwise the compiler will throw an error.

69) What is the output of the following Java program?

The super() is implicitly invoked by the compiler if no super() or this() is included explicitly within the derived class constructor. Therefore, in this case, The Person class constructor is called first and then the Employee class constructor is called.

70) Can you use this() and super() both in a constructor?

No, because this() and super() must be the first statement in the class constructor.

71)What is object cloning?

The object cloning is used to create the exact copy of an object. The clone() method of the Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

Core Java - OOPs Concepts: Method Overloading Interview Questions

72) what is method overloading.

Method overloading is the polymorphism technique which allows us to create multiple methods with the same name but different signature. We can achieve method overloading in two ways.

  • By Changing the number of arguments
  • By Changing the data type of arguments

Method overloading increases the readability of the program. Method overloading is performed to figure out the program quickly.

73) Why is method overloading not possible by changing the return type in java?

In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.

74) Can we overload the methods by making them static?

No, We cannot overload the methods by just applying the static keyword to them(number of parameters and types are the same). Consider the following example.

75) Can we overload the main() method?

Yes, we can have any number of main methods in a Java program by using method overloading.

76) What is method overloading with type promotion?

By Type promotion is method overloading, we mean that one data type can be promoted to another implicitly if no exact matching is found.

Java Method Overloading with Type Promotion

As displayed in the above diagram, the byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int, long, float or double and so on. Consider the following example.

77) What is the output of the following Java program?

There are two methods defined with the same name, i.e., sum. The first method accepts the integer and long type whereas the second method accepts long and the integer type. The parameter passed that are a = 20, b = 20. We can not tell that which method will be called as there is no clear differentiation mentioned between integer literal and long literal. This is the case of ambiguity. Therefore, the compiler will throw an error.

Core Java - OOPs Concepts: Method Overriding Interview Questions

78) what is method overriding:.

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to implement the interface methods.

Rules for Method overriding

  • The method must have the same name as in the parent class.
  • The method must have the same signature as in the parent class.
  • Two classes must have an IS-A relationship between them.

79) Can we override the static method?

No, you can't override the static method because they are the part of the class, not the object.

80) Why can we not override static method?

It is because the static method is the part of the class, and it is bound with class whereas instance method is bound with the object, and static gets memory in class area, and instance gets memory in a heap.

81) Can we override the overloaded method?

82) difference between method overloading and overriding..

Method OverloadingMethod Overriding
1) Method overloading increases the readability of the program.Method overriding provides the specific implementation of the method that is already provided by its superclass.
2) Method overloading occurs within the class.Method overriding occurs in two classes that have IS-A relationship between them.
3) In this case, the parameters must be different.In this case, the parameters must be the same.

83) Can we override the private methods?

No, we cannot override the private methods because the scope of private methods is limited to the class and we cannot access them outside of the class.

84) Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of the method.

  • The private can be changed to protected, public, or default.
  • The protected can be changed to public or default.
  • The default can be changed to public.
  • The public will always remain public.

85) Can we modify the throws clause of the superclass method while overriding it in the subclass?

Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there are some rules which are to be followed while overriding in case of exception handling.

  • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception, but it can declare the unchecked exception.
  • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

86) What is the output of the following Java program?

87) can you have virtual functions in java.

Yes, all functions in Java are virtual by default.

88) What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type. The covariant return type specifies that the return type may vary in the same direction as the subclass.

89) What is the output of the following Java program?

The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class, the reference variable b (of type Base class) refers to the instance of the Derived class. Here, Runtime polymorphism is achieved between class Base and Derived. At compile time, the presence of method baseMethod checked in Base class, If it presence then the program compiled otherwise the compiler error will be shown. In this case, baseMethod is present in Base class; therefore, it is compiled successfully. However, at runtime, It checks whether the baseMethod has been overridden by Derived class, if so then the Derived class method is called otherwise Base class method is called. In this case, the Derived class overrides the baseMethod; therefore, the Derived class method is called.

Core Java - OOPs Concepts: final keyword Interview Questions

90) what is the final variable.

In Java, the final variable is used to restrict the user from updating it. If we initialize the final variable, we can't change its value. In other words, we can say that the final variable once assigned to a value, can never be changed after that. The final variable which is not assigned to any value can only be assigned through the class constructor.

final keyword in java

91) What is the final method?

If we change any method to a final method, we can't override it. More Details.

92) What is the final class?

If we make any class final, we can't inherit it into any of the subclasses.

93) What is the final blank variable?

A final variable, not initialized at the time of declaration, is known as the final blank variable. We can't initialize the final blank variable directly. Instead, we have to initialize it by using the class constructor. It is useful in the case when the user has some data which must not be changed by others, for example, PAN Number. Consider the following example:

94) Can we initialize the final blank variable?

Yes, if it is not static, we can initialize it in the constructor. If it is static blank final variable, it can be initialized only in the static block. More Details.

95) Can you declare the main method as final?

Yes, We can declare the main method as public static final void main(String[] args){}.

96) What is the output of the following Java program?

Since i is the blank final variable. It can be initialized only once. We have initialized it to 20. Therefore, 20 will be printed.

97) What is the output of the following Java program?

The getDetails() method is final; therefore it can not be overridden in the subclass.

98) Can we declare a constructor as final?

The constructor can never be declared as final because it is never inherited. Constructors are not ordinary methods; therefore, there is no sense to declare constructors as final. However, if you try to do so, The compiler will throw an error.

99) Can we declare an interface as final?

No, we cannot declare an interface as final because the interface must be implemented by some class to provide its definition. Therefore, there is no sense to make an interface final. However, if you try to do so, the compiler will show an error.

100) What is the difference between the final method and abstract method?

The main difference between the final method and abstract method is that the abstract method cannot be final as we need to override them in the subclass to give its definition.

You may also like:

  • Java Interview Questions
  • SQL Interview Questions
  • Python Interview Questions
  • JavaScript Interview Questions
  • Angular Interview Questions
  • Selenium Interview Questions
  • Spring Boot Interview Questions
  • HR Interview Questions
  • C Programming Interview Questions
  • C++ Interview Questions
  • Data Structure Interview Questions
  • DBMS Interview Questions
  • HTML Interview Questions
  • IAS Interview Questions
  • Manual Testing Interview Questions
  • OOPs Interview Questions
  • .Net Interview Questions
  • C# Interview Questions
  • ReactJS Interview Questions
  • Networking Interview Questions
  • PHP Interview Questions
  • CSS Interview Questions
  • Node.js Interview Questions
  • Spring Interview Questions
  • Hibernate Interview Questions
  • AWS Interview Questions
  • Accounting Interview Questions

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence Tutorial

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking Tutorial

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering Tutorial

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • ▼Java Exercises
  • ▼Java Basics
  • Basic Part-I
  • Basic Part-II
  • ▼Java Data Types
  • Java Enum Types
  • ▼Java Control Flow
  • Conditional Statement
  • Recursive Methods
  • ▼Java Math and Numbers
  • ▼Object Oriented Programming
  • Java Constructor
  • Java Static Members
  • Java Nested Classes
  • Java Inheritance
  • Java Abstract Classes
  • Java Interface
  • Java Encapsulation
  • Java Polymorphism
  • Object-Oriented Programming
  • ▼Exception Handling
  • Exception Handling Home
  • ▼Functional Programming
  • Java Lambda expression
  • ▼Multithreading
  • Java Thread
  • Java Multithreading
  • ▼Data Structures
  • ▼Strings and I/O
  • File Input-Output
  • ▼Date and Time
  • ▼Advanced Concepts
  • Java Generic Method
  • ▼Algorithms
  • ▼Regular Expressions
  • Regular Expression Home
  • ▼JavaFx Exercises
  • JavaFx Exercises Home
  • ..More to come..

Java Conditional Statement : Exercises, Practice, Solution

Java conditional statement exercises [32 exercises with solution].

[ An editor is available at the bottom of the page to write and execute the scripts.   Go to the editor ]

1. Write a Java program to get a number from the user and print whether it is positive or negative.

Test Data Input number: 35 Expected Output : Number is positive Click me to see the solution

2. Write a Java program to solve quadratic equations (use if, else if and else).

Test Data Input a: 1 Input b: 5 Input c: 1 Expected Output : The roots are -0.20871215252208009 and -4.7912878474779195 Click me to see the solution

3. Write a Java program that takes three numbers from the user and prints the greatest number.

Test Data Input the 1st number: 25 Input the 2nd number: 78 Input the 3rd number: 87 Expected Output : The greatest: 87 Click me to see the solution

4. Write a Java program that reads a floating-point number and prints "zero" if the number is zero. Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000.

Test Data Input a number: 25 Expected Output : Input value: 25 Positive number

Click me to see the solution

5. Write a Java program that takes a number from the user and generates an integer between 1 and 7. It displays the weekday name.

Test Data Input number: 3 Expected Output : Wednesday

6. Write a Java program that reads two floating-point numbers and tests whether they are the same up to three decimal places.

Test Data Input floating-point number: 25.586 Input floating-point another number: 25.589 Expected Output : They are different

7. Write a Java program to find the number of days in a month.

Test Data Input a month number: 2 Input a year: 2016 Expected Output : February 2016 has 29 days

8. Write a Java program that requires the user to enter a single character from the alphabet. Print Vowel or Consonant, depending on user input. If the user input is not a letter (between a and z or A and Z), or is a string of length > 1, print an error message.

Test Data Input an alphabet: p Expected Output : Input letter is Consonant

9. Write a Java program that takes a year from the user and prints whether it is a leap year or not.

Test Data Input the year: 2016 Expected Output : 2016 is a leap year

10. Write a Java program to display the first 10 natural numbers.

Expected Output :

11. Write a Java program to display n terms of natural numbers and their sum.

Test Data Input the number: 2 Expected Output :

Click me to see the solution.

12. Write a program in Java to input 5 numbers from the keyboard and find their sum and average.

Test Data Input the 5 numbers : 1 2 3 4 5 Expected Output :

13. Write a Java program to display the cube of the given number up to an integer.

Test Data Input number of terms : 4 Expected Output :

14. Write a Java program to display the multiplication table of a given integer.

Test Data Input the number (Table to be calculated) : Input number of terms : 5 Expected Output :

15. Write a Java program that displays the sum of n odd natural numbers.

Test Data Input number of terms is: 5 Expected Output :

16. Write a Java program to display the pattern like a right angle triangle with a number.

Test Data Input number of rows : 10 Expected Output :

17. Write a program in Java to make such a pattern like a right angle triangle with a number which repeats a number in a row.

The pattern is as follows :

18. Write a Java program to make such a pattern like a right angle triangle with the number increased by 1.

The pattern like :

19. Write a Java program to make such a pattern like a pyramid with a number that repeats in the same row.

20. Write a Java program to print Floyd's Triangle.

Test Data Input number of rows : 5 Expected Output :

21. Write a Java program to display the pattern like a diamond.

Test Data Input number of rows (half of the diamond) : 7 Expected Output :

22. Write a Java program to display Pascal's triangle.

Test Data Input number of rows: 5 Expected Output :

23. Write a Java program to generate the following * triangles.

Test Data Input the number: 6 Expected Output :

24. Write a Java program to generate the following @'s triangle.

25. Write a Java program to display the number rhombus structure.

Test Data Input the number: 7 Expected Output :

26. Write a Java program to display the following character rhombus structure.

27. Write a Java program that reads an integer and check whether it is negative, zero, or positive.

Test Data Input a number: 7 Expected Output :

28. Write a Java program that reads a floating-point number. If the number is zero it prints "zero", otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1, or "large" if it exceeds 1,000,000.

Test Data Input a number: -2534 Expected Output :

29. Write a Java program that reads an positive integer and count the number of digits the number (less than ten billion) has.

Test Data Input an integer number less than ten billion: 125463 Expected Output :

30. Write a Java program that accepts three numbers and prints "All numbers are equal" if all three numbers are equal, "All numbers are different" if all three numbers are different and "Neither all are equal or different" otherwise.

Test Data Input first number: 2564 Input second number: 3526 Input third number: 2456 Expected Output :

31. Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise.

Test Data Input first number: 1524 Input second number: 2345 Input third number: 3321 Expected Output :

32. Write a Java program that accepts two floating­point numbers and checks whether they are the same up to two decimal places.

Test Data Input first floating­point number: 1235 Input second floating­point number: 2534 Expected Output :

Java Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics

Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.

  • online courses
  • certification
  • free resources

Thursday, January 12, 2023

Top 53 java programs for coding and programming interviews, 50+ java coding problems from programming job interviews.

Top 50 Java Programs from Coding and Programming Interviews

  • 10 Courses to Prepare for Programming Interviews
  • 10 Books to Prepare Technical Programming/Coding Job Interviews
  • 20+ String Algorithms Interview Questions
  • 25 Software Design Interview Questions for Programmers
  • 20+ array-based Problems for interviews
  • 40 Binary Tree Interview Questions for Java Programmers
  • 10 Dynamic Programming Questions from Coding Interviews
  • 25 Recursion Programs from Coding Interviews
  • Review these Java Interview Questions for Programmers
  • 7 Best Courses to learn Data Structure and Algorithms
  • 10 OOP Design Interview Questions with solution
  • Top 30 Object-Oriented Programming Questions
  • Top 5 Courses to learn Dynamic Programming for Interviews
  • 10 Algorithm Books Every Programmer Should Read
  • Top 5 Data Structure and Algorithm Books for Java Developers
  • 100+ Data Structure and Algorithm Questions with Solution
  • 75+ Coding Interview Questions for 2 to 5 years experience
  • 10 Programming and Coding Job interview courses for programmers

good questions, thanks

Feel free to comment, ask questions if you have any doubt.

IMAGES

  1. Java Solved Programs, Problems with Solutions

    java problem solving questions and answers

  2. Coursera: Java Programming Solving Problems With Software Answers

    java problem solving questions and answers

  3. Solved Java 101: Problem Solving Practic X ACFrOgCQSxmU3ORN1

    java problem solving questions and answers

  4. Solved Problem 1 Develop a program in Java to demonstrate

    java problem solving questions and answers

  5. problem solving in java

    java problem solving questions and answers

  6. Java: An Introduction to Problem Solving and Programming

    java problem solving questions and answers

COMMENTS

  1. Java programming Exercises, Practice, Solution

    The best way we learn anything is by practice and exercise questions. Here you have the opportunity to practice the Java programming language concepts by solving the exercises starting from basic to more complex exercises. It is recommended to do these exercises by yourself first before checking the solution.

  2. Java Exercises

    OOPs Interview Questions and Answers; Java Exercises; ... We hope these exercises have helped you understand Java better and you can solve beginner to advanced-level questions on Java programming. Solving these Java programming ... It is a general perception that the approach using loops is treated as naive approach to solve a problem statement

  3. 200+ Core Java Interview Questions and Answers (2024)

    Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and performance. In this article, we will provide 200+ Core Java Interview Questions tailored for both freshers and experienced professionals with 3, 5, and 8 years of experience.

  4. Top 50 Java Programs from Coding Interviews

    Here is a big list of Java programs for Job Interviews. As I said, it includes questions from problem-solving, linked list, array, string, matrix, bitwise operators and other miscellaneous parts of programming. Once you are gone through these questions, you can handle a good number of questions on real Job interviews. 1. Fibonacci series

  5. Top 50 Java Programming Interview Questions

    Consider that, for a given number N, if there is a prime number M between 2 to √N (square root of N) that evenly divides it, then N is not a prime number. 5. Write a Java program to print a Fibonacci sequence using recursion. A Fibonacci sequence is one in which each number is the sum of the two previous numbers.

  6. Solve Java

    Join over 23 million developers in solving code challenges on HackerRank, one of the best ways to prepare for programming interviews.

  7. Java Coding Practice

    Explore the Java coding exercises for practicing with commands below. First, read the conditions, scroll down to the Solution box, and type your solution. Then, click Verify (above the Conditions box) to check the correctness of your program. Exercise 1 Exercise 2 Exercise 3. Start task.

  8. Practice Java

    Complete your Java coding practice with our online Java practice course on CodeChef. Solve over 180 coding problems and challenges to get better at Java. ... Multiple Choice Question: Easy: CodeChef Learn Problem Solving: 287: Multiple Choice Question: Easy: Learning SQL: 339: Multiple Choice Question: Easy: Parking Charges: 416: 6. Conditional ...

  9. The Java Interview Prep Handbook

    Java is well-known for its robustness in Object-Oriented Programming (OOP), and it provides a comprehensive foundation essential for developers at every level. This handbook offers a detailed pathway to help you excel in Java interviews. It focuses on delivering insights and techniques relevant to roles in esteemed big tech companies, ensuring ...

  10. Java Exercises

    We have gathered a variety of Java exercises (with answers) for each Java Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  11. Java Programming Exercises with Solutions

    Highlights. Binary Tree problems are common at Google, Amazon and Facebook coding interviews.; Sharpen your lambda and streams skills with Java 8 coding practice problems.; Check our Berlin Clock solution, a commonly used code exercise.; We have videos too! Check out the FizzBuzz solution, a problem widely used on phone screenings.

  12. Top 80 Java Interview Questions and Answers [2024]

    Two important properties of a Java object are behavior and state. An object is created as soon as the JVM comes across the new keyword. 17. Define classes in Java. A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language.

  13. 800+ Java Practice Challenges // Edabit

    How Edabit Works. This is an introduction to how challenges on Edabit work. In the Code tab above you'll see a starter function that looks like this: public static boolean returnTrue () { } All you have to do is type return true; between the curly braces { } and then click the Check button. If you did this correctly, the button will turn re ...

  14. Java Object Oriented Programming

    Write a Java program to create a class called "Book" with attributes for title, author, and ISBN, and methods to add and remove books from a collection. Click me to see the solution. 6. Write a Java program to create a class called "Employee" with a name, job title, and salary attributes, and methods to calculate and update salary.

  15. Java Interview Programming Questions and Answers

    Java Interview Programming Questions and Answers. Java is an object-oriented programming language and computing platform first released by Sun Microsystems in 1995. During an interview it does not matter whatever framework you know, the initial stage of the interview is always based on the programming sense, coding skills, and problem-solving ...

  16. Java Basic Programming Exercises

    Write a Java program to test if an array of integers contains an element 10 next to 10 or an element 20 next to 20, but not both. Click me to see the solution. 94. Write a Java program to rearrange all the elements of a given array of integers so that all the odd numbers come before all the even numbers. Click me to see the solution. 95.

  17. 100+ Java Interview Questions and Answers (2024)

    Basic Core Java Interview Questions: Q1. What is the difference between an Inner Class and a Sub-Class? Ans: An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

  18. 300 Core Java Interview Questions (2024)

    There is the list of 300 core Java interview questions. If there is any core Java interview question that has been asked to you, kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview questions and answers. The answers to the Core Java interview questions are short and to the point.

  19. 51 Java Programming Interview Questions (And Sample Answers)

    Here's a list of additional java interview questions that hiring managers may ask you: 41. Write a program to sort a sequence of numbers in ascending order. 42. Using Java 8 date-time library in CLASSPATH (package private) file, write a program that shows how you can add time to any time with respect to midnight on Jan. 1, 2000.

  20. Java Exercises: Conditional Statement exercises

    Java Conditional Statement Exercises [32 exercises with solution] [ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor] 1. Write a Java program to get a number from the user and print whether it is positive or negative. Test Data Input number: 35 Expected Output : Number is positive Click me to ...

  21. Top 53 Java Programs for Coding and Programming Interviews

    1. For a given array of integers (positive and negative) find the largest sum of a contiguous sequence. 2. Algorithm: Implement a queue using 2 stacks (solution) 3. Algorithm: Integer division without the division operator (/) (solution) 4. How to print All permutations of a Given String in Java ( solution) 5.

  22. Problems

    Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

  23. Coding Games and Programming Challenges to Code Better

    The #1 tech hiring platform. SCREENINGINTERVIEWING. CodinGame is a challenge-based training platform for programmers where you can play with the hottest programming topics. Solve games, code AI bots, learn from your peers, have fun.