Java Interview Questions for Freshers
Java Interview Questions for Freshers
So let’s get started with the first set of basic core Java technical interview questions
which is primarly useful for freshers.
• 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.
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 and 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.
Easy: Java is a language that is considered easy to learn. One fundamental concept of
OOP Java has a catch to understand.
Secured Feature: Java has a secured feature that helps develop a virus-free and
tamper-free system for the users.
OOP: OOP stands for Object-Oriented Programming language. OOP signifies that, in
Java, everything is considered an object.
We get two major things along with the Java Download file.
JDK JRE
4. What is a ClassLoader?
Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?
• Class Memory
• Heap Memory
• Stack Memory
• Program Counter-Memory
6. What are the differences between Heap and Stack Memory in Java?
Stack memory in data structures 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.
Neither the Local Variables nor any primitives and Object references have any default
value stored in them.
• 200Simplilearn
• E-Learning Company100100
The term aggregation refers to the relationship between two classes best described as
a “whole/part” and “has-a” relationship. This kind is the most specialized version of an
association relationship. It contains the reference to another class and is said to have
ownership of that class.
A Paradigm that is based on the concepts of “Objects.” It contains data and code. Data
that is in the form of fields, and regulation, that is in the form of procedures. The exciting
feature of this paradigm is that the object’s procedures can access and often modify the
data fields themselves.
17. Define Wrapper Classes in Java.
In Java, when you declare primitive datatypes, then Wrapper classes are responsible
for converting them into objects(Reference types).
A class that can possess only one object at a time is called a singleton class. To
implement a singleton class given steps are to be followed:
The package is a collective bundle of classes and interfaces and the necessary libraries
and JAR files. The use of packages helps in code reusability.
Java Virtual Machine takes care of memory management implicitly. Java's primary
motto was to keep programming simple. So, accessing memory directly through
pointers is not a recommended action. Hence, pointers are eliminated in Java.
For instance, variables are declared inside a class, and the scope of variables in
javascript is limited to only a specific object.
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.
An Exception handling in Java is considered an unexpected event that can disrupt the
program's normal flow. These events can be fixed through the process of Exception
Handling.
The term final is a predefined word in Java that is used while declaring values to
variables. When a value is declared using the final keyword, then the variable's value
remains constant throughout the program's execution.
When the main method is not declared as static, then the program may be compiled
correctly but ends up with a severe ambiguity and throws a run time error that reads
"NoSuchMethodError."
One of the most well-known and widely used programming languages is Java. It is a
programming language that is independent of platforms. Java doesn't demand that the
complete programme be rewritten for every possible platform. The Java Virtual Machine
and Java Bytecode are used to support platform independence. Any JVM operating
system can run this platform-neutral byte code. The application is run after JVM
translates the byte code into machine code. Because Java programmes can operate on
numerous systems without having to be individually rewritten for each platform, the
language is referred to as "Write Once, Run Anywhere" (WORA).
Java's main() function is static by default, allowing the compiler to call it either before or
after creating a class object. The main () function is where the compiler begins
programme execution in every Java programme. Thus, the main () method needs to be
called by the compiler. If the main () method is permitted to be non-static, the JVM must
instantiate its class when calling the function.
28. What part of memory - Stack or Heap - is cleaned in the garbage
collection process?
29. What is the difference between the program and the process?
30. What are the differences between constructor and method of a class in
Java?
Initializing the state of the object is done by constructors. A function Object () { [native
code] }, like methods, contains a group of statements (or instructions) that are carried
out when an object is created. A method is a group of statements that work together to
complete a certain task and return the outcome to the caller. A method has the option of
working without returning anything.
31. Which among String or String Buffer should be preferred when there are a
lot of updates required to be done in the data?
32. What happens if the static modifier is not included in the main method
signature in Java?
The main function is called by the JVM even before the objects are created, thus even if
the code correctly compiles, there will still be an error at runtime.
This technique designates whether the active thread is a user thread or a daemon
thread. For instance, tU.setDaemon(true) would convert a user thread named tU into a
daemon thread. On the other side, executing tD.setDaemon(false) would convert a
Daemon thread, tD, into a user thread.
34. What happens if there are multiple main methods inside one class in
Java?
There is no limit to the number of major approaches you can use. Overloading is the
ability to have main methods with different signatures than main (String []), and the JVM
will disregard those main methods.
In the event that an exception is not caught, it is initially thrown from the top of the stack
and then moves down the call stack to the preceding method. The runtime system looks
for a way to handle an exception that a method throws. The ordered list of methods that
were called to get to the method where the error occurred is the collection of potential
"somethings" that can be used to manage the exception. The call stack is the list of
methods, and exception propagation is the search technique.
If you don't deal with an exception once it occurs, the programme will end abruptly and
the code after the line where the exception occurred won't run.
Each attempt block does not necessarily have to be followed by a catch block. Either a
catch block or a final block ought to come after it. Additionally, any exceptions that are
expected to be thrown should be mentioned in the method's throws clause.
Yes, a class may include any number of constructors, and each function Object ()
{[native code] } may call the others using the this() function Object() { [native code] } call
function [please do not mix the this() function Object() { [native code] } call function with
this keyword]. The constructor's first line should be either this () or this(args).
Overloading of constructors is what this is called.
39. Contiguous memory locations are usually used for storing actual values in
an array but not in ArrayList. Explain.
Primitive data types like int, float, and others are typically present in an array. In such
circumstances, the array immediately saves these elements at contiguous memory
regions. While an ArrayList does not contain primitive data types. Instead of the actual
object, an ArrayList includes the references to the objects' many locations in memory.
The objects are not kept in consecutive memory regions because of this.
The distance from the array's beginning is just an offset. There is no distance because
the first element is at the beginning of the array. Consequently, the offset is 0.
41. Why is the remove method faster in the linked list than in an array?
42. How many overloaded add() and addAll() methods are available in the List
interface? Describe the need and uses.
List is an interface in the Java Collections Framework. The add() and addAll()
methods are the main methods at the List interface. The add() method is used to add
an element to the list, while the addAll() method is used to add a collection of elements
to the list.
The List interface contains two overloaded versions of the add() method:
The first add() method accepts a single argument of type E, the element to be added to
the list.
The second add() method accepts a variable number of arguments of type E, which are
the elements to be added to the list.
The List interface also contains two overloaded versions of the addAll() method:
The first addAll() method accepts a single argument of type Collection<? Extends E>,
which is the collection of elements to be added to the list.
The second addAll() method accepts a variable number of arguments of type E, which
are the elements to be added to the list.
43. How does the size of ArrayList grow dynamically? And also state how it is
implemented internally?
Aggregation (HAS-A) and composition are its two forms (Belongs-to). In contrast to
composition, which has a significant correlation, the aggregation has a very modest
association. Aggregation can be thought of as a more confined version of the
composition. Since all compositions are aggregates but not all aggregates are
compositions, aggregate can be thought of as the superset of composition.
46. How is the creation of a String using new() different from that of a literal?
The new () operator always produces a new object in heap memory when creating a
String object. The String pool may return an existing object if we build an object using
the String literal syntax, such as "Baeldung," on the other hand.
47. How is the ‘new' operator different from the ‘newInstance()' operator in
java?
Both the new operator and the newInstance() method are used to create objects in
Java. If we already know the kind of object to create, we can use the new operator;
however, if the type of object to create is supplied to us at runtime, we must use the
newInstance() function.
Yes, even with a garbage collector in place, the programme could still run out of
memory. Garbage collection aids in identifying and removing programme objects that
are no longer needed in order to release the resources they use. When an object in a
programme cannot be reached, trash collection is executed with respect to that object. If
there is not enough memory available to create new objects, a garbage collector is used
to free up memory for things that have been removed from the scope. When the amount
of memory released is insufficient for the creation of new objects, the program's memory
limit is exceeded.
Multiple threads trying to access the same resources in a multi-threaded software may
frequently result in unexpected and incorrect outcomes. Therefore, it must be ensured
through some form of synchronization that only one thread can access the resource at
any given time. Java offers a method for setting up threads and synchronizing their
operations with the aid of synchronized blocks. The synchronized keyword in Java is
used to identify synchronized blocks. In Java, a synchronized block is one that is tied to
an object. Only one thread can be running at a time inside synchronized blocks since
they are all synchronized on the same object. Until the thread inside the synchronized
block exits the block, all other threads trying to enter the block are blocked.
System.out.println() in Java outputs the argument that was supplied to it. On the
monitor, the println() method displays the findings. An objectname is typically used to
call a method.
• New: A new thread is always in the new state when it is first formed. The function
hasn't been run yet, thus it hasn't started to execute for a thread in the new state.
• Active: A thread switches from the new state to the active state when it calls the
start() method. The runnable state and the running state are both contained within
the active state.
• Blocked or Waiting: A thread is either in the blocked state or the waiting state when it
is inactive for a while (but not indefinitely).
• Timed waiting: When we use the sleep () method on a particular thread, we are
actually engaging in timed waiting. The thread enters the timed wait state using the
sleep () function. The thread awakens when the allotted time has passed and
resumes execution where it left off.
• Termination: A thread that has been terminated means it is no longer active in the
system. In other words, the thread is inactive and cannot be revived (made active
again after being killed).
52. What could be the tradeoff between the usage of an unordered array
versus the usage of an ordered array?
53. Is it possible to import the same class or package twice in Java and what
happens to it during runtime?
The same package or class may be imported more than once. Neither the JVM nor the
compiler raise an objection. Even if you import the same class several times, the JVM
will only internally load it once.
54. In case a package has sub packages, will it suffice to import only the main
package? e.g. Does importing of com.myMainPackage.* also import
com.myMainPackage.mySubPackage.*?
Sub-packages won't be imported when a package is imported. When you import a
package, all of its classes and interfaces—with the exception of those from its sub-
packages—are imported.
55. Will the final block be executed if the code System.exit(0) is written at the
end of the try block?
The system is established as the last line to be run, after which nothing will happen,
therefore both the catch and finally blocks are essentially ignored.
The outer braces of the double-brace initialization construct an anonymous class that is
descended from the provided class and gives an initializer block for that class (the inner
braces).
57. Why is it said that the length() method of String class doesn't return
accurate results?
Since this char [] array is used by the Java String class internally, the length variable
cannot be made public.
58. What are the possible ways of making objects eligible for garbage
collection (GC) in Java?
If a reference variable for an object is removed from the programme while it is running,
the object may be trash collected. They are also referred to as inaccessible objects
occasionally. The new operator returns a reference to an object after dynamically
allocating memory for it.
59. In the below Java Program, how many objects are eligible for garbage
collection?
I don't know about the program, but generally, three objects are eligible for garbage
collection.
The first object is created when the program is started and is no longer needed when
the program ends.
The second object is created when the user inputs their name and is no longer required
when the program ends.
The third object is created when the user inputs their address and is no longer needed
when the program ends.
60. What is the best way to inject dependency? Also, state the reason.
Constructor injection. A class requesting its dependencies through its function Object() {
[native code] } is the most typical instance of dependency injection. Since the client
cannot be constructed without the required dependencies, this guarantees that it is
always in a correct state.
61. How we can set the spring bean scope. And what supported scopes does
it have?
There are four ways to set the scope of a Spring bean: singleton, prototype, request,
and session.
The singleton scope creates a single instance of a bean, which is shared by all objects
that request it.
The prototype scope creates a new instance of a bean for each object that requests it.
The request and session scopes are only available in a web-based context. The request
scope creates a new bean instance for each HTTP request, and the session scope
creates a single instance of a bean shared by all objects in a single HTTP session.
The three categories of Java design patterns are creational, structural, and behavioural
design patterns.
A memory leak is the slow degradation of system performance over time brought on by
the fragmentation of a computer's RAM as a result of shoddy application design or
programming that fails to release memory chunks when they are no longer required.
These memory leaks frequently result from session items in excess, insertion into
Collection objects without deletion, infinite caches, excessive page switching on the
operating system, listener methods that are not called, and bespoke data structures that
are poorly written.
64. Assume a thread has a lock on it, calling the sleep() method on that thread
will release the lock?
No, the thread might release the locks using notify, notifyAll(), and wait() methods.
class FibonacciExample2{
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibonacci(count-1);
int count=10;
66. Write a Java program to check if the two strings are anagrams.
import java.util.Arrays;
if (s1.length() != s2.length()) {
status = false;
} else {
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
}
if (status) {
} else {
isAnagram("Keep", "Peek");
Output
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
69. Write a Java Program to check if any number is a magic number or not. A
number is said to be a magic number if after doing the sum of digits in each
step and in turn doing the sum of digits of that sum, the ultimate result (when
there is only one digit left) is 1.
class GFG
int sum = 0;
if (n == 0)
{
n = sum;
sum = 0;
sum += n % 10;
n /= 10;
// Driver code
int n = 1234;
if (isMagic(n))
System.out.println("Magic Number");
else
}
}
super(str);
}
else {
System.out.println("welcome to vote");
// main method
try
validate(13);
//matrix to rotate
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
System.out.print(" "+a[i][j]+"\t");
}
System.out.println("\n");
for(int i=0;i<3;i++)
for(int j=2;j>=0;j--)
System.out.print(""+a[j][i]+"\t");
System.out.println("\n");
72. Write a java program to check if any number given as input is the sum of 2
prime numbers.
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
// is prime or not
bool isPrime(int n)
if (n <= 1)
return false;
if (n % i == 0)
return false;
return true;
bool isPossible(int N)
{
// if the number is prime,
return true;
else
return false;
// Driver code
int main()
int n = 13;
if (isPossible(n))
printf("%s", "Yes");
else
printf("%s", "No");
return 0;
}
73. Write a Java program for solving the Tower of Hanoi Problem.
class GFG
if (n == 1)
return;
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod
" +to_rod);
// Driver method
{
int n = 4; // Number of disks
import java.util.*;
// Main class
class GFG {
// Method 1
// overflow of indices
if (r >= l && l <= arr.length - 1) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
// in right subarray
// array
return -1;
// Method 2
// Main driver method
// Length of array
int n = arr.length;
int x = 10;
// Element present
if (result == -1)
// Print statement
else
// Print statement
+ result);
No, these keywords do not exist in Java. Delete, Next, Exit are the operations
performed in the Java program, Main is the predefined method, and Null is the default
String type.
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.
Now, let's have a look at some of the most asked Java technical interview questions for
intermediate experienced professionals.
JDK is an abbreviation for Java Development Kit. It is a combined Package of JRE and
Developer tools used for designing Java Applications and Applets. Oracle has the
following variants.
JVM has a Just in Time (JIT) compiler tool that converts all the Java source code into
the low-level compatible machine language. Therefore, it runs faster than the regular
application.
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.
JIT compiler refers to Just in Time compiler. It is the simplest way of executing the
computer code that takes in compilation during the execution of a program rather than
before performance. It commonly uses bytecode translation to machine code. It is then
executed directly.
79. 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.
Yes, A constructor can return a value. It replaces the class's current instance implicitly;
you cannot make a constructor return a value explicitly.
The term "this" is a particular keyword designated as a reference keyword. The "this"
keyword is used to refer to the current class properties like method, instance, variable,
and constructors.
The process of creating multiple method signatures using one method name is called
Method Overloading in Java. Two ways to achieve method overloading are:
No, Java does not support the Overloading of a static method. The process would throw
an error reading "static method cannot be referenced."
Binding is a process of unifying the method call with the method's code segment. Late
binding happens when the method's code segment is unknown until it is called during
the runtime.
Become a Skilled Web Developer in Just 9 Months!
The Dynamic method dispatch is a process where the method call is executed during
the runtime. A reference variable is used to call the super-class. This process is also
known as Run-Time Polymorphism.
88. Why is the delete function faster in the linked list than an array?
Delete Function is faster in linked lists in Java 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
2. Start
3. Stop
4. Destroy
5. Paint
Compile-time type safety is provided by using generics. Compile-time type safety allows
users to catch unnecessary invalid types at compile time. Generic methods and classes
help programmers specify a single method declaration, a set of related methods, or
related types with an available class declaration.
The Externalizable interface helps with control over the process of serialization. An
"externalisable" interface incorporates readExternal and writeExternal methods.
The Daemon thread can be defined as a thread with the least priority. This Daemon
thread is designed to run in the background during the Garbage Collection in Java.
Enumeration or enum is an interface in Java. Enum allows the sequential access of the
elements stored in a collection in Java.
97. 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.
The finalize method is called the Garbage collector. For every object, the Garbage
Collector calls the finalize() method just for one time.
Now, lets move on to our last section of Advanced Core Java Interview Questions which
is primarly useful for experienced and working professionals.
No, "this" and "super" keywords should be used in the first statement in the class
constructor. The following code gives you a brief idea.
baseClass() {
super();
this();
}
}
JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of
text.
• Static Data
• JSP elements
Java Training in Bangalore Java Training New York Java Course London
Java Training in Chennai Java Training San Diego Java Course Singapore
Directives are instructions processed by JSP Engine. After the JSP page is compiled
into a Servlet, Directives set page-level instructions, insert external files, and define
customized tag libraries. Directives are defined using the symbols below:
start with "< %@" and then end with "% >"
• 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
Objects that inherit the "Observable class" take care of a list of "observers."
When an Observable object gets upgraded, it calls the update() method of each of its
observers.
After that, it notifies all the observers that there is a change of state.
The Observer interface gets implemented by objects that observe Observable objects.
• 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.
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.
The Java Persistence API enables us to create the persistence layer for desktop and
web applications. Java Persistence deals in the following:
2. Query Language
Authentication options are available in Servlets: There are four different options for
authentication in servlet:
• Basic Authentication:
Usernames and passwords are given by the client to authenticate the user.
• Form-based authentication:
• 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.
110. Explain FailFast iterator and FailSafe iterator along with examples for
each.
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.
Ex: CopyOnWriteArrayList
111. How do we reverse a string?
package simplilearnJava;
return source;
return reverse;
}
Expected Output:
The Square root of a number can be found by using the following program.
package simplilearnJava;
import java.util.Scanner;
Expected Output:
25
The square root is: 5
The program that finds the duplicate elements in a string is written below:
package simplilearnJava;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
printDuplicateCharacters("Simplilearn");
if (charMap.containsKey(ch)) {
charMap.put(ch, 1);
if (entry.getValue() > 1) {
Expected output:
i: 2
l: 2
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
num.add(1);
num.add(2);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.addAll(primesWithoutDuplicates);
Expected Output:
package simplilearnJava;
import java.util.HashMap;
if (map.containsKey(split[i])) {
int count = map.get(split[i]);
} else {
map.put(split[i], 1);
System.out.println(map);
Expected Output:
The following program can be used to find the second biggest number in an array list.
package simplilearnJava;
int array[] = { 1, 2, 3, 4, 11, 12, 13, 14, 21, 22, 23, 24, 31, 32};
int high = 0;
int nextHigh = 0;
System.out.print(array[i] + "\t");
nextHigh = high;
high = array[i];
nextHigh = array[i];
Expected Output:
1 2 3 4 11 12 13 14 21 22 23 24 31 32
System.out and System.err represent the monitor by default and thus can be used to
send data or results to the monitor. System.out is used to display normal messages and
results. System.eerr is used to display error messages. System.in represents
InputStream object which by default represents standard input device, i.e., keyboard.
The simplest implementation that can be given is that of a List wherein one can place
ordered words and perform a Binary search. The other implementation with a better
search performance is HashMap where the key is used as the first character of the word
and the value as a LinkedList.
hashmap {
119. How would you tackle it if you might have to encounter pattern programs
in Java?
With this, we have come to the end of this Java Interview Questions article. Moving
ahead, we will look into the next crucial steps that you could pursue, to master Java.
Generally, instance variables are declared in a class but outside methods whereas a
local variable is declared within the blocks of code.
//Local Variable
import Java.io.*;
class Main {
//Instance variable
import Java.io.*;
class Main {
Yes, the main method can be overloaded as many times as we want. Nevertheless,
JVM prefers to call the main method with the help of its predefined calling method.
Example:
class Main {
Method overloading occurs during the compile time, whereas method overriding occurs
during the run time. Static binding is used during overloading, whereas dynamic binding
is used during methods overriding.
//Function overloading
#function1
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");
void show()
System.out.println("I am Child");
class Main {
{
Parent obja = new Parent();
obja.show();
objb.show();
123. 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.
124. Do final, finally and finalize keywords have the same function?
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.
Basically, the super keyword is used to refer to the parent class. When there are the
same fields in both parent and child classes, then one can use a super keyword to
access data members of the parent class.
An abstract class can have a combination of both abstract and non-abstract methods,
whereas an interface has only abstract methods in it.
There are two ways to define and implement a thread in Java. They are by
implementing the runnable interface and extending the thread class.
System.out.println("Thread runs...");
ib.start();
ib.start();
Implementing a thread using the method of Runnable interface is more preferred and
advantageous as Java does not have support for multiple inheritances of classes.
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.
129. 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.
130. Identify the output of the below Java program and Justify your answer.
class Main {
class InterviewBit{
InterviewBit(){
Scaler(){
Scaler(int x){
this();
super();
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.
Java works as a “pass by value” phenomenon, because “pass by reference” needs the
help of pointers. But there are no pointers in Java.
132. How to not allow serialization of attributes of a class in Java?
133. 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.
Data encapsulation is one of the properties of OOPS concepts, where all the data such
as variables and methods are enclosed together as a single unit.
135. 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.
An infinite loop can be declared in Java by breaking the logic in the instruction
block. For example,
//statements
138. 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.
139. 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.
140. 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.
The main goal of using garbage collection is to free the heap memory by eliminating
unnecessary objects.
142. Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
143. Which of the below generates a compile-time error? State the reason.
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.
The string class is immutable but the other two are mutable in nature. StringBuffer is
synchronous whereas the StringBuilder is asynchronous. String uses string pool as
memory storage whereas the other two use heap memory for storage purposes.
In a HashSet, the elements are unsorted and work faster than a Tree set. It is
implemented using a hash table.
148. 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.
149. What are the differences between HashMap and HashTable in Java?
HashMap HashTable
Reflection is a property of Java, enabling the Java code to inspect itself. A Java class,
for example, can get the names of all its members and showcase them.
151. 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.
It is not a pure object-oriented language because it supports primitive data types like int,
double, and char, which are not objects, and it supports static methods and variables.
Two ways to use threads in Java one is by extending the Thread class or by
implementing the Runnable interface. Another way to use threads in Java is by using
the Executor framework, which provides a higher level of abstraction for managing
threads.
156. How do you achieve Object Cloning in Java?
Creating a new object with the same state as an existing object called Object Cloning in
Java. This can be achieved by implementing the Cloneable interface and overriding the
clone() method in the class.
It is an abstract machine that provides a runtime environment for Java programs to run.
The JVM interprets the compiled Java code and executes it on the underlying operating
System.
158. What gives Java its 'write once and run anywhere' nature?
Java's 'write once and run anywhere' nature is achieved by using Java Virtual Machine
(JVM) and bytecode. Java code is compiled into bytecode, which can be executed on
any platform that has a JVM installed.
Packages in Java provide a way to organize classes and interfaces into namespaces.
This helps to avoid naming conflicts and makes it easier to manage large codebases.
Packages provide a way to create reusable code through the use of libraries.
A static variable in Java is a variable that is associated with the class rather than an
instance of the class. This means that all instances of the class share the same static
variable. They are declared using the static keyword.
public Example() {
count++;
}
}
Diagram - The diagram below illustrates the relationship between the class and the
static variable:
+----------+
Example | count=0 |
+----------+
||
Instance1 | |
+----------+
||
Instance2 | |
+----------+
A static block in Java is a block of code that is executed when the class is loaded into
memory. Static blocks are enclosed in curly braces and are marked with the static
keyword.
The main difference between a static method and an instance method in Java is that a
static method is associated with the class, while an instance method is associated with
an instance of the class.
It is the process of calling one constructor from another constructor in the same class.
This can be achieved using this keyword.
164. Which class is the superclass for all the classes?
The Object class is the only superclass for all classes in Java.
Multiple inheritances are not supported in Java because it can lead to several problems,
including the diamond problem and name conflicts.
166. Why is method overloading not possible by changing the return type in
Java?
It is not possible by changing the return type in Java because the return type of a
method is not part of its signature.
Method overloading with type promotion in Java is the process of defining multiple
methods in the same class with the same name but different parameter types.
168. Can we change the scope of the overridden method in the subclass?
No, we cannot change the scope of the overridden method in the subclass.
The covariant return type is a feature introduced in Java 5 that allows a subclass
method to return a type that is a subclass of the return type of the overridden method in
the superclass.
The final blank variable in Java is a final variable that is not initialized when it is
declared.
175. Difference between the final method and the abstract method
The main difference between a final method and an abstract method in Java is that a
final method cannot be overridden in a subclass, while an abstract method must be
overridden in a subclass.
Heap and Stack are two types of memory in Java used for storing data. Heap memory
is used for storing objects, while Stack memory is used for storing local variables and
method calls. One of the main differences between Heap and Stack memory is their
allocation and deallocation. Heap memory is allocated when an object is created and
deallocated when there are no more references to that object. Stack memory, on the
other hand, is allocated when a method is called and deallocated when the method
returns.
Another difference between Heap and Stack memory is their size. Heap memory is
larger than Stack memory because it is used for storing objects. Stack memory is
smaller because it is used for storing local variables and method calls only.
177. What do you understand about an instance variable and a local variable?
Instance variables and local variables are two types of variables in Java. Instance
variables are declared inside a class but outside any method. They are used to store
data that is specific to an object. Local variables, on the other hand, are declared inside
a method and are used to store temporary data that is required only within that method.
One of the main differences between instance variables and local variables is their
scope. Instance variables have a larger scope than local variables. The second
difference between instance variables and local variables is their initialization. Instance
variables are initialized automatically by default values if not initialized explicitly, while
local variables must be initialized explicitly before they can be used.
JIT (Just-In-Time) compiler is a part of the Java Virtual Machine (JVM) that compiles
Java bytecode into native machine code at run time.
179. Can you tell the difference between the equals() method and equality
operator (==) in Java?
Equals() method and equality operator (==) are used for comparing objects in Java.
However, they differ in their functionality. Equals() method is used to compare the
contents of two objects, while the equality operator (==) is used to compare the
references of two objects.
When we use the equality operator (==) to compare two objects, it checks if both
objects refer to the same memory location. On the other hand, when we use the
Equals() method, it checks if the contents of the two objects are equal.
It is a Java.lang public
In Java, it is a binary operator.
method.Object type.
It can be applied to derived types as well as primitive It can only be applied to derived
types types.
Primitive forms are most suitable for it. It works best with derived types.
Shallow copy and deep copy are two types of object copying in Java. SC creates a new
object with the same values as the original object, while deep copy creates a new object
with new values.
x = 5;
changeValue(num);
System.out.println(num);
In this code, we pass the value of num to the changeValue() method. However, when
we change the value of x inside the method, it does not affect the value of num outside
the method. This is because Java passes a copy of the value of num, not the actual
object.
In Java, array indexing starts with 0. This is because an array is a contiguous block of
memory where each element occupies a fixed amount of space. It is the offset from the
start of the array.
Consider the following code:
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
In this code, we declare an array of size five and assign values to each element. The
index of the first element is coming 0, and the last element index is coming 4, which is
the size of the array minus 1.
Java thread life cycle consists of several states, including New, Runnable, Blocked,
Waiting, Timed Waiting, and Terminated.
The New State represents a thread that has been created but not started yet. The
Runnable state represents a thread that is ready to run but may not be scheduled to run
by the operating System. The Blocked state represents a thread that is waiting for a
monitor lock to be released. The Waiting state represents a thread that is waiting for
another thread to perform a specific action. The Timed Waiting state represents a
thread that is waiting for a specific amount of time to elapse. The Terminated state
represents a thread that has completed its execution.
184. What are the possible ways of making objects eligible for garbage
collection (GC) in Java?
In Java, objects are automatically garbage collected when they are no longer
referenced. However, we can also make objects eligible for garbage collection manually
using the System.gc() method or by setting the object reference to null.
obj = null;
System.gc();
In this code, we create an object of the MyObject class and then set the object
reference to null. We then call the System.gc() method to request the garbage collector
to run.
Java Design Patterns can be categorized into three categories: Creational, Structural,
and Behavioral.
Creational patterns are used for creating objects. Some examples of Creational patterns
are Singleton, Factory, and Abstract Factory.
Structural patterns are used for assembling objects and creating relationships between
them. Some examples of Structural patterns are Adapters, bridges, and Composites.
Java is a popular programming language that is widely used for developing applications.
Some of the features of Java programming language are:
1. Platform Independence: Java code can run on any platform that has a JVM installed.
3. Memory Management: Java has automatic memory management, which means that
it manages memory allocation and deallocation automatically.
7. Garbage Collection: Java has automatic garbage collection, which means that it
automatically frees the memory.