0% found this document useful (0 votes)
210 views

Java Passes Everything by Value, and Not by Reference. and When We Say Everything, We

Java passes all variables by value. A marker interface has no methods but indicates something to the compiler or JVM. We can create our own marker interfaces but they will not interact with the JVM like built-in marker interfaces. IS-A relationships refer to inheritance while HAS-A relationships involve composition or aggregation. Polymorphism allows objects to take different forms at runtime through method overriding. Upcasting is implicit while downcasting requires an explicit cast.

Uploaded by

Bhargav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
210 views

Java Passes Everything by Value, and Not by Reference. and When We Say Everything, We

Java passes all variables by value. A marker interface has no methods but indicates something to the compiler or JVM. We can create our own marker interfaces but they will not interact with the JVM like built-in marker interfaces. IS-A relationships refer to inheritance while HAS-A relationships involve composition or aggregation. Polymorphism allows objects to take different forms at runtime through method overriding. Upcasting is implicit while downcasting requires an explicit cast.

Uploaded by

Bhargav
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

JAVA

1. Is java pass by value or pass by reference?

Java passes everything by value, and not by reference. And when we say everything, we
mean everything – objects, arrays (which are objects in Java), primitive types (like ints and
floats), etc. – these are all passed by value in Java.

http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-
reference-or-by-value/

2. What is a marker interface and why do we use it?

The interface does not have any method to be implemented is called marker interface. It is
used to indicate something to compiler or JVM. It is used to store state of an object.

Eg: Serializable, cloneable

3. Can we write our own marker interface?

Marker interface has no method. Java has built-in marker interface like Serializable,
Clonable etc that are understood by JVM.

We can create our own marker interface but it has nothing to do with JVM, we can add
some checks with instanceOf.

interface Marker{ }

class A implements Marker{


int add(int a, int b){
return a+b;
}
}

class Main{
public static void main(String[] args){
A ob = new A();
if (ob instanceOf Marker){
System.out.println(ob.add(2, 5));
}
else{
System.out.println("hi");
}
}
}
How Annotations are better than Marker Interfaces? - They let you achieve the same
purpose of conveying metadata about the class to its consumers without creating a separate type
for it. Annotations are more powerful, too, letting programmers pass more sophisticated
information to classes that "consume" it.

4. instanceof in java?

The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).

5. What is persistent state java object means?

Persistent java object means, the state of the object can be stored to the persistent storage
(eg. hard drive) for later use. State of java object means at particular instance what
information its members are consisting. For object persistence to be possible, the class must
implement the Serializable interface. This interface does not have any method to be
implemented that is why called marker interface.

6. How does it relate to transient variables ?

Sometimes you may want some of your members not required to be saved as part of object
state. You make those member variables transient so that while serialization takes place, all
the members get serialized except transient variables. Static members are not part of
object, they are for class, so no serialization for them also.

7. What is “IS-A and HAS-A relationships”?

IS-A Relationship :

This refers to inheritance or implementation. Expressed using keyword “extends”. Main


advantage is code reusability.

HAS-A Relationship :

Has-A means an instance of one class “has a” reference to an instance of another class
or another instance of same class. It is also known as “composition” or “aggregation”.

There is no specific keyword to implement HAS-A relationship but mostly we are


depended upon “new” keyword.

8. Understanding-Association-Aggregation-and-Composition

http://www.codeproject.com/Articles/330447/Understanding-Association-Aggregation-and-
Composit

Association Aggregation Composition


Owner No owner Single owner Single owner

Life time Have their own lifetime Have their own lifetime Owner's life time

Child Child objects all are Child objects belong to a Child objects belong to a
object independent single parent single parent
Below is a visual representation of how the relationships have emerged from the
requirements.
1. Manager is an employee of XYZ limited corporation. -- Inheritance
2. Manager uses a swipe card to enter XYZ premises. -- Association
3. Manager has workers who work under him. -- Aggregation
4. Manager has the responsibility of ensuring that the project is successful.
--Composition
5. Manager's salary will be judged based on project success. -- Composition

9. Polymorphism
o Polymorphism is the ability of an object to take on many forms.
o There are two types of polymorphism in java- Runtime polymorphism(Dynamic
polymorphism) and Compile time polymorphism (static polymorphism).
o Compile time polymorphism is nothing but the method overloading in java. In simple
terms we can say that a class can have more than one methods with same name but
with different number of arguments or different types of arguments or both
o Method overriding is a perfect example of runtime polymorphism. In this kind of
polymorphism, reference of class X can hold object of class X or an object of any sub
classes of class X. For e.g. if class Y extends class X then both of the following statements
are valid:
 Y obj = new Y();
 //Parent class reference can be assigned to child object
 X obj = new Y();
o Since in method overriding both the classes (base class and child class) has same
method, compile doesn’t figure out which method to call at compile-time. In this case
JVM (java virtual machine) decides which method to call at runtime that’s why it is
known as runtime or dynamic polymorphism.
o Static binding happens at compile-time while dynamic binding happens at runtime.
o Binding of private, static and final methods always happen at compile time since these
methods cannot be overridden. Binding of overridden methods happen at runtime.
o Java uses static binding for overloaded methods and dynamic binding for overridden
methods.
o Important Points
 Final methods cannot be overrided but can be accessed in subclass
 Private methods can be overrided and cannot be accessed in subclass or any
other class
 Static methods can be overrided and can be accessed in subclass
 If class A is a parent class and class B is a sub class
 A has static void add()
 A has void sub()
 Scenario 1 (Both methods are overrided in subclass)
o A a=new B();
o a.add(); --Super class method will be called as it is static
o a.sub(); --Sub class will be called
 Scenario 2 (Both methods are not overrided in subclass)
o A a=new B();
o a.add(); -- Super class method will be called
o a.sub(); -- Super class method will be called
 Scenario 3(Both methods are not available in class A and available
only in class B)
o A a=new B();
o a.add(); -- Compile time error since the method is undefined for
class A
o a.sub(); -- Compile time error since the method is undefined for
class A
10. What is the difference between up-casting and down-casting?

Up-casting: The upcasting is casting from the child class to base class. The upcasting in java
is implicit which means that you don't have to put the braces (type) as an indication for
casting.

public class Animal {


public void callme(){
System.out.println("Animal");
}

public class Dog extends Animal{

public void callme(){


System.out.println("Dog");
}

public void callme2(){


System.out.println("Dog222");
}

public static void main(String[] args) {

//upcasting from subclass to super class


Animal a = new Dog();
a.callme();

}
}

Down-casting: The downcasting is the casting from base class to child class. Downcasting is
explicit note the usage of braces(type)

//Downcasting of reference to subclass reference.

((Dog)a).callme2();

Or

Dog d = (Dog)a;
d.callme2();

If we try in a below way, then ClassCastException is thrown.

Animal animal = new Animal();

Dog dog = (Dog) animal;

The reason why is because animal's runtime type is Animal, and so when you tell the
runtime to perform the cast it sees that animal isn't really a Dog and so throws a
ClassCastException.

11. Java Interfaces


Interface is a pure abstract class. They are syntactically similar to classes, but you cannot
create instance of an Interface and their methods are declared without any body. Interface
is used to achieve complete abstraction in Java.

public interface SampleInterface


{
public static final int i = 10;

public abstract void go();


}

Every field in an interface is public, static and final, even if you


omit one or more of the modifiers.

Every method in an interface is public and abstract, even if you omit


one or more of the modifiers.

12. Why are interface variables static and final by default?


 Java interfaces cannot be instantiated on their own. Since the interface variables are
static, they can be accessed without any instance.
 The final modifier ensures the value assigned to the interface variable is a true
constant that cannot be re-assigned by program code.

13. Difference between abstract class and interface

Abstract class Interfaces


 abstract class can extend only one class or  interface can extend any number of
one abstract class at a time interfaces at a time
 abstract  class  can extend from a class or  interface can extend only from an
from an abstract class interface
 abstract  class  can  have  both  abstract and  interface can  have only abstract
concrete methods methods
 A class can implement any number of
 A class can extend only one abstract class
interfaces
 In abstract class keyword ‘abstract’ is  In an interface keyword ‘abstract’ is
mandatory to declare a method as an optional to declare a method as an
abstract abstract
 abstract  class can have  protected , public  Interface can have only public abstract
and public abstract methods methods i.e. by default
 abstract class can have  static, final  or static  interface  can  have only public static
final  variable with any access specifier final (constant) variable i.e. by default
A Java abstract class cannot be instantiated, Interface is absolutely abstract and
but can be invoked if a main() exists. cannot be instantiated

http://beginnersbook.com/2013/05/abstract-class-vs-interface-in-java/

14. When to use abstract class and interface in Java?


 Interface:
If your child classes should all implement a certain group of methods/functionalities
but each of the child classes is free to provide its own implementation then use
interfaces.
 Abstract Classes
When you have a requirement where your base class should provide default
implementation of certain methods whereas other methods should be open to
being overridden by child classes use abstract classes.
 An abstract class is good if you think you will plan on using inheritance since it
provides a common base class implementation to derived classes.
 An abstract class is also good if you want to be able to declare non-public members.
In an interface, all methods must be public.
 If you think you will need to add methods in the future, then an abstract class is a
better choice. Because if you add new method headings to an interface, then all of
the classes that already implement that interface will have to be changed to
implement the new methods. That can be quite a hassle.
 Interfaces are a good choice when you think that the API will not change for a while.
 Interfaces are also good when you want to have something similar to multiple
inheritance, since you can implement multiple interfaces.

15. Abstraction and Encapsulation


 Data encapsulation in it's simple form means wrapping the relevant data in a class
and controlling it's access. We achieve data encapsulation in java by using access
modifiers - private, package-private and protected.

We can achieve complete encapsulation in java by making members of a class


private and access them outside the class only through getters and setters. The
whole idea behind encapsulation is to hide the implementation details from
users. If a data member is private it means it can only be accessed within the
same class. No outside class can access private data member (variable) of other
class. However if we setup public getter and setter methods to update (for
e.g. void setSSN(int ssn))and read (for e.g.  int getSSN()) the private data fields
then the outside class can access those private data fields via public methods.
This way data can only be accessed by public methods thus making the private
fields and their implementation hidden for outside classes. That’s why
encapsulation is known as data hiding

 Data abstraction simply means generalizing something to hide the complex logic
that goes underneath. We achieve data abstraction in Java primarily by using
Interfaces and abstract classes.

16. How to create a String?


Java 9 : String enhancement
https://dzone.com/articles/will-your-applications-run-faster-with-java-9?
edition=327501&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=Daily
%20Digest%202017-09-28

There are two ways to create a String object in Java:

 Using the new operator. For example,


String str = new String("Hello");.
 Using a string literal or constant expression). For example,
String str="Hello"; (string literal) or
String str="Hel" + "lo"; (string constant expression).

17. What is difference between these String's creations?

In Java, the equals method can be considered to perform a deep comparison of the
value of an object, whereas the == operator performs a shallow comparison. The equals
method compares the content of two objects rather than two objects' references. The
== operator with reference types (i.e., Objects) evaluates as true if the references are
identical - point to the same object. With value types (i.e., primitives) it evaluates as true
if the value is identical. The equals method is to return true if two objects have identical
content - however, the equals method in the java.lang.Object class - the default equals
method if a class does not override it - returns true only if both references point to the
same object.

Default implementation of equals checks for only the references and not the content.
Only if we override equals() method, content will be compared. Since the String literal
overrides equals() method by default, it checks the content.

18. String Literal Pool

http://www.journaldev.com/797/what-is-java-string-pool

String allocation, like all object allocation, proves costly in both time and memory. The
JVM performs some trickery while instantiating string literals to increase performance
and decrease memory overhead. To cut down the number of String objects created in
the JVM, the String class keeps a pool of strings. Each time your code creates a string
literal, the JVM checks the string literal pool first. If the string already exists in the pool,
a reference to the pooled instance returns. If the string does not exist in the pool, a new
String object instantiates then is placed in the pool. Java can make this optimization
since strings are immutable and can be shared without fear of data corruption. For
example

public class Program


{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
System.out.print(str1 == str2);
}
}
The result is

true

Unfortunately, when you use

String a=new String("Hello");

A String object is created out of the String literal pool, even if an equal string already
exists in the pool. Considering all that, avoid new String unless you specifically know that
you need it! For example

public class Program


{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = new String("Hello");
System.out.print(str1 == str2 + " ");
System.out.print(str1.equals(str2));
}
}
The result is

false true

A JVM has a string pool where it keeps at most one object of any String. String literals
always refer to an object in the string pool. String objects created with the new operator
do not refer to objects in the string pool but can be made to using String's intern()
method. The java.lang.String.intern() returns an interned String, that is, one that has an
entry in the global String pool. If the String is not already in the global String pool, then it
will be added. For example

public class Program


{
public static void main(String[] args)
{
// Create three strings in three different ways.
String s1 = "Hello";
String s2 = new StringBuffer("He").append("llo").toString();
String s3 = s2.intern();

// Determine which strings are equivalent using the ==


// operator
System.out.println("s1 == s2? " + (s1 == s2));
System.out.println("s1 == s3? " + (s1 == s3));
}
}
The output is

s1 == s2? false

s1 == s3? true

There is a table always maintaining a single reference to each unique String object in the
global string literal pool ever created by an instance of the runtime in order to optimize
space. That means that they always have a reference to String objects in string literal
pool, therefore, the string objects in the string literal pool not eligible for garbage
collection.

19. Difference between String and StringBuffer

String StringBuffer
 String class is immutable  StringBuffer class is mutable
 String is slow and consumes more memory
 StringBuffer is fast and consumes less
when you concat too many strings because
memory when you cancat strings.
every time it creates new instance.
 String class overrides the equals() method of
StringBuffer class doesn't override the
Object class. So you can compare the
equals() method of Object class.
contents of two strings by equals() method.
String literals can be declared in the following StringBuffer s = “india”; is not possible. It
way. can be created only through “new”
String s = “india”; keyword.
String s= new String("india"); StringBuffer s = new StringBuffer(“india”);
20. Difference between StringBuilder and StringBuffer

StringBuffer StringBuilder
 StringBuilder is non-synchronized i.e. not
StringBuffer is synchronized i.e. thread safe. It
thread safe. It means two threads can call
means two threads can't call the methods of
the methods of StringBuilder
StringBuffer simultaneously.
simultaneously.
 StringBuffer is less efficient than  StringBuilder is more efficient than
StringBuilder. StringBuffer.

21. What is an Exception?

An Exception is an unwanted situation or event that occurs during the execution of a


program, exceptions may lead to termination of the program if not handled properly.

22. Exceptions in java?

Whenever an error occurs within a Java code on runtime, an Object is created called
Exception Object, it contains all information about exception including type or class of
exception and the location where the exception is occurred in the program.

Java run time environment searches for an appropriate handler for this exception object, it
starts searching from the current method to calling methods in reverse and at last the main
method. If an appropriate handler code is found then the exception is handled normally,
otherwise program terminates.

Event handling is a mechanism that provides handler code snippets to the program, so that
the exceptions can be caught and programming flow can be maintained.

23. Exception hierarchy


Throwable is the parent class of all Exceptions that is further extended by two classes,
Exception and Error. In Java Exceptions can be categorized in two main streams
1) Unchecked Exception

The exceptions that are not checked at compile time are called unchecked
exceptions. It means if your program is throwing an unchecked exception and even if
you didn’t handle/declare that exception, the program won’t give a compilation error.
Most of the times these exception occurs due to the bad data provided by user during
the user-program interaction. It is up to the programmer to judge the conditions in
advance, that can cause such exceptions and handle them appropriately. classes that
extends RuntimeException comes under unchecked exceptions. Examples of some
unchecked exceptions are listed below.

ArithmeticException

Mathematical operations that are not permitted in normal conditions


i.e. dividing a number from ‘0’.

package com.beingjavaguys.core;
public class ExceptionTest {
public static void main(String[] args) {
int i = 10/0;
}
}
Console :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:6)
ArrayIndexOutOfBoundsException

Trying to access an index that does not exists or inserting values to


wrong indexes results to ArrayIndesOutOfBound Exception at runtime.
package com.beingjavaguys.core
public class ExceptionTest {
public static void main(String[] args) {
int arr[] = {'0','1','2'};
System.out.println(arr[4]);
}
}

Console :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
4 at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:7)

NullPointerException

Trying to access a null object or performing operations on an object


having a null value.
package com.beingjavaguys.core;
import java.util.ArrayList;
public class ExceptionTest {
public static void main(String[] args) {
String string = null;
System.out.println(string.length());
}
}

Console:
Exception in thread "main" java.lang.NullPointerException
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:9)

2) Checked Exception

Exceptions that are checked at compile-time are called checked exceptions, in


Exception hierarchy all classes that extends Exception class except UncheckedException
comes under checked exception category. 

If some code within a method throws a checked exception, then the method must
either handle the exception or it must specify the exception using throws keyword.

For example, consider the following Java program that opens file at location
“C:\test\a.txt” and prints first three lines of it. The program doesn’t compile, because the
function main() uses FileReader() and FileReader() throws a checked
exception FileNotFoundException. It also uses readLine() and close() methods, and
these methods also throw checked exception IOException
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}

Output:

Exception in thread "main" java.lang.RuntimeException:


Uncompilable source code - unreported exception
java.io.FileNotFoundException; must be caught or declared to be
thrown at Main.main(Main.java:5)

