Java Interview Questions
Java Interview Questions
Concept.
C++ is not platform-independent; the principle behind C++ programming is “write once, compile anywhere.”
In contrast, because the byte code generated by the Java compiler is platform-independent, it can run on any
machine, Java programs are written once and run everywhere.
Languages Compatibility.
C++ is a programming language that is based on the C programming language. Most other high-level
languages are compatible with C++.
Most of the languages of Java are incompatible. Java is comparable to those of C and C++.
It can access the native system libraries directly in C++. As a result, it’s better for programming at the system
level.
Java’s native libraries do not provide direct call support. You can use Java Native Interface or access the
libraries.
Characteristics.
C++ distinguishes itself by having features that are similar to procedural and object-oriented languages. The
characteristic that sets Java apart is automatic garbage collection. Java doesn’t support destructors at the
moment.
Primitive and object types in C++ have the same kind of semantics. The primitive and object classes of Java,
on the other hand, are not consistent.
Java refers to a compiled and interpreted language. In contrast, C++ is only a compiled language.
In Java, the source code is the compiled output is a platform-independent byte code.
In C++, the source program is compiled into an object code that is further executed to produce an output.
Secured Feature: Java has a secured feature that helps develop a virus-free and tamper-free system for the
users.
OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in Java, everything is
considered an object.
Independent Platform: Java is not compiled into a platform-specific machine; instead, it is compiled into
platform-independent bytecode. This code is interpreted by the Virtual Machine on which the platform runs.
Q 3. What do you get in the Java download file? How do they differ from one
another?
We get two major things along with the Java Download file.
JDK JRE
Class Memory
Heap Memory
Stack Memory
Program Counter-Memory
Q 6. What are the differences between Heap and Stack Memory in Java?
Stack memory is the amount of memory allocated to each individual programme. It is a fixed memory space.
Heap memory, in contrast, is the portion that was not assigned to the Java code but will be available for use by
the Java code when it is required, which is generally during the program's runtime.
public class MySingletonClass {
private static MySingletonClass instance = null;
public String str;
private MySingletonClass () { }
public static MySingletonClass getInstance() {
if (instance == null){
instance = new SingletonClass();
}
return instance;
}
}
A local variable can be anywhere inside a method or a specific block of code. Also, the scope is limited to the
code segment where the variable is declared.
With this we are done with the first section that is Basic Java Interview Question, Now, lets move on to our next
section of Intermediate Java Interview Questions.
JRE has class libraries and other JVM supporting files. But it doesn’t have any tool for java development such
as compiler or debugger.
JDK has tools that are required to write Java Programs and uses JRE to execute them. It has a compiler, Java
application launcher, and an applet viewer.
Q 29. What are Brief Access Specifiers and Types of Access Specifiers?
Access Specifiers are predefined keywords used to help JVM understand the scope of a variable, method, and
class. We have four access specifiers.
Public Access Specifier
Parameterized Constructors: Parameterized constructor accepts the parameters with which users can initialize
the instance variables. Users can initialize the class variables dynamically at the time of instantiating the class.
Default constructors: This type doesn’t accept any parameters; rather, it instantiates the class variables with
their default values. It is used mainly for object creation.
Q 38. Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists as the user needs to make a minor update to the pointer value so that
the node can point to the next successor in the list
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
>> operator does the job of right shifting the sign bits
1. Initialization
2. Start
3. Stop
4. Destroy
5. Paint
Q 47. Can you run a code before executing the main method?
Yes, we can execute any code, even before the main method. We will be using a static block of code when
creating the objects at the class's load time. Any statements within this static block of code will get executed at
once while loading the class, even before creating objects in the main method.
Static Data
JSP elements
JDBC is an abstraction layer used to establish connectivity between an existing database and a Java
application
start with "< %@" and then end with "% >"
The various types of directives are shown below:
Include directive
It includes a file and combines the content of the whole file with the currently active pages.
Page directive
Page Directive defines specific attributes in the JSP page, like the buffer and error page.
Taglib
Taglib declares a custom tag library, which is used on the page.
When an Observable object gets upgraded, it calls the update() method of each of its observers.
After that, it notifies all the observers that there is a change of state.
Q 54. What is Session Management in Java?
A session is essentially defined as the random conversation's dynamic state between the client and the server.
The virtual communication channel includes a string of responses and requests from both sides. The popular
way of implementing session management is establishing a session ID in the client's communicative discourse
and the server.
Exception handler method: In this kind of exception handling, the user will get the @ExceptionHandler
annotation type used to annotate a method to handle exceptions.
XML Configuration: The user can use the SimpleMappingExceptionResolver bean in Spring’s application file
and map the exception.
Developers use Java Cryptography Architecture to combine the application with the security applications. Java
Cryptography Architecture helps in implementing third party security rules and regulations.
Java Cryptography Architecture uses the hash table, encryption message digest, etc. to implement the security.
2. Query Language
Usernames and passwords are given by the client to authenticate the user.
Form-based authentication:
Digest Authentication:
It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula
makes digest more secure.
It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client
Authentication requires the SSL protocol.
Q 60. Explain FailFast iterator and FailSafe iterator along with examples for
each.
FailFast iterators and FailSafe iterators are used in Java Collections.
FailFast iterators do not allow changes or modifications to the Java Collections, which means they fail when the
latest element is added to the collection or an existing element gets removed from the collection. The FailFast
iterators tend to fail and throw an exception called ConcurrentModificationException.
Whereas, on the other hand, FailSafe iterators allow changes or modifications to be done on the Java
Collections. It is possible, as the FailSafe iterators usually operate on the cloned copy of the collection. Hence,
they do not throw any specific exception.
Ex: CopyOnWriteArrayList
package simplilearnJava;
public class StringReverse {
public static void main(String args[]) {
String str = "Simplilearn";
String reverse = new StringBuffer(str).reverse().toString();
System.out.printf("Actual Word: %s, Word after reversing %s", str, reverse);
}
public static String reverse(String source) {
if (source == null || source.isEmpty()) {
return source;
}
String reverse = "";
for (int i = source.length() - 1; i >= 0; i--) {
reverse = reverse + source.charAt(i);
}
return reverse;
}
}
Expected Output:
Actual Word: GOD, Word after reversing DOG
package simplilearnJava;
import java.util.Scanner;
public class SRoot {
public static void main(String args[]) {
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Input a number to find square root: ");
double square = sc.nextDouble();
double squareRoot = Math.sqrt(square);
System.out.printf("The square root is: %f ", squareRoot);
}
}
}
Expected Output:
Input a number to find square root:
25
import java.util.HashMap;
public class P2 {
public static void main(String[] args) {
String str = "Hello World, Welcome to Simplilearn";
String[] split = str.split(" ");
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < split.length; i++) {
if (map.containsKey(split[i])) {
int count = map.get(split[i]);
map.put(split[i], count + 1);
}
else {
map.put(split[i], 1);
}
}
System.out.println(map);
}
public class P3 {
public static void main(String[] args)
{
int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};
int high = 0;
int nextHigh = 0;
System.out.println("The given array is:");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + "\t");
}
for (int i = 0; i < array.length; i++)
{
if (array[i] > high)
{
nextHigh = high;
high = array[i];
}
else if (array[i] > nextHigh)
{
nextHigh = array[i];
}
}
System.out.println("Second Highest is:" + nextHigh);
System.out.println("Highest Number is: " +high);
}
}
//Local Variable
import Java.io.*;
class Main {
public static void main(String[] args)
{
int var = 145;
System.out.println("Local Variable: " + var);
}
}
//Instance variable
import Java.io.*;
class Main {
public int value = 12;
public static void main(String[] args)
{
Main va = new Main();
System.out.println("My value is: " + va.value);
}
}
Example:
class Main {
public static void main(String args[]) {
System.out.println(" Main Method");
}
public static void main(int[] args){
System.out.println("Overloaded Integer array Main Method");
}
public static void main(char[] args){
System.out.println("Overloaded Character array Main Method");
}
public static int main(double[] args){
System.out.println("Overloaded Double array Main Method");
}
public static void main(float args){
System.out.println("Overloaded float Main Method");
}
}
//Function overloading
#function1
void addPodium(int a, int b)
{
System.out.println(a + b);
}
#function2
float addPodium(float a, float b, float c)
{
System.out.println(a + b + c);
}
//Function overriding
class Parent {
void show()
{
System.out.println("I am Parent");
}
}
class Child extends Parent {
void show()
{
System.out.println("I am Child");
}
}
class Main {
public static void main(String[] args)
{
Parent obja = new Parent();
obja.show();
Parent objb = new Child();
objb.show();
}
}
Q 72. A single try block and multiple catch blocks can co-exist in a Java
Program. Explain.
One or more catch blocks can follow a try block. Each catch block must have a unique exception handler. So, if
you want to perform multiple tasks in response to various exceptions, use the Java multi-catch block.
Q 73. Do final, finally and finalize keywords have the same function?
No, final, finally and finalize keywords have different functionalities.
Final is used to restrict classes, variables, or methods, the final keyword.
Finally is used to execute the code written inside the block without handling any exceptions.
Finalize is used to call the function of the implementation of cleaning the garbage collection of an object.
start() method is used for creating a separate call stack for the thread execution. Once the call stack is created,
JVM calls the run() method for executing the thread in that call stack.
Q 78. What is the difference between the ‘throw' and ‘throws' keyword in
Java?
The throw keyword is often used to explicitly throw an exception. It can only throw one exception at a time
whereas throws can be used to declare multiple exceptions.
Q 79. Identify the output of the below Java program and Justify your answer.
class Main {
public static void main(String args[]) {
Scaler s = new Scaler(5);
}
}
class InterviewBit{
InterviewBit(){
System.out.println(" Welcome to InterviewBit ");
}
}
class Scaler extends InterviewBit{
Scaler(){
System.out.println(" Welcome to Scaler Academy ");
}
Scaler(int x){
this();
super();
System.out.println(" Welcome to Scaler Academy 2");
}
}
The above code will throw the compilation error. It is because the super() is used to call the parent class
constructor. But there is the condition that super() must be the first statement in the block. Now in this case, if
we replace this() with super() then also it will throw the compilation error. Because this() also has to be the first
statement in the block. So in conclusion, we can say that we cannot use this() and super() keywords in the
same block.
Q 82. What are the default values assigned to variables and instances in
Java?
By default, for a numerical value it is 0, for the boolean value it is false and for objects it is NULL.
Q 84. Can you tell the difference between equals() method and equality
operator (==) in Java?
Equality operator (==) is used to check the equality condition between two variables. But the equals() method is
used to check the equality condition between two objects.
Q 87. Explain the use of the final keyword in variable, method and class.
In Java, one can apply the final keyword to a variable, methods, and class. With the help of the final keyword,
the variable turns out to be a constant, the method cannot be inherited and the class cannot be overridden.
Q 88. Is it possible that the ‘finally' block will not be executed? If yes then list
the case.
Yes, there is a possibility that the ‘finally’ block cannot get executed. Here are some of the cases where the
above situation occurs.
1. During the time of fatal errors such as memory exhaustion, memory access error, etc.
2. During the time of using System.exit()
Q 89. Difference between static methods, static variables, and static classes
in Java.
A variable, method, or class can be made static by using the static keyword. A static class cannot be
instantiated. When both objects or instances of a class share the same variables, this is referred to as static
variables. Static methods are simply methods that refer to the class in which they are written.
Q 91. Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
Because of security, synchronization, concurrency, caching, and class loading, the String is immutable in Java.
The reason for making string final would be to destroy its immutability and help stop others from trying to
extend it. String objects are cached in the String pool, making them immutable.
Q 92. Which of the below generates a compile-time error? State the reason.
int[] n1 = new int[0];
boolean[] n2 = new boolean[-200];
double[] n3 = new double[2241423798];
char[] ch = new char[20];
We get a compile-time error in line 3. The error we will get in Line 3 is - the integer number too large. It is
because the array requires size as an integer. And Integer takes 4 Bytes in the memory. And the number
(2241423798) is beyond the capacity of the integer. The maximum array size we can declare is -
(2147483647).
Because the array requires the size in integer, none of the lines (1, 2, and 4) will give a compile-time error. The
program will compile fine. But we get the runtime exception in line 2. The exception is -
NegativeArraySizeException.
Here what will happen is - At the time when JVM will allocate the required memory during runtime then it will
find that the size is negative. And the array size can’t be negative. So the JVM will throw the exception.
Q 97. Why is the character array preferred over string for storing confidential
information?
Because Strings are immutable, any change will result in the creation of a new String, whereas char[] allows
you to set all of the elements to blank or zero. So storing a password in a character array clearly reduces the
security risk of password theft.
Q 98. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
Q 100. What are the different types of Thread Priorities in Java? And what is
the default priority of a thread assigned by JVM?
There are different types of thread properties in Java. They are MIN_PRIORITY, MAX_PRIORITY, and
NORM_PRIORITY. By default, the thread is assigned NORM_PRIORITY.