Top 50+ Java Interview Questions with Answers., Lecture notes of Computer Science

This document includes explanation of the Top 50+ Java Interview Questions with Answers.

Typology: Lecture notes

2019/2020

Uploaded on 02/19/2020

Sikander_Iqbal
Sikander_Iqbal 🇵🇰

5

(1)

7 documents

1 / 24

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Top 50+ Java Interview
Questions with Answers
We covered nearly 50 + primary Java interview questions in this
tutorial for fresh and experienced candidates.
Q.1- What is Java?
Ans- Java is a high-level programming language and is platform independent. Java is a
collection of objects. It was developed by Aun Microsystems. There are a lot of applications,
websites and games that are developed using Java.
Q.2- What are features of Java?
Ans- The following are the features of Java:
Oops concepts
oObject-oriented
oInheritance
oEncapsulation
oPolymorphism
oAbstraction
Platform independent: A single program works on different platforms without any
modification.
High Performance: JIT (Just In Time compiler) enables high performance in Java.
JIT converts the bytecode into machine language and then JVM starts the execution.
Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread
which is called main thread. The user can create multiple threads by extending the
thread class or by implementing Runnable interface.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download Top 50+ Java Interview Questions with Answers. and more Lecture notes Computer Science in PDF only on Docsity!

Top 50+ Java Interview

Questions with Answers

We covered nearly 50 + primary Java interview questions in this

tutorial for fresh and experienced candidates.

Q.1- What is Java?

Ans- Java is a high-level programming language and is platform independent. Java is a

collection of objects. It was developed by Aun Microsystems. There are a lot of applications,

websites and games that are developed using Java.

Q.2- What are features of Java?

Ans- The following are the features of Java:

 Oops concepts

o Object-oriented

o Inheritance

o Encapsulation

o Polymorphism

o Abstraction

 Platform independent: A single program works on different platforms without any

modification.

 High Performance: JIT (Just In Time compiler) enables high performance in Java.

JIT converts the bytecode into machine language and then JVM starts the execution.

 Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread

which is called main thread. The user can create multiple threads by extending the

thread class or by implementing Runnable interface.

Q.3- How does Java enable high performance?

Ans- To enable high-performance, Java uses just in time compilers. JIT is used for byte

coding of the instructions.

Q.4- What are the Java IDE’s?

Ans- Eclipse and NetBeans are the IDE’s of Java.

Q.5- What do you mean by Constructor?

Ans- The following points will explain the Constructor in detail:

 A constructor is called up according to the class when a new object is installed on a

program.

 The builder is a process with the same name as the name of the unit.

 A default builder will be created if a user does not construct a builder implicitly.

 You can overload the manufacturer.

 Once a builder with a parameter is created, the user will specifically create a builder with no

parameter. Q.6- What is meant by the Local variable and Instance variable?

Ans- Local variables are defined in the method and scope of variables that have existed inside

the method itself.

An instance variable is defined inside the class and outside the method and scope of variables

exist throughout the class.

Q.7- What is a class?

Ans- The class is the definition of all Java codes. A class has different parameters and

methods.

Variables are attributes that define the class status.

Methods is the exact location for carrying out business logic. It contains a set of declarations

(or) to fulfil the specific requirement.

Q.8- What is an Object?

Ans- An instance of a class is called object. The object has state and behaviour.

Whenever the JVM reads the “new()” keyword then it will create an instance of that class.

Q.9- What are the Oops concepts?

Ans- The Oops concepts include:

 Inheritance  Encapsulation  Polymorphism  Abstraction  Interface