To fix the above program, we either need to specify list of exceptions using throws, or we
need to use try-catch block. We have used throws in the below program.
Since FileNotFoundException is a subclass of IOException, we can just
specify IOException in the throws list and make the above program compiler-error-free.

class Main {
public static void main(String[] args)throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}

Output: First three lines of file “C:\test\a.txt”

24. What are the Exception Handling Keywords in Java?

There are four keywords used in java exception handling.

A. throw: Sometimes we explicitly want to create exception object and then throw it to
halt the normal processing of the program. throw keyword is used to throw exception
to the runtime to handle it.
B. throws: When we are throwing any checked exception in a method and not handling
it, then we need to use throws keyword in method signature to let caller program
know the exceptions that might be thrown by the method. The caller method might
handle these exceptions or propagate it to its caller method using throws keyword.
We can provide multiple exceptions in the throws clause and it can be used
with main() method also.
C. try-catch: We use try-catch block for exception handling in our code. try is the start of
the block and catch is at the end of try block to handle the exceptions. We can have
multiple catch blocks with a try and try-catch block can be nested also. catch block
requires a parameter that should be of type Exception.
D. finally: finally block is optional and can be used only with try-catch block. Since
exception halts the process of execution, we might have some resources open that
will not get closed, so we can use finally block. finally block gets executed always,
whether exception occurrs or not.

25. How to write custom exception in Java?

All exceptions must be a child of Throwable. We can extend Exception class or any of it’s


subclasses to create our custom exception class. The custom exception class can have it’s
own variables and methods that we can use to pass error codes or other exception related
information to the exception handler.
A simple example of custom exception is shown below.

1. Writing a customer defined exception in Java

MyException.java
public class MyException extends Exception
{
public MyException(String message)
{
super(message);
}
}

Analysis of the above code:

"MyException" is our exception class name. You can give any name of your
choice. Important thing to be noted is our class extends "Exception" class. This is
all we need to do make a custom defined exception
"Now we define a constructor of my class. This constructer takes a "String"
argument. We call super class' constructor (super class here is "Exception class")
and pass this string to it. Now Java creates a new Exception with the message
passed in the input String

2. Using the custom defined exception in Java

ExceptionDemo.java
public class ExceptionDemo
{
public static void main(String args[]) throws Exception
{
ExceptionDemo exceptionDemo = new ExceptionDemo();
exceptionDemo.displayNumbers();
}

public void displayNumbers() throws MyException


{
for(int i=0;i<10;i++)
{
System.out.println("i= "+i);
if(i==6)
{
throw new MyException("My Exception Occurred");
}
}
}
}

26. What is OutOfMemoryError and StackOverflowError ?


When you start JVM you define how much RAM it can use for processing. JVM divides this
into certain memory locations for its processing purpose, two of those are Stack & Heap
OutOfMemoryError is related to Heap. If you have large objects (or) referenced objects in
memory, then you will see OutofMemoryError. If you have strong references to objects, then GC
can't clean the memory space allocated for that object. When JVM tries to allocate memory for
new object and not enough space available it throws OutofMemoryError because it can't
allocate required amount of memory.
How to avoid: Make sure un-necessary objects are available for GC

StackOverflowError is related to stack. All your local variables and methods calls related
data will be on stack. For every method call one stack frame will be created and local as well as
method call related data will be placed inside the stack frame. Once method execution is
completed, stack frame will be removed. ONE WAY to reproduce this is, have infinite loop for
method call, you will see stackoverflow error, because stack frame will be populated with
method data for every call but it won't be freed (removed).
How to avoid Make sure method calls are ending (not in infinite loop)

StackOverflowError happens when you execute too many methods one inside another (for
example with an infinite recursion), which is limited by the size of the stack.
OutOfMemoryError happens when the JVM runs out of space to allocate new objects, which are
allocated on the heap.

27. How to create thread?

There are two ways to create a thread:

1. By extending Thread class

class Multi extends Thread{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi t1=new Multi();  
t1.start();  
 }  
}  
2. By implementing Runnable interface.

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
  }  
}  
If you are not extending the Thread class, your class object would not be treated
as a thread object. So you need to explicitly create Thread class object. We are
passing the object of your class that implements Runnable so that your class
run() method may execute.

Who makes your class object as thread object?


Thread class constructor allocates a new thread object. When you create object of Multi class, your class
constructor is invoked(provided by Compiler) from where Thread class constructor is invoked (by
super() as first statement). So your Multi class object is thread object now.

28. Life cycle of a thread

29. Can we start a thread twice?

After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.

30. What if we call run() method directly instead start() method?

Each thread starts in a separate call stack. Invoking the run() method from main thread, the
run() method goes onto the current call stack rather than at the beginning of a new call
stack.

31. Difference between sleep(), join() , yield()

We can prevent a thread from execution by using any of the 3 methods of Thread class:

1. yield() method pauses the currently executing thread temporarily for giving a chance to
the remaining waiting threads of the same priority to execute. If there is no waiting
thread or all the waiting threads have a lower priority then the same thread will continue
its execution. The yielded thread when it will get the chance for execution is decided by
the thread scheduler whose behavior is vendor dependent.
2. join() If any executing thread t1 calls join() on t2 i.e; t2.join() immediately t1 will enter
into waiting state until t2 completes its execution.
3. sleep() Based on our requirement we can make a thread to be in sleeping state for a
specified period of time. It holds the lock.

32. Wait(), notify() and notifyAll()

wait(): It is a method on Object class. It makes the current thread into the "Not Runnable"
state. Wait is called on a object, not a thread. Before calling wait() method, the object
should be synchronized, means the object should be inside synchronized block. The call to
wait() releases the acquired lock

notify() This method is inherited from Object class. It wakes up the first thread that
called wait() on the same object. It should be noted that calling notify() does not actually
give up a lock on a resource. It tells a waiting thread that that thread can wake up. However,
the lock is not actually given up until the notifier’s synchronized block has completed. So, if a
notifier calls notify() on a resource but the notifier still needs to perform 10 seconds of
actions on the resource within its synchronized block, the thread that had been waiting will
need to wait at least another additional 10 seconds for the notifier to release the lock on the
object, even though notify() had been called.

notifyAll() : This method is inherited from Object class. It wakes up all the threads that
called wait() on the same object. The highest priority thread will run first in most of the
situation, though not guaranteed. Other things are same as notify() method above.

 wait(): This method is inherited from Object class. This method makes current
thread to wait until another thread invokes the notify() or the notifyAll() for this
object.

33. What is final, finally and finalize?

final: final is a keyword. The variable decleared as final should be initialized only once and
cannot be changed. Java classes declared as final cannot be extended. Methods declared as
final cannot be overridden.

finally: finally is a block. The finally block always executes when the try block exits. This
ensures that the finally block is executed even if an unexpected exception occurs. But finally
is useful for more than just exception handling - it allows the programmer to avoid having
cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in
a finally block is always a good practice, even when no exceptions are anticipated.

finalize: finalize is a method. Before an object is garbage collected, the runtime system calls
its finalize() method. You can write system resources release code in finalize() method
before getting garbage collected

34. What is synchronization and why is it important?


Synchronization is the process of allowing threads to execute one after another.

Synchronization control the access the multiple threads to a shared resources. Without
synchronization of threads, one thread can modify a shared variable while another thread
can update the same shared variable, which leads to significant errors.

35. What are the differences between synchronized method and synchronized block (statement)?

The practical differences are in controlling scope and the monitor. With a synchronized
method, the lock is obtained for the duration of the entire method. With synchronized
blocks you can specify exactly when the lock is needed.

Basically, synchronized blocks are more general, and synchronized methods can be
rewritten to use synchronized blocks:

class Program {
public synchronized void f() {
.........
}
}
is equivalent to

class Program {
public void f() {
synchronized(this){
...
}
}
}
For example, You have a method with some parts that need synchronized and others don't. The
synchronized block lets you synchronize only the partial line codes that really need it.

36. What is the difference between static synchronized and synchronized methods?

Static synchronized methods synchronize on the class object. If one thread is executing a
static synchronized method, all other threads trying to execute any static synchronized
methods will be blocked.

Non-static synchronized methods synchronize on this ie the instance of the class. If one
thread is executing a synchronized method, all other threads trying to execute any
synchronized methods will be blocked.

37. Give the list of Java Object class methods.

clone() - Creates and returns a copy of this object.

equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.

getClass() - Returns the runtime class of an object.

hashCode() - Returns a hash code value for the object.

notify() - Wakes up a single thread that is waiting on this object's monitor.

notifyAll() - Wakes up all threads that are waiting on this object's monitor.

toString() - Returns a string representation of the object.

wait() - Causes current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.

38. What is Volatile variable in Java and when to use?


 By making a variable volatile using volatile keyword in Java, application programmer
ensures that its value should always been read from main memory and thread should
not use cached value of that variable from their own stack.
 Any variable which is shared between multiple threads should be made volatile, in order
to ensure that all thread must see latest value of volatile variable.
 A signal to compiler and JIT to ensure that compiler does not change ordering or volatile
variable and moves them out of synchronized context.
 You want to save cost of synchronization as volatile variables are less expensive than
synchronization.
 http://tutorials.jenkov.com/java-concurrency/volatile.html

39. What is Covariant Return Type?

The covariant return type specifies that the return type may vary in the same direction as
the subclass.

Before Java5, it was not possible to override any method by changing the return type. But
now, since Java5, it is possible to override method by changing the return type if subclass
overrides any method whose return type is Non-Primitive but it changes its return type to
subclass type. Let's take a simple example:

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[]){
new B1().get().message();
}
}
As you can see in the above example, the return type of the get() method of A class is A but
the return type of the get() method of B class is B. Both methods have different return type
but it is method overriding. This is known as covariant return type.

40. What is collection?

A collection — sometimes called a container — is simply an object that groups multiple


elements into a single unit.

41. What is a Collections Framework?

Collection framework represents a unified architecture for storing and manipulating group
of objects. It has:

 Interfaces and its implementations i.e. classes


 Algorithm(Searching and Sorting)

42. What is Array and how it is created and limitations?

An array is a container object that holds elements of similar data type. The length of an
array is established when the array is created.

Limitations:
 These are fixed in size i.e. once we created an array object there is no
chance of increasing or decreasing size based on our requirement. Hence If
we don’t know size in advance , arrays are not recommended to use.
 Arrays can hold only homogeneous elements. 
 To delete one element in the array, we need to traverse throughout the
array.

43. Methods in Java Array


 Declare an array

int[] i = new int[]{5,8,9,7,2};


String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};

 Print an array in Java

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d

System.out.println(intArrayString);
// [1, 2, 3, 4, 5]

 Create an ArrayList from an array


String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]

 Check if an array contains a certain value


String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true

 Concatenate two arrays


int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
// include apache-commons-lang.jar and import org.apache.commons.lang.ArrayUtils;
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

 Convert an ArrayList to an array


String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);

 Convert an array to a set


String[] stringArray = { "a", "b", "c", "d", "e" };
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]

 Reverse an array
int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]

 Remove element of an array


int[] intArray = { 11, 42, 53, 84, 15 };
int[] removed = ArrayUtils.removeElement(intArray, 53);//array, element
int[] removed = ArrayUtils.remove(intArray, 3); // array,index
System.out.println(Arrays.toString(removed));

44. Wrapper classes

Wrapper classes are used to convert any primitive data type into an object and object into
data type

int k = 100;
Integer it1 = new Integer(k); or Integer it1=Integer.valueOf(k);

The int data type k is converted into an object, it1 using Integer class. The it1 object can be
used in Java programming wherever k is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object
it1.

int m = it1.intValue();
System.out.println(m*m); // prints 10000

intValue() is a method of Integer class that returns an int data type.

45. List of Wrapper Classes

Primitive Type Wrapper Class


Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double

46. Autoboxing and Unboxing

Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object
into primitive automatically. The automatic conversion of primitive into object is known and
autoboxing and vice-versa unboxing.

//Converting int into Integer

int a=20;
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally

//Converting Integer to int

Integer a=new Integer(3);


int j=a;//unboxing, now compiler will write a.intValue() internally

47. Collection vs Collections

48. Class hierarchy of Collection

49. Class hierarchy of Map


50. Difference between list, set and map

Duplicity: List allows duplicate elements. Any number of duplicate elements can be inserted
into the list without affecting the same existing values and their indexes.

Set doesn’t allow duplicates. Set and all of the classes which implements Set interface
should have unique elements.

Map stored the elements as key & value pair. Map doesn’t allow duplicate keys while it
allows duplicate values.

Null values: List allows any number of null values.

Set allows single null value at most.

Map can have single null key at most and any number of null values.

Order: List and all of its implementation classes maintains the insertion order.

Set doesn’t maintain any order; still few of its classes sort the elements in an order such as
LinkedHashSet maintains the elements in insertion order.

Similar to Set, Map also doesn’t stores the elements in an order, however few of its classes
does the same. For e.g. TreeMap sorts the map in the ascending order of keys and
LinkedHashMap sorts the elements in the insertion order, the order in which the elements
got added to the LinkedHashMap.

51. Difference between ArrayList and Vector


 ArrayList uses an Array of Object to store the data internally.
 ArrayList and Vector both implements List interface and maintains insertion order.
 Both allows duplicate and null values
 ArrayList can be made synchronized by
List list = Collections.synchronizedList(new ArrayList());

synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
System.out.println(i.next());
}
}

ArrayList Vector
ArrayList is not synchronized and gives Vector is synchronized and gives poor
better performance(fast). performance(slow)
ArrayList grow by half of its size if Vector doubles the array size if total
number of element exceeds from its number of element exceeds than its
capacity capacity
ArrayList is not a legacy class, it is Vector is a legacy class
introduced in JDK 1.2
The iterator and listIterator returned by The Enumeration returned by Vector is
ArrayList are fail-fast not fail-fast

52. Difference between fail-fast and fail-safe iterator in java?

A fail-fast system is nothing but immediately report any failure that is likely to lead to
failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this
behavior with iterators. In case, you have called iterator on a collection object, and another
thread tries to modify the collection object, then concurrent modification exception will be
thrown. This is called fail-fast.

Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is
modified structurally while one thread is Iterating over it because they work on clone of
Collection instead of original collection and that’s why they are called as fail-safe iterator.
Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator

Iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw
ConcurrentModificationException in Java.

53. Equals and hashcode

HashTable, HashMap and HashSet are the Collection classes in java.util package that make
use of hashing algorithm to store objects. In all these Collection classes except HashSet,
objects are stored as key-value pairs. For the storage and the retrieval of any user-defined
objects it is a good practice to override the following methods which is mentioned below,
hashCode()

equals()

These methods are available in the Object class and hence available to all java classes. Using
these two methods, an object can be stored or retrieved from a Hashtable, HashMap or
HashSet.

hashCode() method

This method returns a hashcode value as an int for the object. Default implementation for
hashcode() should be overridden in order to make searching of data faster. The
implementation of hashCode() method for an user-defined object should be calculated
based on the properties of the class which we wish to consider.

equals() method

This method returns a boolean which specifies whether two objects are equal or not. The
default implementation of equals() method given by the Object Class uses the ‘==’ operator
to compare two object references, and returns true only if they refer to the same object.
But, we can meaningfully re-define this equals() method to have en equality check based on
our own criteria.

Consider the following code, which defines two user defined classes Employee and
EmployeeId which are supposed to be stored in a Map.

Employee.java

public class Employee {


private String name;
public Employee(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
EmployeeId.java

public class EmployeeId {


private String id;
public EmployeeId(String id) {
this.id = id;
}
public String toString() {
return id;
}
}
The following class makes use of the above classes by storing it in a Map for later retrieval.
We are adding Employee objects into the Map keyed with Employee Id.

HashCodeTest.java

public class HashCodeTest {


public static void main(String[] args) {
Map<employeeId, Employee>
employees = new HashMap<employeeId, Employee>();
employees.put(new EmployeeId("111"), new Employee("Johny"));
employees.put(new EmployeeId("222"), new Employee("Jeny")); // Line A
employees.put(new EmployeeId("333"), new Employee("Jessie"));
Employee emp = employees.get(new EmployeeId("222"));// Line B
System.out.println(emp); // Line C
}
}
}
}
In Line B, we try to retrieve the Employee object who has Employee Id with a value of 222.
We expect the output to be ‘Jeny’, because the Employee with Employee Id (222) was
already there in the Collection, but surprisingly, the output of the above code is null. The
reason is that we did not override the equals() method for EmployeeId and Employee
classes because the default implementation of equals() in the Object class considers the new
EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement as
two different instances, and hence the call to get() in Line B returns null.

Let us look at how the same code works when we provide our desired implementation for
hashcode() and equals() methods. We basically override hashcode() here just to make the
object to be searched fast.

Employee.java

public class Employee {


private String name;
public Employee(String name) {
this.name = name;
}
public String toString() {
return name;
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != getClass()) {
return false;
}
Employee emp = (Employee) obj;
if (this.name == emp.name) {
return true;
}
return false;
}

@Override
public int hashCode() {
return name.hashCode();
}
}

EmployeeId.java

public class EmployeeId {


private String id;
public EmployeeId(String id) {
this.id = id;
}
public String toString() {
return id;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj.getClass() != getClass()) {
return false;
}
EmployeeId empId = (EmployeeId) obj;
if (this.id == empId.id) {
return true;
}
return false;
}

@Override
public int hashCode() {
return id.hashCode();
}
}
Now, we get the desired output ‘Jeny’, because as per our implementation for the equals()
method, the new EmployeeId("222") in the put statement and new EmployeeId("222") in
the get statement are considered one and the same.
54. Difference between HashMap and HashTable

HashMap HashTable
HashMap is not synchronized and gives HashTable is synchronized and gives
better performance(fast) poor performance(slow)
HashMap allows one null key and Hashtable doesn't allow any null key or
multiple null values value.
HashMap is a new class introduced in Hashtable is a legacy class
JDK 1.2
HashMap is traversed by Iterator and is Hashtable is traversed by Enumerator
fail-fast and Iterator and is not fail-fast
We can make the HashMap as Hashtable is internally synchronized and
synchronized by calling this code can't be unsynchronized.
Map m =
Collections.synchronizedMap(hashMap);
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

55. Difference between ArrayList and LinkedList

Similarities:

o Both ArrayList and LinkedList are implementation of List interface.


o They both maintain the elements insertion order which means while displaying ArrayList
and LinkedList elements the result set would be having the same order in which the
elements got inserted into the List.
o Both these classes are non-synchronized and can be made synchronized explicitly by
using Collections.synchronizedList method.
o The iterator and listIterator returned by these classes are fail-fast (if list is structurally
modified at any time after the iterator is created, in any way except through the
iterator’s own remove or add methods, the iterator will throw
a ConcurrentModificationException).

ArrayList LinkedList
ArrayList internally uses dynamic array to LinkedList internally uses doubly linked
store the elements. Search operation is list to store the elements.
pretty fast
ArrayList search operation is pretty fast. LinkedList requires the traversal through
get(int index) in ArrayList gives the all the elements for searching an element
performance of O(1) and its performance is O(n)
ArrayList gives variable LinkedList insert and remove operation
performance: O(n) in worst case (while gives O(1) performance
removing first element) and O(1) in best
case (While removing last element).
ArrayList maintains indexes and element LinkedList maintains element data and
data and so less memory overhead two pointers for neighbor nodes hence
the memory consumption is high in
LinkedList

56. When to Use ArrayList and LinkedList?

In real world applications , you will more frequently use ArrayList than LinkedList. But in a
very specific situations LinkedList can be preferred.

1. ArrayList is preferred when there are more get(int) or search operations need to be
performed as every search operation runtime is O(1).

2. If application requires more insert(int) , delete(int) operations then the get(int) operations
then LinkedList is preferred as they do not need to maintain back and forth like arraylist to
preserve continues indices.

57. Difference between HashSet and TreeSet

Similarities:

o Both HashSet and TreeSet does not hold duplicate elements


o Both of these classes are non-synchronized that means they are not thread-safe and
should be synchronized explicitly using Collections.synchronizedSet .
o If you want a sorted Set then it is better to add elements to HashSet and then convert it
into TreeSet rather than creating a TreeSet and adding elements to it.
HashSet<String> hset = new HashSet<String>(); // Create a HashSet
hset.add("Element1"); //add elements to HashSet
hset.add("Element2");

Set<String> tset = new TreeSet<String>(hset); // Creating a TreeSet of HashSet elements


HashSet TreeSet
HashSet gives better performance (faster) TreeSet offers log(n) time cost for the
and offers constant time cost operations like add, remove, contains,
size etc.
HashSet does not maintain any order of TreeSet elements are sorted in ascending
elements order by default.
HashSet can store null object  TreeSet does not allow null object. If one
try to store null object in TreeSet object ,
it will throw Null Pointer Exception.
HashSet uses equals() method for TreeSet uses compareTo() method for
comparison in java maintaining ordering .

58. Differences between the Comparator and the Comparable interfaces

http://javahungry.blogspot.com/2013/08/difference-between-comparable-and.html

Parameter Comparable Comparator

Sorting logic Sorting logic must be in same Sorting logic is in separate class.
class whose objects are being Hence we can write different
sorted. Hence this is called sorting based on different
natural ordering of objects attributes of objects to be
sorted. E.g. Sorting using
id,name etc.
Implementatio Class whose objects to be Class whose objects to be sorted
sorted must implement this do not need to implement this
n interface. e.g Country class interface. Some other class can
needs to implement implement this interface. E.g.-
comparable to collection of CountrySortByIdComparator
country object by id class can implement Comparator
interface to sort collection of
country object by id
Sorting method int compareTo(Object o1) int compare(Object o1,Object
o2)
This method compares this
object with o1 object and This method compares o1 and
returns  a integer. Its value has o2 objects. and returns  a
following meaning integer.Its value has following
1. positive – this object is meaning.
greater than o1 1. positive – o1 is greater than
2. zero – this object equals to o2
o1 2. zero – o1 equals to o2
3. negative – this object is less 3. negative – o1 is less than o1
than o1
Calling method Collections.sort(List) Collections.sort(List,
Here objects will be sorted on Comparator)
the basis of CompareTo Here objects will be sorted on
method the basis of Compare method in
Comparator
Package Java.lang.Comparable Java.util.Comparator

Sort sequence : In comparable ,Only one sort sequence can be created while in comparator
many sort sequences can be created .

Methods Used : Comparator interface in Java has method public int compare (Object o1,
Object o2) which returns a negative integer, zero, or a positive integer as the first argument
is less than, equal to, or greater than the second. While Comparable interface has method
public int compareTo(Object o) which returns a negative integer, zero, or a positive integer
as this object is less than, equal to, or greater than the specified object.

Objects needed for Comparision : If you see then logical difference between these two is
Comparator in Java compare two objects provided to it , while Comparable interface
compares "this" reference with the object specified. So only one object is provided which is
then compared to "this" reference.

Modify Classes : One has to modify the class whose instances you want to sort while in
comparator one build a class separate from the class whose instances one want to sort .

Package : Comparator in Java is defined in java.util package while Comparable interface in


Java is defined in java.lang package, which very much says that Comparator should be used
as an utility to sort objects which Comparable should be provided by default.

59. Comparator example

Employee.java

