Core Java Interview Questions and Answers
Core Java Interview Questions and Answers
Mainly used for C++ is mainly used for system Java is mainly used for application programm
programming. is widely used in window, web-based, enterp
mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an interpre
applications programming. It was an printing systems but later extended as a sup
extension of C programming language. network computing. It was designed with a g
being easy to use and accessible to a broade
audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance thr
inheritance class. It can be achieved by interfaces in java
Pointers C++ supports pointers. You can write Java supports pointer internally. However, yo
pointer program in C++. write the pointer program in java. It means j
restricted pointer support in Java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both. Java
Interpreter compiled and run using the compiler code is converted into bytecode at compilatio
which converts source code into The interpreter executes this bytecode at run
machine code so, C++ is platform and produces output. Java is interpreted that
dependent. it is platform independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is no
Call by reference call by reference. reference in java.
Structure and C++ supports structures and unions. Java doesn't support structures and unions.
Union
Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party
libraries for thread support.
Documentation C++ doesn't support documentation Java supports documentation comment (/**
comment comment. to create documentation for java source code
Virtual Keyword C++ supports virtual keyword so that Java has no virtual keyword. We can override
we can decide whether or not override non-static methods by default. In other word
a function. static methods are virtual by default.
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>> opera
shift >>> that fills zero at the top for the negative num
For positive numbers, it works same like >>
operator.
Inheritance Tree C++ creates a new inheritance tree Java uses a single inheritance tree always be
always. all classes are the child of Object class in jav
object class is the root of the inheritance tree
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 Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the
combination of different type of objects that incorporates both data and behavior.
o Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every
machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
o Platform Independent: Java is a platform independent programming language. It is different from other
programming languages like C and C++ which needs a platform to be executed. Java comes with its platform
on which its code is executed. Java doesn't depend upon the operating system to be executed.
o Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode
and Exception handling which makes it more secured.
o Robust: Java is a strong programming language as it uses strong memory management. The concepts like
Automatic garbage collection, Exception handling, etc. make it more robust.
o Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size
of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
o High Performance: Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
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.
o Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling
the methods from any machine on the internet.
o Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
There is the list of 300 core Java interview questions. If there is any core Java interview question that has been aske
kindly post it in the ask question section. We assure that you will get here the 90% frequently asked interview quest
answers.
The answers to the Core Java interview questions are short and to the point. The core Java interview questions are
categorized in Basics of Java interview questions, OOPs interview questions, String Handling interview questions,
Multithreading interview questions, collection interview questions, JDBC interview questions, etc.
1 2 3 4 5
1) What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performan
Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also b
as the platform as it provides its own JRE and API.
Mainly used for C++ is mainly used for system Java is mainly used for application progra
programming. is widely used in window, web-based, ent
mobile applications.
Design Goal C++ was designed for systems and Java was designed and created as an inte
applications programming. It was an printing systems but later extended as a s
extension of C programming language. network computing. It was designed with
being easy to use and accessible to a broa
audience.
Goto C++ supports the goto statement. Java doesn't support the goto statement.
Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance class. It can be achieved by interfaces in j
Pointers C++ supports pointers. You can write Java supports pointer internally. However
pointer program in C++. write the pointer program in java. It mean
restricted pointer support in Java.
Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both. J
Interpreter compiled and run using the compiler code is converted into bytecode at compil
which converts source code into The interpreter executes this bytecode at
machine code so, C++ is platform and produces output. Java is interpreted t
dependent. it is platform independent.
Call by Value and C++ supports both call by value and Java supports call by value only. There is
Call by reference call by reference. reference in java.
Structure and C++ supports structures and unions. Java doesn't support structures and union
Union
Thread Support C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party
libraries for thread support.
unsigned right C++ doesn't support >>> operator. Java supports unsigned right shift >>> op
shift >>> that fills zero at the top for the negative n
For positive numbers, it works same like >
operator.
Inheritance Tree C++ creates a new inheritance tree Java uses a single inheritance tree always
always. all classes are the child of Object class in
object class is the root of the inheritance
java.
o Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program
o Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the com
of different type of objects that incorporates both data and behavior.
o Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every ma
Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
o Robust: Java is a strong programming language as it uses strong memory management. The concepts like A
garbage collection, Exception handling, etc. make it more robust.
o Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size
types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
o Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
o High Performance: Java is faster than other traditional interpreted programming languages because Java by
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
o Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads.
advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory
Threads are important for multi-media, Web applications, etc.
o Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and
used for creating distributed applications. This feature of Java makes us able to access files by calling the met
from any machine on the internet.
o Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded o
demand. It also supports functions from its native languages, i.e., C and C++.
Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-tim
which calls the main method present in the Java code. JVM is the specification which must be implemented in the com
system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native co
5) What is the difference between JDK, JRE, and JVM?
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in wh
bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementatio
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 instanc
is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instan
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set o
tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implem
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 Jav
applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any o
below given Java Platforms released by Oracle Corporation:
More Details.
Many types:
1. Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method
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 invoc
return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created
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.
More Details.
7) What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have
functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compi
to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
A platform is the hardware or software environment in which a piece of software is executed. There are two types of
platforms, software-based and hardware-based. Java provides the software-based platform.
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-bas
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 lan
between source code and machine code. This bytecode is not platform specific and can be executed on any compute
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded f
classloader. There are three built-in classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It load
the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net pa
classes, java.util package classes, java.io package classes, java.sql package classes, etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classload
loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class f
the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-c
classpath" switch. It is also known as Application classloader.
Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classnam
take a simple example:
1. //save by .java only
2. class A{
3. public static void main(String args[]){
4. System.out.println("Hello java");
5. }
6. }
7. //compile by javac .java
8. //run by java A
run it by java A
No.
14) If I don't provide any arguments on the command line, then what will the value s
in the String array passed into the main() method, empty or NULL?
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.
In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a vari
Java, there are four access specifiers given below.
o Public The classes, methods, or variables which are defined as public, can be accessed by any class or metho
o Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or w
same class.
o Default Default are accessible within the package only. By default, all the classes, methods, and variables ar
default scope.
o Private The private class, methods, or variables defined as private can be accessed within the class only.
The methods or variables defined as static are shared among all the objects of the class. The static is the part of the
not of the object. The static variables are stored in the class area, and we do not need to create the object to access
variables. Therefore, static is used in the case, where we need to define variables or methods which are common to
objects of the class.
For example, In the class simulating the collection of the students in a college, the name of the college is the commo
attribute to all the students. Therefore, the college name will be defined as static.
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 a
concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.
In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be
concatenated with 20 to be Javatpoint1020.
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 multiplic
higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpointto prod
output as Javatpoint200.
The above code will give the compile-time error because the for loop demands a boolean value in the second part an
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.
26) What will be the initial value of an object reference which is defined as an
instance variable?
All object references are initialized to null in Java.
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.
. class Student3{
. int id;
. String name;
.
. void display(){System.out.println(id+" "+name);}
.
. public static void main(String args[]){
. Student3 s1=new Student3();
. Student3 s2=new Student3();
0. s1.display();
1. s2.display();
2. }
3. }
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.
. class Test
. {
. int i;
. public Test(int k)
. {
. i=k;
. }
. public Test(int k, int m)
. {
0. System.out.println("Hi I am assigning the value max(k, m) to i");
1. if(k>m)
2. {
3. i=k;
4. }
5. else
6. {
7. i=m;
8. }
9. }
0. }
1. public class Main
2. {
3. public static void main (String args[])
4. {
5. Test test1 = new Test(10);
6. Test test2 = new Test(12, 15);
7. System.out.println(test1.i);
8. System.out.println(test2.i);
9. }
0. }
1.
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.
. //Java program to initialize the values from one object to another
. class Student6{
. int id;
. String name;
. //constructor to initialize integer and string
. Student6(int i,String n){
. id = i;
. name = n;
. }
0. //constructor to initialize another object
1. Student6(Student6 s){
2. id = s.id;
3. name =s.name;
4. }
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student6 s1 = new Student6(111,"Karan");
9. Student6 s2 = new Student6(s1);
0. s1.display();
1. s2.display();
2. }
3. }
Test it Now
Output:
111 Karan
111 Karan
35) What are the differences between the constructors and methods?
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an object. A method is used to expose the behav
an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you don't have any The method is not provided by the com
constructor in a class. any case.
The constructor name must be same as the class name. The method name may or may not be
as class name.
36) What is the output of the following Java program?
. public class Test
. {
. Test(int a, int b)
. {
. System.out.println("a = "+a+" b = "+b);
. }
. Test(int a, float b)
. {
. System.out.println("a = "+a+" b = "+b);
0. }
1. public static void main (String args[])
2. {
3. byte a = 10;
4. byte b = 15;
5. Test test = new Test(a,b);
6. }
7. }
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.
The output of the program is 0 because the variable i is initialized to 0 internally. As we know that a default
constructor is invoked implicitly if there is no constructor in the class, the variable i is initialized to 0 since there is no
constructor in the class.
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.
. //Program of static variable
.
. class Student8{
. int rollno;
. String name;
. static String college ="ITS";
.
. Student8(int r,String n){
. rollno = r;
0. name = n;
1. }
2. void display (){System.out.println(rollno+" "+name+" "+college);}
3.
4. public static void main(String args[]){
5. Student8 s1 = new Student8(111,"Karan");
6. Student8 s2 = new Student8(222,"Aryan");
7.
8. s1.display();
9. s2.display();
0. }
1. }
Test it Now
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.
. class A2{
. static{System.out.println("static block is invoked");}
. public static void main(String args[]){
. System.out.println("Hello main");
. }
. }
Test it Now
More Details.
46) What if the static modifier is removed from the signature of the main method?
Program compiles. However, at runtime, It throws an error "NoSuchMethodError."
47) What is the difference between static (class) method and instance method?
1)A method that is declared as static is known as the static method. A method that is not declared as sta
known as the instance method.
2)We don't need to create the objects to call the static methods. The object is required to call the ins
methods.
3)Non-static (instance) members cannot be accessed in the static context Static and non-static variables both
(static method, static block, and static nested class) directly. accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;} For example: public void msg(){...}
50) Can we declare the static variables and methods in an abstract class?
Yes, we can declare static variables and methods in an abstract method. As we know that there is no requirement to
make the object to access the static context, therefore, we can access the static context declared inside the abstract
class by using the name of the abstract class. Consider the following example.
. abstract class Test
. {
. static int i = 102;
. static void TestMethod()
. {
. System.out.println("hi !! I am good !!");
. }
. }
. public class TestClass extends Test
0. {
1. public static void main (String args[])
2. {
3. Test.TestMethod();
4. System.out.println("i = "+Test.i);
5. }
6. }
Output
hi !! I am good !!
i = 102
Core Java - OOPs Concepts: Inheritance Interview Questions
More Details.
. public class Test
. {
. public Test()
. {
. this = null;
. System.out.println("Test class constructor called");
. }
. public static void main (String args[])
. {
0. Test t = new Test();
1. }
2. }
Output
. public class Test
. {
. static int i = 10;
. public Test ()
. {
. System.out.println(this.i);
. }
. public static void main (String args[])
. {
0. Test t = new Test();
1. }
2. }
Output
10
. public class Employee
. {
. int id,age;
. String name, address;
. public Employee (int age)
. {
. this.age = age;
. }
. public Employee(int id, int age)
0. {
1. this(age);
2. this.id = id;
3. }
4. public Employee(int id, int age, String name, String address)
5. {
6. this(id, age);
7. this.name = name;
8. this.address = address;
9. }
0. public static void main (String args[])
1. {
2. Employee emp = new Employee(105, 22, "Vikas", "Delhi");
3. System.out.println("ID: "+emp.id+" Name:"+emp.name+" age:"+emp.age+" address: "+emp.address)
;
4. }
5.
6. }
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.
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.
. class A{
. void msg(){System.out.println("Hello");}
. }
. class B{
. void msg(){System.out.println("Welcome");}
. }
. class C extends A,B{//suppose if it were
.
. Public Static void main(String args[]){
0. C obj=new C();
1. obj.msg();//Now which msg() method would be invoked?
2. }
3. }
Test it Now
Address.java
. public class Address {
. String city,state,country;
.
. public Address(String city, String state, String country) {
. this.city = city;
. this.state = state;
. this.country = country;
. }
.
0. }
Employee.java
. public class Emp {
. int id;
. String name;
. Address address;
.
. public Emp(int id, String name,Address address) {
. this.id = id;
. this.name = name;
. this.address=address;
0. }
1.
2. void display(){
3. System.out.println(id+" "+name);
4. System.out.println(address.city+" "+address.state+" "+address.country);
5. }
6.
7. public static void main(String[] args) {
8. Address address1=new Address("gzb","UP","india");
9. Address address2=new Address("gno","UP","india");
0.
1. Emp e=new Emp(111,"varun",address1);
2. Emp e2=new Emp(112,"arun",address2);
3.
4. e.display();
5. e2.display();
6.
7. }
8. }
Output
111 varun
gzb UP india
112 arun
gno UP india
Output:
animal is created
dog is created
More Details.
66) How can constructor chaining be done by using the super keyword?
. class Person
. {
. String name,address;
. int age;
. public Person(int age, String name, String address)
. {
. this.age = age;
. this.name = name;
. this.address = address;
0. }
1. }
2. class Employee extends Person
3. {
4. float salary;
5. public Employee(int age, String name, String address, float salary)
6. {
7. super(age,name,address);
8. this.salary = salary;
9. }
0. }
1. public class Test
2. {
3. public static void main (String args[])
4. {
5. Employee e = new Employee(22, "Mukesh", "Delhi", 90000);
6. System.out.println("Name: "+e.name+" Salary: "+e.salary+" Age: "+e.age+" Address: "+e.address);
7. }
8. }
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.
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:
. public class Test{
. Test()
. {
. super();
. this();
. System.out.println("Test class object is created");
. }
. public static void main(String []args){
. Test t = new Test();
0. }
1. }
Output:
. protected Object clone() throws CloneNotSupportedException
.
More Details.
Core Java - OOPs Concepts: Method Overloading Interview Questions
Method overloading increases the readability of the program. Method overloading is performed to figure out the
program quickly.
More Details.
73) Why is method overloading not possible by changing the return type in java?
In Java, method overloading is not possible by changing the return type of the program due to avoid the ambiguity.
. class Adder{
. static int add(int a,int b){return a+b;}
. static double add(int a,int b){return a+b;}
. }
. class TestOverloading3{
. public static void main(String[] args){
. System.out.println(Adder.add(11,11));//ambiguity
. }}
Test it Now
Output:
Compile Time Error: method add(int, int) is already defined in class Adder
More Details.
. public class Animal
. {
. void consume(int a)
. {
. System.out.println(a+" consumed!!");
. }
. static void consume(int a)
. {
. System.out.println("consumed static "+a);
0. }
1. public static void main (String args[])
2. {
3. Animal a = new Animal();
4. a.consume(10);
5. Animal.consume(20);
6. }
7. }
Output
More Details.
. class OverloadingCalculation1{
. void sum(int a,long b){System.out.println(a+b);}
. void sum(int a,int b,int c){System.out.println(a+b+c);}
.
. public static void main(String args[]){
. OverloadingCalculation1 obj=new OverloadingCalculation1();
. obj.sum(20,20);//now second int literal will be promoted to long
. obj.sum(20,20,20);
. }
0. }
Test it Now
Output
40
60
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 implementation of the met
readability of the program. is already provided by its superclass.
2) Method overloading occurs within the Method overriding occurs in two classes that have IS-A relationship
class. between them.
3) In this case, the parameters must be In this case, the parameters must be the same.
different.
84) Can we change the scope of the overridden method in the subclass?
Yes, we can change the scope of the overridden method in the subclass. However, we must notice that we cannot
decrease the accessibility of the method. The following point must be taken care of while changing the accessibility of
the method.
85) Can we modify the throws clause of the superclass method while overriding it in
the subclass?
Yes, we can modify the throws clause of the superclass method while overriding it in the subclass. However, there
are some rules which are to be followed while overriding in case of exception handling.
o If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception, but it can declare the unchecked exception.
o If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.
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.
. class A{
. A get(){return this;}
. }
.
. class B1 extends A{
. B1 get(){return this;}
. void message(){System.out.println("welcome to covariant return type");}
.
. public static void main(String args[]){
0. new B1().get().message();
1. }
2. }
Test it Now
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.
. class Bike9{
. final int speedlimit=90;//final variable
. void run(){
. speedlimit=400;
. }
. public static void main(String args[]){
. Bike9 obj=new Bike9();
. obj.run();
. }
0. }//end of class
Test it Now
. class Bike{
. final void run(){System.out.println("running");}
. }
.
. class Honda extends Bike{
. void run(){System.out.println("running safely with 100kmph");}
.
. public static void main(String args[]){
. Honda honda= new Honda();
0. honda.run();
1. }
2. }
Test it Now
. final class Bike{}
.
. class Honda1 extends Bike{
. void run(){System.out.println("running safely with 100kmph");}
.
. public static void main(String args[]){
. Honda1 honda= new Honda1();
. honda.run();
. }
0. }
Test it Now
Output:Compile Time Error
More Details.
. class Student{
. int id;
. String name;
. final String PAN_CARD_NUMBER;
. ...
. }
More Details.
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.
Output
Explanation
The getDetails() method is final; therefore it can not be overridden in the subclass.
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 binding, overridin
binding, or overloading. dynamic method dispatch.
4 It provides fast execution because the type It provides slower execution as compare to compile-time b
of an object is determined at compile-time. type of an object is determined at run-time.
5 Compile-time polymorphism provides less Run-time polymorphism provides more flexibility because a
flexibility because all the things are resolved things are resolved at runtime.
at compile-time.
10. In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.
300 Java interview questions | Set 2
1 2 3 4 5
101) What is the difference between compile-time polymorphism and runtime polym
There are the following differences between compile-time polymorphism and runtime polymorphism.
2 It is also known as static binding, early It is also known as dynamic binding, late binding, overr
binding, or overloading. dynamic method dispatch.
4 It provides fast execution because the type It provides slower execution as compare to compile-tim
of an object is determined at compile-time. type of an object is determined at run-time.
5 Compile-time polymorphism provides less Run-time polymorphism provides more flexibility becau
flexibility because all the things are resolved things are resolved at runtime.
at compile-time.
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved
rather than at compile-time. In this process, an overridden method is called through the reference variable of a supe
determination of the method to be called is based on the object being referred to by the reference variable.
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:
In this process, an overridden method is called through the reference variable of a superclass. The determination of
to be called is based on the object being referred to by the reference variable.
More details.
Output:
90
104) What is the difference between static binding and dynamic binding?
In case of the static binding, the type of the object is determined at compile-time whereas, in the dynamic binding,
the type of the object is determined at runtime.
Static Binding
. class Dog{
. private void eat(){System.out.println("dog is eating...");}
.
. public static void main(String args[]){
. Dog d1=new Dog();
. d1.eat();
. }
. }
Dynamic Binding
. class Animal{
. void eat(){System.out.println("animal is eating...");}
. }
.
. class Dog extends Animal{
. void eat(){System.out.println("dog is eating...");}
.
. public static void main(String args[]){
. Animal a=new Dog();
0. a.eat();
1. }
2. }
Output
Test:print() called
Explanation
It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime. At compile-
time, it is checked whether that method is present in the Base class. In this case, it is overridden in the child class,
therefore, at runtime the derived class method is called.
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
300 Java interview questions | Set 2
1 2 3 4 5
There are the following differences between compile-time polymorphism and runtime polymorphism.
2 It is also known as static binding, early It is also known as dynamic binding, late binding
binding, or overloading. or dynamic method dispatch.
4 It provides fast execution because the It provides slower execution as compare to comp
type of an object is determined at because the type of an object is determined at ru
compile-time.
Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method
runtime rather than at compile-time. In this process, an overridden method is called through the referen
a superclass. The determination of the method to be called is based on the object being referred to by th
variable.
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:
In this process, an overridden method is called through the reference variable of a superclass. The deter
method to be called is based on the object being referred to by the reference variable.
More details.
No, because method overriding is used to achieve runtime polymorphism and data members cannot be o
can override the member functions but not the data members. Consider the example given below.
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.
104) What is the difference between static binding and dynamic binding?
In case of the static binding, the type of the object is determined at compile-time whereas, in the dynam
type of the object is determined at runtime.
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.
Output
Test:print() called
Explanation
It is an example of Dynamic method dispatch. The type of reference variable b is determined at runtime.
time, it is checked whether that method is present in the Base class. In this case, it is overridden in the c
therefore, at runtime the derived class method is called.
The instanceof in Java is also known as type comparison operator because it compares the instance with
returns either true or false. If we apply the instanceof operator with any variable that has a null value, it
Consider the following example.
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
referred by either Dog or Animal class.
Core Java - OOPs Concepts: Abstraction Interview Questions
o Abstract Class
o Interface
. abstract class Bike{
. abstract void run();
. }
. class Honda4 extends Bike{
. void run(){System.out.println("running safely");}
. public static void main(String args[]){
. Bike obj = new Honda4();
. obj.run();
. }
0. }
Test it Now
Output
running safely
More details.
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.
. public interface Serializable{
. }
118) What are the differences between abstract class and interface?
An abstract class can have a method body (non-abstract The interface has only abstract methods.
methods).
An abstract class can have instance variables. An interface cannot have instance variables.
An abstract class can have the constructor. The interface cannot have the constructor.
An abstract class can have static methods. The interface cannot have static methods.
You can extend one abstract class. You can implement multiple interfaces.
The abstract class can provide the implementation of the The Interface can't provide the implement
interface. the abstract class.
The abstract keyword is used to declare an abstract class. The interface keyword is used to declare a
An abstract class can extend another Java class and implement An interface can extend another Java interfa
multiple Java interfaces.
A Java abstract class can have class members like private, Members of a Java interface are public by de
protected, etc.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
119) Can we define private and protected modifiers for the members in interfaces?
No, they are implicitly public.
. //A Java class which has only getter methods.
. public class Student{
. //private data member
. private String college="AKG";
. //getter method for college
. public String getCollege(){
. return college;
. }
. }
. //A Java class which has only setter methods.
. public class Student{
. //private data member
. private String college;
. //getter method for college
. public void setCollege(String college){
. this.college=college;
. }
. }
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.
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.
128) Do I need to import java.lang package any time? Why?
No. It is by default loaded internally by the JVM.
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.
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.
132) What is Exception Handling?
Exception Handling is a mechanism that is used to handle runtime errors. It is used primarily to handle checked
exceptions. Exception handling maintains the normal flow of the program. There are mainly two types of exceptions:
checked and unchecked. Here, the error is considered as the unchecked exception.
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.
136) Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch
block OR a finally block. So whatever exceptions are likely to be thrown should be declared in the throws clause of
the method. Consider the following example.
. public class Main{
. public static void main(String []args){
. try{
. int a = 1;
. System.out.println(a/0);
. }
. finally
. {
. System.out.println("rest of the code...");
0. }
1. }
2. }
3.
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.
More details.
2) The checked exceptions cannot be propagated The checked exception can be propagated with throws
with throw only.
4) The throw keyword is used within the method. The throws keyword is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions, e.g., public void metho
IOException, SQLException.
More details.
Output
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.
145) Can subclass overriding method declare an exception if parent class method
doesn't throw an exception?
Yes but only unchecked exception not checked.
More details.
. class TestExceptionPropagation1{
. void m(){
. int data=50/0;
. }
. void n(){
. m();
. }
. void p(){
. try{
0. n();
1. }catch(Exception e){System.out.println("exception handled");}
2. }
3. public static void main(String args[]){
4. TestExceptionPropagation1 obj=new TestExceptionPropagation1();
5. obj.p();
6. System.out.println("normal flow...");
7. }
8. }
Test it Now
Output:
exception handled
normal flow...
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.
. class Testimmutablestring{
. public static void main(String args[]){
. String s="Sachin";
. s.concat(" Tendulkar");//concat() method appends the string at the end
. System.out.println(s);//will print Sachin because strings are immutable objects
. }
. }
Test it Now
Output:
Sachin
More details.
More details.
. 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:
. String s1="Welcome";
. String s2="Welcome";//It doesn't create a new instance
2) By new keyword
. String s=new String("Welcome");//creates two objects and one reference variable
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).
Only one object will be created using the above code because strings in Java are immutable.
More details.
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 too The StringBuffer is fast and cons
) many strings because every time it creates a new instance. memory when you cancat string
3 The String class overrides the equals() method of Object class. So you The StringBuffer class doesn't ov
) can compare the contents of two strings by equals() method. equals() method of Object class
159) What are the differences between StringBuffer and StringBuilder?
The differences between the StringBuffer and StringBuilder is given below.
. public final class Employee{
. final String pancardNumber;
.
. public Employee(String pancardNumber){
. this.pancardNumber=pancardNumber;
. }
.
. public String getPancardNumber(){
. return pancardNumber;
0. }
1.
2. }
More details.
. class Student{
. int rollno;
. String name;
. String city;
.
. Student(int rollno, String name, String city){
. this.rollno=rollno;
. this.name=name;
. this.city=city;
0. }
1.
2. public String toString(){//overriding the toString() method
3. return rollno+" "+name+" "+city;
4. }
5. public static void main(String args[]){
6. Student s1=new Student(101,"Raj","lucknow");
7. Student s2=new Student(102,"Vijay","ghaziabad");
8.
9. System.out.println(s1);//compiler writes here s1.toString()
0. System.out.println(s2);//compiler writes here s2.toString()
1. }
2. }
Output:
163) Write a Java program to count the number of words present in a string?
Program:
. public class Test
. {
. public static void main (String args[])
. {
. String s = "Sharma is a good player and he is so punctual";
. String words[] = s.split(" ");
. System.out.println("The Number of words present in the string are : "+words.length);
. }
. }
Output
o MatchResult Interface
o Matcher class
o Pattern class
o PatternSyntaxException class
165) How the metacharacters are different from the ordinary characters?
Metacharacters have the special meaning to the regular expression engine. The metacharacters are ^, $, ., *, +, etc.
The regular expression engine does not consider them as the regular characters. To enable the regular expression
engine treating the metacharacters as ordinary characters, we need to escape the metacharacters with the
backslash.
166) Write a regular expression to validate a password. A password must start with
an alphabet and followed by alphanumeric characters; Its length must be in
between 8 to 20.
The regular expression for the above criteria will be: ^[a-zA-Z][a-zA-Z0-9]{8,19} where ^ represents the start of
the regex, [a-zA-Z] represents that the first character must be an alphabet, [a-zA-Z0-9] represents the
alphanumeric character, {8,19} represents that the length of the password must be in between 8 and 20.
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.
. class Java_Outer_class{
. //code
. class Java_Nested_class{
. //code
. }
. }
.
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 is decided by
Class compiler.
172) Is there any difference between nested classes and inner classes?
Yes, inner classes are non-static nested classes. In other words, we can say that inner classes are the part of nested
classes.
More details.
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?
. public class Person {
. String name, age, address;
. class Employee{
. float salary=10000;
. }
. class BusinessMen{
. final String gstin="£4433drt3$";
. }
. public static void main (String args[])
0. {
1. Person p = new Person();
2. }
3. }
. abstract class Person{
. abstract void eat();
. }
. class TestAnonymousInner{
. public static void main(String args[]){
. Person p=new Person(){
. void eat(){System.out.println("nice fruits");}
. };
. p.eat();
0. }
1. }
Test it Now
Output:
nice fruits
Consider the following example for the working of the anonymous class using interface.
. interface Eatable{
. void eat();
. }
. class TestAnnonymousInner1{
. public static void main(String args[]){
. Eatable e=new Eatable(){
. public void eat(){System.out.println("nice fruits");}
. };
. e.eat();
0. }
1. }
Test it Now
Output:
nice fruits
. interface interface_name{
. ...
. interface nested_interface_name{
. ...
. }
. }
.
More details.
More details.
More details.
More details.
. public class TestGarbage1{
. public void finalize(){System.out.println("object is garbage collected");}
. public static void main(String args[]){
. TestGarbage1 s1=new TestGarbage1();
. TestGarbage1 s2=new TestGarbage1();
. s1=null;
. s2=null;
. System.gc();
. }
0. }
Test it Now
1) By nulling a reference:
. Employee e=new Employee();
. e=null;
3) By anonymous object:
. new Employee();
. public class FinalizeTest {
. int j=12;
. void add()
. {
. j=j+12;
. System.out.println("J="+j);
. }
. public void finalize()
. {
0. System.out.println("Object is garbage collected");
1. }
2. public static void main(String[] args) {
3. new FinalizeTest().add();
4. System.gc();
5. new FinalizeTest().add();
6. }
7. }
8.
1 Final is used to apply restrictions on class, Finally is used to place Finalize is used to
) method, and variable. The final class can't be important code, it will be clean up processi
inherited, final method can't be overridden, and executed whether an before an object
final variable value can't be changed. exception is handled or not. collected.
. public class Runtime1{
. public static void main(String args[])throws Exception{
. Runtime.getRuntime().exec("notepad");//will open a new notepad
. }
. }
191) 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. The ByteStream classes are used to perform input-output of 8-bit bytes whereas the CharacterStream
classes are used to perform the input/output for the 16-bit Unicode system. There are many classes in the
ByteStream class hierarchy, but the most frequently used classes are FileInputStream and FileOutputStream. The
most frequently used classes CharacterStream class hierarchy is FileReader and FileWriter.
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.
. import java.io.FileOutputStream;
. public class FileOutputStreamExample {
. public static void main(String args[]){
. try{
. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
. fout.write(65);
. fout.close();
. System.out.println("success...");
. }catch(Exception e){System.out.println(e);}
0. }
1. }
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.
. import java.io.FileInputStream;
. public class DataStreamExample {
. public static void main(String args[]){
. try{
. FileInputStream fin=new FileInputStream("D:\\testout.txt");
. int i=fin.read();
. System.out.print((char)i);
.
. fin.close();
0. }catch(Exception e){System.out.println(e);}
1. }
2. }
3.
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.
. package com.javatpoint;
. import java.io.*;
. import java.security.PermissionCollection;
. public class FilePermissionExample{
. public static void main(String[] args) throws IOException {
. String srg = "D:\\IO Package\\java.txt";
. FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");
. PermissionCollection permission = file1.newPermissionCollection();
. permission.add(file1);
0. FilePermission file2 = new FilePermission(srg, "write");
1. permission.add(file2);
2. if(permission.implies(new FilePermission(srg, "read,write"))) {
3. System.out.println("Read, Write permission is granted for the path "+srg );
4. }else {
5. System.out.println("No Read, Write permission is granted for the path "+srg); }
6. }
7. }
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 InputStreamReader(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());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String---");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +scanner.delimiter());
17. scanner.close();
18. }
19. }
20.
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. }
More details.
201) How can you avoid serialization in child class if the base class is implementing
the Serializable interface?
It is very tricky to prevent serialization of child class if the base class is intended to implement the Serializable
interface. However, we cannot do it directly, but the serialization can be avoided by implementing the writeObject()
or readObject() methods in the subclass and throw NotSerializableException from these methods. Consider the
following example.
. import java.io.FileInputStream;
. import java.io.FileOutputStream;
. import java.io.IOException;
. import java.io.NotSerializableException;
. import java.io.ObjectInputStream;
. import java.io.ObjectOutputStream;
. import java.io.Serializable;
. class Person implements Serializable
. {
0. String name = " ";
1. public Person(String name)
2. {
3. this.name = name;
4. }
5. }
6. class Employee extends Person
7. {
8. float salary;
9. public Employee(String name, float salary)
0. {
1. super(name);
2. this.salary = salary;
3. }
4. private void writeObject(ObjectOutputStream out) throws IOException
5. {
6. throw new NotSerializableException();
7. }
8. private void readObject(ObjectInputStream in) throws IOException
9. {
0. throw new NotSerializableException();
1. }
2.
3. }
4. public class Test
5. {
6. public static void main(String[] args)
7. throws Exception
8. {
9. Employee emp = new Employee("Sharma", 10000);
0.
1. System.out.println("name = " + emp.name);
2. System.out.println("salary = " + emp.salary);
3.
4. FileOutputStream fos = new FileOutputStream("abc.ser");
5. ObjectOutputStream oos = new ObjectOutputStream(fos);
6.
7. oos.writeObject(emp);
8.
9. oos.close();
0. fos.close();
1.
2. System.out.println("Object has been serialized");
3.
4. FileInputStream f = new FileInputStream("ab.txt");
5. ObjectInputStream o = new ObjectInputStream(f);
6.
7. Employee emp1 = (Employee)o.readObject();
8.
9. o.close();
0. f.close();
1.
2. System.out.println("Object has been deserialized");
3.
4. System.out.println("name = " + emp1.name);
5. System.out.println("salary = " + emp1.salary);
6. }
7. }
. import java.io.*;
. class Depersist{
. public static void main(String args[])throws Exception{
.
. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
. Student s=(Student)in.readObject();
. System.out.println(s.id+" "+s.name);
.
. in.close();
0. }
1. }
211 ravi
2 It is used to "mark" Java classes so that objects The Externalizable interface provides control of the se
) of these classes may get the certain capability. logic to the programmer.
3 It is easy to implement but has the higher It is used to perform the serialization and often result
) performance cost. performance.
4 No class constructor is called in serialization. We must call a public default constructor while using
) interface.
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.
210) Write a program in Java to establish a connection between client and server?
Consider the following program where the connection between the client and server is established.
File: MyServer.java
. import java.io.*;
. import java.net.*;
. public class MyServer {
. public static void main(String[] args){
. try{
. ServerSocket ss=new ServerSocket(6666);
. Socket s=ss.accept();//establishes connection
. DataInputStream dis=new DataInputStream(s.getInputStream());
. String str=(String)dis.readUTF();
0. System.out.println("message= "+str);
1. ss.close();
2. }catch(Exception e){System.out.println(e);}
3. }
4. }
File: MyClient.java
. import java.io.*;
. import java.net.*;
. public class MyClient {
. public static void main(String[] args) {
. try{
. Socket s=new Socket("localhost",6666);
. DataOutputStream dout=new DataOutputStream(s.getOutputStream());
. dout.writeUTF("Hello Server");
. dout.flush();
0. dout.close();
1. s.close();
2. }catch(Exception e){System.out.println(e);}
3. }
4. }
211) How do I convert a numeric IP address like 192.18.97.39 into a hostname like
java.sun.com?
By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the IP address. Consider the
following example.
. import java.io.*;
. import java.net.*;
. public class InetDemo{
. public static void main(String[] args){
. try{
. InetAddress ip=InetAddress.getByName("195.201.10.8");
.
. System.out.println("Host Name: "+ip.getHostName());
. }catch(Exception e){System.out.println(e);}
0. }
1. }
2.
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.
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.
Syntax
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
219)What are autoboxing and unboxing? When does it occur?
The autoboxing is the process of converting primitive data type to the corresponding wrapper class object, eg., int to
Integer. The unboxing is the process of converting wrapper class object to primitive data type. For eg., integer to int.
Unboxing and autoboxing occur automatically in Java. However, we can externally convert one into another by using
the methods like valueOf() or xxxValue().
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.
226) What comes to mind when someone mentions a shallow copy in Java?
Object cloning.
. class Singleton{
. private static Singleton single_instance = null;
. int i;
. private Singleton ()
. {
. i=90;
. }
. public static Singleton getInstance()
. {
0. if(single_instance == null)
1. {
2. single_instance = new Singleton();
3. }
4. return single_instance;
5. }
6. }
7. public class Main
8. {
9. public static void main (String args[])
0. {
1. Singleton first = Singleton.getInstance();
2. System.out.println("First instance integer value:"+first.i);
3. first.i=first.i+90;
4. Singleton second = Singleton.getInstance();
5. System.out.println("Second instance integer value:"+second.i);
6. }
7. }
8.
228) Write a Java program that prints all the values given at command-line.
Program
. class A{
. public static void main(String args[]){
.
. for(int i=0;i<args.length;i++)
. System.out.println(args[i]);
.
. }
. }
. compile by > javac A.java
. 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
. import java.util.*;
. public class LocaleExample {
. public static void main(String[] args) {
. Locale locale=Locale.getDefault();
. //Locale locale=new Locale("fr","fr");//for the specific locale
.
. System.out.println(locale.getDisplayCountry());
. System.out.println(locale.getDisplayLanguage());
. System.out.println(locale.getDisplayName());
0. System.out.println(locale.getISO3Country());
1. System.out.println(locale.getISO3Language());
2. System.out.println(locale.getLanguage());
3. System.out.println(locale.getCountry());
4.
5. }
6. }
Output:
United States
English
English (United States)
USA
eng
en
US
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:
244) What are the steps involved to write RMI based programs?
There are 6 steps which are performed to write RMI based programs.
. public class BubbleSort {
. public static void main(String[] args) {
. int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
. for(int i=0;i<10;i++)
. {
. for (int j=0;j<10;j++)
. {
. if(a[i]<a[j])
. {
0. int temp = a[i];
1. a[i]=a[j];
2. a[j] = temp;
3. }
4. }
5. }
6. System.out.println("Printing Sorted List ...");
7. for(int i=0;i<10;i++)
8. {
9. System.out.println(a[i]);
0. }
1. }
2. }
Output:
. import java.util.*;
. public class BinarySearch {
. public static void main(String[] args) {
. int[] arr = {16, 19, 20, 23, 45, 56, 78, 90, 96, 100};
. int item, location = -1;
. System.out.println("Enter the item which you want to search");
. Scanner sc = new Scanner(System.in);
. item = sc.nextInt();
. location = binarySearch(arr,0,9,item);
0. if(location != -1)
1. System.out.println("the location of the item is "+location);
2. else
3. System.out.println("Item not found");
4. }
5. public static int binarySearch(int[] a, int beg, int end, int item)
6. {
7. int mid;
8. if(end >= beg)
9. {
0. mid = (beg + end)/2;
1. if(a[mid] == item)
2. {
3. return mid+1;
4. }
5. else if(a[mid] < item)
6. {
7. return binarySearch(a,mid+1,end,item);
8. }
9. else
0. {
1. return binarySearch(a,beg,mid-1,item);
2. }
3. }
4. return -1;
5. }
6. }
Output:
. public class SelectionSort {
. public static void main(String[] args) {
. int[] a = {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
. int i,j,k,pos,temp;
. for(i=0;i<10;i++)
. {
. pos = smallest(a,10,i);
. temp = a[i];
. a[i]=a[pos];
0. a[pos] = temp;
1. }
2. System.out.println("\nprinting sorted elements...\n");
3. for(i=0;i<10;i++)
4. {
5. System.out.println(a[i]);
6. }
7. }
8. public static int smallest(int a[], int n, int i)
9. {
0. int small,pos,j;
1. small = a[i];
2. pos = i;
3. for(j=i+1;j<10;j++)
4. {
5. if(a[j]<small)
6. {
7. small = a[j];
8. pos=j;
9. }
0. }
1. return pos;
2. }
3. }
Output:
. import java.util.Scanner;
.
. public class Leniear_Search {
. public static void main(String[] args) {
. int[] arr = {10, 23, 15, 8, 4, 3, 25, 30, 34, 2, 19};
. int item,flag=0;
. Scanner sc = new Scanner(System.in);
. System.out.println("Enter Item ?");
. item = sc.nextInt();
0. for(int i = 0; i<10; i++)
1. {
2. if(arr[i]==item)
3. {
4. flag = i+1;
5. break;
6. }
7. else
8. flag = 0;
9. }
0. if(flag != 0)
1. {
2. System.out.println("Item found at location" + flag);
3. }
4. else
5. System.out.println("Item not found");
6.
7. }
8. }
Output:
Enter Item ?
23
Item found at location 2
Enter Item ?
22
Item not found
. public class MyMergeSort
. {
. void merge(int arr[], int beg, int mid, int end)
. {
.
. int l = mid - beg + 1;
. int r = end - mid;
.
. intLeftArray[] = new int [l];
0. intRightArray[] = new int [r];
1.
2. for (int i=0; i<l; ++i)
3. LeftArray[i] = arr[beg + i];
4.
5. for (int j=0; j<r; ++j)
6. RightArray[j] = arr[mid + 1+ j];
7.
8.
9. int i = 0, j = 0;
0. int k = beg;
1. while (i<l&&j<r)
2. {
3. if (LeftArray[i] <= RightArray[j])
4. {
5. arr[k] = LeftArray[i];
6. i++;
7. }
8. else
9. {
0. arr[k] = RightArray[j];
1. j++;
2. }
3. k++;
4. }
5. while (i<l)
6. {
7. arr[k] = LeftArray[i];
8. i++;
9. k++;
0. }
1.
2. while (j<r)
3. {
4. arr[k] = RightArray[j];
5. j++;
6. k++;
7. }
8. }
9.
0. void sort(int arr[], int beg, int end)
1. {
2. if (beg<end)
3. {
4. int mid = (beg+end)/2;
5. sort(arr, beg, mid);
6. sort(arr , mid+1, end);
7. merge(arr, beg, mid, end);
8. }
9. }
0. public static void main(String args[])
1. {
2. intarr[] = {90,23,101,45,65,23,67,89,34,23};
3. MyMergeSort ob = new MyMergeSort();
4. ob.sort(arr, 0, arr.length-1);
5.
6. System.out.println("\nSorted array");
7. for(int i =0; i<arr.length;i++)
8. {
9. System.out.println(arr[i]+"");
0. }
1. }
2. }
Output:
Sorted array
23
23
23
34
45
65
67
89
90
101
. public class QuickSort {
. public static void main(String[] args) {
. int i;
. int[] arr={90,23,101,45,65,23,67,89,34,23};
. quickSort(arr, 0, 9);
. System.out.println("\n The sorted array is: \n");
. for(i=0;i<10;i++)
. System.out.println(arr[i]);
. }
0. public static int partition(int a[], int beg, int end)
1. {
2.
3. int left, right, temp, loc, flag;
4. loc = left = beg;
5. right = end;
6. flag = 0;
7. while(flag != 1)
8. {
9. while((a[loc] <= a[right]) && (loc!=right))
0. right--;
1. if(loc==right)
2. flag =1;
3. elseif(a[loc]>a[right])
4. {
5. temp = a[loc];
6. a[loc] = a[right];
7. a[right] = temp;
8. loc = right;
9. }
0. if(flag!=1)
1. {
2. while((a[loc] >= a[left]) && (loc!=left))
3. left++;
4. if(loc==left)
5. flag =1;
6. elseif(a[loc] <a[left])
7. {
8. temp = a[loc];
9. a[loc] = a[left];
0. a[left] = temp;
1. loc = left;
2. }
3. }
4. }
5. returnloc;
6. }
7. static void quickSort(int a[], int beg, int end)
8. {
9.
0. int loc;
1. if(beg<end)
2. {
3. loc = partition(a, beg, end);
4. quickSort(a, beg, loc-1);
5. quickSort(a, loc+1, end);
6. }
7. }
8. }
Output:
254) Write a program in Java to create a doubly linked list containing n nodes.
Consider the following program to create a doubly linked list containing n nodes.
. public class CountList {
.
. //Represent a node of the doubly linked list
.
. class Node{
. int data;
. Node previous;
. Node next;
.
0. public Node(int data) {
1. this.data = data;
2. }
3. }
4.
5. //Represent the head and tail of the doubly linked list
6. Node head, tail = null;
7.
8. //addNode() will add a node to the list
9. public void addNode(int data) {
0. //Create a new node
1. Node newNode = new Node(data);
2.
3. //If list is empty
4. if(head == null) {
5. //Both head and tail will point to newNode
6. head = tail = newNode;
7. //head's previous will point to null
8. head.previous = null;
9. //tail's next will point to null, as it is the last node of the list
0. tail.next = null;
1. }
2. else {
3. //newNode will be added after tail such that tail's next will point to newNode
4. tail.next = newNode;
5. //newNode's previous will point to tail
6. newNode.previous = tail;
7. //newNode will become new tail
8. tail = newNode;
9. //As it is last node, tail's next will point to null
0. tail.next = null;
1. }
2. }
3.
4. //countNodes() will count the nodes present in the list
5. public int countNodes() {
6. int counter = 0;
7. //Node current will point to head
8. Node current = head;
9.
0. while(current != null) {
1. //Increment the counter by 1 for each node
2. counter++;
3. current = current.next;
4. }
5. return counter;
6. }
7.
8. //display() will print out the elements of the list
9. public void display() {
0. //Node current will point to head
1. Node current = head;
2. if(head == null) {
3. System.out.println("List is empty");
4. return;
5. }
6. System.out.println("Nodes of doubly linked list: ");
7. while(current != null) {
8. //Prints each node by incrementing the pointer.
9.
0. System.out.print(current.data + " ");
1. current = current.next;
2. }
3. }
4.
5. public static void main(String[] args) {
6.
7. CountList dList = new CountList();
8. //Add nodes to the list
9. dList.addNode(1);
0. dList.addNode(2);
1. dList.addNode(3);
2. dList.addNode(4);
3. dList.addNode(5);
4.
5. //Displays the nodes present in the list
6. dList.display();
7.
8. //Counts the nodes present in the given list
9. System.out.println("\nCount of nodes present in the list: " + dList.countNodes());
0. }
1. }
Output:
255) Write a program in Java to find the maximum and minimum value node from a
circular linked list.
Consider the following program.
. public class MinMax {
. //Represents the node of list.
. public class Node{
. int data;
. Node next;
. public Node(int data) {
. this.data = data;
. }
. }
0.
1. //Declaring head and tail pointer as null.
2. public Node head = null;
3. public Node tail = null;
4.
5. //This function will add the new node at the end of the list.
6. public void add(int data){
7. //Create new node
8. Node newNode = new Node(data);
9. //Checks if the list is empty.
0. if(head == null) {
1. //If list is empty, both head and tail would point to new node.
2. head = newNode;
3. tail = newNode;
4. newNode.next = head;
5. }
6. else {
7. //tail will point to new node.
8. tail.next = newNode;
9. //New node will become new tail.
0. tail = newNode;
1. //Since, it is circular linked list tail will points to head.
2. tail.next = head;
3. }
4. }
5.
6. //Finds out the minimum value node in the list
7. public void minNode() {
8. Node current = head;
9. //Initializing min to initial node data
0. int min = head.data;
1. if(head == null) {
2. System.out.println("List is empty");
3. }
4. else {
5. do{
6. //If current node's data is smaller than min
7. //Then replace value of min with current node's data
8. if(min > current.data) {
9. min = current.data;
0. }
1. current= current.next;
2. }while(current != head);
3.
4. System.out.println("Minimum value node in the list: "+ min);
5. }
6. }
7.
8. //Finds out the maximum value node in the list
9. public void maxNode() {
0. Node current = head;
1. //Initializing max to initial node data
2. int max = head.data;
3. if(head == null) {
4. System.out.println("List is empty");
5. }
6. else {
7. do{
8. //If current node's data is greater than max
9. //Then replace value of max with current node's data
0. if(max < current.data) {
1. max = current.data;
2. }
3. current= current.next;
4. }while(current != head);
5.
6. System.out.println("Maximum value node in the list: "+ max);
7. }
8. }
9.
0. public static void main(String[] args) {
1. MinMax cl = new MinMax();
2. //Adds data to the list
3. cl.add(5);
4. cl.add(20);
5. cl.add(10);
6. cl.add(1);
7. //Prints the minimum value node in the list
8. cl.minNode();
9. //Prints the maximum value node in the list
0. cl.maxNode();
1. }
2. }
Output:
256) Write a program in Java to calculate the difference between the sum of the
odd level and even level nodes of a Binary Tree.
Consider the following program.
. import java.util.LinkedList;
. import java.util.Queue;
.
. public class DiffOddEven {
.
. //Represent a node of binary tree
. public static class Node{
. int data;
. Node left;
0. Node right;
1.
2. public Node(int data){
3. //Assign data to the new node, set left and right children to null
4. this.data = data;
5. this.left = null;
6. this.right = null;
7. }
8. }
9.
0. //Represent the root of binary tree
1. public Node root;
2.
3. public DiffOddEven(){
4. root = null;
5. }
6.
7. //difference() will calculate the difference between sum of odd and even levels of binary tree
8. public int difference() {
9. int oddLevel = 0, evenLevel = 0, diffOddEven = 0;
0.
1. //Variable nodesInLevel keep tracks of number of nodes in each level
2. int nodesInLevel = 0;
3.
4. //Variable currentLevel keep track of level in binary tree
5. int currentLevel = 0;
6.
7. //Queue will be used to keep track of nodes of tree level-wise
8. Queue<Node> queue = new LinkedList<Node>();
9.
0. //Check if root is null
1. if(root == null) {
2. System.out.println("Tree is empty");
3. return 0;
4. }
5. else {
6. //Add root node to queue as it represents the first level
7. queue.add(root);
8. currentLevel++;
9.
0. while(queue.size() != 0) {
1.
2. //Variable nodesInLevel will hold the size of queue i.e. number of elements in queue
3. nodesInLevel = queue.size();
4.
5. while(nodesInLevel > 0) {
6. Node current = queue.remove();
7.
8. //Checks if currentLevel is even or not.
9. if(currentLevel % 2 == 0)
0. //If level is even, add nodes's to variable evenLevel
1. evenLevel += current.data;
2. else
3. //If level is odd, add nodes's to variable oddLevel
4. oddLevel += current.data;
5.
6. //Adds left child to queue
7. if(current.left != null)
8. queue.add(current.left);
9. //Adds right child to queue
0. if(current.right != null)
1. queue.add(current.right);
2. nodesInLevel--;
3. }
4. currentLevel++;
5. }
6. //Calculates difference between oddLevel and evenLevel
7. diffOddEven = Math.abs(oddLevel - evenLevel);
8. }
9. return diffOddEven;
0. }
1.
2. public static void main (String[] args) {
3.
4. DiffOddEven bt = new DiffOddEven();
5. //Add nodes to the binary tree
6. bt.root = new Node(1);
7. bt.root.left = new Node(2);
8. bt.root.right = new Node(3);
9. bt.root.left.left = new Node(4);
0. bt.root.right.left = new Node(5);
1. bt.root.right.right = new Node(6);
2.
3. //Display the difference between sum of odd level and even level nodes
4. System.out.println("Difference between sum of odd level and even level nodes: " + bt.difference());
5. }
6. }
Output: