Java Viva Question
Java Viva Question
Java Viva Question
• Concept.
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.
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.
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 - Java Development Kit
JDK JRE
JDK is a dedicated kit for solely JRE is a set of software and library designed for
software development executing Java Programs
JDK package is a set of tools for JRE Package is one that only supports files and
debugging and Developing libraries for a runtime environment
JDK package will be provided with an JRE Package does not get an installer but has
installer file only a runtime environment
4. What is a ClassLoader?
A classloader in Java is a subsystem of Java Virtual Machine, dedicated to loading
class files when a program is executed; ClassLoader is the first to load the
executable file.
Also Read: What is Bootstrap and How to Embed Bootstrap into Angular?
• Class Memory
• Heap Memory
• Stack Memory
• Program Counter-Memory
Yes, the program will successfully execute if written so. Because, in Java, there is no
specific rule for the order of specifiers
8. What is the default value stored in Local Variables?
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.
22. Explain Java String Pool.
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.
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.
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.
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.
40. Why does the java array index start with 0?
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.
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.
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.
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.
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.
A thread can be in any of the following states in Java. These are the states:
• 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.
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.
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.
Since this char [] array is used by the Java String class internally, the length variable
cannot be made public.
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.
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.
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;
import java.util.Arrays;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
if (status) {
} else {
isAnagram("Keep", "Peek");
Output
Keep and Peek are anagrams
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
Output: 5
class GFG
{
public static boolean isMagic(int n)
int sum = 0;
if (n == 0)
n = sum;
sum = 0;
sum += n % 10;
n /= 10;
}
// Return true if sum becomes 1.
// Driver code
int n = 1234;
if (isMagic(n))
System.out.println("Magic Number");
else
{
// calling the constructor of parent Exception
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");
#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;
}
// Function to check if a prime number
bool isPossible(int N)
return true;
else
return false;
// Driver code
int main()
int n = 13;
if (isPossible(n))
printf("%s", "Yes");
else
printf("%s", "No");
return 0;
class GFG
if (n == 1)
return;
}
// Driver method
import java.util.*;
// Main class
class GFG {
// Method 1
// overflow of indices
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
// in right subarray
// array
return -1;
// Method 2
// Length of array
int n = arr.length;
int x = 10;
// Element present
if (result == -1)
// Print statement
else
// Print statement
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.
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.
Access Specifiers are predefined keywords used to help JVM understand the scope
of a variable, method, and class. We have four access specifiers.
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.
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:
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.
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.
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
90. Explain the difference between >> and >>>
operators.
• >> operator does the job of right shifting the sign bits
1. Initialization
2. Start
3. Stop
4. Destroy
5. Paint
The Externalizable interface helps with control over the process of serialization. An
"externalisable" interface incorporates readExternal and writeExternal methods.
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.
No, "this" and "super" keywords should be used in the first statement in the class
constructor. The following code gives you a brief idea.
super();
this();
JSP is an abbreviation for Java Servlet Page. The JSP page consists of two types of
text.
• Static Data
• JSP elements
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.
• 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.
Ex: CopyOnWriteArrayList
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
package simplilearnJava;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
printDuplicateCharacters("Simplilearn");
if (charMap.containsKey(ch)) {
} else {
charMap.put(ch, 1);
}
}
if (entry.getValue() > 1) {
Expected output:
i: 2
l: 2
package simplilearnJava;
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.clear();
num.addAll(primesWithoutDuplicates);
Expected Output:
package simplilearnJava;
import java.util.HashMap;
if (map.containsKey(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;
public class NextHighest {
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];
}
else if (array[i] > nextHigh)
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.
118. Could you provide some implementation of a
Dictionary having a large number of words?
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 {
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.
//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
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 {
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.
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.
125. When can you use the "super" keyword?
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.
In the case of a shallow copy, primitive data types are copied, whereas in the case of
a deep copy along with primitive data types the object references are also copied.
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();
System.out.println("Thread runs...");
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.
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.
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.
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
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.
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.
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.
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.
144. How would you differentiate between a String,
StringBuffer, and a StringBuilder?
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 Java, you could indeed override a private or static method. If you create a similar
method in a child class with the same return type and method arguments, it will hide
the super class method; this is known as method hiding. Similarly, you cannot
override a private method in a subclass because it is not accessible from that.
In a HashSet, the elements are unsorted and work faster than a Tree set. It is
implemented using a hash table.
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.
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.
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.
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.
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.
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.
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.
No, we cannot change the scope of the overridden method in the subclass.
The final blank variable in Java is a final variable that is not initialized when it is
declared.
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.
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.
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.
Shallow copy Deep copy
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.
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.
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.
185. What are the different categories of Java Design
patterns?
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.
1. Platform Independence: Java code can run on any platform that has a JVM
installed.
5. Security: Java has built-in security features that protect the System from
malicious attacks.
6. Exception Handling: Java has a robust exception-handling mechanism that
allows developers to handle errors and exceptions effectively.