Java is one of the most popular programming language in today's world and thus learning it to a great extent can be a huge asset for anyone. Therefore I have brought an extensive list of some of the most tricky Java interview questions that will surely set you apart whether you are preparing for your technical interview or are a Java enthusiast.
Note : This is second part of the series :
Most Tricky Java Interview Questions.
So let's get started with our exquisite list of the most tricky Java interview question.
1. How is Java platform independent ?
The problem with C++,C and most other languages is that they are
designed to be compiled for a specific target. Although it is possible
to compile a C++ program for just about any type of CPU, to do so requires a
full C++ compiler targeted for that CPU.The problem is that
compilers are expensive and time-consuming to create.
Java
language solves this problem.It is a
portable and platform independent language.
The key that allows
Java to solve this portability problem is that the
output of Java compiler is not executable code, but it is Bytecode. Bytecode is a highly optimized set of instructions designed to be executed
by the Java Virtual Machine(JVM). Translating a Java program into Bytecode
helps to achieve platform independence because now only the JVM needs to be
implemented for each platform.
Although the details of the JVM will differ from platform to platform, all
understand the same Java Bytecode. If a Java program were compiled to native code (like C++), then different
versions of the same program would have to exist for each type of CPU.
Step by step Execution of Java Program:
1.The programmer writes source code in Java language.
2.
Java code is compiled by compiler(javac). The result of the Java compiler is
the .class file or the Bytecode and not the machine native code (unlike C
compiler).
3. The Bytecode generated is a non-executable code and
needs an interpreter to execute on a machine. This interpreter is the JVM.
4.
Finally program runs to give the desired output.
2. What are wrapper classes in java? Also explain Autoboxing and Autounboxing.
Primitive types are important as they provide
better performance for simple tasks. But despite the performance
benefit , there are times when you will need an object representation. For
example, you can’t pass a primitive type by reference to a method. Also, many
of the standard data structures implemented by Java operate on objects, which
means that you can’t store primitive types in these data structures. To handle
such situations, Java provides type wrappers.
A Wrapper class is a class whose object encapsulates (stores) primitive
data types. When we create an object to a wrapper class, it contains a field and in
this field, we can store the corresponding primitive data type.
The type
wrappers are Double, Float, Long, Integer, Short, Byte, Character, and
Boolean. You can tell their corresponding primitive types by their names.
Let's
discuss one of them : Integer class.
This is used to encapsulate
int values.
This class has a constructor : Integer(int number)
To
extract int value from Integer object use method : int intValue()
Other
wrapper classes also have similar constructor and method for extracting the
corresponding primitive type value.
Now,
The process of
encapsulating a value within an object is called boxing.
This line
boxes the value 100 into an Integer:
Integer object = new
Integer(100);
The process of extracting a value from a type wrapper
is called unboxing.
This line unboxes the value in object
int
i = object.intValue();
Java has added two important features:
autoboxing and auto-unboxing.
Autoboxing is the process by
which a primitive type is automatically encapsulated (boxed)
into its
equivalent type wrapper whenever an object of that type is required. There is
no need
to explicitly construct an object.
For example, here is the
modern way to construct an Integer object that has the value 100:
Integer
object= 100; // autobox an int
Auto-unboxing is the process
by which the value of a boxed object is automatically extracted (unboxed) from
a type wrapper when its value is required. There is no need to call a method
such as intValue( ).
For example, to unbox object, you can use this line:
int i = object; // auto-unbox
Java handles the internal
details for you.
Advantages of Autoboxing and Autounboxing :
a. They remove the task of manually boxing and unboxing values.
b. They
help to prevent errors.
c. They are very important for Generics in Java
as they only work with objects.
d. Working with Collections framework
becomes much simpler using these features.
3. What is static block in Java ?
Java provides a special block called as static block.
It is used for initializing the static variables of the class.The block is
executed only once before the execution of the main method. This is because the class has to be loaded into the main memory before its
usage, and static block is executed during the loading of the class.
A
class can have multiple Static blocks, which will execute in the same sequence
in which they have been written into the program.
Example :
class CodingWithArt{
static int num;
static String codingStr;
static{ // static block
num = 100;
codingStr = "Hello developers!";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of codingStr: "+codingStr);
}
}
You cannot access instance variable inside static block as it is static therefore it is not an object's property but a class property.
4. Explain final, finally and finalize in Java.
1. Final :
Final is a keyword in Java which is used to restrict a user’s access to a
class, variable or method.
It is used in several contexts:
a. Final Variable :
Final variable value can't be changed after initialization.
b. Final Method : Method declared as final can't be overridden by a subclass.
c. Final Class :
Final class can't be inherited by any other class.
2. Finally :
In Java, finally is an optional block which is used for Exception Handling. It
is generally preceded by a try-catch block. When we use try-catch blocks in
our program, the execution order breaks and there are chances that some
important section of code gets missed for execution.Thus finally block is used
to execute important codes such as resource cleanup or free the memory usage,
etc. A finally block will be executed irrespective of the fact whether an
exception is handled or not.
class CodingWithArt {
public static void main(String args[]) {
try {
System.out.println("Try Block");
throw new ArithmeticException();
} catch (Exception e) {
System.out.println("Catch Block");
} finally {
System.out.println("Finally Block executed whether exception caught or not");
}
}
}
3. Finalize :
Finalize is a protected instance method defined in the Object class and thus
is available for all the objects in Java.
This method is called by the garbage collector before an object is
completely destroyed. An object might have to complete some important tasks like closing open
connections, freeing up resources held by it, etc before it gets destroyed. If
these tasks are not done, it might decrease the efficiency of the program and
may also waste memory. Thus, the garbage collector calls it for the objects
that aren’t referenced anymore and have been marked for garbage collection.
It
is implicitly defined inside every class to be empty. We can override this
method to perform any important task on the object before it gets
destroyed.
import java.io.*;
import java.lang.*;
public class CodingWithArt {
protected void finalize(){
System.out.println(" Object getting destroyed ");
}
public static void main(String[] args) {
CodingWithArt obj = new CodingWithArt();
obj = null; // this makes it eligible for garbage collection which will eventually call finalize()
System.gc();
}
}
5. What is Just in Time (JIT) Compiler in java ?
It is a compiler program that helps in transforming the Java Bytecode
into native machine instructions that are sent directly to the processor. By
default, the JIT compiler is enabled in Java and is activated whenever a Java
method is invoked. The JIT compiler then compiles the Bytecode of the invoked
method into native machine code, compiling it at runtime (just in time) to
execute. Once the method has been compiled, the JVM takes the compiled code of
that method directly rather than interpreting it. Code that looks like it can
be re-optimized is called "hot". Code can be monitored, and hot code paths can
be created to optimize code, as opposed to having the same sequence of code be
interpreted multiple times which may occur in other compiler types. With less
chance of code being interpreted multiple times, there is less overhead. This
is why it is often responsible for the performance optimization of Java
applications at the run time.
6. What is the difference between ArrayList and vector in Java?
How to choose between ArrayList and Vector?
In a single-threaded environment, ArrayList is the obvious choice as it gives
better performance, but where multi-threading is concerned, vectors are often
preferable for synchronization among threads.
If we don’t know how
much data we are going to have, but know the rate at which it grows, Vector
has an advantage since we can set the increment value in vectors.
But,
ArrayList is newer and generally faster than vector.
This brings us to the end of this article. Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook.
Happy Learning!!