You are on page 1of 36

CORE JAVA

Questions and Answers

Compiled by: Deepak Bhagat


Fusion Functional Consultant,
Solution Architect & ADF Trainer
Core Java Questions and Answers

Table of Contents
1 Overview ................................................................................................................. 1
2 Operators .............................................................................................................. 14
3 Arrays ................................................................................................................... 15
4 Strings .................................................................................................................. 16
5 Encapsulation ........................................................................................................ 16
6 Inheritance ............................................................................................................ 17
7 Polymorphism ........................................................................................................ 17
8 Classes and Objects ............................................................................................... 18
9 Methods ................................................................................................................ 20
10 Abstract Classes .................................................................................................. 24
11 Interfaces ........................................................................................................... 24
12 Packages ............................................................................................................ 27
13 Wrapper Classes ................................................................................................. 27
14 Threads .............................................................................................................. 28
15 Collections .......................................................................................................... 30
16 Exception Handling ............................................................................................. 31
17 I/O Streams ........................................................................................................ 33

ADF Essentials Training by Deepak Bhagat


Core Java Questions and Answers

1 Overview
1. What is meant by Object Oriented Programming?
OOP is a method of programming in which programs are organized as cooperative collections of
objects. Each object is an instance of a class and each class belongs to a hierarchy.

2. What is the difference between procedural and object-oriented


programs?
In a procedural program, programming logic follows certain procedures and the instructions are
executed one after another. In the OOP program, a unit of program is an object, which is nothing
but a combination of data and code. b) In a procedural program, data is exposed to the whole
program whereas in the OOPs program, it is accessible within the object and which in turn assures
the security of the code.

3. What are the important features of the Java 8 release?


Java 8 has been one of the biggest release after Java 5 annotations and generics. Some of the
important features of Java 8 are:
Interface changes with the default and static methods
Functional interfaces and Lambda Expressions
Java Stream API for collection classes
Java Date Time API

4. What do you mean by platform independence?


Platform independence means that we can write and compile the java code in one platform (e.g.
Windows) and can execute the class in any other supported platform e.g. (Linux, Solaris, etc.).

5. How does Java achieve platform independence?


A Java source file on compilation produces an intermediary .class rather than an executable file.
This .class file is interpreted by the JVM. Since JVM acts as an intermediary layer.

6. What is Byte code?


Byte code is a set of instructions generated by the compiler. JVM executes the byte code.

7. What is a JVM?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

8. Is JVM's platform-independent?
JVM's are not platform-independent. JVM's are platform specific run time implementation provided
by the vendor.

9. What is the most important feature of Java?


Java is a platform-independent language.

10. What is the difference between a JDK and a JVM?


JDK is Java Development Kit which is for development purpose and it includes execution
environment also but JVM is purely a run time environment and hence you will not be able to
compile your source files using a JVM.
1/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

11. What is the difference between JVM and JRE?


Java Runtime Environment (JRE) is the implementation of JVM. JRE consists of JVM and java
binaries and other classes to execute any program successfully. JRE doesn’t contain any
development tools like java compiler, debugger, etc. If you want to execute any java program,
you should have JRE installed.

12. What is the use of bin and lib in JDK?


The bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and
all packages.

13. Java Compiler is stored in JDK, JRE or JVM?


The task of java compiler is to convert java program into bytecode, we have javac executable for
that. So it must be stored in JDK, we don’t need it in JRE and JVM is just the specs.

14. What is the difference between path and classpath variables?


PATH is an environment variable used by the operating system to locate the executables. That’s
why when we install Java or want any executable to be found by OS, we need to add the directory
location in the PATH variable. If you work on Windows OS, read this post to learn how to set up
the PATH variable on Windows.
Classpath is specific to Java and used by java executables to locate class files. We can
provide the classpath location while running java application and it can be a directory, ZIP
files, JAR file, etc.

15. How to run a JAR file through command prompt?


We can run a jar file using java command but it requires Main-Class entry in jar manifest file.
Main-Class is the entry point of the jar and used by java command to execute the class.

16. What is a pointer and does Java support pointers?


The pointer is a reference handle to a memory location. Improper handling of pointers leads to
memory leaks and reliability issues hence Java doesn't support the usage of pointers.

17. What are the good programming practices for better memory
management?
We shouldn't declare unwanted variables and objects.
We should avoid declaring variables or instantiating objects inside loops.
When an object is not required, its reference should be nullified.
We should minimize the usage of String objects and SOP.

18. What is meant by abstraction?


Abstraction defines the essential characteristics of an object that distinguish it from all other kinds
of objects. Abstraction provides crisply defined conceptual boundaries relative to the perspective
of the viewer. It’s the process of focusing on the essential characteristics of an object. Abstraction
is one of the fundamental elements of the object model.

19. What is meant by static binding?

2/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
Static binding is a binding in which the class association is made during compile time. This is also
called as Early binding.

20. What is meant by Dynamic binding?


Dynamic binding is a binding in which the class association is not made until the object is created
at execution time. It is also called as Late binding.

21. Explain the meaning of each keyword of public static void


main(String args[])?
public- main(..) is the first method called by java environment when a program is
executed so it has to accessible from java environment. Hence the access specifier has
to be public.
static: Java environment should be able to call this method without creating an
instance of the class, so this method must be declared as static.
void: main does not return anything so the return type must be void. The argument
String indicates the argument type which is given at the command line and arg is an
array for string given during the command line.

22. Is Java a pure object-oriented language?


Java is a pure object-oriented language. Except for the primitives, everything else is objects in
Java.

23. What is Garbage Collection and how to call it explicitly?


When an object is no longer referred to by any variable, java automatically reclaims memory used
by that object. This is known as garbage collection. System.gc() method may be used to call it
explicitly.

24. What is the purpose of garbage collection in Java, and when is it used?
The purpose of garbage collection is to identify and discard objects that are no longer needed by
a program so that their resources can be reclaimed and reused. A Java object is subject to garbage
collection when it becomes unreachable to the program in which it is used.

25. What are the two steps in the Garbage Collection?


Detection of garbage collectible objects and marking them for garbage collection.
Freeing the memory of objects marked for GC.

26. Does garbage collection guarantee that a program will not run out of
memory?
Garbage collection does not guarantee that a program will not run out of memory. Programs can
use up memory resources faster than they are garbage collected. It is also possible for programs
to create objects that are not subject to garbage collection

27. What is the difference between static and non-static variables?


Or
What are the class variables?
Or
3/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

What is static in java?


Or
What is a static method?
A static variable is associated with the class as a whole rather than with specific instances of a
class. Each object will share a common copy of the static variables i.e. there is only one copy per
class, no matter how many objects are created from it. Class variables or static variables are
declared with the static keyword in a class. These are declared outside a class and stored in static
memory. Class variables are mostly used for constants. Static variables are always called by the
class name. This variable is created when the program starts and gets destroyed when the
programs stop. The scope of the class variable is the same as an instance variable. Its initial value
is the same as an instance variable and gets a default value when it’s not initialized corresponding
to the data type. Similarly, a static method is a method that belongs to the class rather than any
object of the class and doesn’t apply to an object or even require that any objects of the class
have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and
static methods are attached to a class, not an object. A static method in a superclass can be
shadowed by another static method in a subclass, as long as the original method was not declared
final. However, you can’t override a static method with a non-static method. In other words, you
can’t change a static method into an
instance method in a subclass. Non-static variables take on unique values with each object
instance.

28. What is a transient variable?


A transient variable is a variable that may not be serialized.

29. To what value is a variable of the String type automatically initialized?


The default value of a String type is null.

30. What happens to a static variable that is defined within a method of a


class?
Can't do it. You'll get a compilation error.

31. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable
that is declared local to a method.

32. To what value is a variable of the boolean type automatically initialized?


The default value of the boolean type is false.

33. How to define a constant variable in Java?


The variable should be declared as static and final. So only one copy of the variable exists for all
instances of the class and the value can't be changed also. static final int PI = 2.14; is an example
for constant.

34. What is a default constructor?

4/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
The default constructor is a no-argument constructor that initializes the instance variables to their
default values. This will be provided by the compiler at the time of compilation. The default
constructor will be provided only when you don’t have any constructor defined.

35. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.

36. What is a destructor?


Destructor is an operation that frees the state of an object and/or destroys the object itself. In
Java, there is no concept of destructors. It’s taken care of by the JVM.

37. Does Java have destructors?


No garbage collector does the job working in the background

38. How is this() and super() used with constructors?


this() is used to invoke a constructor of the same class. super() is used to invoke a
superclass constructor.

39. What is constructor chaining and how is it achieved in Java?


A child object constructor always first needs to construct its parent (which in turn calls its parent
constructor). In Java, it is done via an implicit call to the no-args constructor as the first statement.

40. Explain “this” operator?


“this” is used to refer to the currently executing object and its state. “this” is also used for chaining
constructors and methods.

41. Explain about the “super” operator?


“super” is used to refer to the parent object of the currently running object. “super” is also to
invoke superclass methods and classes.

42. How to pass an argument to the main method?


You should pass the argument as a command-line argument. Command-line arguments are
separated by a space. The following is an example: java Hello Tom Jerry in the above command
line Hello is the class, Tom is the first argument
and Jerry is the second argument.

43. What is a Monitor?


A monitor is an object which contains some synchronized code in it.

44. What are the access modifiers?


Java provides access control through public, private and protected access modifier keywords.
When none of these are used, it’s called default access modifier. A java class can only have public
or default access modifier. Read Java Access Modifiers to learn more about these in detail.

45. State the significance of public, private, protected, default modifiers both
singly and in combination and state the effect of package relationships
on declared items qualified by these modifiers.
5/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

public: Public class is visible in other packages, the field is visible everywhere (class
must be public too)
private: Private variables or methods may be used only by an instance of the same
class that declares the variable or method, a private feature may only be accessed by
the class that owns the feature.
protected: Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature. This access is provided even
to subclasses that reside in a different package from the class that owns the protected
feature.
default: What you get by default i.e., without any access modifier (i.e., public private
or protected). It means that it is visible to all within a particular package.

46. What is the access scope of a protected method?


A protected method can be accessed by the classes within the same package or by the subclasses
of the class in any package.

47. What modifiers may be used with an inner class that is a member of an
outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

48. What is the static block?


Java static block is the group of statements that gets executed when the class is loaded into
memory by Java ClassLoader. It is used to initialize the static variables of the class. Mostly it’s
used to create static resources when class is loaded.

49. Want to print "Hello" even before the main is executed. How will you
achieve that?
Print the statement inside a static block of code. Static blocks get executed when the class gets
loaded into the memory and even before the creation of an object. Hence it will be executed
before the main method.

50. What if I write static public void instead of the public static void?
The program compiles and runs properly.

51. What is the difference between a while statement and a do statement?


A while statement checks at the beginning of a loop to see whether the next loop iteration should
occur. A do statement checks at the end of a loop to see whether the next iteration of a loop
should occur. The do statement will always execute the body of a loop at least once.

52. What is the difference between a break statement and a continue


statement?
A break statement results in the termination of the statement to which it applies (switch, for, do,
or while). A continue statement is used to end the current loop iteration and return control to the
loop statement.

53. Can a for statement loop indefinitely?

6/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
Yes, for statement can loop indefinitely. For example, consider the following: for(;;);

54. What is the difference between an if statement and a switch statement?


If the statement is used to select among two alternatives. It uses a boolean expression to decide
which alternative should be executed. The switch statement is used to select among multiple
alternatives. It uses an int expression to determine which alternative should be executed. This will
now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using
fully qualified class names.

55. What restrictions are placed on the values of each case of a switch
statement?
During compilation, the values of each case of a switch statement must evaluate to a value that
can be promoted to an int value.

56. Is Empty .java file a valid source file?


Yes, an empty .java file is a perfectly valid source file.

57. Is ‘main’ a keyword in Java?


No, ‘main’ is not a keyword in Java.

58. Is sizeof a keyword?


The sizeof operator is not a keyword.

59. Are true and false keywords?


The values true and false are not keywords.

60. What happens if you don’t initialize an instance variable of any of the
primitive types in Java?
Java by default initializes it to the default value for that primitive type. Thus an int will be initialized
to 0, a boolean will be initialized to false.

61. What will be the initial value of an object reference which is defined as
an instance variable?
The object references are all initialized to null in Java. However, to do anything useful with these
references, you must set them to a valid object, else you will get NullPointerExceptions everywhere
you try to use such default initialized references.

62. What are the different scopes for Java variables?


The scope of a Java variable is determined by the context in which the variable is declared. Thus
a java variable can have one of the three scopes at any given point in time.
Instance: - These are typical object level variables, they are initialized to default
values at the time of the creation of an object, and remain accessible as long as the
object is accessible.
Local: - These are the variables that are defined within a method. They remain
accessible only during the course of method execution. When the method finishes
execution, these variables fall out of scope.

7/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

Static: - These are the class level variables. They are initialized when the class is
loaded in JVM for the first time and remain there as long as the class remains loaded.
They are not tied to any particular object instance.

63. What is the difference between Assignment and Initialization?


The assignment can be done as many times as desired whereas initialization can be done only
once.

64. How many ways can an argument be passed to a subroutine? Explain.


An argument can be passed in two ways. They are passing by value and passing by reference.
Passing by value: This method copies the value of an argument into the formal parameter of the
subroutine. Passing by reference: In this method, a reference to an argument (not the value of
the argument) is passed to the parameter.

65. If I do not provide any arguments on the command line, then the String
array of the main method will be empty or null?
It is empty. But not null.

66. What is the difference between an argument and a parameter?


While defining method, variables passed in the method are called parameters. While using those
methods, values passed to those variables are called arguments.

67. What will be the output of the following statement? System.out.println


("1" + 3);
It will print 13.

68. What is UNICODE?


Unicode is used for internal representation of characters and strings and it uses 16 bits to represent
each other.

69. What are Transient and Volatile Modifiers?


Transient: The transient modifier applies to variables only and it is not stored as part of its object’s
Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to
variables only and it tells the compiler that the variable modified by volatile can be changed
unexpectedly by other parts of the program.

70. What does the super keyword do?


the super keyword can be used to access super class method when you have overridden the
method in the child class.
We can use the super keyword to invoke super class constructor in child class constructor
but in this case, it should be the first statement in the constructor method.
SuperClass.java
package com.journaldev.access;
public class SuperClass {
public SuperClass(){
}
public SuperClass(int i){}
8/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
public void test(){
System.out.println("super class test method");
}
}
The use of super keyword can be seen in below child class implementation.
ChildClass.java
package com.journaldev.access;
public class ChildClass extends SuperClass {
public ChildClass(String str){
//access super class constructor with super keyword
super();
//access child class method
test();
//use super to access super class method
super.test();
}
@Override
public void test(){
System.out.println("child class test method");
}
}

71. What type of parameter passing does Java support?


Java supports both pass by value as well as pass by reference.

72. What is the difference between this() and super()?


this() can be used to invoke a constructor of the same class whereas super() can be used to invoke
a super class constructor.

73. What is the first argument of the String array in the main method?
The String array is empty. It does not have any element. This is unlike C/C++ where
the first element by default is the program name.

74. What environment variables do I need to set on my machine to be able


to run Java programs?
CLASSPATH and PATH are the two variables.

75. What is the difference between declaring a variable and defining a


variable?
Ina declaration, we just mention the type of the variable and its name. We do not initialize it. But
defining means declaration + initialization. e.g. String s; is just a declaration while String s = new
String ("abcd"); Or String s = "abcd"; are both definitions.

76. What is the default value of an object reference declared as an instance


variable?
Null unless we define it explicitly.

9/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

77. Primitive data types are passed by reference or pass by value?


Primitive data types are passed by value.

78. What happens to the static fields of a class during serialization? Are
these fields serialized as a part of each serialized object?
Yes, the static fields do get serialized. If the static field is an object, then it must have implemented
a Serializable interface. The static fields are serialized as a part of every object. But the
commonness of the static fields across all the instances is maintained even after serialization.

79. Objects are passed by value or by reference?


Objects are always passed by reference. Thus any modifications done to an object inside the called
method will always reflect in the caller method.

80. Does Java provide any construct to find out the size of an object?
No there is no sizeof operator in Java. So there is not a direct way to determine the size of an
object directly in Java.

81. What is pass by reference and pass by value?


Pass by Reference means the passing the address itself rather than passing the value. Pass by
Value means passing a copy of the value to be passed.

82. Does Java have "goto"?


No

83. Are there any global variables in Java, which can be accessed by another
part of your program?
No, it is not the main method in which you define variables. Global variables are not possible
because the concept of encapsulation is eliminated here.

84. What is the ResourceBundle class?


The ResourceBundle class is used to store locale-specific resources that can be loaded by a
program to tailor the program's appearance to the particular locale in which it is being run.

85. What does the "abstract" keyword mean in front of a method? A class?
Abstract keyword declares either a method or a class. If a method has an abstract keyword in
front of it, it is called an abstract method. An abstract method has no body. It has only arguments
and return type. Abstract methods act as placeholder methods that are implemented in the
subclasses. Abstract classes can't be instantiated. If a class is declared as abstract, no objects of
that class can be created. If a class contains an abstract method, it must be declared as abstract.

86. What is the static keyword?


Static keyword can be used with class-level variables to make it global i.e. all the objects will share
the same variable.
static keyword can be used with methods also. A static method can access only static variables of
class and invoke only static methods of the class.

87. What is the final keyword?


10/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
the final keyword is used with Class to make sure no other class can extend it, for example, String
class is final and we can’t extend it. We can use the final keyword with methods to make sure
child classes can’t override it. final keyword can be used with variables to make sure that it can
be assigned only once.
However, the state of the variable can be changed, for example, we can assign a final variable to
an object only once but the object variables can change later on. Java interface variables are by
default final and static.

88. What is the purpose of declaring a variable as final?


A final variable's value can't be changed. final variables should be initialized before using them.

89. Can you give a few examples of final classes defined in Java API?
java.lang.String, java.lang.Math is the final classes.

90. Which non-Unicode letter characters may be used as the first character
of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier

91. What is casting?


Casting is used to convert the value of one type to another. There are two types of casting, casting
between primitive numeric types and casting between object references. Casting between numeric
types is used to convert larger values, such as double values, to smaller values, such as byte
values. Casting between object references is used to refer to an object by a compatible class,
interface, or array type reference.

92. What is Downcasting?


Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy

93. What is the return type of a program's main() method?


Void.

94. If a variable is declared as private, where may the variable be accessed?


A private variable may only be accessed within the class in which it is declared.

95. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-
8 characters?
Unicode requires 16 bits and ASCII requires 7 bits Although the ASCII character set uses only 7
bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18-bit
patterns. UTF-16 uses 16-bit and larger bit patterns.

96. What is the order of precedence and associativity, and how are they
used?
Order of precedence determines the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-to-right or right-to-left.

97. Can an anonymous class be declared as implementing an interface and


extending a class?
11/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
An anonymous class may implement an interface or extend a superclass, but may not be declared
to do both.

98. What is the range of the char type?


The range of the char type is 0 to 216 - 1 (i.e. 0 to 65535.)

99. What is the range of the short type?


The range of the short type is -(215) to 215 - 1. (i.e. -32,768 to 32,767)

100. Why isn't there operator overloading?


Because C++ has proven by example that operator overloading makes code almost impossible to
maintain.

101. How is rounding performed under the integer division?


The fractional part of the result is truncated. This is known as rounding toward zero.

102. What does it mean that a method or field is "static"?


Static variables and methods are instantiated only once per class. In other words, they are class
variables, not instance variables. If you change the value of a static variable in a particular object,
the value of that variable changes for all instances of that class. Static methods can be referenced
with the name of the class rather than the name of a particular object of the class (though that
works too). That's how library methods like System.out.println() work. out is a static field
in the java.lang.System class.

103. Which characters may be used as the second character of an identifier,


but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used
after the first character of an identifier.

104. If a class is declared without any access modifiers, where may the class
be accessed?
A class that is declared without any access modifiers is said to have package access. This means
that the class can only be accessed by other classes and interfaces that are defined within the
same package.

105. Name the eight primitive Java types.


The eight primitive types are a byte, char, short, int, long, float, double, and boolean.

106. What modifiers can be used with a local inner class?


A local inner class may be final or abstract.

107. What happens when you add a double value to a String?


A result is a String object.

108. What is the numeric promotion?


Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that
integer and floating-point operations may take place. In numerical promotion, byte, char, and
12/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
short values are converted to int values. The int values are also converted to long values, if
necessary. The long and float values are converted to double values, as required.

109. How many static initializers can you have?


As many as you want, but the static initializers and class variable initializers are executed in textual
order and may not refer to class variables declared in the class whose declarations appear textually
after the use, even though these class variables are in scope.

110. Can a double value be cast to a byte?


Yes, a double value can be cast to a byte.

