Java Interview Questions
Java Interview Questions
Mainly used for C++ is mainly used Java is mainly used for application programming. It is widely used
for system in window, web-based, enterprise and mobile applications.
programming.
Design Goal C++ was designed for Java was designed and created as an interpreter for printing
systems and systems but later extended as a support network computing. It was
applications designed with a goal of being easy to use and accessible to a
programming. It was broader audience.
an extension of C
programming
language.
Multiple C++ supports Java doesn't support multiple inheritance through class. It can be
inheritance multiple inheritance. achieved by interfaces in java.
Compiler and C++ uses compiler Java uses compiler and interpreter both. Java source code is
Interpreter only. C++ is compiled converted into bytecode at compilation time. The interpreter
and run using the executes this bytecode at runtime and produces output. Java is
compiler which interpreted that is why it is platform independent.
converts source code
into machine code so,
C++ is platform
dependent.
Call by Value C++ supports both Java supports call by value only. There is no call by reference in
and Call by call by value and call java.
reference by reference.
Structure and C++ supports Java doesn't support structures and unions.
Union structures and unions.
Thread Support C++ doesn't have Java has built-in thread support.
built-in support for
threads. It relies on
third-party libraries
for thread support.
Documentation C++ doesn't support Java supports documentation comment (/** ... */) to create
comment documentation documentation for java source code.
comment.
Virtual C++ supports virtual Java has no virtual keyword. We can override all non-static
Keyword keyword so that we methods by default. In other words, non-static methods are virtual
can decide whether or by default.
not override a
function.
unsigned right C++ doesn't support Java supports unsigned right shift >>> operator that fills zero at
shift >>> >>> operator. the top for the negative numbers. For positive numbers, it works
same like >> operator.
Inheritance C++ creates a new Java uses a single inheritance tree always because all classes are
Tree inheritance tree the child of Object class in java. The object class is the root of
always. the inheritance tree in java.
o Simple: Java is easy to learn. The syntax of Java is based on C++ which makes
easier to write the program in it.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for
the program execution.
o Multithreaded: We can write Java programs that deal with many tasks at once by
defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the
runtime environment in which Java bytecode can be executed. It is a specification which
specifies the working of Java Virtual Machine. Its implementation has been provided by
Oracle and other companies. Its implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform
dependent). It is a runtime instance which is created when we run the Java class. There
are three notions of the JVM: specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of
JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development environment
which is used to develop Java applications and applets. It physically exists. It contains JRE
+ development tools. JDK is an implementation of any one of the below given Java
Platforms released by Oracle Corporation:
More Details.
1. Class(Method) Area: Class Area stores per-class structures such as the runtime
constant pool, field, method data, and the code for methods.
2. Heap: It is the runtime data area in which the memory is allocated to the objects
3. Stack: Java Stack stores frames. It holds local variables and partial results, and plays
a part in method invocation and return. Each thread has a private JVM stack,
created at the same time as the thread. A new frame is created each time a method
is invoked. A frame is destroyed when its method invocation completes.
4. Program Counter Register: PC (program counter) register contains the address
of the Java virtual machine instruction currently being executed.
5. Native Method Stack: It contains all the native methods used in the application.
9) What are the main differences between the Java platform and
other platforms?
There are the following differences between the Java platform and other platforms.
o Java is the software-based platform whereas other platforms may be the hardware
platforms or software-based platforms.
o Java is executed on the top of other hardware platforms whereas other platforms
can only have the hardware components.
10) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file (Byte Code)
which is the intermediate language between source code and machine code. This
bytecode is not platform specific and can be executed on any computer.
run it by java A
15) What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter
in Java.
o Public The classes, methods, or variables which are defined as public, can be
accessed by any class or method.
o Protected Protected can be accessed by the class of the same package, or by the
sub-class of this class, or within the same class.
o Default Default are accessible within the package only. By default, all the classes,
methods, and variables are of default scope.
o Private The private class, methods, or variables defined as private can be accessed
within the class only.
For example, In the class simulating the collection of the students in a college, the name
of the college is the common attribute to all the students. Therefore, the college name
will be defined as static.
1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 + 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 + 20);
7. }
8. }
30Javatpoint
Javatpoint1020
Explanation
In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30
is treated as the string and concatenated with the string Javatpoint. Therefore, the output
will be 30Javatpoint.
1. class Test
2. {
3. public static void main (String args[])
4. {
5. System.out.println(10 * 20 + "Javatpoint");
6. System.out.println("Javatpoint" + 10 * 20);
7. }
8. }
200Javatpoint
Javatpoint200
Explanation
In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is
treated as the string and concatenated with the string Javatpoint to produce the
output 200Javatpoint.
In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the
precedence of the multiplication is higher than addition. The result 200 will be treated as
the string and concatenated with the string Javatpointto produce the output
as Javatpoint200.
22) What is the output of the following Java program?
1. class Test
2. {
3. public static void main (String args[])
4. {
5. for(int i=0; 0; i++)
6. {
7. System.out.println("Hello Javatpoint");
8. }
9. }
10. }
The above code will give the compile-time error because the for loop demands a boolean
value in the second part and we are providing an integer value, i.e., 0.
o Object-oriented languages follow all the concepts of OOPs whereas, the object-
based language doesn't follow all the concepts of OOPs like inheritance and
polymorphism.
o Object-oriented languages do not have the inbuilt objects whereas Object-based
languages have the inbuilt objects, for example, JavaScript has window object.
o Examples of object-oriented programming are Java, C#, Smalltalk, etc. whereas the
examples of object-based languages are JavaScript, VBScript, etc.
More Details.
o Default Constructor: default constructor is the one which does not accept any
value. The default constructor is mainly used to initialize the instance variable with
the default values. It can also be used for performing some useful task on object
creation. A default constructor is invoked implicitly by the compiler if there is no
constructor defined in the class.
o Parameterized Constructor: The parameterized constructor is the one which can
initialize the instance variables with the given values. In other words, we can say
that the constructors which can accept the arguments are called parameterized
constructors.
29) What is the purpose of a default constructor?
The purpose of the default constructor is to assign the default value to the objects. The
java compiler creates a default constructor implicitly if there is no constructor in the class.
1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }
Test it Now
Output:
0 null
0 null
Explanation: In the above class, you are not creating any constructor, so compiler
provides you a default constructor. Here 0 and null values are provided by default
constructor.
More Details.
1. class Test
2. {
3. int i;
4. public Test(int k)
5. {
6. i=k;
7. }
8. public Test(int k, int m)
9. {
10. System.out.println("Hi I am assigning the value max(k, m) to i");
11. if(k>m)
12. {
13. i=k;
14. }
15. else
16. {
17. i=m;
18. }
19. }
20. }
21. public class Main
22. {
23. public static void main (String args[])
24. {
25. Test test1 = new Test(10);
26. Test test2 = new Test(12, 15);
27. System.out.println(test1.i);
28. System.out.println(test2.i);
29. }
30. }
31.
In the above program, The constructor Test is overloaded with another constructor. In the
first call to the constructor, The constructor with one argument is called, and i will be
initialized with the value 10. However, In the second call to the constructor, The
constructor with the 2 arguments is called, and i will be initialized with the value 15.
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
Output:
111 Karan
111 Karan
A constructor must not have a return type. A method must have a retur
The Java compiler provides a default constructor if you don't have any The method is not provided
constructor in a class. in any case.
The constructor name must be same as the class name. The method name may or m
as class name.
36) What is the output of the following Java program?
a = 10 b = 15
Here, the data type of the variables a and b, i.e., byte gets promoted to int, and the first
parameterized constructor with the two integer parameters is called.
1. class Test
2. {
3. int i;
4. }
5. public class Main
6. {
7. public static void main (String args[])
8. {
9. Test test = new Test();
10. System.out.println(test.i);
11. }
12. }
There is a compiler error in the program because there is a call to the default constructor
in the main method which is not present in the class. However, there is only one
parameterized constructor in the class Test. Therefore, no default constructor is invoked
by the constructor implicitly.
More Details.
41) What are the restrictions that are applied to the Java static
methods?
Two main restrictions are applied to the static methods.
o The static method can not use non-static data member or call the non-static
method directly.
o this and super cannot be used in static context as they are non-static.
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Test it Now
Output: static block is invoked
Hello main
More Details.
1)A method that is declared as static is known as the static method. A method that is not dec
known as the instance me
2)We don't need to create the objects to call the static methods. The object is required to
methods.
3)Non-static (instance) members cannot be accessed in the static context Static and non-static varia
(static method, static block, and static nested class) directly. accessed in instance meth
4)For example: public static int cube(int n){ return n*n*n;} For example: public void m
Output
hi !! I am good !!
i = 102
More Details.
Output
10
Output
56) What are the advantages of passing this into a method instead
of the current class object itself?
As we know, that this refers to the current class object, therefore, it must be similar to the
current class object. However, there can be two main advantages of passing this into a
method instead of the current class object.
o this is a final variable. Therefore, this cannot be assigned to any new value whereas
the current class object might not be final and can be changed.
o this can be used in the synchronized block.
o Single-level inheritance
o Multi-level inheritance
o Multiple Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Multiple inheritance is not supported in Java through class.
More Details.
o Inheritance provides code reusability. The derived class does not need to redefine
the method of base class unless it needs to provide the specific implementation of
the method.
o Runtime polymorphism cannot be achieved without using inheritance.
o We can simulate the inheritance of classes with the real-time objects which makes
OOPs more realistic.
o Inheritance provides data hiding. The base class can hide some data from the
derived class by making it private.
o Method overriding cannot be achieved without inheritance. By method overriding,
we can give a specific implementation of some basic method contained by the
base class.
Since the compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have the same method or different, there will
be a compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Address.java
Employee.java
Output
111 varun
gzb UP india
112 arun
gno UP india
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13. }
Test it Now
Output:
animal is created
dog is created
More Details.
1. class Person
2. {
3. String name,address;
4. int age;
5. public Person(int age, String name, String address)
6. {
7. this.age = age;
8. this.name = name;
9. this.address = address;
10. }
11. }
12. class Employee extends Person
13. {
14. float salary;
15. public Employee(int age, String name, String address, float salary)
16. {
17. super(age,name,address);
18. this.salary = salary;
19. }
20. }
21. public class Test
22. {
23. public static void main (String args[])
24. {
25. Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
26. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+"
Address: "+e.address);
27. }
28. }
Output
o super can be used to refer to the immediate parent class instance variable.
o super can be used to invoke the immediate parent class method.
o super() can be used to invoke immediate parent class constructor.
68) What are the differences between this and super keyword?
There are the following differences between this and super keyword.
o The super keyword always points to the parent class contexts whereas this keyword
always points to the current class context.
o The super keyword is primarily used for initializing the base class variables within
the derived class constructor whereas this keyword primarily used to differentiate
between local and instance variables when passed in the class constructor.
o The super and this must be the first statement inside constructor otherwise the
compiler will throw an error.
1. class Person
2. {
3. public Person()
4. {
5. System.out.println("Person class constructor called");
6. }
7. }
8. public class Employee extends Person
9. {
10. public Employee()
11. {
12. System.out.println("Employee class constructor called");
13. }
14. public static void main (String args[])
15. {
16. Employee e = new Employee();
17. }
18. }
Output
Explanation
The super() is implicitly invoked by the compiler if no super() or this() is included explicitly
within the derived class constructor. Therefore, in this case, The Person class constructor
is called first and then the Employee class constructor is called.
Example:
Output:
More Details.
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now
Output:
Compile Time Error: method add(int, int) is already defined in class Adder
More Details.
Output
More Details.
As displayed in the above diagram, the byte can be promoted to short, int, long, float or
double. The short datatype can be promoted to int, long, float or double. The char
datatype can be promoted to int, long, float or double and so on. Consider the following
example.
1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9. }
10. }
Test it Now
Output
40
60
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Output
Explanation
There are two methods defined with the same name, i.e., sum. The first method accepts
the integer and long type whereas the second method accepts long and the integer type.
The parameter passed that are a = 20, b = 20. We can not tell that which method will be
called as there is no clear differentiation mentioned between integer literal and long
literal. This is the case of ambiguity. Therefore, the compiler will throw an error.
o The method must have the same name as in the parent class.
o The method must have the same signature as in the parent class.
o Two classes must have an IS-A relationship between them.
More Details.
1) Method overloading increases the Method overriding provides the specific implementatio
readability of the program. that is already provided by its superclass.
2) Method overloading occurs within the Method overriding occurs in two classes that have
class. between them.
3) In this case, the parameters must be In this case, the parameters must be the same.
different.
1. class Base
2. {
3. void method(int a)
4. {
5. System.out.println("Base class method called with integer a = "+a);
6. }
7.
8. void method(double d)
9. {
10. System.out.println("Base class method called with double d ="+d);
11. }
12. }
13.
14. class Derived extends Base
15. {
16. @Override
17. void method(double d)
18. {
19. System.out.println("Derived class method called with double d ="+d);
20. }
21. }
22.
23. public class Main
24. {
25. public static void main(String[] args)
26. {
27. new Derived().method(10);
28. }
29. }
Output
Explanation
The method() is overloaded in class Base whereas it is derived in class Derived with the
double type as the parameter. In the method call, the integer is passed.
1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
Output: welcome to covariant return type
More Details.
1. class Base
2. {
3. public void baseMethod()
4. {
5. System.out.println("BaseMethod called ...");
6. }
7. }
8. class Derived extends Base
9. {
10. public void baseMethod()
11. {
12. System.out.println("Derived method called ...");
13. }
14. }
15. public class Test
16. {
17. public static void main (String args[])
18. {
19. Base b = new Derived();
20. b.baseMethod();
21. }
22. }
Output
Explanation
The method of Base class, i.e., baseMethod() is overridden in Derived class. In Test class,
the reference variable b (of type Base class) refers to the instance of the Derived class.
Here, Runtime polymorphism is achieved between class Base and Derived. At compile
time, the presence of method baseMethod checked in Base class, If it presence then the
program compiled otherwise the compiler error will be shown. In this case, baseMethod
is present in Base class; therefore, it is compiled successfully. However, at runtime, It
checks whether the baseMethod has been overridden by Derived class, if so then the
Derived class method is called otherwise Base class method is called. In this case, the
Derived class overrides the baseMethod; therefore, the Derived class method is called.
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error
1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
More Details.
1. class Main {
2. public static void main(String args[]){
3. final int i;
4. i = 20;
5. System.out.println(i);
6. }
7. }
Output
20
Explanation
Since i is the blank final variable. It can be initialized only once. We have initialized it to
20. Therefore, 20 will be printed.
97) What is the output of the following Java program?
1. class Base
2. {
3. protected final void getInfo()
4. {
5. System.out.println("method of Base class");
6. }
7. }
8.
9. public class Derived extends Base
10. {
11. protected final void getInfo()
12. {
13. System.out.println("method of Derived class");
14. }
15. public static void main(String[] args)
16. {
17. Base obj = new Base();
18. obj.getInfo();
19. }
20. }
Output
Explanation
The getDetails() method is final; therefore it can not be overridden in the subclass.
98) Can we declare a constructor as final?
The constructor can never be declared as final because it is never inherited. Constructors
are not ordinary methods; therefore, there is no sense to declare constructors as final.
However, if you try to do so, The compiler will throw an error.
100) What is the difference between the final method and abstract
method?
The main difference between the final method and abstract method is that the abstract
method cannot be final as we need to override them in the subclass to give its definition.
2 It is also known as static binding, early It is also known as dynamic binding, late bindin
binding, or overloading. dynamic method dispatch.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6. public static void main(String args[]){
7. Bike b = new Splendor();//upcasting
8. b.run();
9. }
10. }
Test it Now
Output:
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6. public static void main(String args[]){
7. Bike obj=new Honda3();
8. System.out.println(obj.speedlimit);//90
9. }
Test it Now
Output:
90
More details.
Static Binding
1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }
Dynamic Binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
More details.
1. class BaseTest
2. {
3. void print()
4. {
5. System.out.println("BaseTest:print() called");
6. }
7. }
8. public class Test extends BaseTest
9. {
10. void print()
11. {
12. System.out.println("Test:print() called");
13. }
14. public static void main (String args[])
15. {
16. BaseTest b = new Test();
17. b.print();
18. }
19. }
Output
Test:print() called
Explanation
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Test it Now
Output
true
An object of subclass type is also a type of parent class. For example, if Dog extends
Animal then object of Dog can be referred by either Dog or Animal class.
Core Java - OOPs Concepts: Abstraction Interview Questions
o Abstract Class
o Interface
More details.
More details.
Output
running safely
More details.
111) Is the following program written correctly? If yes then what will
be the output of the program?
Yes, the program is written correctly. The Main class provides the definition of abstract
method multiply declared in abstract class Calculation. The output of the program will be:
Output
384
112) Can you use abstract and final both with a method?
No, because we need to override the abstract method to provide its implementation,
whereas we can't override the final method.
More details.
An abstract class can have a method body (non-abstract The interface has only abstract metho
methods).
An abstract class can have instance variables. An interface cannot have instance va
An abstract class can have the constructor. The interface cannot have the constr
An abstract class can have static methods. The interface cannot have static meth
You can extend one abstract class. You can implement multiple interface
The abstract class can provide the implementation of the The Interface can't provide the imp
interface. the abstract class.
The abstract keyword is used to declare an abstract class. The interface keyword is used
interface.
An abstract class can extend another Java class and An interface can extend another Jav
implement multiple Java interfaces.
An abstract class can be extended using keyword extends An interface class can be impl
keyword implements
A Java abstract class can have class members like private, Members of a Java interface are publ
protected, etc.
Example: Example:
public abstract class Shape{ public interface
public abstract void draw(); void
} }
o By providing only the setter or getter method, you can make the class read-only
or write-only. In other words, you can skip the getter or setter methods.
o It provides you the control over the data. Suppose you want to set the value of id
which should be greater than 100 only, you can write the logic inside the setter
method. You can write the logic not to store the negative numbers in the setter
methods.
o It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
o The encapsulate class is easy to test. So, it is better for unit testing.
o The standard IDE's are providing the facility to generate the getters and setters. So,
it is easy and fast to create an encapsulated class in Java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
More details.
o Define a package package_name. Create the class with the name class_name and
save this file with your_class_name.java.
o Now compile the file by running the following command on the terminal.
1. javac -d . your_class_name.java
The above command creates the package with the name package_name in the
present working directory.
o Now, run the class file by using the absolute class file name, like following.
1. java package_name.class_name
o By using the fully qualified name: To access a class in a different package, either
we must use the fully qualified name of that class, or we must import the package
containing that class.
o By using the relative path, We can use the path of the class that is related to the
package that contains our class. It can be the same or subpackage.
129) Can I import same package/class twice? Will the JVM load
the package twice at runtime?
One can import the same package or the same class multiple times. Neither compiler nor
JVM complains about it. However, the JVM will internally load the class only once no
matter how many times you import the same class.
130) What is the static import?
By static import, we can access the static members of a class directly, and there is no to
qualify it with the class name.
More details.
o Checked Exception: Checked exceptions are the one which are checked at
compile-time. For example, SQLException, ClassNotFoundException, etc.
o Unchecked Exception: Unchecked exceptions are the one which are handled at
runtime because they can not be checked at compile-time. For example,
ArithmaticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
o Error: Error cause the program to exit since they are not recoverable. For Example,
OutOfMemoryError, AssertionError, etc.
More details.
1) Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions, e.g., IOException, SQLException, etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions, e.g.,
ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at
compile-time.
More details.
Output:
Output
Explanation
ArithmaticException is the subclass of Exception. Therefore, it can not be used after
Exception. Since Exception is the base class for all the exceptions, therefore, it must be
used at last to handle the exception. No class can be used after this.
1) The throw keyword is used to throw an The throws keyword is used to declare an exceptio
exception explicitly.
2) The checked exceptions cannot be The checked exception can be propagated with thr
propagated with throw only.
4) The throw keyword is used within the The throws keyword is used with the method signa
method.
5) You cannot throw multiple exceptions. You can declare multiple exceptions, e.g
method()throws IOException, SQLException.
More details.
Explanation
In Java, the throwable objects can only be thrown. If we try to throw an integer object,
The compiler will show an error since we can not throw basic data type from a block of
code.
Output
Explanation
The object of Calculation is thrown from the try block which is caught in the catch block.
The add() of Calculation class is called with the integer values 10 and 20 by using the
object of this class. Therefore there sum 30 is printed. The object of the Main class can
only be thrown in the case when the type of the object is throwable. To do so, we need
to extend the throwable class.
More details.
Output:
exception handled
normal flow...
More details.
147) What is the output of the following Java program?
Output
Explanation
In the main method, a() of Main is called which prints a message and call b(). The method
b() prints some message and then call c(). The method c() throws an exception which is
handled by the catch block of method b. However, It propagates this exception by
using throw Exception() to be handled by the method a(). As we know, finally block is
always executed therefore the finally block in the method b() is executed first and prints
a message. At last, the exception is handled by the catch block of the method a().
Output
result = 290
Explanation
The instance variable a of class Calculation is initialized to 10 using the class constructor
which is called while instantiating the class. The add method is called which returns an
integer value result. In add() method, a is incremented by 10 to be 20. Then, in the first
try block, 10 is again incremented by 10 to be 30. In the second try block, a is multiplied
by 10 to be 300. The second try block throws the exception which is caught by the catch
block associated with this try block. The catch block again alters the value of a by
decrementing it by 10 to make it 290. Thus the add() method returns 290 which is assigned
to result. However, the catch block associated with the outermost try block will never be
executed since there is no exception which can be handled by this catch block.
1. class Testimmutablestring{
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
Test it Now
Output:
Sachin
More details.
More details.
152) How many ways can we create the string object?
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. String
objects are stored in a special memory area known as the string constant pool For
example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the constant string pool. The variable s will refer to
the object in a heap (non-pool).
1. String s1="Welcome";
2. String s2="Welcome";
3. String s3="Welcome";
Only one object will be created using the above code because strings in Java are
immutable.
More details.
154) Why java uses the concept of the string literal?
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
More details.
More details.
Output
a equals b
Explanation
The operator == also check whether the references of the two string objects are equal or
not. Although both of the strings contain the same content, their references are not equal
because both are created by different ways(Constructor and String literal) therefore, a ==
b is unequal. On the other hand, the equal() method always check for the content. Since
their content is equal hence, a equals b is printed.
Output
true
Explanation
The intern method returns the String object reference from the string pool. In this case,
s1 is created by using string literal whereas, s2 is created by using the String pool.
However, s2 is changed to the reference of s1, and the operator == returns true.
2) The String is slow and consumes more memory when you concat The StringBuffer is fast an
too many strings because every time it creates a new instance. memory when you cancat
3) The String class overrides the equals() method of Object class. So The StringBuffer class doe
you can compare the contents of two strings by equals() method. equals() method of Object
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than Strin
1. class Student{
2. int rollno;
3. String name;
4. String city;
5.
6. Student(int rollno, String name, String city){
7. this.rollno=rollno;
8. this.name=name;
9. this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16. Student s1=new Student(101,"Raj","lucknow");
17. Student s2=new Student(102,"Vijay","ghaziabad");
18.
19. System.out.println(s1);//compiler writes here s1.toString()
20. System.out.println(s2);//compiler writes here s2.toString()
21. }
22. }
Output:
Output
o MatchResult Interface
o Matcher class
o Pattern class
o PatternSyntaxException class
1. import java.util.regex.*;
2. class RegexExample2{
3. public static void main(String args[]){
4. System.out.println(Pattern.matches(".s", "as")); //line 4
5. System.out.println(Pattern.matches(".s", "mk")); //line 5
6. System.out.println(Pattern.matches(".s", "mst")); //line 6
7. System.out.println(Pattern.matches(".s", "amms")); //line 7
8. System.out.println(Pattern.matches("..s", "mas")); //line 8
9. }}
Output
true
false
false
false
true
Explanation
line 4 prints true since the second character of string is s, line 5 prints false since the
second character is not s, line 6 prints false since there are more than 3 characters in the
string, line 7 prints false since there are more than 2 characters in the string, and it contains
more than 2 characters as well, line 8 prints true since the third character of the string is
s.
o Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of the outer class including private.
o Nested classes are used to develop a more readable and maintainable code
because it logically groups classes and interfaces in one place only.
o Code Optimization: It requires less code to write.
1. class Java_Outer_class{
2. //code
3. class Java_Nested_class{
4. //code
5. }
6. }
7.
There are two types of nested classes, static nested class, and non-static nested class. The
non-static nested class can also be called as inner-class
More details.
o Inner classes increase the total number of classes used by the developer and
therefore increases the workload of JVM since it has to perform some routine
operations for those extra classes which result in slower performance.
o IDEs provide less support to the inner classes as compare to the top level classes
and therefore it annoys the developers while working with inner classes.
171) What are the types of inner classes (non-static nested class)
used in Java?
There are mainly three types of inner classes used in Java.
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing an interface or extending class. Its name i
Class java compiler.
173) Can we access the non-final local variable, inside the local
inner class?
No, the local variable must be constant if you want to access it in the local inner class.
More details.
174) How many class files are created on compiling the OuterClass
in the following program?
Output:
nice fruits
Consider the following example for the working of the anonymous class using interface.
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
Test it Now
Output:
nice fruits
1. interface interface_name{
2. ...
3. interface nested_interface_name{
4. ...
5. }
6. }
7.
More details.
More details.
More details.
More details.
1) By nulling a reference:
3) By anonymous object:
1. new Employee();
InputStream Hierarchy
190) What do you understand by an IO stream?
The stream is a sequence of data that flows from source to destination. It is composed of
bytes. In Java, three streams are created for us automatically.
192) What are the super most classes for all the streams?
All the stream classes can be divided into two types of classes that are ByteStream classes
and CharacterStream Classes. The ByteStream classes are further divided into InputStream
classes and OutputStream classes. CharacterStream classes are also divided into Reader
classes and Writer classes. The SuperMost classes for all the InputStream classes is
java.io.InputStream and for all the output stream classes is java.io.OutPutStream. Similarly,
for all the reader classes, the super-most class is java.io.Reader, and for all the writer
classes, it is java.io.Writer.
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also
read character-stream data. However, for reading streams of characters, it is
recommended to use FileReader class. Consider the following example for reading bytes
from a file.
1. import java.io.FileInputStream;
2. public class DataStreamExample {
3. public static void main(String args[]){
4. try{
5. FileInputStream fin=new FileInputStream("D:\\testout.txt");
6. int i=fin.read();
7. System.out.print((char)i);
8.
9. fin.close();
10. }catch(Exception e){System.out.println(e);}
11. }
12. }
13.
o D:\\IO\\-: It indicates that the permission is associated with all subdirectories and
files recursively.
o D:\\IO\\*: It indicates that the permission is associated with all directory and files
within this directory excluding subdirectories.
Let's see the simple example in which permission of a directory path is granted with read
permission and a file of this directory is granted for write permission.
1. package com.javatpoint;
2. import java.io.*;
3. import java.security.PermissionCollection;
4. public class FilePermissionExample{
5. public static void main(String[] args) throws IOException {
6. String srg = "D:\\IO Package\\java.txt";
7. FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");
8. PermissionCollection permission = file1.newPermissionCollection();
9. permission.add(file1);
10. FilePermission file2 = new FilePermission(srg, "write");
11. permission.add(file2);
12. if(permission.implies(new FilePermission(srg, "read,write"))) {
13. System.out.println("Read, Write permission is granted for the path "+srg );
14. }else {
15. System.out.println("No Read, Write permission is granted for the path "+s
rg); }
16. }
17. }
Output
198) In Java, How many ways you can take input from the console?
In Java, there are three ways by using which, we can take input from the console.
o Using BufferedReader class: we can take input from the console by wrapping
System.in into an InputStreamReader and passing it into the BufferedReader. It
provides an efficient reading as the input gets buffered. Consider the following
example.
1. import java.io.BufferedReader;
2. import java.io.IOException;
3. import java.io.InputStreamReader;
4. public class Person
5. {
6. public static void main(String[] args) throws IOException
7. {
8. System.out.println("Enter the name of the person");
9. BufferedReader reader = new BufferedReader(new InputStreamRead
er(System.in));
10. String name = reader.readLine();
11. System.out.println(name);
12. }
13. }
o Using Scanner class: The Java Scanner class breaks the input into tokens using a
delimiter that is whitespace by default. It provides many methods to read and parse
various primitive values. Java Scanner class is widely used to parse text for string
and primitive types using a regular expression. Java Scanner class extends Object
class and implements Iterator and Closeable interfaces. Consider the following
example.
1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){
4. String str = "Hello/This is JavaTpoint/My name is Abhishek.";
5. //Create scanner with the specified String Object
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scanner.hasNextBoolean());
o Using Console class: The Java Console class is used to get input from the console.
It provides methods to read texts and passwords. If you read the password using
the Console class, it will not be displayed to the user. The java.io.Console class is
attached to the system console internally. The Console class is introduced since 1.5.
Consider the following example.
1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }
Serialization Interview Questions
1. import java.io.FileInputStream;
2. import java.io.FileOutputStream;
3. import java.io.IOException;
4. import java.io.NotSerializableException;
5. import java.io.ObjectInputStream;
6. import java.io.ObjectOutputStream;
7. import java.io.Serializable;
8. class Person implements Serializable
9. {
10. String name = " ";
11. public Person(String name)
12. {
13. this.name = name;
14. }
15. }
16. class Employee extends Person
17. {
18. float salary;
19. public Employee(String name, float salary)
20. {
21. super(name);
22. this.salary = salary;
23. }
24. private void writeObject(ObjectOutputStream out) throws IOException
25. {
26. throw new NotSerializableException();
27. }
28. private void readObject(ObjectInputStream in) throws IOException
29. {
30. throw new NotSerializableException();
31. }
32.
33. }
34. public class Test
35. {
36. public static void main(String[] args)
37. throws Exception
38. {
39. Employee emp = new Employee("Sharma", 10000);
40.
41. System.out.println("name = " + emp.name);
42. System.out.println("salary = " + emp.salary);
43.
44. FileOutputStream fos = new FileOutputStream("abc.ser");
45. ObjectOutputStream oos = new ObjectOutputStream(fos);
46.
47. oos.writeObject(emp);
48.
49. oos.close();
50. fos.close();
51.
52. System.out.println("Object has been serialized");
53.
54. FileInputStream f = new FileInputStream("ab.txt");
55. ObjectInputStream o = new ObjectInputStream(f);
56.
57. Employee emp1 = (Employee)o.readObject();
58.
59. o.close();
60. f.close();
61.
62. System.out.println("Object has been deserialized");
63.
64. System.out.println("name = " + emp1.name);
65. System.out.println("salary = " + emp1.salary);
66. }
67. }
Deserialization is the process of reconstructing the object from the serialized state. It is
the reverse operation of serialization. An ObjectInputStream deserializes objects and
primitive data written using an ObjectOutputStream.
1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
211 ravi
1) The Serializable interface does not have any The Externalizable interface contains is not a m
method, i.e., it is a marker interface. contains two methods, i.e., writeExternal() and rea
2) It is used to "mark" Java classes so that objects of The Externalizable interface provides control of the
these classes may get the certain capability. to the programmer.
3) It is easy to implement but has the higher It is used to perform the serialization and ofte
performance cost. performance.
4) No class constructor is called in serialization. We must call a public default constructor while us
209) What are the steps that are followed when two computers
connect through TCP?
There are the following steps that are performed when two computers connect through
TCP.
o The ServerSocket object is instantiated by the server which denotes the port number to
which, the connection will be made.
o After instantiating the ServerSocket object, the server invokes accept() method of
ServerSocket class which makes server wait until the client attempts to connect to the
server on the given port.
o Meanwhile, the server is waiting, a socket is created by the client by instantiating Socket
class. The socket class constructor accepts the server port number and server name.
o The Socket class constructor attempts to connect with the server on the specified name. If
the connection is established, the client will have a socket object that can communicate
with the server.
o The accept() method invoked by the server returns a reference to the new socket on the
server that is connected with the server.
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
1. import java.io.*;
2. import java.net.*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=InetAddress.getByName("195.201.10.8");
7.
8. System.out.println("Host Name: "+ip.getHostName());
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
12.
o forName() method of Class class: The forName() method is used to load the class
dynamically. It returns the instance of Class class. It should be used if you know the fully
qualified name of the class. This cannot be used for primitive types.
o getClass() method of Object class: It returns the instance of Class class. It should be used
if you know the type. Moreover, it can be used with primitives.
o the .class syntax: If a type is available, but there is no instance then it is possible to obtain
a Class by appending ".class" to the name of the type. It can be used for primitive data
type also.
215) What is the output of the following Java program?
1. class Simple{
2. public Simple()
3. {
4. System.out.println("Constructor of Simple class is invoked");
5. }
6. void message(){System.out.println("Hello Java");}
7. }
8.
9. class Test1{
10. public static void main(String args[]){
11. try{
12. Class c=Class.forName("Simple");
13. Simple s=(Simple)c.newInstance();
14. s.message();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }
Output
Explanation
The newInstance() method of the Class class is used to invoke the constructor at runtime.
In this program, the instance of the Simple class is created.
javap fully_class_name
217) Can you access the private method from outside the class?
Yes, by changing the runtime behavior of a class if the class is not secured.
More details.
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
It can occur whenever a wrapper class object is expected, and primitive data type is
provided or vice versa.
Output
bye
Explanation
The Integer class caches integer values from -127 to 127. Therefore, the Integer objects
can only be created in the range -128 to 127. The operator == will not work for the value
greater than 127; thus bye is printed.
o You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4-
or 5-line long clone() method.
o It is the easiest and most efficient way of copying objects, especially if we are applying it
to an already developed or an old project. Just define a parent class, implement Cloneable
in it, provide the definition of the clone() method and the task will be done.
o Clone() is the fastest way to copy the array.
o To use the Object.clone() method, we have to change many syntaxes to our code, like
implementing a Cloneable interface, defining the clone() method and handling
CloneNotSupportedException, and finally, calling Object.clone(), etc.
o We have to implement the Cloneable interface while it does not have any methods in it.
We have to use it to tell the JVM that we can perform a clone() on our object.
o Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.
o Object.clone() does not invoke any constructor, so we do not have any control over object
construction.
o If you want to write a clone method in a child class, then all of its superclasses should
define the clone() method in them or inherit it from another parent class. Otherwise, the
super.clone() chain will fail.
o Object.clone() supports only shallow copying, but we will need to override it if we need
deep cloning.
o Standard input
o Error output streams
o Standard output
o utility method to copy the portion of an array
o utilities to load files and libraries
There are the three fields of Java System class, i.e., static printstream err, static inputstream
in, and standard output stream.
1. class Singleton{
2. private static Singleton single_instance = null;
3. int i;
4. private Singleton ()
5. {
6. i=90;
7. }
8. public static Singleton getInstance()
9. {
10. if(single_instance == null)
11. {
12. single_instance = new Singleton();
13. }
14. return single_instance;
15. }
16. }
17. public class Main
18. {
19. public static void main (String args[])
20. {
21. Singleton first = Singleton.getInstance();
22. System.out.println("First instance integer value:"+first.i);
23. first.i=first.i+90;
24. Singleton second = Singleton.getInstance();
25. System.out.println("Second instance integer value:"+second.i);
26. }
27. }
28.
228) Write a Java program that prints all the values given at
command-line.
Program
1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
Output
sonoo
jaiswal
1
3
abc
o init()
o start()
o paint()
o stop()
o destroy()
236) Can you write a Java class that could be used both as an
applet as well as an application?
Yes. Add a main() method to the applet.
Internationalization Interview Questions
1. import java.util.*;
2. public class LocaleExample {
3. public static void main(String[] args) {
4. Locale locale=Locale.getDefault();
5. //Locale locale=new Locale("fr","fr");//for the specific locale
6.
7. System.out.println(locale.getDisplayCountry());
8. System.out.println(locale.getDisplayLanguage());
9. System.out.println(locale.getDisplayName());
10. System.out.println(locale.getISO3Country());
11. System.out.println(locale.getISO3Language());
12. System.out.println(locale.getLanguage());
13. System.out.println(locale.getCountry());
14.
15. }
16. }
Output:
United States
English
English (United States)
USA
eng
en
US
238)How will you load a specific locale?
By ResourceBundle.getBundle(?) method.
1. //Employee.java
2. package mypack;
3. public class Employee implements java.io.Serializable{
4. private int id;
5. private String name;
6. public Employee(){}
7. public void setId(int id){this.id=id;}
8. public int getId(){return id;}
9. public void setName(String name){this.name=name;}
10. public String getName(){return name;}
11. }
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes the method on the stub object, it does the following tasks:
Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:
o It reads the parameter for the remote method.
o It invokes the method on the actual remote object.
o It writes and transmits (marshals) the result to the caller.
244) What are the steps involved to write RMI based programs?
There are 6 steps which are performed to write RMI based programs.
Output:
1. import java.util.*;
2. public class BinarySearch {
3. public static void main(String[] args) {
4. int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
5. int item, location = -1;
6. System.out.println("Enter the item which you want to search");
7. Scanner sc = new Scanner(System.in);
8. item = sc.nextInt();
9. location = binarySearch(arr,0,9,item);
10. if(location != -1)
11. System.out.println("the location of the item is "+location);
12. else
13. System.out.println("Item not found");
14. }
15. public static int binarySearch(int[] a, int beg, int end, int item)
16. {
17. int mid;
18. if(end >= beg)
19. {
20. mid = (beg + end)/2;
21. if(a[mid] == item)
22. {
23. return mid+1;
24. }
25. else if(a[mid] < item)
26. {
27. return binarySearch(a,mid+1,end,item);
28. }
29. else
30. {
31. return binarySearch(a,beg,mid-1,item);
32. }
33. }
34. return -1;
35. }
36. }
Output:
Output:
Output:
Enter Item ?
23
Item found at location 2
Enter Item ?
22
Item not found
252) How to perform merge sort in Java?
Consider the following program to perform merge sort in Java.
Output:
Sorted array
23
23
23
34
45
65
67
89
90
101
Output:
Output:
Output:
1. import java.util.LinkedList;
2. import java.util.Queue;
3.
4. public class DiffOddEven {
5.
6. //Represent a node of binary tree
7. public static class Node{
8. int data;
9. Node left;
10. Node right;
11.
12. public Node(int data){
13. //Assign data to the new node, set left and right children to null
14. this.data = data;
15. this.left = null;
16. this.right = null;
17. }
18. }
19.
20. //Represent the root of binary tree
21. public Node root;
22.
23. public DiffOddEven(){
24. root = null;
25. }
26.
27. //difference() will calculate the difference between sum of odd and even levels
of binary tree
28. public int difference() {
29. int oddLevel = 0, evenLevel = 0, diffOddEven = 0;
30.
31. //Variable nodesInLevel keep tracks of number of nodes in each level
32. int nodesInLevel = 0;
33.
34. //Variable currentLevel keep track of level in binary tree
35. int currentLevel = 0;
36.
37. //Queue will be used to keep track of nodes of tree level-wise
38. Queue<Node> queue = new LinkedList<Node>();
39.
40. //Check if root is null
41. if(root == null) {
42. System.out.println("Tree is empty");
43. return 0;
44. }
45. else {
46. //Add root node to queue as it represents the first level
47. queue.add(root);
48. currentLevel++;
49.
50. while(queue.size() != 0) {
51.
52. //Variable nodesInLevel will hold the size of queue i.e. number of elements in
queue
53. nodesInLevel = queue.size();
54.
55. while(nodesInLevel > 0) {
56. Node current = queue.remove();
57.
58. //Checks if currentLevel is even or not.
59. if(currentLevel % 2 == 0)
60. //If level is even, add nodes's to variable evenLevel
61. evenLevel += current.data;
62. else
63. //If level is odd, add nodes's to variable oddLevel
64. oddLevel += current.data;
65.
66. //Adds left child to queue
67. if(current.left != null)
68. queue.add(current.left);
69. //Adds right child to queue
70. if(current.right != null)
71. queue.add(current.right);
72. nodesInLevel--;
73. }
74. currentLevel++;
75. }
76. //Calculates difference between oddLevel and evenLevel
77. diffOddEven = Math.abs(oddLevel - evenLevel);
78. }
79. return diffOddEven;
80. }
81.
82. public static void main (String[] args) {
83.
84. DiffOddEven bt = new DiffOddEven();
85. //Add nodes to the binary tree
86. bt.root = new Node(1);
87. bt.root.left = new Node(2);
88. bt.root.right = new Node(3);
89. bt.root.left.left = new Node(4);
90. bt.root.right.left = new Node(5);
91. bt.root.right.right = new Node(6);
92.
93. //Display the difference between sum of odd level and even level nodes
94. System.out.println("Difference between sum of odd level and even level nodes: " +
bt.difference());
95. }
96. }
Output: