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

Constructor: You Need To Save Your Java Program by The Name of The Class Containing

OOPS concepts include encapsulation, inheritance, polymorphism, and abstraction. Encapsulation involves data hiding using access modifiers like public and private. Inheritance allows subclasses to inherit states and behaviors from parent classes. Polymorphism enables one form to be represented in multiple forms through method overloading and overriding. Abstraction hides unnecessary details and shows only required properties and behaviors.

Uploaded by

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

Constructor: You Need To Save Your Java Program by The Name of The Class Containing

OOPS concepts include encapsulation, inheritance, polymorphism, and abstraction. Encapsulation involves data hiding using access modifiers like public and private. Inheritance allows subclasses to inherit states and behaviors from parent classes. Polymorphism enables one form to be represented in multiple forms through method overloading and overriding. Abstraction hides unnecessary details and shows only required properties and behaviors.

Uploaded by

FuadNaserAl-deen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

What is OOPS?

A basic program in Java will consist of at least


- is the programming technique to write programs based on the following components:
the real-world objects.  Compile a Java Program
You need to save your Java Program
by the name of the class containing
What are the advantages of OOPS concepts? main() method along with .java
extension.
className.java
1. Simplicity: OOPS programming objects model real Call the compiler using javac
world objects, so the complexity is reduced and the program command.
structure is clear. javac className
2. Modularity: Each object forms a separate entity Finally, execute the program using
whose internal workings are decoupled from other parts of the
system.
3. Modifiability: It is easy to make minor changes in the data representation or the procedures in an OO
program. Changes inside a class do not affect any other part of a program, since the only public interface that the
external world has to a class is through the use of methods.
4. Reusability: Objects can be reused in different programs.

What is a constructor in Java?


 A constructor is used to initialize the objects of a class.
 Constructors have similar syntax as methods but constructors
do not have return types.
 Constructors have the same name as the class name.
 At the time of calling constructor, memory for the object is
allocated in the memory.
 Every time an object is created using the new() keyword, at
least one constructor is called.
 It calls a default constructor if there is no constructor
available in the class. In such case, Java compiler provides
a default constructor by default.

What does it mean that object is immutable?  Immutable means that once the constructor for an object has completed
execution that in-  stance can't be altered.  This is useful as it means you can pass references to the object around,
without worrying that  someone else is going to change its contents. Especially when dealing with concurrency, there 
are no locking issues with objects that never change. 
Is String type immutable in java?  Yes 

How to make a java object immutable? 


public final class Student { 
private final String name; 
private final String age; 
public Student(String name, String age) { 
this.name = name; 
this.age = age; 

public String getName() { 
return name; 

public String getAge() { 
return age; 

}   
To make an immutable class:   
•Make your class final 
•Make all the fields private and final Don't provide any methods that change the state of your instance 

•If you have mutable fields in your class, like List or Date, making them final won't 
suffice.
You should return a defensive copy (deep copy) from their getters, so that their  state isn't mutated by calling methods.
Example:   
public Date getDate() { 
return new Date(this.date.getTime()); 

Abstraction – contract - - Information Hiding - You can achieve abstraction in two ways in Java:

1. Using Abstract Class.


2. Using Interface.

OOPS core concepts are:

1. Encapsulation - data hiding - concept to create and define the permissions ‫הרשאות‬- is implemented using four
types of access level modifiers: public, protected, no modifier (default) and private.
Encapsulation provides the security that keeps data and methods safe from inadvertent changes.

2. Inheritance Multi inheritance  Diamond problem


 A subclass can inherit the states and behaviours of its A
super class is known as inheritance. / \
{fun()} B C {fun()}
 Vehicle parent class is known as base class or
\ /
superclass. Car is known as derived class, Child class fun() - D {?}
or subclass. Compile error
 This makes it easy to reuse another class by
extending it (inheriting from it). Java don’t allow multi-inheritance- why?
Due for there is a scenario that parent class have same
name method in both .. then the compiler will crash due for
he doesn’t know which one he should reference.
3. Polymorphism - The ability to change form .
The process of representing one form in multiple forms

. ‫היכולת לשנות צורה‬


‫תהליך הייצוג של טופס אחד בטפסים מרובים‬

 How to achieve Polymorphism:

 Static or Compile time polymorphism, by method overloading

Overloading - compile time polymorphism. 


At least two methods with the same name but different parameter

public void print (int i){


System.out.println("Second Method with only int- "+ i);}
public void print (String s, int i){
System.out.println("Third Method with both- "+ s + "--" + i);

 Dynamic or Runtime polymorphism, by method overriding


Ooverriding (or subtype polymorphism) - runtime polymorphism.
A child class can have the same method - signature

We can override an instance method of parent class in the child class.


When you refer to a child class object using a Parent reference
(e.g.  Parent p = new Child()) and invoke a method, the overriden child class
method will be invoked. Here, the actual method called will depend on the object at
runtime, not the reference type. 

Casting - Casting means converting one data type to another data type.
 There is to kind of casting
o primitive casting – casting on primitive variable.
o Reference casting – casting on reference variable.

primitive casting
1. Implicit Type Casting or Widening Casting (automatically)
2. Explicit Type Casting or Narrowing Casting (manually)

Widening Casting ‫ התרחבות‬-

Whenever smaller capacity data type is being stored in larger


capacity data type, automatically implicit type casting or
widening takes place.

 No loss of information in such type casting.


 Smaller to Bigger data type casting.

Narrowing Casting - ‫צמצום‬

Whenever larger capacity data type is being stored in smaller


capacity data type, explicit type casting or narrowing takes place.

 Loss of information in such type casting.


 Bigger to smaller data type casting.

Why do we need it?


long a = 5;
Suppose there is a case where one needs to store the larger size data
int b = (int)a ;
type in a lower sized data type- the type of a is long and
can’t insert type long into
int x = 100; type of int  so casting
double y = 20.3;

x = y; // ERROR; Double(8 bytes)can't be assigned to int(4 byte)


For such kind of situations, we need to perform explicit type casting or narrowing. Java has its defined way of
performing narrowing casting.

x = (int)20.3; // Explicit TypeCasting


*******************************************************

Reference casting 1. Upcasting 2 - ‫התרחבות‬. Down Casting

Up casting : Assigning child class object to parent class reference .

Syntax for up casting is : Parent p = new Child();

Here p is a parent class reference but point to child Object.

This reference can access all the methods and variables of parent class but only those methods of child class which is
overridden.

‫ הוא‬,)(Child ‫ אבל לשיטות שיש אותם ב‬, Child ‫ או‬parent ‫ הוא יכול לממש כל פונקציה שנמצאת אצל‬,‫ הוא אף פעם לא עף לשגיאה‬,‫במילים אחרות‬
.parent ‫ יממשו ב‬, )(Child ‫ ואלה שאין אותם ב‬overriden ‫ממש אותם כי‬

Down casting : Assigning parent class reference (which is pointing to child class object) to child class reference .

When subclass reference refers to super class object, it is called narrowing or Just because E extends C,
downcasting in java. In other words, when sub class type is converted into super class
type, it is called downcasting. C doesn't become an E...

Syntax for down casting : Child c = (Child)p; E on the other hand is a C

Here p is pointing to the object of child class as we saw earlier and now, we casted
this parent reference p to child class reference c. Now this child class reference c can access all the methods and
variables of child class as well as parent class.

For example, if we have two classes, say Machine and Laptop which extends Machine class.

Now for upcasting, every laptop will be a machine

but for downcasting, every machine may not be a laptop because there may be some machines which can be CPU,
Mobile, etc.

Hence downcasting is not safe, and we explicitly write the class names before doing downcasting. So, it won’t give an
error at compile time but it may throw ClassCastExcpetion at run time if the parent class reference is not pointing to the
appropriate child class.

Let’s see the below example to understand this :

Machine machine = new Machine ();

Laptop laptop = machine; //compilation error because machine here is type Shape i.e. parent

Laptop laptop = (Laptop)machine; //won't give error while compiling

//laptop is a reference of Laptop class and machine is a reference of Machine class and Pointing to Machine class
Object .So logically assigning machine reference to laptop reference is invalid because when laptop ref try to access
methods from Laptop class which are not be visible to laptop reference.And hence throws ClassCastException at run
time .

To get rid of ClassCastException we can use instanceof operator to check right type of class reference in case of down
casting .
Machine machine = new Machine(); //machine3 points to object of Ma-chine class.
Laptop laptop = (Laptop) machine; //here reference laptop2 points to object of Machine class
//This won't give compilation error but it will fail at run time giving an exception for classCastException
//Remember that all machines won't be laptops , they can be CPU or Mo-bile etc.

So, Casting comes into picture when we need to narrow the scope i.e. we move from general type (parent) to more
specific type (child).
Using casting in below statement you tell compiler that i know reference ‘machine’ is of type Machine but it is actually
holding the object of laptop hence knowing that i am casting it and holding it in Laptop reference.

Finally, you can try to downcast. If it’s the correct type, it will be successful. Otherwise, you’ll get a ClassCastException.

recursion.
A recursive method calls itself (contains a call to the method from inside of the method).
A recursive method should have at least one way to stop the recursion. This is called a base
case.

base case - A way to stop the recursive calls. This is a return without a recursive
call.
call stack - A class defines what all objects of that class know (fields) and can do
(methods). You can also have data and behaviour in the object that represents the class
(class fields and methods). All objects of a class have access to class fields and class
methods, but these can also be accessed using className.field or className.method().
recursive method - A method that contains at least one call to itself inside the
method.

 Object − Objects have states and behaviours. Example: A dog has states - colour,
name, breed as well as behaviour such as wagging their tail, barking, eating. An
object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behaviour/state that the object of its type supports.
 Methods − A method is basically a behaviour. A class can contain many methods.
It is in methods where the logics are written, data is manipulated and all the
actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.

3 types of variable in Java:


Local Variables Instance Variables Static Variables
 Static variable public class A {
‫הוא לא שייך לאיסנטנס ספיציפי אלא הוא שייך לקלאס עצמו לכן כל‬ static int aa ;
‫שינוי נשמר‬
‘Constant’ word in the English language basically refers to ‘a public static void main(String[] args) {
situation that does not change‘. System.out.println(a);}}

 Instance Method
Instance method are methods which require an object of its class to be created before it can be called

‫שרשור‬
System.out.printIn(“hello”+5+3) – output – hello53
-due for hello is string and the default in + in strings is ‫שרשור‬

‫ מניח שאתה עדיין צריך לשרשר וממשיך בפעולה‬JAVA ‫לכן‬

System.out.printIn(“hello”+(5+3)) – output – hello8

public class TestStatic {


 Static Method
Static methods are the methods in Java that can public static int getStaticVariable() {…}}
be called without creating an object of class. public static void main(String[] args) {
They are referenced by the class name itself or
reference to the Object of that class. TestStatic.getStaticVariable())//that’s ok if
the main in another class.
Restrictions ‫ מגבלות‬- If it in the same class
There are two main restrictions. They are:
1. The static method can not use non static getStaticVariable())// that’s work too
data member or call non-static method
directly.
2. this and super cannot be used in static context.
3. Static method can’t be override.
4. The static variable has an independent memory location.

Question: Why do we have main() function?


The execution of the program begins from the main() method.

Question: Why is the main method public?

So that it be accessible to the JVM which begins to execute the program from outside of the class.

Question: Why is the main method static?


So that it be available for execution without the need of any object.

Question: Difference between nested and inner classes?


Inner classes are non-static nested classes.

Question: What is a nested interface?

Any interface declared inside a class or an interface. It is static by default.

Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java
byte code into machine language.

The JVM has two primary functions. They are:

1. It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.
2. It manages and optimizes program memory.
The JVM memory manager creates memory pools during the runtime of the program.

There are two types of memory pools namely the stack memory and the heap memory.

The main difference between stack memory and the heap memory is that the stack is used to store only the small
datatypes whereas heap stores all the instances of the class.

Stack Memory Key Features of Stack Memory


Apart from what we have discussed so far, following
Stack Memory is used for static memory allocation and the are some other features of stack memory:
execution of a thread.
 It grows and shrinks as new methods are
called and returned respectively
It contains primitive values that are specific to a method and
references to objects that are in a heap, referred from the
 Variables inside stack exist only as long as
method. the method that created them is running

Access to this memory is in Last-In-First-Out (LIFO) order.  It's automatically allocated and deallocated
when method finishes execution
Whenever a new method is called, a new block on top of the
stack is created which contains values specific to that method,  If this memory is full, Java throws
like primitive variables and references to object java.lang.StackOverFlowError

 Access to this memory is fast when


compared to heap memory

 This memory is thread safe as each thread


Heap Space

is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always
created in heap space and the references to this objects are stored in stack memory.

These objects have global access and can be accessed from anywhere in the application.

This memory model is further broken into smaller parts called generations,
these are:
1. Young Generation – this is where all new objects are allocated and aged. A minor Garbage collection occurs
when this fills up
2. Old or Tenured Generation – this is where long surviving objects are stored. When objects are stored in the
Young Generation, a threshold for the object's age is set and when that threshold is reached, the object is
moved to the old generation
3. Permanent Generation – this consists of JVM metadata for the runtime classes and application methods

What is
the difference between stack and heap?   
 Stack is used to store local variables and function calls while heap memory is used to 
 store objects in Java. 
 Each thread has their own stack. 
 If there is no memory left in the stack JVM will throw java.lang.StackOverFlowError, 
while if there is no heap space JVM will throw java.lang.OutOfMemoryError: Java Heap  Space. 
 Size of stack memory is a lot lesser than the size of heap memory. 
 Variables stored in stacks are only visible to the owner thread while objects created in 
.the heap are visible to all threads

 .How many stack memories are there in java?  One stack per thread

‫טיים אוניברסלי‬TC int s = 153;//char s = ‘d’; U


1970\1\1 ‫התחילו\הכניסו אותו לשפת תוכנה ב‬ System.out.println(s);
boolean p = Integer.class.isInstance(s);
‫סוגים של לולאות‬ System.out.println(p); //true , false
‫לולאה רקורסיבית – רקורסיה‬ ‫אם אני רוצה לדעת אם המשתנה הזה מספר או לא‬
for \ while \ do– ‫לולאה אטרקטיבית‬
Java is always pass-by-value. The difficult thing to understand is that Java passes objects as references and those
references are passed by value.

‫ עותק‬.‫ הוא לא שומר ערך מחוץ לבלוקיים שהוא מוגד‬-‫ בעיקרון – הוא חיי רק בתוך הפונקציה שהוא מוגדר בה‬- Call by value
.‫ אין לו עותק‬,‫ שינוי באיזה מקום שינוי בערך עצמו‬- ‫ – שומר ערך –כל שינוי נשמר‬Call by refference

If we need to do swapping without additional


variable :

int x = 10;
int y = 20;
System.out.println("value of x:" + x);
System.out.println("value of y:" + y);
System.out.println("After swapping");
x = x + y; //30
y = x - y; //30-20 = 10
x = x - y; //30 – 20 = 20

String is always pass by reference

String stored in head in its variable in stack


String str1 = “Hello” =>
str1 = 321 in stack
And 321 its memory in heap and // “hello” = 321 in heap
: Nested Class
Nested classes are divided into two types:

1. Nested, non-static classes- Non-static classes are an


inner class. We know that a class cannot be
associated with the private access modifier, but if
we have the class as a member of another class,
then the inner class can be made private. And this is
also used to access private members of a class.

2. Static nested classes −These are members of a class


and declared static are called static nested classes.  It can be accessed without creating an instance of the
external class, using other static members. Like static members, a static nested class does not have access to the
instance variables and methods of the external class.

There is three Type of non-Static Nested class :

1)Member Inner Class


2)Local Inner Class
3) Anonymous Inner Class

1) Member Inner Class