public class Employee {

private int empId;


private String name;
private int age;

public int getEmpId() {


return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

public Employee(int empId, String name, int age){


this.empId = empId;
this.name = name;
this.age = age;
}

//this is required to print the user friendly information about the Employee
public String toString(){
return "Employee{" + "id=" + empId + ", name=" + name + ", age="
+ age + '}';

EmployeeMain.java

import java.util.*;

public class EmployeeMain {

public static void main(String[] args) {

Employee e1 = new Employee(1,"Gousalya",28);


Employee e2 = new Employee(2,"Akshara",24);
Employee e3 = new Employee(3,"Sathish",31);
Employee e4 = new Employee(4,"Praveen",28);

List list = new ArrayList();


list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);

Collections.sort(list, new AgeComparator());

for (Object obj : list){


System.out.println(obj);
}
}

NameComparator.java

import java.util.Comparator;

public class NameComparator implements Comparator{

public int compare(Object o1, Object o2){


Employee e1 = (Employee)o1;
Employee e2 = (Employee)o2;
return e1.getName().compareTo(e2.getName());

AgeComparator.java

import java.util.Comparator;

public class AgeComparator implements Comparator{

public int compare(Object o1, Object o2){


Employee e1 = (Employee)o1;
Employee e2 = (Employee)o2;
/*if(e1.getAge() == e2.getAge())
return 0;
else if(e1.getAge() > e2.getAge())
return 1;
else
return -1;*/ (or)
return e1.getAge() - e2.getAge();
}

60. Comparable Example

Employee.java

import java.lang.Comparable;

public class Employee implements Comparable{

private int empId;


private String name;
private int age;
private int salary;
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

public Employee(int empId, String name, int age, int salary){


this.empId = empId;
this.name = name;
this.age = age;
this.salary = salary;
}

//this is required to print the user friendly information about the


Employee
public String toString(){
return "Employee{" + "id=" + empId + ", name=" + name + ", age="
+ age + ", salary=" + salary + '}';

public int compareTo(Object obj){


Employee emp = (Employee)obj;
//return this.age - emp.age;
return this.name.compareTo(emp.name);
}

EmployeeMain.java

import java.util.*;

public class EmployeeMain {


public static void main(String[] args) {

Employee e1 = new Employee(1,"Gousalya",28, 6700);


Employee e2 = new Employee(2,"Akshara",24, 13400);
Employee e3 = new Employee(3,"Sathish",31, 8900);
Employee e4 = new Employee(4,"Praveen",28, 16500);

List list = new ArrayList();


list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);

Collections.sort(list);

for (Object obj : list){


System.out.println(obj);
}

61. How HashMap internally works in java?

http://www.ekiras.com/2014/09/how-does-hashmap-works-internally-in-java.html

http://www.javamadesoeasy.com/2015/02/hashmap-custom-implementation.html

HashMap works on the principal of hashing.

Map.Entry interface - This interface gives a map entry (key-value pair). HashMap in Java
stores both key and value object, in bucket, as an object of Entry class which implements
this nested interface Map.Entry.

hashCode() - HashMap provides put(key, value) for storing and get(key) method for
retrieving Values from HashMap. When put() method is used to store (Key, Value) pair,
HashMap implementation calls hashcode on Key object to calculate a hash that is used to
find a bucket where Entry object will be stored. When get() method is used to retrieve
value, again key object is used to calculate a hash which is used then to find a bucket where
that particular key is stored.

equals() - equals() method is used to compare objects for equality. In case of HashMap key
object is used for comparison, also using equals() method Map knows how to handle
hashing collision (hashing collision means more than one key having the same hash value,
thus assigned to the same bucket. In that case objects are stored in a linked list Where
hashCode method helps in finding the bucket where that key is stored, equals method helps
in finding the right key as there may be more than one key-value pair stored in a single
bucket.

Bucket term used here is actually an index of array, that array is called
table in HashMap implementation. Thus table[0] is referred as bucket0,
table[1] as bucket1 and so on

In a nutshell there are three scenarios in case of put() -

 Using hashCode() method, hash value will be calculated. Using that hash it will be
ascertained, in which bucket particular entry will be stored.
 equals() method is used to find if such a key already exists in that bucket, if no then
a new node is created with the map entry and stored within the same bucket. A
linked-list is used to store those nodes.
 If equals() method returns true, which means that the key already exists in the
bucket. In that case, the new value will overwrite the old value for the matched key.

Pictorial representation of how Entry (key-value pair) objects


will be stored in table array

How get() methods works internally


As we already know how Entry objects are stored in a bucket and what happens in
the case of Hash Collision it is easy to understand what happens when key object is
passed in the get method of the HashMap to retrieve a value. Using the key again hash
value will be calculated to determine the bucket where that Entry object is stored, in
case there are more than one Entry object with in the same bucket stored as a linked-list
equals() method will be used to find out the correct key. As soon as the matching key is
found get() method will return the value object stored in the Entry object.

In case of null Key

As we know that HashMap also allows null, though there can only be one null key in
HashMap. While storing the Entry object HashMap implementation checks if the key is
null, in case key is null, it always map to bucket 0 as hash is not calculated for null keys.

62. What is the time complexity of Hashmap get() and put() method ?

The hashmap implementation provides constant time performance for (get and put) basic
operations i.e the complexity of get() and put() is O(1) , assuming the hash function
disperses the elements properly among the buckets.

63. Difference between HashMap and ConcurrentHashMap

HashMap ConcurrentHashMap
HashMap is not thread-safe ConcurrentHashMap is thread-safe that
is the code can be accessed by single
thread at a time
HashMap can be synchronized by using     ConcurrentHashMap synchronizes or
synchronizedMap(HashMap)  method. By locks on the certain portion of the Map .
using this method we get a HashMap To optimize the performance of
object which is equivalent to the ConcurrentHashMap , Map is divided
HashTable object. So every modification into different partitions depending
is performed on  Map is locked on Map upon the Concurrency level . So that we
object. do not need to synchronize the whole
Map Object.
 In HashMap there can only be one null ConcurrentHashMap does not allow
key . NULL values . So the key cannot be null
In multiple threaded environment In ConcurrentHashMap, as only single
HashMap is usually faster since any thread can access the certain portion of
number of threads can access the code at the Map, it reduces the performance .
the same time
64. HashMap example

Student.java

public class Student {

private int id;


private String name;
private String dept;
Address obj;

public Student(int id, String name, String dept, Object obj){


this.id = id;
this.name = name;
this.dept = dept;
this.obj = (Address)obj;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public Address getObj() {
return obj;
}
public void setObj(Address obj) {
this.obj = obj;
}

public String toString(){


return "Student ID:"+ id +",Name:"+ name + ",Dept:"+ dept +
", Address DoorNo:"+ obj.getDoorNo() +",City:"+
obj.getCity() + ",State:"+ obj.getState();
}

Address.java

public class Address {


private int doorNo;
private String city;
private String state;

public Address(int doorNo, String city, String state){


this.doorNo = doorNo;
this.city = city;
this.state = state;
}

public int getDoorNo() {


return doorNo;
}

public void setDoorNo(int doorNo) {


this.doorNo = doorNo;
}

public String getCity() {


return city;
}

public void setCity(String city) {


this.city = city;
}

public String getState() {


return state;
}

public void setState(String state) {


this.state = state;
}

StudentMain.java

import java.util.*;

public class StudentMain {

public static void main(String[] args) {

Address a1 = new Address(1445, "Chennai", "TN");


Address a2 = new Address(11, "Salem", "TN");
Address a3 = new Address(456, "Namakkal", "TN");
Address a4 = new Address(228, "Erode", "TN");

Student s1 = new Student(123,"Harish", "ECE", a1);


Student s2 = new Student(154,"Raja", "CSE" , a2);
Student s3 = new Student(111,"Abinaya", "MECH", a3);
Student s4 = new Student(121,"Gousalya", "EEE", a4);

HashMap<Integer,Student> hm = new HashMap<Integer, Student>();


hm.put(1, s1);
hm.put(2, s2);
hm.put(4, s3);
hm.put(3, s4);

for(Map.Entry<Integer, Student> m : hm.entrySet()){


System.out.println(m.getValue());
}}}
65. How can we sort elements in a ArrayList without using Collections.sort() method?

Create an array list and add it into a TreeSet

ArrayList alist=new ArrayList();


alist.add("c");
alist.add("a");
alist.add("b");
TreeSet ts=new TreeSet();
ts.addAll(alist);
System.out.println(ts);

output will b
a,b,c

66. Many immutable objects are available. But why only String has String constant pool not other
data types?
http://stackoverflow.com/questions/20394116/java-why-is-constant-pool-maintained-
only-for-string-values

67. What will be output of the below program?

final String s = "abc";


s.concat("xyz");
System.out.println(s);
output: abc because String is always immutable.

final StringBuffer sb = new StringBuffer("abc");


sb.append("xyz");
System.out.println(sb);
Output: abcxyz because StringBuffer is mutable.

Note: Eventhough, we are trying to modify a final String variable, error will not be
thrown because we are just trying to append and not assign.

String s = “abc”;
s = s + “def”; or s = s.concat(“def”);
System.out.println(s);
output: abcdef Since we are assigning a new value, it creates a new entry in String
pool and points the reference to “abcdef”.
class Singleton{
String s = "abc";
public static void main(String args[]){
String s ="";
s = s.concat("xyz");
System.out.println(s);
}
}
Output:xyz since static methods will be loaded at the compile time.

68. Is char a = 20; is possible?

Yes, it is possible. It will give the equivalent ASCII value.

Char a =65 gives the output as “A” because the equivalent ASCII code for 65 is A

69. Program to find the max and min element in an array.


int[] a = {56,89,66,22,75};
Arrays.sort(a);
System.out.println("Min element:"+a[0]+" and Max element:"+a[4]);

70. Program to reverse a String


String s = "gousalya";
int len = s.length();
String temp = "";

for(int i = length()-1; i >= 0; i--){


temp = temp + s.charAt(i-1);
}

System.out.println(temp);

71. Program to check whether a given no is prime number or not


public class MyPrimeNumCheck {
public boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}

public static void main(String a[]){


MyPrimeNumCheck mpc = new MyPrimeNumCheck();
System.out.println("Is 19 prime number? +mpc.isPrimeNumber(19));
System.out.println("Is 15 prime number? +mpc.isPrimeNumber(15));
}
}
72. Program to find 2nd largest element in array in java
public class SecondLargest {
public static void main(String[] args) {

int arr[] = { 14, 46, 47, 92, 96, 52, 48, 99, 66, 85 };
int largest = arr[0];
int secondLargest = arr[0];

System.out.println("The given array is:" );


for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++) {

if (arr[i] > largest) {


secondLargest = largest;
largest = arr[i];

} else if (arr[i] > secondLargest) {


secondLargest = arr[i];

}
}

System.out.println("\nSecond largest number is:" +secondLargest);

}
}

73. Program to find whether the given no is power of 2


public class isPowerOfTwo {
public static void main(String[] args) {

int number = 64;


boolean isPowerOfTwo = true;
int reminder = 0;

while(number > 1){


reminder = number % 2;
if(reminder != 0){
isPowerOfTwo = false;
break;
}else{
number = number / 2;
}
}
System.out.println( isPowerOfTwo);
}
}

74. Program to find the count of the letters in a string


public class Countchars {
public static void main(String[] args) {
// TODO Auto-generated method stub

String str = "aabaccadab";


char[] chArr = new char[str.length()];
for(int i =0;i<str.length();i++) {
chArr[i] = str.charAt(i);
}

Map<Character,Integer> map = new HashMap<Character,Integer>();

for(Character c: chArr) {
if(map.containsKey(c)) {
map.put(c, map.get(c)+1);
} else {
map.put(c, 1);
}
}

for(Map.Entry<Character, Integer> m : map.entrySet()) {


System.out.println("the letter "+m.getKey()+" is repeated:
"+m.getValue()+" times");
}

75. Program to find whether the given number is a Palindrome


class Palindrome{
public static void main(String args[]){
int num = 885;
int n = num; //used at last time check
int reverse=0,remainder;
while(num > 0){
remainder = num % 10;
reverse = reverse * 10 + remainder;
num = num / 10;
}
if(reverse == n)
System.out.println(n+" is a Palindrome Number");
else
System.out.println(n+" is not a Palindrome Number");
}
}

76. Program to find whether the given string is a Palindrome


class Palindrome{
public static void main(String args[]){
String s = "malayalam";
int len = s.length();
String reverse = "";
for(int i = len; i > 0; i--){
reverse = reverse + s.charAt(i-1);
}

if(reverse.equalsIgnoreCase(s))
System.out.println(s+" is a Palindrome String");
else
System.out.println(s+" is not a Palindrome String");
}
}

77. Program to print the Fibonacci series(0 1 1 2 3 5 8 13 21 34 55…)


class Singleton{
public static void main(String args[]){
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1

for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are


already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

78. Program to find the factorial of the given number(4! = 4*3*2*1)


class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

79. Is the following way of instantiating the class using interface reference is valid?
interface a {
int i =0;
public void animal();
}

public class test implements a{


public void animal(){
System.out.println("hi");
}
public static void main(String args[]){
a obj = new test();
obj.animal();
}
}

Ans: Yes it is Valid. Output will be “hi”.

80. HashSet implementation internally in java

http://www.ekiras.com/2014/09/internal-implementation-of-hashset-and-how-hashset-
works-internally-in-java.html

public class HashSet extends AbstractSet implements Set, Cloneable,


java.io.Serializable
{
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();

public HashSet() {
map = new HashMap<>();
}

public boolean add(E e) {


return map.put(e, PRESENT)==null;
}

Set  achieves the uniqueness in its elements through  HashMap . In  HashMap ,
each key is unique. So, when an object of HashSet  is created, it will create an object
of  HashMap . When an element is passed to  Set , it is added as a key in the HashMap  in
the  add(Element e)  method. Now, a value needs to be associated to the key. Java
uses a Dummy value ( new Object ) which is called  PRESENT  in  HashSet .
In  HashMap , the  put(Key k,Value V)  method returns:
1. null, if the key is unique. The key will be added to the map.
2. old value of the key, if the key is duplicated.

public V put(K key, V value) {


/* Some code */
}
In HashSet  add(e)  method, the return value of  map.put(key,value)  method
will be checked with  null  value.
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
If  map.put(key,value)  returns  null , then  map.put(e, PRESENT)==null  will
return  true  and element is added to the HashSet .
If  map.put(key,value)  returns the old value of the key, then  map.put(e,
PRESENT)==null will return  false  and element wont be added to the  HashSet .
remove()  method also works in the same way.

public boolean remove(Object o) {


return map.remove(o)==PRESENT;
}

81. How Set or TreeSet or HashSet is not allowing duplicate elements? How is it restricting?

Internally TreeSet store element using HASHTABLE. HASHTABLE is a structure of Key value
pairs. Here what the values passed by the SET is treated as Keys of HASHTABLE Internally.
keys are unique cannot be duplicated. That is the reason if you pass any duplicate value it
return false and does not added to the SET ...

If the adding element return true it will added into SET. Else it return False, that why it won't
give any compilation or runtime error and it won’t be added to SET

Set s = new TreeSet();


s.add(1);
s.add(6);
s.add(null);
s.add(0);
for(Object a:s){
System.out.println(a);
}

The above program will throw “java.lang.NullPointerException” on execution


because TreeSet uses Hashtable and null key is not allowed in Hashtable

Similarly HashSet uses HashMap for checking duplicate elements. As we know that in
HashMap , key should be unique. When element is added to HashSet, it is added to internal
HashMap as Key. This HashMap required some value so a dummy Object(eg : PRESENT) is
used as value in this HashMap.

so , actually when you are adding a line in HashSet like hashset.add(3) , what java does
internally is that it will put that 3 as a key in the HashMap(created during HashSet object
creation) and some dummy value that is Object's object is passed as a value to the key .

Set s = new HashSet();


s.add(1);
s.add(6);
s.add(null);
s.add(0);
for(Object a:s){
System.out.println(a);
}

The above program will print the below output

0
null
1
6

on execution because HashSet uses HashMap and one null key is allowed in
HashMap and output can be in any order

82. Which of the below statements are correct in inserting value into Hashtable?
Hashtable<String, String> h = new Hashtable<String, String>();
h.put(" ", "bbb"); //correct
h.put("", "ccccc"); //correct
h.put(null, "aaaa"); //throws null pointer exception since
hashtable does not allow null key
for(Map.Entry m : h.entrySet()){
System.out.println(m.getKey() + " " + m.getValue());
}

83. Program to find the duplicates in a list.


List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");

Set<String> duplicates = new HashSet<String>();


Set<String> unique = new HashSet<String>();

for(String t : list) {
if(!unique.add(t)) {
duplicates.add(t);
}
}
System.out.println(duplicates);
Output : [b,c,a]

84. Program to find the count of duplicates in a list.


List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));

Output : d: 1
b: 2
c: 2
a: 4

85. Can compile time exception thrown at runtime?

"CompileTimeException"- there is no such type of concept in java.

The Exceptions wich are checked by compiler for smooth execution of the program at
runtime is called checked exception.

Whether the Exception is checked or unchecked it always occured at runtime only . there
is no chance of occuring at compile time.

But in the program if there is any chance of raising checked exception ex:IOException,
InterruptedException( generally raised when we are using Files concept and Thread.sleep()
etc) compiler wont accept that code, we must handle that code by using either "try, catch"
or "throws" keyword.

86. Can we declare run time exception using throws keyword?

Any exception either run time or compile exception can be declared using throws keyword.

class sample{
public static void bar(int i) throws ArithmeticException {
int result = 0;
try{
result = i/0;
}catch(Exception e){
System.out.println(e);
}

}
public static void main(String args[]){
sample s = new sample();
s.bar(10);
}
}
Output: java.lang.ArithmeticException: / by zero

87. Can we throw checked exception using custom exception?

Yes, both checked and unchecked exception can be thrown using custom exception.

In Java, if we create custom exception by extending Exception class then it will be


considered as checked exception.

The checked/unchecked refers to the requirement of handling the exception by the code
that uses your method throwing exception.

Say You throw an unchecked exception in your method (RuntimeException or its subclass).
You do not have to signal that your method throws it and anyone that uses your code does
not need to explicitly handle it.

However if You throw checked exception (Exception that isn't subclass of RuntimeException)
then your method must explicitly say that it throws exception and anyone that uses your
code must handle that exception - either by also declaring their method as method that
throws an exception (rethrow) or by using a try-catch block, around invocation of your
method that throws checked exception.

Creating user defined checked exception:

class UserDefinedException extends Exception {

UserDefinedException(String s) {
super(s);
}

By extending java.lang.Exception, we can create checked exception.

Creating user defined unchecked exception

class UserDefinedException extends RuntimeException {

UserDefinedException(String s) {
super(s);
}

By extending java.lang.RuntimeException, we can create unchecked exception.

88. Main difference between checked and unchecked exception


Main difference between RuntimeException and checked Exception is that, it is mandatory
to provide try catch or try finally block to handle checked Exception and failure to do so will
result in compile time error, while in case of RuntimeException this is not mandatory.

http://java67.blogspot.com/2012/12/difference-between-runtimeexception-and-checked-
exception.html#ixzz4BYsLbfBY

89. What is an immutable class?

An immutable class is one whose state cannot be changed once created. Immutable objects
are good for caching purpose because you don’t need to worry about the value changes.
Other benefit of immutable class is that it is inherently thread-safe, so you don’t need to
worry about thread safety in case of multi-threaded environment.

90. Can we create our own immutable class? If so how?

There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable.

Guidelines to make a class immutable

 Don’t allow subclasses to override methods


The simplest way to do this is to declare the class as final. Final classes in java
can not be overridden.
 Make all fields final and private
This is another way to increase immutability. Fields declared private will not be
accessible outside the class and making them final will ensure the even
accidentally you can not change them.
 Don’t provide “setter” methods — methods that modify fields or objects referred
to by fields.
This principle says that for all mutable properties in your class, do not provide
setter methods. Setter methods are meant to change the state of object and this
is what we want to prevent here.

public final class Employee{


private final String pancardNumber;

public Employee(String pancardNumber){


this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}

91. Why string is always used as key in HashMap?


One of the reason why we generally use String as a key in HashMap is that since String is
immutable in Java that allows String to cache its hashcode , being immutable String in Java
caches its hash code and do not calculate every time we call hashcode method of String,
which makes it very fast as HashMap key.

92. How HashMap handles collision?

HashMap handles collision by using linked list to store map entries (entry set) ended up in
same array location or bucket location

93. Difference between equals() and compareTo()

equals() checks if two objects are the same or not and returns a boolean. 

compareTo() (from interface Comparable) returns an integer. It checks which of the two
objects is "less than", "equal to" or "greater than" the other. 

94. Java 5 features


 Generics : It adds compile-time type safety to the Collections Framework and
eliminates the necessity for type casting.
eg:List<String> names = new ArrayList<String>();
 Enhanced for Loop (for-each loop): Enhanced for loop is also referred as ‘forEach’ Loop
and is specifically designed to iterate through arrays and collections.
eg: List<String> names = new ArrayList<String>();
names.add("Ram");
names.add("Peter");
names.add("Khan");
names.add("Singh");

for (String name : names) {


System.out.println(" Name = " + name);
}
 Autoboxing/Unboxing: refer question no.43
 StringBuilder class

The StringBuffer class has been part of the Java Library since the beginning
whereas the StringBuilder class was added in Java 5. The difference between the
two lies in thread safety. StringBuffer is thread-safe and StringBuilder is not
thread-safe. Most of the time, you do not need thread safety and using
StringBuffer in those cases has a performance penalty. This is the reason that
StringBuilder was added later.

 Typesafe Enums
 Covariant Return Type
 Metadata (Annotations) :Built-In Java Annotations used in java code

@Override
@SuppressWarnings
@Deprecated
 Varags
 Static Import

95. New features in Java SE 6


 Scripting Language Support
 JDBC 4.0 API
 Java Compiler API
 Pluggable Annotations
 New Collections introduced NavigableSet and ConcurrentSkipListSet
 Native PKI, Java GSS, Kerberos and LDAP support.
 Integrated Web Services.
 Lot more enhancements.

96. Using ArrayList or HashMap for better speed


 The ArrayList has O(n) performance for every search, so for n searches its performance
is O(n^2).
 The HashMap has O(1) performance for every search (on average), so for n searches its
performance will be O(n).
 While the HashMap will be slower at first and take more memory, it will be faster for
large values of n.
 The reason the ArrayList has O(n) performance is that every item must be checked for
every insertion to make sure it is not already in the list. We will do n insertions, so it is
O(n^2) for the whole operation.
 The reason the HashMap has O(1) performance is that the hashing algorithm takes the
same time for every key and then the lookup to find the key also takes constant time.
There can be occasions when the hash table exceeds its load factor and needs to be
reallocated, and that is why it is constant on average.
 So finally, to answer your question, my advice is to use the HashMap.

97. How to avoid ambiguity if we implement multiple interfaces?

Via type casting, we are overcoming ambiguity.

http://stackoverflow.com/questions/22675604/multiple-interfaces-in-a-java-class-which-
gets-used-for-method-calls
Java 8:

https://www.softwaretestinghelp.com/java-8-interview-questions/

https://www.interviewbit.com/java-8-interview-questions/

Print random numbers using java 8 (if needed in sorted order add .sorted() after limit in the
below program)

import java.util.Random;

public class RandomNumberJava8 {

public static void main(String[] args) {


// TODO Auto-generated method stub
Random random = new Random();
random.ints().limit(5).forEach(System.out::println);

}}

Sum of numbers in a list

import java.util.ArrayList;

public class SumInList {

public static void main(String args[]) {


ArrayList<Integer> list = new ArrayList<Integer>();

list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

System.out.println(sum(list));
}

private static int sum(ArrayList<Integer> list) {


return list.stream().mapToInt(i -> i).sum();

Write a Java 8 program to square the list of numbers and then filter out the numbers
greater than 100 and then find the average of the remaining numbers?

import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
 
public class Java8 {
    public static void main(String[] args) {
        Integer[] arr = new Integer[] { 100, 100, 9, 8, 200 };
        List<Integer> list = Arrays.asList(arr);
        // Stored the array as list
        OptionalDouble avg = list.stream().mapToInt(n -> n * n).filter(n -> n
> 100).average();
         
        /* Converted it into Stream and filtered out the numbers
            which are greater than 100. Finally calculated the average
        */
         
        if (avg.isPresent())
            System.out.println(avg.getAsDouble());
    }
}

Q #28) Write a Java 8 program to find the lowest and highest number of a Stream?
import java.util.Comparator;
import java.util.stream.*;
 
public class Java8{
   public static void main(String args[]) {
         
    Integer highest = Stream.of(1, 2, 3, 77, 6, 5)
                        .max(Comparator.comparing(Integer::valueOf))
                        .get();
     
    /* We have used max() method with Comparator.comparing() method
       to compare and find the highest number
    */
          
    Integer lowest = Stream.of(1, 2, 3, 77, 6, 5)
                        .min(Comparator.comparing(Integer::valueOf))
                        .get();
     
    /* We have used max() method with Comparator.comparing() method
       to compare and find the highest number
    */
     
    System.out.println("The highest number is: " + highest);
    System.out.println("The lowest number is: " + lowest);
   }
}

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class RevListLambda {


public static void main(String args[]) {
ArrayList<Integer> list = new ArrayList<Integer>();

list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);

List<Integer> list1 = list.stream()


.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());

for(Integer i : list1) {
System.out.println(i);
}
}
}

Given a list of integers, find out all the even numbers exist in the
list using Stream functions?

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,32);


myList.stream()
.filter(n -> n%2 == 0)
.forEach(System.out::println);

Given a list of integers, find out all the numbers starting with 1 using
Stream functions?

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,32);


myList.stream()
.map(s -> s + "") // Convert integer to String
.filter(s -> s.startsWith("1"))
.forEach(System.out::println);

 How to find duplicate elements in a given integers list in java using


Stream functions?

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);


Set<Integer> set = new HashSet();
myList.stream()
.filter(n -> !set.add(n))
.forEach(System.out::println);

Given the list of integers, find the first element of the list using Stream
functions?

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);


myList.stream()
.findFirst()
.ifPresent(System.out::println);

Given a list of integers, find the total number of elements present in the
list using Stream functions?
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
long count = myList.stream()
.count();
System.out.println(count);

Given a list of integers, find the maximum value element present in it


using Stream functions?
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
int max = myList.stream()
.max(Integer::compare)
.get();
System.out.println(max);

Given a String, find the first non-repeated character in it using Stream


functions?
Character result = input.chars() // Stream of String
.mapToObj(s ->
Character.toLowerCase(Character.valueOf((char) s))) // First convert to Character
object and then to lowercase
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting())) //Store the chars in map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);

Given a String, find the first repeated character in it using Stream


functions?
String input = "Java Hungry Blog Alive is Awesome";

Character result = input.chars() // Stream of String


.mapToObj(s ->
Character.toLowerCase(Character.valueOf((char) s))) // First convert to Character
object and then to lowercase
.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting())) //Store the chars in map with count
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1L)
.map(entry -> entry.getKey())
.findFirst()
.get();
System.out.println(result);

Given a list of integers, sort all the values present in it using Stream
functions?

List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);

myList.stream()
.sorted()
.forEach(System.out::println);

https://www.java67.com/2018/10/java-8-stream-and-functional-programming-interview-questions-
answers.html
Program to count the duplicate characters
public class StringCountDuplicateCharJava8Streams {

public static void main(String[] args) {

printCountOfDuplicateCharJava8Stream("bbbcccccddddddaaaa");
printCountOfDuplicateCharJava8Stream("##^$!%^$!^%@!$^@!
kds");

// Using hashmap : print count of each character in a given


string.
private static void
printCountOfDuplicateCharJava8Stream(String input) {

// Step 1
IntStream intStream = input.chars();

// Step 2
Stream<Character> charsStream = intStream.mapToObj(ch ->
(char) ch);

// Step 3
Map<Character, Long> output =
charsStream.collect(Collectors.groupingBy(ch -> ch,
Collectors.counting()));

System.out.println(output);

Comparator with Lambda


List<Employee> employees = getEmployeesFromDB();

//Sort all employees by first name


employees.sort(Comparator.comparing(e -> e.getFirstName()));

//OR you can use below


employees.sort(Comparator.comparing(Employee::getFirstName));

//Sort all employees by first name in reverse order


Comparator<Employee> comparator = Comparator.comparing(e -> e.getFirstName());
employees.sort(comparator.reversed());
//Sorting on multiple fields; Group by.
Comparator<Employee> groupByComparator =
Comparator.comparing(Employee::getFirstName).thenComparing(Employee::getLastName);
employees.sort(groupByComparator);

You might also like