We need to render all the instance variables as private for encapsulation and build setter and getter for those variables. Which in effect will cause others to call the setters instead of directly accessing the data. Q.12- What is Polymorphism? Ans: Polymorphism means many forms. A single object can refer the super class or sub-class depending on the reference type which is called polymorphism. Example: 1 Public class Manipulation() { //Super class 2 public void add(){ 3 } 4 } 5 public class Addition extends Manipulation(){ // Sub class 6 public void add(){ 7 } 8 public static void main(String args[]){ 9 Manipulation addition = new Addition();//Manipulation is reference type and Addition is reference type 10 addition.add(); 11 } 12 } Using Manipulation reference type we can call the Addition class “add()” method. This ability is known as Polymorphism. Polymorphism is applicable for overriding and not for overloading. Q.13- What is meant by Method Overriding? Ans: Method overriding happens if the sub class method satisfies the below conditions with the Super class method:  Method name should be same  Argument should be same  Return type also should be same The key benefit of overriding is that the Sub class can provide some specific information about that sub class type than the super class. Example: public class Manipulation{ //Super classpublic void add(){………………}}Public class Addition extends Manipulation(){Public void add(){………..}Public static void main(String args[]){Manipulation addition = new Addition(); //Polimorphism is appliedaddition.add(); // It calls the Sub class add() method}} addition.add() method calls the add() method in the Sub class and not the parent class. So it overrides the Super class method and is known as Method Overriding.

Q.14- What is meant by Overloading? Ans: Method overloading happens for different classes or within the same class. For method overloading, subclass method should satisfy the below conditions with the Super class method (or) methods in the same class itself:  Same method name  Different argument type  May have different return types Example: public class Manipulation{ //Super classpublic void add(String name){ //String parameter………………}}Public class Addition extends Manipulation(){Public void add(){// No Parameter………..}Public void add(int a){ //integer parameter}Public static void main(String args[]){Addition addition = new Addition(); addition.add(); }} Here the add() method having different parameters in the Addition class is overloaded in the same class as well as with the super class. Note: Polymorphism is not applicable for method overloading. Q.15- What is meant by Interface? Ans: Multiple inheritance cannot be achieved in java. To overcome this problem Interface concept is introduced. An interface is a template which has only method declarations and not the method implementation. Example: 1 Public abstract interface IManupulation{ //Interface declaration 2 Public abstract void add();//method declaration 3 public abstract void subtract(); 4 }  All the methods in the interface are internally public abstract void.  All the variables in the interface are internally public static final that is constants.  Classes can implement the interface and not extends.  The class which implements the interface should provide an implementation for all the methods declared in the interface. 1 public class Manupulation implements IManupulation{ //Manupulation class uses the interface 2 Public void add(){ 3 …………… 4 } 5 Public void subtract(){ 6 ……………. 7 } 8 } Q.16- What is meant by Abstract class? Ans: We can create the Abstract class by using “Abstract” keyword before the class name. An abstract class can have both “Abstract” methods and “Non-abstract” methods that are a concrete class.

Then the older value retains in the constant string pool. String Buffer:  Here string values are stored in a stack. If the values are changed then the new value replaces the older value.  The string buffer is synchronized which is thread-safe.  Performance is slower than the String Builder. Example: String Buffer name =”book”; Once the name value has been changed to “pen” then the “book” is erased in the stack. String Builder: This is same as String Buffer except for the String Builder which is not threaded safety that is not synchronized. So obviously performance is fast. Q.19- Explain about Public and Private access specifiers. Ans: Methods and instance variables are known as members. Public: Public members are visible in the same package as well as the outside package that is for other packages.

Public members in Class A are visible to Class B (Same package) as well as Class C (Different package). Private: Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages. Private members in class A is visible only in that class. It is invisible for class B as well as class C. Q.20- Difference between Default and Protected access specifiers. Ans: Default: Methods and variables declared in a class without any access specifiers are called default. Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package. So Class A members are visible to the Class B and invisible to the Class C. Protected: .

 Sorting  Manipulation  Insertion  Deletion A group of objects is known as collections. All the classes and interfaces for collecting are available in Java utile package. Q.25- What are all the Classes and Interfaces that are available in the collections? Ans: Given below are the Classes and Interfaces that are available in Collections: Interfaces:  Collection  List  Set  Map  Sorted Set  Sorted Map  Queue Classes:  Lists:  Array List  Vector  Linked List Sets:  Hash set  Linked Hash Set  Tree Set Maps:  Hash Map  Hash Table  Tree Map  Linked Hashed Map Queue:  Priority Queue Q.26- What is meant by Ordered and Sorted in collections? Ans: Ordered: It means the values that are stored in a collection is based on the values that are added to the collection. So, we can iterate the values from the collection in a specific order. Sorted:

Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects. Q #27) Explain about the different lists available in the collection. Ans: Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed. Types of Lists are: Array List:  Fast iteration and fast Random Access.  It is an ordered collection (by index) and not sorted.  It implements Random Access Interface. Example: public class Fruits{public static void main (String [ ] args){ArrayList names=new ArrayList ();names.add (“apple”);names.add (“cherry”);names.add (“kiwi”);names.add (“banana”);names.add (“cherry”);System.out.println (names);}} Output: [Apple, cherry, kiwi, banana, cherry] From the output, Array List maintains the insertion order and it accepts the duplicates. But not sorted. Vector: It is same as Array List.  Vector methods are synchronized.  Thread safety.  It also implements the Random Access.  Thread safety usually causes a performance hit. Example: public class Fruit {public static void main (String [ ] args){Vector names = new Vector ( ); names.add (“cherry”);names.add (“apple”);names.add (“banana”);names.add (“kiwi”);names.add (“apple”);System.out.println (“names”);}} Output: [cherry,apple,banana,kiwi,apple] Vector also maintains the insertion order and accepts the duplicates. Linked List:  Elements are doubly linked to one another.  Performance is slow than Array list.  Good choice for insertion and deletion.  In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc. Example: public class Fruit {public static void main (String [ ] args){Linkedlist names = new linkedlist

Example: public class Fruits{public static void main (String[ ]args) {Treeset names= new TreeSet( ) ;names.add(“cherry”);names.add(“banana”);names.add(“apple”);na mes.add(“kiwi”);names.add(“cherry”);System.out.println(names);}} Output: [apple, banana, cherry, kiwi] TreeSet sorts the elements in an ascending order. And duplicates are not allowed. Q #29). Explain about Map and their types. Ans: Map cares about unique identifier. We can map a unique key to a specific value. It is a key/value pair. We can search a value, based on the key. Like set, Map also uses “equals ( )” method to determine whether two keys are same or different. Hash Map:  Unordered and unsorted map.  Hashmap is a good choice when we don’t care about the order.  It allows one null key and multiple null values. Example: Public class Fruit{Public static void main(String[ ] args){HashMap<Sting,String> names =new HashMap<String,String>( );names.put(“key1”,“cherry”);names.put (“key2”,“banana”);names.put (“key3”,“apple”);names.put (“key4”,“kiwi”);names.put (“key1”,“cherry”);System.out.println(names);} } Output: {key2 =banana, key1=cherry, key4 =kiwi, key3= apple} Duplicate keys are not allowed in Map. Doesn’t maintain any insertion order and is unsorted. Hash Table:  Like vector key, methods of the class are synchronized.  Thread safety and therefore slows the performance.  Doesn’t allow anything that is null. Example: public class Fruit{public static void main(String[ ]args){Hashtable<Sting,String> names =new Hashtable<String,String>( );names.put(“key1”,“cherry”);names.put(“key2”,“apple”);na mes.put(“key3”,“banana”);names.put(“key4”,“kiwi”);names.put(“key2”,“orange”);Syst em.out.println(names);} } Output: {key2=apple, key1=cherry,key4=kiwi, key3=banana} Duplicate keys are not allowed. Linked Hash Map:

 Maintains insertion order.  Slower than Hash map.  Can expect a faster iteration. Example: public class Fruit{public static void main(String[ ] args){LinkedHashMap<Sting,String> names =new LinkedHashMap<String,String>( ); names.put(“key1”,“cherry”); names.put(“key2”,“apple”); names.put(“key3”,“banana”); names.put(“key4”,“kiwi”); names.put(“key2”,“orange”); System.out.println(names); } } Output: {key2=apple, key1=cherry,key4=kiwi, key3=banana} Duplicate keys are not allowed. TreeMap:  Sorted Map.  Like Tree set, we can construct a sort order with the constructor. Example: public class Fruit{public static void main(String[ ]args){TreeMap<Sting,String> names =new TreeMap<String,String>( );names.put(“key1”,“cherry”);names.put(“key2”,“banana”);na mes.put(“key3”,“apple”);names.put(“key4”,“kiwi”);names.put(“key2”,“orange”);Syste m.out.println(names);}} Output: {key1=cherry, key2=banana, key3 =apple, key4=kiwi} It is sorted in ascending order based on the key. Duplicate keys are not allowed. Q.30- What is meant by Exception?

Ans- An Exception is an issue that can occur during an execution's normal flow. When

something wails at runtime, a method can throw an exception. If the exception can not be

treated, the execution will be terminated before the task is completed.

If the exception is treated, the normal flow should proceed. Exceptions are

java.lang.Exception subclasses.

Q.31- What are types of exception?

Ans- Two types of exceptions are described in detail below:

Checked Exception: At the time of compilation, the compiler tests certain exceptions. Classes

that extend the Throwable class with the exception of Runtime and Error are called Exception

Checked.

Checked Exceptions either have to announce the exception using keyword throes (or)

followed by correct attempt / catch.

E.g. ClassNotFound Error Unchecked Exception: The compiler does not test such exceptions

during the compilation period. Such exceptions are not treated by the compiler.

Q.35- What are Exception handling keywords in Java? Ans: Given below are the two Exception Handling Keywords: try: When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory. catch: This is followed by try block. Exceptions are caught here. finally: This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here. are explained below: #1) Using try/catch: A risky code is surrounded by try block. If an exception occurs, then it is caught by the catch block which is followed by the try block. Example: 1 class Manipulation{ 2 public static void main(String[] args){ 3 add(); 4 } 5 Public void add(){ 6 try { 7 addition(); 8 } catch (Exception e){ 9 e.printStacktrace(); 10 } 11 } 12 } #2) By declaring throws keyword: At the end of the method, we can declare the exception using throws keyword. Example: 1 class Manipulation{ 2 public static void main(String[] args){ 3 add(); 4 } 5 public void add() throws Exception{ 6 addition(); 7 } 8 }

Q.36- Explain about Exception Propagation.

Ans: Exception is first thrown from the method which is at the top of the stack. If it doesn’t

catch, then it pops up the method and moves to the previous method and so on until they are

got.

This is called Exception propagation.

Example: 1 public class Manipulation{ 2 public static void main(String[] args){ 3 add(); 4 } 5 public void add(){ 6 addition(); 7 } From the above example, the stack looks like as shown below:

If an exception occurred in the addition() method is not caught, then it moves to the method

add(). Then it is moved to the main() method and then it will stop the flow of execution. It is

called Exception Propagation.

Q.37- What is the final keyword in Java?

Ans:

Final variable:

Once a variable is declared as final, then the value of the variable could not be changed. It is

like a constant.

Example:

final int = 12;

Final method:

A final keyword in a method that couldn’t be overridden. If a method is marked as a final,

then it can’t be overridden by the subclass.

Final class:

If a class is declared as final, then the class couldn’t be subclassed. No class can extend the

final class.

Q.38- What is a Thread?

Ans: In Java, the flow of a execution is called Thread. Every java program has at least one

thread called main thread, the Main thread is created by JVM. The user can define their own

threads by extending Thread class (or) by implementing Runnable interface. Threads are

executed concurrently.

2 Thread t = new Thread (); 3 t.start (); 4 } 5 public void run(){ 6 Thread.yield(); 7 } 8 } Q.41- Explain about wait () method.

Ans: wait () method is used to make the thread to wait in the waiting pool. When a wait ()

method is executed during a thread execution then immediately the thread gives up the lock

on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given

amount of time.

Then the thread will wake up after notify () (or) notify all () method is called.

Wait() and the other above-mentioned methods do not give the lock on the object

immediately until the currently executing thread completes the synchronized code. It is

mostly used in synchronization.

Example: 1 public static void main (String[] args){ 2 Thread t = new Thread (); 3 t.start (); 4 Synchronized (t) { 5 Wait(); 6 } 7 } Q.42- Difference between notify() method and notifyAll() method in Java.

Ans: Given below are few differences between notify() method and notifyAll() method

notify() notifyAll() This method is used to send a signal to wake up a single thread in the waiting pool. This method sends the signal to wake up all the threads in a waiting spool. Q.43- How to stop a thread in java? Explain about sleep () method in a thread?

Ans: We can stop a thread by using the following thread methods.

 Sleeping

 Waiting

 Blocked

Sleep:

Sleep () method is used to sleep the currently executing thread for the given amount of time.

Once the thread is wake up it can move to the runnable state. So sleep () method is used to

delay the execution for some period.

It is a static method.

Example:

Thread. Sleep (2000)

So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted

exception, hence we need to surround the block with try/catch.

1 public class ExampleThread implements Runnable{ 2 public static void main (String[] args){ 3 Thread t = new Thread (); 4 t.start (); 5 } 6 public void run(){ 7 try{ 8 Thread.sleep(2000); 9 }catch(InterruptedException e){ 10 } 11 } Q.44- When to use Runnable interface Vs Thread class in Java?

Ans: If we need our class to extend some other classes other than the thread then we can go

with the runnable interface because in java we can extend only one class.

If we are not going to extend any class then we can extend the thread class.

Q.45- Difference between start() and run() method of thread class.

Ans: Start() method creates new thread and the code inside the run () method is executed in

the new thread. If we directly called the run() method then a new thread is not created and the

currently executing thread will continue to execute the run() method.

Q.46- What is Multi-threading?

Ans: Multiple threads are executed simultaneously. Each thread starts their own stack based

on the flow (or) priority of the threads.

Example Program: 1 public class MultipleThreads implements Runnable 2 { 3 public static void main (String[] args){//Main thread starts here 4 Runnable r = new runnable (); 5 Thread t=new thread (); 6 t.start ();//User thread starts here 7 Addition add=new addition (); 8 }