111. How does Java handle integer overflows and underflows?


It uses those low order bytes of the result that can fit into the size of the type allowed by the
operation.

112. What is this keyword?


this keyword provides a reference to the current object and it’s mostly used to make sure that
object variables are used, not the local variables having the same name.
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
We can also use this keyword to invoke other constructors from a constructor.
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

113. What is Enum in Java?


Enum was introduced in Java 1.5 as a new type whose fields consist of a fixed set of constants.
For example, in Java, we can create Direction as an enum with fixed fields as EAST, WEST, NORTH,
SOUTH.
enum is the keyword to create an enum type and similar to a class. Enum constants are implicitly
static and final. Read more in detail at java enum.

114. What are Java Annotations?


Java Annotations provide information about the code and they have no direct effect on the code
they annotate. Annotations are introduced in Java 5. Annotation is metadata about the program
embedded in the program itself. It can be parsed by the annotation parsing tool or by the compiler.
13/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
We can also specify annotation availability to either compile time only or till runtime also. Java
Built-in annotations are @Override, @Deprecated and @SuppressWarnings.

115. What is a composition in java?


The composition is the design technique to implement a has-a relationship in classes. We can use
Object composition for code reuse.
Java composition is achieved by using instance variables that refer to other objects. The benefit
of using composition is that we can control the visibility of another object to client classes and
reuse only what we need.

116. What is Classloader in Java?


Java Classloader is the program that loads the byte code program into memory when we want to
access any class. We can create our classloader by extending the ClassLoader class and overriding
loadClass(String name) method. Learn more at java classloader.

117. What are the different types of classloaders?


There are three types of built-in Class Loaders in Java:
Bootstrap Class Loader – It loads JDK internal classes, typically loads rt.jar and other
core classes.
Extensions Class Loader – It loads classes from the JDK extensions directory, usually
$JAVA_HOME/lib/ext directory.
System Class Loader – It loads classes from the current classpath that can be set while
invoking a program using -cp or -classpath command line options.

118. What is the difference between Heap and Stack Memory?


The major difference between Heap and Stack memory are as follows:
Heap memory is used by all the parts of the application whereas stack memory is used
only by one thread of execution.
Whenever an object is created, it’s always stored in the Heap space and stack memory contains
the reference to it. Stack memory only contains local primitive variables and reference variables
to objects in heap space.
Memory management in the stack is done in a LIFO manner whereas it’s more complex in Heap
memory because it’s used globally.

2 Operators
119. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first
operand by the second operand.

120. What are the legal operands of the instanceof operator?


The left operand is an object reference or null value and the right operand is a class, interface or
array type.

121. What is the difference between the prefix and postfix forms of the ++
operator?

14/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
The prefix form performs the increment operation and returns the value of the increment
operation. The postfix form returns the current value all of the expression and then performs the
increment operation on that value.

122. What is the difference between the Boolean & operator and the &&
operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated.
Then the & operator is applied to the operand. When an expression involving the && operator is
evaluated, the first operand is evaluated. If the first operand returns a value of true, then the
second operand is evaluated. The && operator is then applied to the first and second operands.
If the first operand evaluates to false, the evaluation of the second operand is skipped.

123. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been
shifted out.

124. What is a ternary operator in java?


