Java Basic Questions For Interview Preparation
Java Basic Questions For Interview Preparation
1. What is Java?
Answer: Java is a programming language and computing platform first released by
Sun Microsystems in 1995. There are lots of applications and websites that will not work
unless you have Java installed, and more are created every day. Java is fast, secure, and
reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell
phones to the Internet, Java is everywhere!
Java is a general-purpose computer programming language that is concurrent, class-
based, object-oriented, and specifically designed to have as few implementation
dependencies as possible. It is intended to let application developers “write once, run
anywhere” (WORA), meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation.
For example, you can write and compile a Java program on UNIX and run it on
Microsoft Windows, Macintosh, or UNIX machine without any modifications to the
source code.
The Oracle implementation is packaged into two different distributions:
Java Runtime Environment (JRE) which contains the parts of the Java SE platform
required to run Java programs and is intended for end users.
Java Development Kit (JDK) which is intended for software developers and includes
development tools such as the Java compiler, Javadoc, Jar, and a debugger.
Answer: “Java Platform, Standard Edition 8 (Java SE 8)” is released on 18th March
2014. Along with the Java SE 8 platform, the product that implements the platform,
“Java SE Development Kit 8 (JDK 8)” and “Java SE Runtime Environment 8 (JRE 8)” is
also released.
Some of the important Java 8 features are;
forEach() method in Iterable interface
default and static methods in Interfaces
Functional Interfaces and Lambda Expressions
Java Stream API for Bulk Data Operations on Collections
Java Time API
Collection API improvements
Concurrency API improvements
Java IO improvements
Miscellaneous Core API improvements
Answer: Java is not fully object oriented because it supports primitive data type like it,
byte, long etc., which are not objects. Because in JAVA we use data types like int, float,
double etc which are not object oriented, and of course is what opposite of OOP is. That
is why JAVA is not 100% objected oriented.
4. What is the parent or base class of all the classes in Java?
Answer: java.lang.Object class is the super base class of all Java classes. Every other
Java classes descends from Object.
6. What is a class?
Answer: A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all objects of
one type. In general, class declarations can include these components, in order:
Modifiers : A class can be public or has default access (Refer this for details).
Class name: The name should begin with a initial letter (capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
Answer: A Java class file is a file containing Java bytecode and having .class extension
that can be executed by JVM. A Java class file is created by a Java compiler from .java
files as a result of successful compilation. As we know that a single Java programming
language source file (or we can say .java file) may contain one class or more than one
class. So if a .java file has more than one class then each class will compile into a
separate class files.
For Example: Save this below code as Test.java on your system.
class Sample
{
}
// Class Declaration--
class Student
{
}
// Class Declaration--
class Test
{
public static void main(String[] args)
{
System.out.println("Class File");
}
}
For Compiling:
After compilation there will be 3 class files in corresponding folder named as:
Sample.class
Student.class
Test.class
Answer: Java bytecode is the instruction set for the Java Virtual Machine. It acts
similar to an assembler which is an alias representation of a C++ code. As soon as a java
program is compiled, java bytecode is generated. In others words, java bytecode is the
machine code in the form of a .class file. With the help of java bytecode we achieve
platform independence in java.
Answer: In java, it is possible to define a class within another class, such classes are
known as nested classes. They enable you to logically group classes that are only used in
one place, thus this increases the use of encapsulation, and create more readable and
maintainable code.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the class in
which it is nested. However, reverse is not true i.e. the enclosing class does not have
access to the members of the nested class.
A nested class is also a member of its enclosing class.
As a member of its enclosing class, a nested class can be declared private, public,
protected, or package private(default).
Nested classes are divided into two categories:
static nested class : Nested classes that are declared static are called static nested
classes.
inner class : An inner class is a non-static nested class.
Syntax:
class OuterClass
{
...
class NestedClass
{
...
}
}
Answer: Stack is used for static memory allocation and Heap for dynamic memory
allocation, both stored in the computer's RAM.
The main difference between heap and stack is that stack memory is used to store local
variables and function call while heap memory is used to store objects in Java.
What is Stack Memory?
Stack in java is a section of memory which contains methods, local variables, and
reference variables. Stack memory is always referenced in Last-In-First-Out order. Local
variables are created in the stack.
What is Heap Memory?
Heap is a section of memory which contains Objects and may also contain reference
variables. Instance variables are created in the heap
The JVM divided the memory into following sections.
Heap
Stack
Code
Static
The code section contains your bytecode.
The Stack section of memory contains methods, local variables, and reference variables.
The Heap section contains Objects (may also contain reference variables).
The Static section contains Static data/methods.
Answer: Java program's main method has to be declared static because keyword static
allows main to be called without creating an object of the class in which the main
method is defined.
Answer: It is simply a value that indicates that the object reference is not currently
referring to an object. The null type has one value, the null reference, represented by the
null literal null, which is formed from ASCII characters. A null literal is always of the
null type.
Answer: Strings has its own feature that they are immutable. ... Primitive data types
has limitation that they have fixed size and can hold data of that type only but String can
vary in size and it can hold any type of data using its wrapper classes and it is one of
reason why STRING IS NON-PRIMITIVE data type.
Answer: The Just-In-Time (JIT) compiler is a an essential part of the JRE i.e. Java
Runtime Environment, that is responsible for performance optimization of java based
applications at run time. Compiler is one of the key aspects in deciding performance of
an application for both parties i.e. the end user and the application developer.
enum WeekDays
class Test
wk = WeekDays.sun; //wk can be assigned only the constants defined under enum type Weekdays
System.out.println("Today is "+wk);
Output:
Today is sun
Answer: In general both equals() and “==” operator in Java are used to compare
objects to check equality but here are some of the differences between the two:
• Main difference between .equals() method and == operator is that one is method and
other is operator.
• We can use == operators for reference comparison (address comparison) and .equals()
method for content comparison. In simple words, == checks if both objects point to the
same memory location whereas .equals() evaluates to the comparison of values in the
objects.
public class Test {
{
String s1 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
Output:
false
true
Answer: you can't create object of abstract class because there is an abstract method
which has nothing so you can call that abstract method too. If we will create an object of
the abstract class and calls the method having no body(as the method is pure virtual) it
will give an error.
29. What is up casting and down casting in Java? How will you use it in
Selenium with an example?
Answer:
31. Why java developer decided to keep object class as super most class in
java hierarchy.
32. What is the difference between instance variable and local variable?
33. To exit the system from the current execution what command is used in
java?
34. Difference between for and foreach loops in java and use of it?
Answer: The biggest differences are that a foreach loop processes an instance of each
element in a collection in turn, while a for loop can work with any data and is not
restricted to collection elements alone.
Answer: The break keyword is used to breaks(stopping) a loop execution, which may
be a for loop, while loop, do while or for each loop. The continue keyword is used to skip
the particular recursion only in a loop execution, which may be a for loop, while loop, do
while or for each loop.
class BreakAndContinue
{
public static void main(String args[])
{
// Example of break statement (execution stops when value of i becomes to 4.)
System.out.println("Break Statement\n....................");
for(int i=1;i<=5;i++)
if(i==4) break;
System.out.println(i);
}
// Example of continue statement (execution skipped when value of i becomes to 1.)
System.out.println("Continue Statement\n....................");
for(int i=1;i<=5;i++)
if(i==1) continue;
System.out.println(i);
}
}
Output:
Break Statement
....................
1
2
3
Continue Statement
....................
2
3
4
5
36. What is the difference between Call by Value and Call by Reference?
Answer: Call by Value means calling a method with a parameter as value. Through
this, the argument value is passed to the parameter.
Call By Value:
public class Tester{
int a = 30;
int b = 45;
swapFunction(a, b);
}
public static void swapFunction(int a, int b) {
// Swap n1 with n2
int c = a;
a = b;
b = c;
Output:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
Call By Reference:
public class JavaTester {
swapFunction(a, b);
}
public static void swapFunction(IntWrapper a, IntWrapper b) {
// Swap n1 with n2
a.a = b.a;
b.a = c.a;
class IntWrapper {
public int a;
Output:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30
Answer: Java uses managed memory, so the only way you can allocate memory is by
using the new operator, and the only way you can deallocate memory is by relying on the
garbage collector. ... You can also call System.gc() to suggest that the garbage collector
run immediately
Answer:
final:
final is used to apply restrictions on class, method and variable. Final class can't be
inherited, final method can't be overridden and final variable value can't be changed.
class FinalExample{
}}
finally:
Finally is used to place important code, it will be executed whether exception is handled
or not.
class FinallyExample{
try{
int x=300;
}catch(Exception e){System.out.println(e);}
}}
Output:
finally block is executed
finalize:
Finalize is used to perform clean up processing just before object is garbage collected.
class FinalizeExample{
f1=null;
f2=null;
System.gc();
}}
Output:
finalize called
finalize called
Answer: In java, string objects are immutable. Immutable simply means unmodifiable
or unchangeable.
Once string object is created its data or state can't be changed but a new string object is
created.
class Testimmutablestring{
String s="Virat";
}
}
Output:
Virat
44. Can we use private and protect access modifiers inside an Interface?
Answer: Interface members are always public because the purpose of an interface is to
enable other types to access a class or struct. No access modifiers can be applied to
interface members
45. What happens when we specify the final non-access modifier with
variables and methods in Java?
46. Can we have multiple public classes inside a single class in Java?
Answer: there can only be one public class per .java file, as public classes must have
the same name as the source file. One Java file can consist of multiple classes with the
restriction that only one of them can be public.
Answer: Main() is declared as static as it is directly call by the JVM without creating
an object of the class in which the it is declared. When java runtime starts,there is no
object of class present.Thats why main method has to be static,so JVM can load the class
into memory and call the main method.
Answer:
• Open a command prompt window and go to the directory where you saved the java
program (MyFirstJavaProgram.java). ...
• Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. ...
• Now, type ' java MyFirstJavaProgram ' to run your program.
• You will be able to see the result printed on the window.
Answer: Both plugins and dependencies are Jar files. But the difference between them
is, most of the work in maven is done using plugins; whereas dependency is just a Jar
file which will be added to the classpath while executing the tasks. For example, you use
a compiler-plugin to compile the java files.
51. How to assign different types of values say integer, character, string,
decimal and boolean into the same array?
Answer: we cannot store multiple datatype in an Array, we can store similar datatype
only in an Array. You can create an array with elements of different data types when
declare the array as Object. Since System.Object is the base class of all other types, an
item in an array of Objects can have a reference to any other type of object.
object[] mixedArray = new object[4];
mixedArray[0]=10;
mixedArray[1]="Jack";
mixedArray[2]=true;
mixedArray[3]=System.DateTime.Now;
In order to retrieve different data types from an Object array, you can convert an
element to the appropriate data type.
int id = int.Parse(mixedArray(0));
DateTime admissionDate = DateTime.Parse(mixedArray(3));
52. In public static void main(String arr[])… what if i replace public with
private
System.out.println("AutomationTestingInsider");
}
}
Output:
AutomationTestingInsider
Explanation:
1)public: It is an access specifier which allows the JVM(Java Virtual Machine) to access
the main method from anywhere.
2)static: static keyword allows the JVM to access the main method without any
instance(object).
3)void: It specifies that the main method doesn’t return anything.
4)main: name of the method(function) configured in JVM.
5)String args[]: Command line arguments.
Now, if we replace ‘public’ with ‘private’ in “public static void main”, the above code
becomes:
class ATI {
private static void main(String args[])
{
System.out.println("AutomationTestingInsider");
}
}
The above code will be compiled successfully, but will throw a runtime error as follows:
Error: Main method not found in class ATI, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application.