Class has created within a class and outside a method

2) Local Inner Class // we access the inner class throught the method

2) Anonymous Inner Class


>>>>>>>>this is anonymous class>>>

An advantage of inner classes


In Java, there are three advantages of inner classes. They
are as follows:

 The inner class could be used only by outer class. Inner classes represent a special type of relationship that
allows access to all members (data members and methods) of the outer class, including the private class.
 Inner classes are used to develop a more readable and maintainable code because they logically group classes
and interfaces in one place.
 Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to
write. It can avoid having a separate class.
The second type is : Static nested classes 

Final keyword can only be assigned once.

Once a final variable has been assigned, the variable cannot be changed.

Therefore, the user tries to change the value using the setter or the constructor, and then the errors are entered into
the program.

Final variable : If you make a variable as final, you cannot change the value of the final variable.

A variable with the final keyword cannot be modified so it becomes constant. The variable has to be initialized to be
used in any java program.

Final variable doesn’t accept set method due for it can’t be change.
Final method :
If we marked method as final , can’t be overriding it in inheritance ((‫ירושה‬.
not allowed !
because if you overriding method that’s mean that you update it or change it like you want and final keyword don’t
allow to change it .

Final class : if we marked class as final then we won’t be able to use the class as parent class . we can’t inheritance
from it , we won’t be able to build a sub class for this final class .

In Java, Which package is always available?


Whenever you write a java program the default package that every program will have access to is "java.lang" package &
you don't need to import it separately.
This package defines the classes in it that a basic java program requires to work.
That's the reason why we've this package included by default.

A package is like a folder of similar things .


If you have three package’s you can build each one with the

same class name.


because each class is
separate from the
other it’s inside a
package
Access Modifier
 Visible to the package, the default. No modifiers
are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses
(protected).

Exception :
Handling Exception with try catch block .
The Exception is the parent object to all the Exception class
e.printStackTrace(); - > to track the exception and print it

Finally black after a catch .


You can implement try/finally block without the catch block. And in all the case’s . finally black always executed. Even if
the catch block catch a exception or not.

Throw/throws
The keyword “throw” is used to throw an exception from any method or static block, while the keyword “throws”, used
in a method declaration, indicates what exception can be thrown with this method. They are not interchangeable.

‫ כי כאשר היא מתבצעת היא זורקת אקספטש ויוצאת ולא ממשיכה למטה לכן אם יש מתחתה כל שורה‬,‫היא חייבת להיות השורה האחרונה בשיטה‬
! ‫גאווה צועק שגיאה‬

Always remember when you create


your own exception keep the
following point in your mind:

 All exception should be a


child of Throwable.
 If you want to write a
checked exception that is
automatically enforced by
the Handle or declare rule,
you must extend the
Exception class.

Enum - Enum is used to define a set of constants in java.

Not only constant by it could also call any method,


constructor associated with it.
We should always use enum when a variable (especially a
method parameter) can only take one from a small set of
possible values.

Enum is default public static hence we can directly reference


variable by Enum Name.

You can define an enum type either independently or as part


of a class.

Boxing / unboxing / Autoboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing.

For example — conversion of int to Integer, long to Long, double to Double, etc.
Primitives and Wrapper classes: 
boolean - Boolean 
byte - Byte 
char - Character 
short - Short 
int - Integer 
long - Long 
float - Float 
double - Double 
When a method is expecting a wrapper class object but the value that is passed as parameter is a primitive type.
arrayList.add(11); //Autoboxing - int primitive to Integer

Unboxing: It is just the reverse process of


autoboxing.
Automatically converting an object of a
wrapper class to its corresponding primitive
type is known as unboxing.

For example — conversion of Integer to int,


Long to long, Double to double etc.

Method is expecting Integer object


(parameter) but we have supplied int.

Automatic conversion(unboxing) happened


that converted Integer to int.
The collections accept
reference type- like
integer, double, string,
But it can accept int,
int num = arrayList.get(0); // unboxing char... by unboxing
because get method returns an Integer
object.

Generics : facility of generic programming


which added to java in 2004 within version J2SE 5.0.
Advantages :
1. reusability, if we can class file, we can
2. re use that.
3. Eliminate type casting statements
(improve the program’s performance)
4. Stronger type checking, better type
safety (reduces run time error)
Thi
s

wildcard in generics is basically the question mark


(?)That is used in Java. The use of this can be done
in various ways.
The wildcard can be used in a variety of situations, such as the type of parameter, field, or local variable; sometimes as a
return type.  In addition, you see the use of this in the case of inheritance.

The unknown Wildcard


The question mark (?), Represents the wildcard character and represents an unknown type in generics. As we do not
know what type of List is typed, we can only read from the collection, and we can only treat the objects read as
being Object instances.

Upper Bounded Wildcards


These wildcards can be used when you want to restrictions on the unknown type to be a specific type or a subtype of
that type. To declare upper-bounded wildcard, we use the wildcard character (<?>), Followed by the extend keyword.

public static void display(List<? extends Vehicle> list

Lower Bounded Wildcards


A lower bounded wildcard restricts the unknown type to be a specific type or a supertype of that type. To declare lower-
bounded wildcard, we use the wildcard character (<?>), followed by the keyword super.

List<? Super Car>

Threads
Threads perform a single task that belongs to a single process.

A thread is a mini process within a process that can execute or perform operations independently. A thread is a
lightweight process. Unlike many other computer languages, Java provides integrated support for multi-threaded
programming. A multi-process program contains two or more parts
that can be executed simultaneously.

Each part of that program is called a subprocess and each subprocess


defines a different execution path. Therefore, multithreading is a
specialized form of multitasking.
In a single-threaded application, only one thread is executed at a time
because the application or the program can only handle one task at a
time.

The following snippet demonstrates that threads exist in several


states:
 New: when we create an instance of the Thread class, a
thread is in a new state.
 Runnable State: Runnable status is a state where the thread is ready to run.
 Running state: A thread is executing where multi-threaded programming is derived by the hardware.
 Blocked/ waiting state: A Java thread can be blocked when a resource is expected.
 Terminated/ dead state: A thread can be terminated, which stops its execution immediately at any time. Once a
thread is finished, it cannot be resumed.
run(); // Run method should be called by JVM

There are two ways for creating threads and associate them with the required code.

1. Creating threads by extending the thread class.


we Extend “Thread class”.
Then override the public void run() method which will be executed when the thread is started.

2. the use of the Runnable


Interface.

The runnable interface declares


the run method that must be
implemented by the class
(implementing it).

Synchronization under
concurrency control

Java synchronization is a concept where errors can appear in the code if the same entity is shared by two or more
threads. Therefore, it can cause different results
each time the execution takes place.

When we start two or more threads within a


program, there may be a situation in which
multiple threads try to access the same
resource. Therefore, it is necessary to
synchronize the action of several threads and
make sure that only one thread can access the
resource at a given time.
Types of Synchronization

1. Synchronized method
2. Synchronized block
3. Static synchronization

Synchronized method

synchronized public void generate() {

with this world before the method, java


Guarantee that in the same loop JUST ONE
THREAD WILL BE.
And the output will be

synchronized is a lock for a specific object, if we create

Brakets braket1 = new Brakets();


Brakets braket2 = new Brakets();
And for thread1 . breaket1.start();
And the same for the other.
the problem will back. Exactly the left output image, because now there is two locks

So , synchronized is for specific object

Again, synchronized is do the job but in all the method, if there is another loop that I don’t want to synchronized I can’t
with this case.

So; the solution is to make block for the specific loop that I need to synchronized
Synchronized block
synchronized (this) {
// synchronized block loop
}

Static synchronization

If we want to be multi-
threading/multi-processing thing we
should use static cuz static don’t share
memory.

Usage of volatile keyword

The usage of volatile keyword is used


to declare the variables that will be modified by
different threads. All changes in the variable will
be directly written back to the memory.
This keyword cannot be applied to class or method. It can only be used with a variable.

When the thread is dependent on the variable always use the volatile keyword. It means this variable will not be cached
by the thread.

This that value of the volatile variable will always be read from main memory and not from Thread’s local cache.

volatile public static int flag = 0;

wait();//wait until some other thread calls the notify method


notify(); // release the specific wait()

how he know which wait() ? it’s depends on the priority of the threads

 Remember wait() and notify() method is defined in the object class, and they must be called inside the
synchronized block.
 When notify() method is called the lock on the wait method would be released. We would be able to perform
the operation.
Interrupt

The basic concepts of interrupt is that it stops the thread that is in an idle state by showing the interrupted exception.
Therefore, it can be given a chance to execute in case of a long wait or sleep functions.

Suppose there are two threads and If one of the threads is blocked in an invocation of the wait() method of this class,
then its interrupt status will be cleared and it will receive an Interrupt Exception, which gives the chance to another
thread to execute the corresponding run() method of another thread which results into high performance and reduces
the waiting time of the threads.

Sometimes there can be a situation where the thread should not work continuously, but it can go in wait state
once a while, to give other threads a chance to do their work. But when a thread is waiting it can’t check actively
whether it should terminate. Then we need to use interrupt() method. We can call the interrupt() method
directly from the run() method.

Join overview

The joining method is an optimal solution to


the problem of inconsistency that occurs due
to threads not having a proper order. The join
method is used to notify that the thread will
wait until the execution of the given thread
before execution.

There are three versions of the join:

1. join () method
will put the current thread on wait until
the thread in which it is called is dead.
If the thread is interrupted,
InterruptedException will be thrown.
2. join (long millis) method will put the
current thread on wait until the thread
in which it is called is dead or wait for
the specified time (milliseconds).
3. join (long millis, int nanos) method
will put the current thread on wait until the thread in which it is called is dead or wait for the specified time
(milliseconds + nanos).

Thread pools
a thread pool that is a software design pattern for achieving concurrency of execution in a computer program. Often,
also called a replicated workers or worker-crew model, a thread pool maintains several threads waiting for tasks to be
allocated for concurrent execution by the supervising program.

In the following program, we have SomeThread class which extend Thread. Inside the App class, we are creating fixed
thread pool from Executors framework. Then we pass the object of thread type for executing threads.  And shut down
the Executor pool.  shutdown() method helps us to finish execution of all the submitted tasks and terminate the thread
pool.

countdown latch

The basic use of this is that we can place the thread that we want to execute after a certain number of threads. This can
be done by setting the countdown number to the number of threads after which we want the specific thread to be
executed.

So, CountDownLatch, it’s used when a thread needs to wait for other threads before starting its work.

As we have seen above program, where we create a task that is going to wait for four threads before it starts. Then we
create four threads and start them.

Here we call the latch.await() method. This method will force the main thread waits for four threads until the lock is
released.

In order to release the lock, we use latch.countDown() method. It reduces the count of the latch and released all
waiting threads.
The blocking queue
is used as a container for objects when the threads are inserting the objects and other threads are taking the objects
out of it. The threads can only continue inserting the objects until a specific limit and take out or use the resources until
a specific limit. Therefore, any limit reached the blocking queue will immediately block the threads.

The following program will demonstrate the capability of blocking queue. In order to understand the concept of
blocking queue, we will start with the producer and consumer. As the name suggests producer thread add the element
in the queue and consumer thread consumes the element from the queue. These two threads works simultaneously on
blocking queue collection.

We have created a producer class which implements the Runnable interface. Producer class will use the put() method to
add elements in the queue and before putting new element the thread will wait for one second.

Once the element in blocking queue reached to the maximum limit, instead of terminating the program blocking queue
will force the thread to wait until there is an empty space.

The Reentrant lock – ‫מנעול חוזר‬


is a mutually exclusive lock. This lock means that the lock can be accessed by the thread that owns it or controls it more
than once. Therefore, if any thread has access to that lock, no other thread, except that thread, can use that. This is the
specific use of that lock.

Here we show how to use ReentrantLock in Java. Reentrant locking is an alternative form of locking apart from the
implicit locking provided by keyword
synchronized in Java.

Use the lock () method to acquire-‫לקבל‬,‫ להשיג‬-


the lock on the shared resource. After
completing the job, call the unlock() method
to release the lock.

A finally block contains all the crucial


declarations that must be executed, whether
an exception occurs or not. The declarations
present in this block will always be executed
regardless of whether an exception occurs in
the try block or not.

It is optional, a try-catch block is sufficient for


exception handling, however, if you place a
finally block then it will always run after the
execution of try block.

Suppose that within for loop we find an


exception in that type of scenario lock will
not be released because we will not be able to call the lock.unlock () method. In that situation, we will use finally
block.

The deadlock

is a condition in which the resources cannot be


allocated to two or more threads in current
resources requirement, which leads to a state of a
halt as the resources cannot be released nor can be
acquired therefore this brings the processing to a
complete halt. So this situation is studied with the
help of threads and locks.

Here is a simple diagram of the Deadlock condition.

In the following program, we have created two


threads, thread1 and thread2. In thread2 synchronized block had a lock on object lock2 and in thread1 synchronized
block had a lock on object lock1.

‘thread1’ prints “Inside thread1 on lock 1” and ‘thread2’ prints “Inside thread2 on lock 2”. ‘thread1’ tries to acquire the
lock on object lock2 but as it is already holed by thread1.

Same happens with thread2. It tries to acquire the lock on object lock1 but it is already holed by thread1, so it waits till it
becomes free.  Hence, both threads are in a wait state, waiting for each other to release locks. But none of them is
ready to release the lock. This intersection causes the deadlock to occur.
https://www.csie.ntu.edu.tw/~d00922011/java2/multithreading/JavaThreads.pdf
Lambda expression

The lambda expression is used mainly to execute programs making the


programs shorter.

We can make use of lambda expression for

An interface with the only a single abstract method is called a functional


interface.

Here the lambda expression on threads is explained. As we know, we


can have created threads with the Runnable method and, therefore,
this could be done more efficiently with the help of lambdas.

Comparator -sort- without lambda- the regular expression.

This is the Lambda expression ! one line

Lambda can accept variable out of the scope


Lambda lambda = ()->10; // >>>>that’s mean return 10

for each loop :different on what we know

The predicate is a simple Boolean function that evaluates the


function to true or false according to the assigned condition.

The predicate is a functional interface and can, therefore, be


used as the assignment target for a lambda expression or
method reference.

Predicate with a method 9-> 3.9 ---4.10


File Handling - Data streams

The stream is a sequence of data. It could be a sequence of input, output or error stream. As the name suggest input
and output. It is used for the purpose of input and output respectively.

In Java streams are automatically created for us. All these streams are attached with console.

1. System.out: Output stream is used to write a file.


2. System.in: input stream is used to read a file.
3. System.err: error stream is used to handle or show the error.

Here is the program that demonstrates to create a file


inside the folder. If you used this type of path on a windows
machine that starts with (/ or \\), the path will be
interpreted as relative to the current project.

to create a subfolder inside the directory. We


use mkdirs() method instead of mkdir(). With mkdirs() you
can create a file inside the directory of the leaf folder in
your path, the path will be interpreted as relative to the
current project.

Create file inside a folder :

Writing into files

The file writing includes the use of Buffered Writer and


File Writer in order to write any statement into the file.

To write content into the file we must use


“BufferedWriter”.  This is used to write single arrays,
characters, and strings.

FileWriter is also a convenient class for writing text


files using the default character encoding of the
operating system.

But BufferedWriter writes text to a character stream with efficiency and provides a convenient method for writing a line
separator: newLine().
Reading into a file

Reading files with BufferredReader


BufferedReader is a class in Java
that is used to read the text of a
character-based input stream. It
can be used to read data line by
line using the readLine()method. It
makes the performance fast.

Reading files with a scanner

In Java as seen above not only we can read files with the
help of File Reader but also scanner class by using some
functions like the hasnext. Therefore, we can read the file
statements by the same class.

Here is a simple code that demonstrates how we can


read a text file line by line using the scanner. Use
nextLine() to read a file line by line.

What is resource leak in java?  A resource leak occurs when you don't close a reader, scanner, buffer, or another
process that  uses resources and needs to clean them up out of memory. 

Scanner vs Buffered reader


The buffered reader and the scanner are compared and their pros and cons are analysed here. Therefore, the conclusion
is that the buffer class should be preferred because of its speed size and synchronous behaviour.

File deletion

The concept of file deletion is shown here. This is done by a simple command of file.delete() method.

The Java File delete() method can be used to delete files, it will return a boolean value. It returns true if the file is
deleted; false if failed.

Try with resources

The try with resources is a command that whenever we allocate some resources, for example, assigning a resource to
take input from the Scanner class. If the user fails to close the resource, then it leads to a resource leak which could
prove dangerous to the execution of a program. Hence after implementing the same in a try block, we can avoid the
resource leak.
The debugging is used in java to rectify the code by setting breakpoints in the code. By setting breakpoints we can verify
the variables and methods current state.

Here the concept of perspective is also stated.

Debug Perspective

The Debug perspective offers additional views that can be used to troubleshoot an application such as breakpoints,
variables, debugging, console, etc. When a Java program is started in debug mode, users are prompted to switch to the
debug perspective.

Marker Interfaces in Java have special significance because of the fact that they have no methods declared
in them which means that the classes implementing these interfaces don't have to override any of
the methods.
A few of the marker interfaces already exist in the JDK like Serializable and Cloneable

Marker interface is an indicator to the jvm to allow specific behavior.

They are used to provide some essential information to the JVM so that JVM may perform some
useful operation.

Marker interface is an empty interface where in doesn't have any fields or methods in it. It is used to
give some kind of command to jvm or a compiler. Example are Serializable, Clonnable etc.. When we
implement empty interface, it tells compiler to do some operations. if the class is serializable then
perform serialize operation and same way if the class is clonnable then it perform clone operation.

They are used because we are telling to JVM that that class have special behaviour.
eg. by serilizable we are telling to JVM class is Seriliazable.
by Cloneable we are telling to JVM class is Cloneable.

we can't create marker interface as you can't instruct JVM to add special behaviour to all classes
implementing special interface. Now a days we do not use Marker Interface, all it's work is done by
annotations.

31. How to force Garbage Collector (GC) to run?  It’s not possible to force it.  You can call System.gc(); but you cannot
be sure that GC will be run. 
2. What finalize() method is for?  finalize() method is called by the garbage collector on an object when garbage
collector deter-  mines that there are no more references to the object. A subclass overrides the finalize  method to
clean system resources or to perform other cleanup.  The finalize method may take any action, including making this
object available again to other  threads; However the usual purpose of finalize is to perform cleanup actions before the
object  is irrevocably discarded. For example, the finalize method for an object that represents an  input/output
connection might perform explicit I/O transactions to break the connection be-  fore the object is permanently
discarded.  The Java programming language does not guarantee which thread will invoke the finalize  method for any
given object. It is guaranteed that the thread that invokes finalize will not be  holding any user-visible synchronization
locks when finalize is invoked. If an uncaught excep-  tion is thrown by the finalize method, the exception is ignored and
finalization of that object  terminates.  The finalize method is never invoked more than once by a Java virtual machine
for any given  object. 

https://studyeasy.org/category/java/

int a[] = {1, 2, 3, 4};


String s = "1234";

a.length //gives the length of the array

s.length() //gives the length of the string

Static

32. In Java, why do we use static


variable?
Whenever we want to have a common property for all objects of a
class, we use a class level variable i.e. a static variable.
This variable is loaded in memory only once at the time of class
loading. So it saves memory, since it is not defined per object in
Java.

33. Why it is not a good practice to


create static variables in Java?
Static variables are common to all the objects of a class. If a new
object is created, there is no need to test the value of static variable.
Any code that uses static variable can be in any state. It can be
within a new object or at a class level. So the scope of static
variable is open ended in a Java class.
If we want tighter control on scope, then variables should be
created at the object creation level.
Also defining static variables is not a good practice because they go
against the principles of Object Oriented Programming.

34. What is the purpose of static method in Java?


Java provides the feature of static method to create behavior at the
class level. The static method is common to all the objects of a
class. We do not need to create any object of a class to call a static
method. So it provides convenience of not creating an object for
calling it.
Also a static method can access and modify static data members.
This also helps in keeping the behavior as well as state at the class
level.

35. Why do we mark main method as


static in Java?
The main method in Java is marked as static, so that JVM can call it
to start the program. If main method is not

36. In what scenario do we use a static


block?
At times, there is a class that has static member variables. These
variables need some complicated initialization. At this time static
block helps as a tool to initialize complex static member variable
initialization.
The static block is executed even before the execution of main.
Sometimes, we can also replace static block with a static method of
class.

39. What is the difference between


static method and instance method in
Java?
Often, there is a need to define a behavior for a class that is not
dependent on member variables of an object. Such behavior is
captured in a static method. If there is a behavior dependent upon
the member variables of an object, then we do not mark it static, it
remains as instance method.
To call as static method, we do not need to create an object. We just
call it with class name. But to call an instance method, we need to
create/get an object first.
Instance member variables cannot be accessed by a static method.
But an instance

Method Overloading and Overriding

40. What is the other name of Method


Overloading?
Method Overloading is also known as Static Polymorphism.

41. How will you implement method


overloading in Java?
In Java, a class can have multiple methods with same name but
different arguments. It is called Method Overloading. To implement
method overloading we have to create two methods with same name
in a class and do one/more of the following:
1. Different number of parameters
2. Different data type of parameters
3. Different sequence of data type of parameters

45. How do we implement method


overriding in Java?
To override a method, we just provide a new implementation of a
method with same name in subclass. So there will be at least two
implementations of the method with same name. One
implementation is in parent class. And another implementation is in
child class.

46. Are we allowed to override a static


method in Java?
No. Java does not allow overriding a static method. If you create a
static method with same name in subclass, then it is a new method,
not an overridden method.

47. Why Java does not allow


overriding a static method?
To override a method, you need an instance of a class. Static method
is not associated with any instance of the class. So the concept of
overriding does not apply here.
Therefore, Java does not allow overriding a static method.

48. Is it allowed to override an


overloaded method?
Yes. You can override an overloaded method in Java.

49. What is the difference between


method overloading and method
overriding in Java?
Differences between method overloading and overriding are:
1. Method overloading is static polymorphism. Method
overriding is runtime polymorphism.
2. Method overloading occurs within the same class. Method
overriding happens in two classes with hierarchy
relationship.
3. Parameters must be different in method overloading.
Parameters must be same in method overriding.
4. Method overloading is a compile time concept. Method
overriding is a runtime concept.

51. What is meant by covariant ‫ \משתנה‬return


type in Java?
A covariant return type of a method is one that can be replaced by a
"narrower" type when the method is overridden in a subclass.
Let say class B is child of class A. There is a get() method in class
A as well as class B. get() method of class A can return an instance
of A, and get() method of class B return an instance of B. Here
class B overrides get() method, but the return type is different.
Before Java 5, any method that overrides the method of parent class
would have same return type.
From Java 5 onwards, a child class can override a method of parent
class and the child class method can return an object that is child of
object return by parent class method.
Polymorphism

52. What is Runtime Polymorphism?


Runtime Polymorphism or Dynamic Polymorphism is the
polymorphism that exists at runtime. In case of method overriding it
is not known which method will be called at runtime. Based on the
type of object, JVM decides the exact method that should be called.
So at compile time it is not known which method will be called at
run time.

53. Is it possible to achieve Runtime


Polymorphism by data members in
Java?
No. We need to create Runtime Polymorphism by implementing
methods at two levels of inheritance in Java.

Abstraction

55. What is Abstraction in Object


Oriented programming?
Abstraction is the process of hiding certain implementation details
of an object and showing only essential features of the object to
outside world.
It is different from Abstract class in Java.
Abstraction process identifies commonalities and hides the
complexity of implementation. It helps us in focusing on the
interface that we share with the outside world.

56. How is Abstraction different from


Encapsulation?
Abstraction happens at class level design. It results in hiding the
implementation details. Encapsulation is also known as
“Information Hiding”. An example of encapsulation is marking the
member variables private and providing getter and setter for these
member variables.

57. What is an abstract class in Java?


An abstract class in Java has one or more abstract methods. An
abstract method is just declared in the abstract class, but it is not
implemented.
An abstract class has to be extended in Java and its abstract
methods have to be implemented by a child class. Also Java does
not allow new instance of Abstract class.

59. Is it allowed to mark a method


abstract as well as final?
No. It will be contradictory statement to mark a method abstract as
well as final.
An abstract method has to be overridden by a child class. And a
final method cannot be overridden. Therefore a method can be
either abstract or final in Java.

60. Can we instantiate an abstract


class in Java?
No. We cannot create an instance of an abstract class in Java.

61. What is an interface in Java?


An Interface in Java is an abstract type blueprint of a class. It
contains the methods that a class must implement. It is like a
protocol.
It has method signatures and constant declarations.

62. Is it allowed to mark an interface


method as static?
Yes, from Java 8 onwards, we can define static and default methods
in an interface. Prior to Java 8, it was not allowed.

63. Why an Interface cannot be


marked as final in Java?
A final method cannot be overridden. But an interface method has to
be implemented by another class. So the interface method cannot be
marked as final.

64. What is a marker interface?


There are interfaces that do not have any data member or methods.
These interfaces are called Marker interface.
E.g. Serializable, Cloneable, Remote etc.

65. What can we use instead of


Marker interface?
We can use annotations instead of Marker interface.

66. How Annotations are better than


Marker Interfaces?
Annotations serve the purpose of conveying metadata about the
class to its consumers without creating a separate type for it.
Annotations are more powerful than a Marker interface. They allow
programmers to pass more sophisticated information to classes that
"consume" it.

67. What is the difference between


abstract class and interface in Java?
Differences between Abstract class and Interface are as follows:
1. An abstract class can have implemented methods with
body (non-abstract methods). Interface has only abstract
methods. From Java 8 onwards, interface can have
static/default methods in implemented form.
2. An abstract class can have instance member variables. An
interface cannot have instance variables. It can only have
constants.
3. An abstract class can have a constructor. Interface cannot
have constructor. It has to be implemented by another
class.
4. A class can extend only one abstract class. A class can
implement more than one interface.

68. Does Java allow us to use private


and protected modifiers for variables
in interfaces?
No. All the variables in an interface are implicitly public.

69. How can we cast to an object


reference to an interface reference?
An Object that implements an Interface can be cast to the same
Interface. Since An Object implementing an Interface already
provides implementation for the methods of that Interface, it is
allowed to do so as per the rules of Inheritance.
Final

70. How can you change the value of a


final variable in Java?
Java does not allow changing the value of a final variable. Once the
value is set, it cannot be changed.

71. Can a class be marked final in


Java?
Yes a class can be marked final in Java. Once a class is marked
final, it cannot be extended.

72. How can we create a final method


in Java?
To mark a method, add modifier final to that method. A final method
can not be overridden by a child class.

74. Why Integer class in final in Java?


Integer class is a wrapper for int. If it is not marked final, then any
other class can extend it and modify the behavior of Integer
operations. To avoid this Integer wrapper class is marked as final.

75. What is a blank final variable in


Java?
When we declare a final variable without giving any initial value,
then it is called blank final variable.

76. How can we initialize a blank final


variable?
A blank final instance variable can be initialized in a constructor.
A blank final static variable can be initialized in the static block of
class.

77. Is it allowed to declare main


method as final?
Yes, we can mark the main method as final.

package

78. What is the purpose of package in


Java?
A package is used to encapsulate a group of classes, interfaces and
sub-packages. Often, it is a hierarchical structure of storing
information. It is easier to organize the related classes and subpackages
in this manner.
A Package also provides access protection for classes and
interfaces. A package also helps in removing naming collision.

80. Which is the most important class


in Java?
It is an open-ended question with many answers. In my view, Object
class is the most important class of Java programming language. It
is the root of all the classes in Java. It provides some very
important and fundamental methods.

81. Is it mandatory to import java.lang


package every time?
No. By default, JVM loads it internally.

Serialization

87. What is the serialization?


Serialization is a process converting an object into a byte array.
This byte array represents the class, version and internal state of the
object. JVM can use this byte array to transmit/read the object over
a network.

88. What is the purpose of


serialization?
Some of the uses of serialization are:
1. Communication: It is used for transmitting an object over
network between two machines.
2. Persistence: We can store the object’s state in a database
and retrieve it from database later on.
3. Caching: Serialization can be used for caching to improve
performance. We may need 10 minutes to build an object,
but it may take just 10 seconds to de-serialize the object.
4. Cross JVM Synchronization: It can be used in same way
across multiple JVM that follow different architecture.

89. What is Deserialization?= ‫התפטרות‬


Deserialization is the process of reconstructing the object from the
serialized state. It is the reverse process of serialization.

90. What is Serialization and


Deserialization conceptually?
Serialization is to convert Object data into a stream of bytes
Deserialization is to convert a stream of bytes back into a copy of
the original object.

91. Why do we mark a data member


transient? = ‫חולף‬
Member variables of an object are marked transient to indicate that
they should not be serialized.
During serialization process the transient variables are not
considered part of the persistent state of an object.

Garbage Collector
101. Why Java provides Garbage
Collector?
In Java, there are no pointers. Memory management and allocation
is done by JVM. Since memory allocation is automated, after some
time JVM may go low on memory. At that time, JVM has to free
memory from unused objects. To help with the process of
reclaiming memory, Java provides an automated process called
Garbage Collector.

103. How does Garbage Collection


work in Java?
Java has an automated process called Garbage Collector for
Memory Management. It is a daemon in JVM that monitors the
memory usage and performs memory cleanup. Once JVM is low on
memory, GC process finds the unused objects that are not
referenced by other objects. These unused objects are cleaned up by
Garbage Collector daemon in JVM.

105. Why do we use finalize() method


in Java?
Java provides finalize() method to perform any cleanup before
Garbage Collection. This method is in Object class, and it is
invoked by JVM internally. Developers are free to implement this
method for any custom cleanup in case of Garbage Collection.
If an Object is not Garbage Collected, then this method may not be
called.
This method is never invoked more than once by JVM.

108. What kind of process is the


Garbage collector thread?
Garbage Collection is a Daemon process in JVM. It is an internal
process that keep checking Memory usage and cleans up the
memory.

String

121. What is the meaning of


Immutable in the context of String
class in Java?
An Immutable object cannot be modified or changed String aa = new String("aa"); in
Java. String System.out.println("aa hash code before
update: " + aa.hashCode() );//aa hash code before
is an Immutable class in Java. update: 3104
Once a String object is created, it cannot be changed. System.out.println("check the hashCode
for aa after update");
When we aa = "fuad";//string us immuteble and if
assign the String to a new value, a new object is we change the value of string, new object will created
System.out.println("aa hash code after
created. update: " + aa.hashCode() );//aa hash code after update:
3154226
122. Why a String object is considered
immutable in java?
Java language uses String for a variety of purposes. For this it has
marked String Immutable.
There is a concept of String literal in Java.
Let say there are 2 String variables A and B that reference to a
String object “TestData”. All these variables refer to same String
literal. If one reference variable A changes the value of the String
literal from “TestData” to “RealData”, then it will affect the other
variable as well. Due to which String is considered Immutable. In
this case, if one variable A changes the value to “RealData”, then a
new String literal with “RealData” is created and A will point to
new String literal. While B will keep pointing to “TestData”

123. How many objects does following


code create?
Code:
String s1="HelloWorld";
String s2=" HelloWorld ";
String s3=" HelloWorld ";
The above code creates only one object. Since there is only one
String Literal “HelloWorld” created, all the references point to
same object.
124. How many ways are there in
Java to create a String object?
Java provides two ways to create a String object. One is by using
String Literal, the other is by using new operator.

128. What is the basic difference


between a String and StringBuffer
object?
String is an immutable object. Its value cannot change after creation.
StringBuffer is a mutable object. We can keep appending or
modifying the contents of a StringBuffer in Java.

129. How will you create an immutable


class in Java?
In Java, we can declare a class final to make it immutable. There
are following detailed steps to make it Immutable:
1. Add final modifier to class to prevent it from getting
extended
2. Add private modifier to all the fields to prevent direct
access
3. Do not provide any setter methods for member variables
4. Add final modifier to all the mutable fields to assign value
only once
5. Use Deep Copy to initialize all the fields by a constructor
6. In clone method, return a copy of object instead of the
actual object reference

131. Arrange the three classes String,


StringBuffer and StringBuilder in the
order of efficiency for String
processing operations?
StringBuilder is the most efficient class. It does not have the
overhead of Synchronization. StringBuffer is a Synchronized class.
It has better performance than String but it is slower than
StringBuilder. String is the slowest for any String processing
operations, since it is leads to creation of new String literal with
each modification.
So the decreasing order of efficiency is: StringBuilder, StringBuffer,
String

Exception Handling
135. What is a finally block in Java?
Java provides a finally block with a try block. This is an optional
block. But finally block is always executed after the execution of try
block.

136. What is the use of finally block in


Java?
As per Java specification, a finally block is always executed,
whether an error occurs or not, whether an exception is handled or
not. It helps in doing the cleanup like- Rollback Transaction, Close
Connection, Close a file etc.

137. Can we create a finally block


without creating a catch block?
Yes. A finally block can follow a try block or catch block. So we
can defined a finally block just after a try block.

138. Do we have to always put a catch


block after a try block?
Java does not enforce the rule to put a catch block after try block.
We can write catch block or finally block after a try block.
Any exception that we want to catch is mentioned in catch block.

139. In what scenarios, a finally block


will not be executed?
There are two main scenarios in which finally block is not
executed:
1. Program exits by calling system.exit() call.
2. A fatal error causes JVM to crash.

141. What is the difference between


throw and throws in Java?
Java provides throw keyword to throw an exception from a method
or a static block. Java provides throws keyword to mention the
probable exception thrown by a method in its declaration.
We use throw to explicitly throw an exception. We used
throws to declare an exception in method definition.
We cannot propagate checked exceptions with throw only. But
checked exceptions can be propagated with throws keyword.
A throw call is followed by an instance. Class or Exception follows
a throws keyword.
Call to throw occurs within a method. throws is just used with
method signature.
We can throw only one exception at a time. But we can mention as
many exceptions in throws clause.

142. What is the concept of


Exception Propagation?
In Exception Propagation, uncaught exceptions are propagated in the
call stack until stack becomes empty. This propagation is called
Exception Propagation.
Let say an exception propagates from one method to another method.
A() calls B(), which calls C(), which calls D(). And if D() throws
an exception, the exception will propagate from D to C to B to A,
unless one of the methods catches the exception.

Java Collection

145. What are the main benefits of


Collections Framework in Java?
Main benefits of Collections Framework in Java are as follows:
1. Reusability: Java Collections Framework provides
common classes and utility methods than can be used with
different types of collections. This promotes the reusability
of the code. A developer does not have to re-invent the
wheel by writing the same method again.
2. Quality: Using Java Collection Framework improves the
program quality, since the code is already tested and used
by thousands of developers.
3. Speed: Most of programmers report that their development
speed increased since they can focus on core logic and use
the generic collections provided by Java framework.
4. Maintenance: Since most of the Java Collections
framework code is open source and API documents is
widely available, it is easy to maintain the code written
with the help of Java Collections framework. One
developer can easily pick the code of previous developer

149. How will you efficiently


remove elements while iterating a
Collection?
The right way to remove elements from a collection while iterating
is by using ListIterator.remove() method.
E.g.
ListIterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();
}
Some developers use following code to remove an element which is
incorrect:
Iterator<Integer> iter = myList.iterator();
while(iter.hasNext()) {
itr.remove();
}
By doing so we get ConcurrentModificationException.
An iterator is first created to traverse the list. But at the same time
the list is changed by remove() method.
In Java, it is not allowed for a thread to modify a collection while
another thread is iterating it. ListIterator provides the capability of
removing an object during traversal.

150. How will you convert a List into


an array of integers like- int[]?
We can use ArrayUtils class in Apache Commons Lang library.
Sample code is:
int[]intArray = ArrayUtils.toPrimitive(myList.toArray(new
Integer[0]));
If we use List.toArray(), it will convert List to Integer[].
Another option is:
int[] intArray = new int[myList.size()];
for (int i=0; i < myList.size(); i++) {
intArray [i] = myList.get(i);
}

153. How will you convert a List to a


Set?
There are two ways to convert a List to a Set in Java.
Option 1: Use HashSet
Set<Integer> mySet = new HashSet<Integer>(myList);
In this case we put a list into a HashSet. Internally hashCode()
method is used to identify duplicate elements.
Option 2: Use TreeSet
In this case we use our own comparator to find duplicate objects.
Set<Integer> mySet = new TreeSet<Integer>(myComparator);
mySet.addAll(myList);

154. How will you remove duplicate


elements from an ArrayList?
The trick in this question is to use a collection that does not allow
duplicate elements. So we use a Set for this purpose.
Option 1: Use Set
If ordering of elements is not important then we just put the elements
of ArrayList in a HashSet and then add them back to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements
Set<Integer> mySet = new HashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);
Option 2: Use LinkedHashSet
If ordering of elements is important then we put the elements of
ArrayList in a LinkedHashSet and then add them back to the
ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements
Set<Integer> mySet = new LinkedHashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);

154. How will you remove duplicate


elements from an ArrayList?
The trick in this question is to use a collection that does not allow
duplicate elements. So we use a Set for this purpose.
Option 1: Use Set
If ordering of elements is not important then we just put the elements
of ArrayList in a HashSet and then add them back to the ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements
Set<Integer> mySet = new HashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);
Option 2: Use LinkedHashSet
If ordering of elements is important then we put the elements of
ArrayList in a LinkedHashSet and then add them back to the
ArrayList.
Sample Code is:
ArrayList myList = // ArrayList with duplicate elements
Set<Integer> mySet = new LinkedHashSet<Integer>(myList);
myList.clear();
myList.addAll(mySet);

155. How can you maintain a


Collection with elements in Sorted
order?
In Java, there are many ways to maintain a Collection with elements
in sorted order.
Some collections like TreeSet store elements in the natural
ordering. In case of natural ordering we have to implement
Comparable interface for comparing the elements.
We can also maintain custom ordering by providing a custom
Comparator to a Collection.
Another option is to use the utility method Collections.sort() to sort
a List. This sorting gives nlog(n) order of performance. But if we
have to use this method multiple times then it will be costly on
performance.
Another option is to use a PriorityQueue that provides an ordered
queue. The main difference between PriorityQueue and
Collections.sort() is that PriorityQueue maintains a queue in Order
all the time, but we can only retrieve head element from queue. We
cannot access the elements of PriorityQueue in Random order.
We can use TreeSet to maintain sorted order of elements in
collection if there are no duplicate elements in collection.

156. What are the differences between


the two data structures: a Vector and
an ArrayList?
An ArrayList is a newer class than a Vector. A Vector is considered a
legacy class in Java. The differences are:
1. Synchronization: Vector is synchronized, but the ArrayList
is not synchronized. So an ArrayList has faster operations
than a Vector.
2. Data Growth: Internally both an ArrayList and Vector use
an array to store data. When an ArrayList is almost full it
increases its size by 50% of the array size. Whereas a
Vector increases it by doubling the underlying array size.

You might also like