Java ternary operator is the only conditional operator that takes three operands. It’s a one liner
replacement for if-then-else statement and used a lot in java programming. We can use ternary
operator if-else conditions or even switch conditions using nested ternary operators.
Syntax of java ternary operator is: result = testStatement ? value1 : value2;
For example:
log.info( "Object foo is " + ( foo.isEnabled() ? "" : "not
" ) + "enabled" );
To me, that's a lot neater than either
if ( foo.isEnabled() )
log.info( "Foo is enabled" );
else
log.info( "Foo is not enabled" );

125. Which Java operator is right associative?


The = operator is right associative.

126. Is the ternary operator written x : y ? z or x ? y : z ?


It is written x ? y : z.

3 Arrays
127. What will be the default values of all the elements of an array defined as
an instance variable?
If the array is an array of primitive types, then all the elements of the array will be initialized to
the default value corresponding to that primitive type. e.g. All the elements of an array of int will
be initialized to 0, while that of boolean type will be initialized to false. Whereas if the array is
an array of references (of any type), all the elements will be initialized to null.

128. How can one prove that the array is not null but empty?
Print args.length. It will print 0. That means it is empty. But if it would have been null
15/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

then it would have thrown a NullPointerException on attempting to print


args.length.

129. Are arrays primitive data types?


In Java, Arrays are objects.

4 Strings
130. What is the importance of == and equals() method concerning String
object?
”== “is used to check whether the references are of the same object. equals() is used to check
whether the contents of the objects are the same. But for strings, object reference with the same
content will refer to the same object.
String str1="Hello";
String str2="Hello";
(str1==str2) and str1.equals(str2) both will be true.
If you take the same example with Stringbuffer, the results would be different.
Stringbuffer str1="Hello";
Stringbuffer str2="Hello";
str1.equals(str2)will be true.
str1==str2 will be false.

131. What will Math.abs() do?


It simply returns the absolute value of the value supplied to the method, i.e. gives you the same
value. If you supply negative value it simply removes the sign.

132. What will Math.ceil() do?


The method returns always double, which is not less than the supplied value. It returns the next
available whole number.

133. What will Math.floor() do?


The method returns always double, which is not greater than the supplied value.

134. What will Math.max() do?


The method returns greater value out of the supplied values.

135. What will Math.min() do?


The min() method returns a smaller value out of the supplied values.

5 Encapsulation
136. What is meant by Encapsulation?
Encapsulation is the process of compartmentalizing the elements of an abstraction that defines
the structure and behavior. Encapsulation helps to separate the contractual interface of an
abstraction and implementation.

16/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

6 Inheritance
137. What modifiers may be used with top-level class?
public, abstract and final can be used for top-level class.

138. What is meant by Inheritance?


Inheritance is a relationship among classes, wherein one class shares the structure or behavior
defined in another class. This is called Single Inheritance. If a class shares the structure or behavior
from multiple classes, then it is called Multiple Inheritance. Inheritance defines "is-a" hierarchy
among classes in which one subclass inherits from one or more generalized super classes.

139. Why Java doesn't support multiple inheritance?


When a class inherits from more than class, it will lead to the diamond problem - say A is the
super class of B and C & D is a subclass of both B and C. D inherits properties of A from two
different inheritance paths i.e., via both B & C. This leads to ambiguity and related problems, so
multiple inheritance is not allowed in Java.

140. What is the difference between superclass and subclass?


A super class is a class that is inherited whereas subclass is a class that does the inheriting.

141. Can you write Java code for declaration of multiple inheritance in Java?
Class C extends A implements B

142. I don't want my class to be inherited by any other class. What should I
do?
You should declare your class as final. But you can't define your class as final if it is an abstract
class. A class declared as final can't be extended by any other class.

143. Are constructors inherited? Can a subclass call the parent's class
constructor? When?
You cannot inherit a constructor. That is, you cannot create an instance of a subclass using a
constructor of one of its super classes. One of the main reasons is because you probably don't
want to override the super classes constructor, which would be possible if they were inherited. By
giving the developer the ability to override a super classes constructor you would erode the
encapsulation abilities of the language.

144. Does a class inherit the constructors of its superclass?


A class does not inherit constructors from any of its super classes.

7 Polymorphism
145. What is meant by Polymorphism?
Polymorphism means taking more than one form. Polymorphism is a characteristic of being able
to assign a different behavior or value in a subclass, to something that was declared in a parent
class.

146. Which Object Oriented Concept is achieved by using overloading and


overriding?
17/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
Polymorphism.

147. Why does Java not support operator overloading?


Operator overloading makes the code very difficult to read and maintain. To maintain code
simplicity, Java doesn't support operator overloading.

148. What restrictions are placed on method overloading?


Two methods may not have the same name and argument list but different return types.

149. Can a method be overloaded based on different return type but the same
argument type?
No, because the methods can be called without using their return type in which case there is
ambiguity for the compiler.

150. If a method is declared as protected, where may the method be


accessed?
A protected method may only be accessed by classes or interfaces of the same package or by
subclasses of the class in which it is declared.

8 Classes and Objects


151. What is a Class?
Class is a template for a set of objects that share a common structure and common behavior.

152. What is an Object?


The object is an instance of a class. It has state, behavior, and identity. It is also called as an
instance of a class.

153. What is the Instance?


An instance has state, behavior, and identity. The structure and behavior of similar classes are
defined in their common class. An instance is also called an object.

154. What is the base class or super class of all classes?


java.lang.The object is the root class for all the java classes and doesn’t need to extend it

155. What is the use of System class?


Java System Class is one of the core classes. One of the easiest ways to log information for
debugging is System.out.print() method.
System class is final so that we can’t subclass and override its behavior through inheritance.
System class doesn’t provide any public constructors, so we can’t instantiate this class and that’s
why all of its methods are static.
Some of the utility methods of System class are for array copy, get the current time, reading
environment variables. Read more at Java System Class.

156. Can a class be declared as protected?


A class can't be declared as protected. only methods can be declared as protected.

18/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

157. What interface must an object implement before it can be written to a


stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a
stream as an object.

158. Can we have multiple public classes in a java source file?


We can’t have more than one public class in a single java source file. A single source file can have
multiple classes that are not public.

159. Can a Class extend more than one Class?


Not possible. A Class can extend only one class but can implement any number of Interfaces.

160. Why is an Interface be able to extend more than one Interface but a Class
can't extend more than one Class?
Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an
Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes (do
remember that the base class of all classes is Object). So an Interface is allowed to extend more
than one Interface.

161. What is an inner class in java?


We can define a class inside a class and they are called nested classes. Any non-static nested class
is known as an inner class. Inner classes are associated with the object of the class and they can
access all the variables and methods of the outer class. Since inner classes are associated with
the instance, we can’t have any static variables in them.
We can have a local inner class or anonymous inner class inside a class.

162. Can a Byte object be cast to a double value?


No, an object cannot be cast to a primitive value.

163. What is an object's lock and which objects have locks?


An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to
the object. A thread may execute a synchronized method of an object only after it has acquired
the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class
object.

164. When can an object reference be cast to an interface reference?


An object reference is cast to an interface reference when the object implements the referenced
interface.

165. Which class is extended by all other classes?


The Object class is extended by all other classes.

166. Can a source file contain more than one class declaration?
Yes, a single source file can contain any number of Class declarations but only one of the class
can be declared as public.

167. Can a class be declared as static?


19/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
No, the class cannot be defined as static. Only a method, a variable or a block of code can be
declared as static.

168. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class's
outer class. A static inner class does not have any object instances

169. What is the difference between the inner class and the nested class?
When a class is defined within the scope of another class, then it becomes an inner class. If the
access modifier of the inner class is static, then it becomes a nested class.

170. What is the difference between a public and a non-public class?


A public class may be accessed outside of its package. A non-public class may not be accessed
outside of its package.

171. What are the inner class and anonymous class?


Inner class: classes defined in other classes, including those defined in methods are
called inner classes. An inner class can have any accessibility including private.
Anonymous class: Anonymous class is a class defined inside a method without a
name and is instantiated and declared in the same place and cannot have explicit
constructors.

172. What are the different types of inner classes?


Nested top-level classes, Member classes, Local classes, Anonymous Classes
Nested top-level classes- If you declare a class within a class and specify the static
modifier, the compiler treats the class just like any other top-level class. Any class
outside the declaring class accesses the nested class with the declaring class name
acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly
have access only to static variables. There can also be inner interfaces. All of these are
of the nested top-level variety.
Member classes - Member inner classes are just like other member methods and
member variables and access to the member class is restricted, just like methods and
variables. This means a public member class acts similarly to a nested top-level class.
The primary difference between member classes and nested top-level classes is that
member classes have access to the specific instance of the enclosing class.
Local classes - Local classes are like local variables, specific to a block of code. Their
visibility is only within the block of their declaration. For the class to be useful beyond
the declaration block, it would need to implement a more publicly available interface.
Because local classes are not members, the modifiers public, protected, private, and
static are not usable.
Anonymous classes - Anonymous inner classes extend local inner classes one level
further. As anonymous classes have no name, you cannot provide a constructor.

9 Methods
173. What is the importance of the main method in Java?
20/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
The main() method is the entry point of any standalone java application. The syntax of the main
method is public static void main(String args[]). The main method is public and static so
that java can access it without initializing the class. The input parameter is an array of String
through which we can pass runtime arguments to the java program. Check this post to learn how
to compile and run a java program.

174. What is the difference between a constructor and a method?


A constructor is a member function of a class that is used to create objects of that class. It has
the same name as the class itself, has no return type, and is invoked using the new operator. A
method is an ordinary member function of a class. It has its name, a return type (which may be
void), and is invoked using the dot operator.

175. What is the purpose of declaring a variable as final?


A final variable's value can't be changed. final variables should be initialized before using them.

176. Can a final variable be declared inside a method?


No. Local variables cannot be declared as final.

177. What is the impact of declaring a method as final?


A method declared as final can't be overridden. A sub-class doesn't have the independence to
provide different implementation to the method.

178. What are methods and how are they defined?


Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes. Method
definition has four parts. They are the name of the method, type of object or primitive type the
method returns, a list of parameters and the body of the method. method’s signature is a
combination of the first three parts mentioned above.

179. What is method overloading and method overriding?


Method overloading: When a method in a class having the same method name with
different arguments is said to be method overloading.
Method overriding: When a method in a class having the same method name with
the same arguments is said to be method overriding.

180. What if the main method is declared as private?


The program compiles properly but at runtime, it will give "Main method not public." message.

181. What if the static modifier is removed from the signature of the main
method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

182. What restrictions are placed on method overloading?


Two methods may not have the same name and argument list but different return types.

183. What do you mean by virtual methods?

21/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
Virtual methods are used to use the polymorphism feature in C++. Say class A is inherited from
class B. If we declare say function f() as virtual in class B and override the same function in
class A then at runtime appropriate method of the class will be called depending upon the type of
the object.

184. Can you have an inner class inside a method and what variables can you
access?
Yes, we can have an inner class inside a method and final variables can be accessed.

185. What restrictions are placed on method overriding?


Overridden methods must have the same name, argument list, and return type. The overriding
method may not limit the access of the method it overrides. The overriding method may not throw
any exceptions that may not be thrown by the overridden method.

186. What if I do not provide the String array as the argument to the method?
Program compiles but throws a runtime error "NoSuchMethodError".

187. Should a main() method be compulsorily declared in all java classes?


No not required. main() method should be defined only if the source class is a java application.

188. What is the return type of the main() method?


Main() method doesn't return anything hence declared void.

189. Why is the main() method declared static?


main() method is called by the JVM even before the instantiation of the class hence it is declared
as static.

190. What is the argument of main() method?


main() method accepts an array of String object as an argument.

191. Can a main() method be declared final?


Yes. Any inheriting class will not be able to have its own default main() method.

192. Can a main() method be overloaded?


Yes. You can have any number of main() methods with different method signature and
implementation in the class.

193. Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main().

194. When will you define a method as static?


When a method needs to be accessed even before the creation of the object of the class then we
should declare the method as static.

195. What is the restriction imposed on a static method or a static block of


code?
22/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
A static method should not refer to instance variables without creating an instance and cannot
use "this" operator to refer to the instance.

196. Can we declare a static variable inside a method?


Static variables are class level variables and they can't be declared inside a method. If declared,
the class will not compile.

197. What is a native method?


A native method is a method that is implemented in a language other than Java.

198. What will be the output of the following programs?


static method in class
package com.journaldev.util;
public class Test {
public static String toString(){
System.out.println("Test toString called");
return "";
}
}
public static void main(String args[]){
System.out.println(toString());
}
}
The code won’t compile because we can’t have an Object class method with the static keyword.
You will get compile time error as “This static method cannot hide the instance method from
Object”. The reason is that static method belongs to the class and since every class base is Object,
we can’t have the same method in an instance as well as in class.
static method invocation
package com.journaldev.util;
public class Test {
public static String foo(){
System.out.println("Test foo called");
return "";
}
public static void main(String args[]){
Test obj = null;
System.out.println(obj.foo());
}
}
}
Well, this is a strange situation. We all have seen NullPointerException when we invoke a method
on an object that is NULL. The compiler will give warning as “The static method foo() from the
type Test should be accessed in a static way” but when executing it will work and prints “Test foo
called”.
Ideally, Java API should have given an error when a static method is called from an object rather
than giving warning, but I think it’s too late now to impose this. And most strange of all is that
even though obj is null here when invoking a static method, it works fine. I think it’s working fine

23/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
because Java runtime figures out that foo() is a static method and calls it on the class loaded
into the memory and doesn’t use the object at all, so no NullPointerException.

10 Abstract Classes
199. What is an Abstract Class?
An abstract class is a class that has no instances. An abstract class is written with the expectation
that its concrete subclasses will add to its structure and behavior, typically by implementing its
abstract operations.

200. Can an abstract class be declared final?


Not possible. An abstract class without being inherited is of no use and a final class cannot be
inherited. So if an abstract class is declared as final, it will result in compile time error.

201. Can you create an object of an abstract class?


Not possible. Abstract classes can't be instantiated.

202. Can an abstract class be defined without any abstract methods?


Yes, it's possible. This is basically to avoid instance creation of the class.

203. What is the use of an abstract variable?


Variables can't be declared as abstract. only classes and methods can be declared as abstract.

204. What does it mean that a method or class is abstract?


An abstract class cannot be instantiated. Abstract methods may only be included in abstract
classes. However, an abstract class is not required to have any abstract methods, though most of
them do. Each subclass of an abstract class must override the abstract methods of its super classes
or it also should be declared abstract.

11 Interfaces
205. What is an Interface?
Java does not allow multiple inheritance for classes (i.e. a subclass being the extension of more
than one superclass). To tie elements of different classes together Java uses an interface.
Interfaces are similar to abstract classes but all methods are abstract and all properties are static
final. As an example, we will build a Working interface for the subclasses of Animal. Since this
interface has the method called work(), that method must be defined in any class using the
Working interface.
public interface Working
{
public void work();
}
When you create a class that uses an interface, you reference the interface with the reserved
word implements Interface_list. Interface_list is one or more interfaces as multiple interfaces are
allowed. Any class that implements an interface must include code for all methods in the interface.
This ensures commonality between interfaced objects.
public class WorkingDog extends Dog implements Working

24/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
{
public WorkingDog(String nm)
{
super(nm); // builds ala parent
}
public void work() // this method specific to WorkingDog
{
speak();
System.out.println("I can herd sheep and cows");
}
}
Interfaces can be inherited (i.e. you can have a sub-interface). As with classes, the extends
keyword is used. Multiple inheritance can be used with interfaces.

206. Why is an Interface be able to extend more than one Interface but a Class
can't extend more than one Class?
Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an
Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes (do
remember that the base class of all classes is Object). So an Interface is allowed to extend more
than one Interface.

207. What is the difference between an Interface and an Abstract class?


An abstract class can have instance methods that implement a default behavior. An Interface can
only declare constants and instance methods, but cannot implement default behavior and all
methods are implicitly abstract. An interface has all public members and no implementation. An
abstract class is a class which may have the usual flavors of class members (private, protected,
etc.), but has some abstract methods.

208. Explain Iterator Interface.


An Iterator is similar to the Enumeration interface. With the Iterator interface methods, you can
traverse a collection from start to end and safely remove elements from the underlying Collection.
The iterator() method generally used in query operations.
Basic methods:
iterator.remove();
iterator.hasNext();
iterator.next();

209. Explain Enumeration Interface.


The Enumeration interface allows you to iterate through all the elements of a collection. Iterating
through an Enumeration is similar to iterating through an Iterator. However, there is no removal
support with Enumeration.
Basic methods:
boolean hasMoreElements();
Object nextElement();

210. What is the difference between Enumeration and Iterator interface?

25/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
The Enumeration interface allows you to iterate through all the elements of a collection. Iterating
through an Enumeration is similar to iterating through an Iterator. However, there is no removal
support with Enumeration.

211. Why do you create interfaces, and when MUST you use one?
You would create interfaces when you have two or more functionalities talking to each other.
Doing it this way helps you in creating a protocol between the parties involved.

212. What is Marker interface?


A marker interface is an empty interface without any method but used to force some functionality
in implementing classes by Java. Some of the well-known marker interfaces are Serializable and
Cloneable.

213. Class C implements Interface I containing method m1 and m2


declarations. Class C has provided the implementation for method m2.
Can I create an object of Class C?
No not possible. Class C should provide an implementation for all the methods in the Interface I.
Since Class C didn't provide the implementation for the m1 method, it has to be declared as
abstract. Abstract classes can't be instantiated.

214. Can an Interface implement another Interface?


Interfaces don't provide implementation hence an interface cannot implement another interface.

215. Can an Interface be final?


Not possible. Doing so will result in a compilation error.

216. Can an Interface extend another Interface?


Yes, an Interface can inherit another Interface, for that matter, an Interface can extend more
than one Interface.

217. Can a class be defined inside an Interface?


Yes, it's possible.

218. Can an Interface be defined inside a class?


Yes, it's possible.

219. What modifiers are allowed for methods in an Interface?


Only public and abstract modifiers are allowed for methods in interfaces.

220. What is a cloneable interface and how many methods does it contain?
It is not having any method because it is a TAGGED or MARKER interface.

221. Can a method inside an Interface be declared as final?


No not possible. Doing so will result in a compilation error. public and abstract are the only
applicable modifiers for method declaration in an interface.

222. Are there any other 'marker' interfaces?


26/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
java.rmi.Remote
java.util.EventListener

223. Can we define private and protected modifiers for variables in interfaces?
No.

12 Packages
224. What is a package?
The package is a collection of related classes and interfaces. The package declaration should be
the first statement in a java class.

225. What is the impact using a * during importing (for example import
java.io.*;?
When a * is used in an import statement, it indicates that the classes used in the current source
can be available in the imported package. Using slightly increases the compilation time but has no
impact on the execution time.

226. What is meant by default access?


default access means the class, method, constructor or the variable can be accessed only within
the package.

227. What is a reflection package?


java. lang. reflect package can analyze itself in runtime.

228. Does importing a package imports the subpackages as well? e.g. Does
importing com.MyTest.* also import com.MyTest.UnitTests.*?
No, you will have to import the subpackages explicitly. Importing com.MyTest.* will import
classes in the package MyTest only. It will not import any class in any of its subpackage.

229. Which package is imported by default?


java.lang package is imported by default even without a package declaration.

230. What restrictions are placed on the location of a package statement


within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and
comments).

231. Can a class declare as private be accessed outside its a package?


Not possible.

13 Wrapper Classes
232. What are the Wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types. These are
called wrapper classes. They are e.g. Integer, Character, Double, etc.

27/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

233. What is the difference between Integer and int?


An integer is a class defined in the java. lang package, whereas int is a primitive data
type defined in the Java language itself. Java does not automatically convert from one
to the other.
Integer can be used as an argument for a method that requires an object, whereas int
can be used for calculations.

14 Threads
234. Describe synchronization concerning multithreading.
For multithreading, synchronization is the capability to control the access of multiple threads to
shared resources. Without synchronization, one thread can modify a shared variable while another
thread is in the process of using or updating the same shared variable. This usually leads to
significant errors.

235. Explain the different ways of using thread?


The thread could be implemented by using a runnable interface or by inheriting from the Thread
class. The former is more advantageous, because when you are going for multiple inheritance.
the only interface can help.

236. What is Thread Priority?


Priority is thread ranking. Some threads can either run for a longer Time slice or run more often
(depending on the operating system). Peers (or equals) get the same time/number of runs. Higher
priority threads interrupt lower priority ones. Priority is set from constants MIN_PRIORITY
(currently 1) to MAX_PRIORITY (currently 10) using the setPriority(int) method.
NORM_PRIORITY is the midrange value (currently 5). These are defined in the Thread class.

237. What are the two ways to create a new thread?


Extend the Thread class and override the run() method.
Implement the Runnable interface and implement the run() method.

238. What is the difference between sleep() and yield()?


When a Thread calls the sleep() method, it will return to its waiting state. When a Thread calls
the yield() method, it returns to the ready state.

239. What is a Daemon Thread?


Daemon is a low priority thread that runs in the background.

240. What does the start() method of Thread do?


The thread's start() method puts the thread in ready state and makes the thread eligible to run.
start() method automatically calls the run () method.

241. What is Synchronization?


For multithreading, synchronization is the capability to control the access of multiple threads to
shared resources. Without synchronization, one thread can modify a shared object while another

28/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
thread is in the process of using or updating that object's value. This often leads to significant
errors.

242. What are synchronized methods and synchronized statements?


Synchronized methods are methods that are used to control access to an object. A thread only
executes a synchronized method after it has acquired the lock for the method's object or class.
Synchronized statements are similar to synchronized methods. A synchronized statement can only
be executed after a thread has acquired the lock for the object or class referenced in the
synchronized statement.

243. What method must be implemented by all threads?


All tasks must implement the run() method, whether they are a subclass of Thread or implement
the Runnable interface.

244. What is the difference between process and thread?


The process is a program in execution whereas thread is a separate path of execution in a
program.

245. What is multithreading and what are the methods for inter-thread
communication and what is the class in which these methods are
defined?
Multithreading is the mechanism in which more than one thread runs independently of each other
within the process. wait (), notify () and notifyAll() methods can be used for inter-thread
communication and these methods are in Object class.
wait(): When a thread executes a call to wait() method, it surrenders the object lock
and enters into a waiting state.
notify() or notifyAll(): To remove a thread from the waiting state, some other
thread must make a call to notify() or notifyAll() method on the same object.

246. What is the class and interface in java to create a thread and which is the
most advantageous method?
Thread class and Runnable interface can be used to create threads and using Runnable interface
is the most advantageous method to create threads because we need not extend thread class
here.

247. What are the states associated with the thread?


The thread contains ready, running, waiting and dead state.

248. When you will synchronize a piece of your code?


When you expect your code will be accessed by different threads and these threads may change
a particular data causing data corruption.

249. What is deadlock?


When two threads are waiting for each other and can’t precede the program is said to be deadlock.

250. What happens when a thread cannot acquire a lock on an object?

29/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
If a thread attempts to execute a synchronized method or synchronized statement and is unable
to acquire an object's lock, it enters the waiting state until the lock becomes available.

15 Collections
251. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available
choices. Only one item may be selected from a Choice. A list may be displayed in such a way that
several List items are visible. A list supports the selection of one or more List items.

252. Explain the Java Collections Framework?


Java Collections Framework provides a well-designed set of interfaces and classes that support
operations on a collection of objects.

253. What is the difference between ArrayList and LinkedList?


The ArrayList Class implements java.util.List interface and uses an array for storage. Array
storages are generally faster but we cannot insert and delete entries in the middle of the list. To
achieve this kind of addition and deletion requires a new array constructed. You can access any
element randomly. The LinkedList Class implements java.util.List interface and uses a linked list
for storage. A linked list allows elements to be added, removed from the collection at any location
in the container by ordering the elements. With this implementation

254. What is the difference between Array and vector?


An array is a set of related data type and static whereas vector is a growable array of objects and
dynamic.

255. What are Vector, Hashtable, LinkedList, and Enumeration?


Vector: The Vector class provides the capability to implement a growable array of
objects.
Hashtable: The Hashtable class implements a Hashtable data structure. Hashtable
indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash
codes are integer values that identify objects.
LinkedList: Removing or inserting elements in the middle of an array can be done
using LinkedList. A LinkedList stores each object in a separate link whereas an array
stores object references in consecutive locations.
Enumeration: An object that implements the Enumeration interface generates a
series of elements, one at a time. It has two methods, namely hasMoreElements()
and nextElement(). HasMoreElemnts() tests if this enumeration has more elements
and the nextElement method returns successive elements of the series.

256. What is the difference between the set and list?


Set stores elements in an unordered way but does not contain duplicate elements, whereas list
stores elements in an ordered way but may contain duplicate elements.

257. What are HashMap and Map?


Map is Interface and Hashmap is a class that implements that.

30/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

258. Difference between HashMap and HashTable?


The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits
nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow). HashMap
does not guarantee that the order of the map will remain constant over time. HashMap is non
synchronized and Hashtable is synchronized.

259. Difference between Vector and ArrayList?


Vector is synchronized whereas arraylist is not.

16 Exception Handling
260. How to create custom exceptions?
Your class should extend class Exception or some more specific type thereof.

261. What is Checked and UnChecked Exception?


A checked exception is some subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses. Making an exception checked forces client programmers to
deal with the possibility that the exception will be thrown. eg, IOException thrown by
java.io.FileInputStream's read() method· Unchecked exceptions is RuntimeException and any of
its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception,
however, the compiler doesn't force client programmers either to catch the exception or declare
it in a throws clause. Client programmers may not even know that the exception could be thrown.
eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions
must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

262. What are Runtime exceptions?


Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input
data or because of wrong business logic etc. These are not checked by the compiler at compile
time.

263. What is the difference between error and an exception?


An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These
JVM errors and you cannot repair them at runtime. While exceptions are conditions that occur
because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not
exist. Or a NullPointerException will take place if you try using a null reference. In most of the
cases, it is possible to recover from an exception (probably by giving the user feedback for entering
proper values, etc.).

264. What happens to an unhandled exception?


One cannot do anything in this scenario. Because Java does not allow multiple inheritance and
does not provide any exception interface as well.

265. How does an exception permeate through the code?


An unhandled exception moves up the method stack in search of a matching When an exception
is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a
search is made for matching catch block. If a matching type is found, then that block will be
invoked. If a matching type is not found, then the exception moves up the method stack and

31/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
reaches the caller method. The same procedure is repeated if the caller method is included in a
try catch block. This process continues until a catch block handling the appropriate type of
exception is found. If it does not find such a block, then finally the program terminates.

266. What are the different ways to handle exceptions?


There are two ways to handle exceptions, by wrapping the desired code in a try block followed by
a catch block to catch the exceptions. And List the desired exceptions in the throws clause of the
method and let the caller of the method handle those exceptions.

267. What classes of exceptions may be caught by a catch clause?


A catch clause can catch any exception that may be assigned to the Throwable type. This includes
the Error and Exception types.

268. What is try-with-resources in java?


One of the Java 7 features is the try-with-resources statement for automatic resource
management. Before Java 7, there was no auto resource management and we should explicitly
close the resource. Usually, it was done in the finally block of a try-catch statement. This approach
used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as
soon as try-catch block gets finished.

269. What is the difference between throw and throws?


The throw is used to explicitly raise an exception within the program, the statement would be
throw new Exception();
throws clause is used to indicate the exceptions that are not handled by the method. It must
specify this behavior so the callers of the method can guard against the exceptions. throws are
specified in the method signature. If multiple exceptions are not handled, then they are separated
by a comma. The statement would be as follows: public void doSomething() throws
IOException, MyException{}

270. What is finally and finalize in java?


finally block is used with try-catch to put the code that you want to get executed
always, even if any exception is thrown by the try-catch block. finally, block is mostly
used to release resources created in the try block.
finalize() is a special method in Object class that we can override in our classes.
This method gets called by the garbage collector when the object is getting garbage
collected. This method is usually overridden to release system resources when the
object is garbage collected.

271. What is the importance of finally block in exception handling?


Finally, block will be executed whether or not an exception is thrown. If an exception is thrown,
the finally block will execute even if no catch statement matches the exception. Any time a method
is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit
return statement, the finally blockk will be executed. Finally, is used to free up resources like
database connections, IO handles, etc.

272. Can we have try without a catch block?


32/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers
Yes, we can have a try-finally statement and hence avoiding the catch block.

273. If I write System.exit (0); at the end of the try block, will the finally
block still execute?
No, in this case, the finally block will not execute because when you say System.exit (0);
the control immediately goes out of the program, and thus finally never executes.

274. What is the basic difference between the 2 approaches to exception


handling? try catch block and specifying the candidate exceptions in the
throws clause? When should you use which approach?
In the first approach as a programmer of the method, you are dealing with the exception. This is
fine if you are in the best position to decide should be done in case of an exception. Whereas if it
is not the responsibility of the method to deal with its exceptions, then do not use this approach.
In this case, use the second approach. In the second approach, we are forcing the caller of the
method to catch the exceptions, that the method is likely to throw. This is often the approach
library creators use. They list the exception in the throws clause and we must catch them. You
will find the same approach throughout the java libraries we use.

275. How does a try statement determine which catch clause should be used
to handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try
statement are examined in the order in which they appear. The first catch clause that is capable
of handling the exceptions executed. The remaining catch clauses are ignored.

276. What is the multi-catch block in java?


Java 7 one of the improvement was the multi-catch block where we can catch multiple exceptions
in a single catch block. This makes our code shorter and cleaner when every catch block has
similar code. If a catch block handles multiple exception, you can separate them using a pipe (|)
and in this case, exception parameter (ex) is final, so you can’t change it.

277. What is the difference between instanceof and isInstance?


instanceof is used to check to see if an object can be cast into a specified type without throwing
a cast class exception. isInstance() determines if the specified object is assignment-compatible
with the object represented by this Class. This method is the dynamic equivalent of the Java
language instanceof operator. The method returns true if the specified Object argument is nonnull
and can be cast to the reference type represented by this Class object without raising a
ClassCastException. It returns false otherwise.

17 I/O Streams
278. What is a stream and what are the types of Streams and classes of the
Streams?
A Stream is an abstraction that either produces or consumes information. There are two types of
Streams and they are:
Byte Streams: Provide a convenient means for handling input and output of bytes.
Character Streams: Provide a convenient means for handling input & output of
33/34
ADF Essentials Training by Deepak Bhagat
Core Java Questions and Answers

characters. Byte Streams classes: Are defined by using two abstract classes, namely
InputStream and OutputStream.
Character Streams classes: Are defined by using two abstract classes, namely Reader
and Writer.

279. What is the difference between Reader/Writer and


InputStream/Output Stream?
The Reader/Writer class is character-oriented and the InputStream/OutputStream class is
byte-oriented.

280. What is an I/O filter?


An I/O filter is an object that reads from one stream and writes to another, usually altering the
data in some way as it is passed from one stream to another.

281. What is the difference between the Reader/Writer class hierarchy and
the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy is byte-oriented.

282. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.

283. What is the difference between String and String Buffer?


String objects are constants and immutable whereas StringBuffer objects are not.
String class supports constant strings whereas StringBuffer class supports
growable and modifiable strings.

34/34
ADF Essentials Training by Deepak Bhagat

You might also like