Java Interview
Java Interview
Java Interview
1. What is Java?
Inheritance
Encapsulation
Polymorphism
Abstraction
Using it, we can compile, document, and package Java programs. JRE (Java
Runtime Environment) is an installation package that provides an
environment to only run(not develop) the Java program(or application)
onto our machine. JVM executes the bytecode.
It produces a class file that contains the Java bytecode. The bytecode
produced is platform-independent. It can be run on any machine
containing JVM.
Interpretation: The Java interpreter takes the class file as input and runs it
on the JVM.
6. What is a Bytecode?
7. What is a Class?
The new keyword is a Java operator that is used to create the object.
Inheritance
1. What is Inheritance?
The class that is derived from another class is called a subclass (also
called a derived/extended/child class).
The class from which the subclass is derived is called a superclass (also
called a base/parent class).
No, we can access only superclass members but not the subclass
members.
Multiple inheritance is not possible in Java. Classes can only extend from
one superclass. In cases where multiple functionalities are required.
For example, to read and write information into the file, the pattern of
composition is preferred. The writer, as well as reader functionalities, can
be made use of by considering them as private members.
JAVA
But we can write the above code easily using composition as follows:
class Manager {
JAVA
Since the compile-time errors are better than runtime errors, Java renders
compile-time errors if you inherit 2 classes. So, whether you have the
same method or a different, there will be a compile-time error.
this can be used to return the current class instance from the method.
10. Why do we need to use inheritance?
15. What happens if both superclass and subclass have an attribute with
the same name?
Only subclass members are accessible if an object of a subclass is
instantiated.
In the case of inheritance, constructors are called from the top to down
hierarchy.
single inheritance
multilevel inheritance
Yes, we can pass that because subclass and superclass are related to each
other by Inheritance which provides IS-A property. For example, a car is a
vehicle so we can pass the car if some method accepts vehicle.
Code
class Superclass {
JAVA
Collapse
Output
Access Modifiers
Access modifiers are the keywords that set access levels when used with
the classes, methods, constructors, attributes, etc.
In Java, we have four access modifiers to set the accessibility. They are,
Private: The access level of a private modifier is only within the declared
class. It is not accessible outside of the class.
Default: The access level of a default modifier is up to the class/subclass
of the same package. It cannot be accessed from outside the package.
static: Used to define a class method or attribute that belongs to the class
and not to any particular instance of the class.
abstract: Used to declare an abstract method that does not have a body
and must be implemented by a subclass.
final attribute:
If any value has not been assigned to that attribute, then it can be
assigned only by the constructor of the class.
final method:
final class:
The final classes cannot be extended (inherited). All the wrapper classes
like String, Integer, Float, etc are final. Hence, we cannot inherit the
wrapper classes.
Submit Feedback
Encapsulation
5. What are the getter(get) and setter(set) methods in Java? Why are they
used?
We use getter and setter methods because the data in the class is
declared private and cannot be accessed directly.
Polymorphism
1. What is Polymorphism?
Polymorphism is derived from two Greek words poly and morphs. The
word poly means "many" and morphs means "forms". So polymorphism
means many forms.
Compile-time polymorphism
Runtime polymorphism
7. What happens if two methods have different return types but share the
same name and same parameters?
The method with the more specific return type will be chosen. For
example, if one method returns an int and the other returns a double, the
method returning the double will be chosen.
No, we can't override the static methods because they are part of the
class, not the object.
Yes, we can change the scope of the overridden method in the subclass.
The access level cannot be more restrictive than the overridden method's
access level.
Below is the hierarchy of the access modifiers based on the access levels,
from more restrictive to less restrictive from left to right.
10. What are the differences between method overriding and overloading?
Occurs between two classes, using inheritance Occurs within the class
Methods involved must have same name and same parameters Methods
involved must have the same name but different number/type of
parameters
Abstraction
1. What is Abstraction?
For example, let's look at a real-life example of a man driving a car. As far
as he knows, pressing the accelerator increases the speed of the car, or
applying the brakes stops it. However, he doesn't know how the speed
actually increases when pressing the accelerator. He doesn't know
anything about the car's inner mechanisms or how the accelerator,
brakes, etc., work.
In Java, if we make the abstract methods static, they will become part of
the class, and we can directly call them which is unnecessary. Calling an
undefined method is not necessary, therefore it is not allowed.
A final method has a body An abstract method does not have a body
It does not contain any body. It simply has a method declaration followed
by a semicolon(;).
when the same method has to perform different tasks depending on the
object calling it.
Even if we don't write a constructor for our abstract class, the compiler
will keep the default constructor.
9. Can we create an abstract attribute?
Interfaces
The interfaces act as a blueprint for a class. The interface keyword is used
to create an interface.
No, we cannot define private and protected modifiers for attributes in the
interfaces because the methods and attributes declared in an interface
are by default public, static, and final.
Abstract class can have abstract and non-abstract methods. Interface can
have abstract, static, default and final methods
Abstract class can have final, non-final, static and non-static attributes.
Interface has only static and final attributes.
An abstract class can extend another Java class and implement multiple
Java interfaces. An interface can extend another Java interface only.
A Java abstract class can have class members like private, protected, etc.
Members of a Java interface are public by default.
By default, they will be treated as public, static, and final. So, it expects
some value to be initialized.
So, there is no need for a constructor in the interface that is the reason
interface doesn't allow us to create a constructor.
No. While overriding any interface methods, we should use public only.
Because all interface methods are public by default and we should not
reduce the access level while overriding them.
Yes, we can declare an interface with the abstract keyword. But, there is
no need to write like that. All interface in Java are abstract by default.
No, the attributes of interfaces are static and final by default. They are
just like constants. we can’t change their value once they got initialized.
A class cannot implement two interfaces that have methods with the
same name but different return type.
Keyword Variables/Identifiers
Keywords are predefined words that get reserved for working program
that have special meanings and cannot get used as variables. Variables
are like containers for storing information.
short
byte
int
long
float
double
boolean
char
array
class
After the first character, the Java variable name can have digits as well
along with a letter, $ and _
- Capital Letters ( A – Z )
- Small Letters ( a – z )
- Digits ( 0 – 9 )
Examples:
Blanks ( )
Commas ( , )
Special Characters
( ~ ! @ # % ^ . ?, etc. )
int
if, etc
6. What are the default or implicitly assigned values for data types in
Java?
boolean false
byte 0
short 0
int 0
long 0L
char /u0000
float 0.0f
double 0.0d
The int is a primitive data type in Java, while Integer is a wrapper class
that wraps the value of the primitive int.
The Integer class provides additional methods for manipulating int values.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Conditional/Ternary operators
+ Addition
– Subtraction
* Multiplication
/ Division
1 Parentheses ()
3 Multiplicative operators *, /, %
4 Additive operators +, -
8 Ternary operator ?:
13. What are the sizes of the primitive data types in Java?
The Math.pow() method in Java returns a double value, even if both the
arguments are of type int.
BigInteger
2. What are the various methods available in the BigInteger class for
performing arithmetic operations in Java?
I/O Basics
The Scanner class is the most commonly used method for getting input
from the user in Java. The Scanner class can be used to read data of
various types, such as int, double, String, etc, from the user.
Type Conversions
1. What is Type Conversion in Java?
Type conversion is a process of converting the value of one data type (int,
char, float, etc.) to another data type.
int bigNum.intValue()
float bigNum.floatValue()
long bigNum.longValue()
double bigNum.doubleValue()
String bigNum.toString()
int to BigInteger :
JAVA
The valueOf() method is used to convert any primitive data type to String.
AND(&&) operator
OR(||) operator
NOT(!) operator
Relational Operators are used for comparing values. It returns true or false
as the result of a comparison.
== (equals to)
On the other hand, .equals() method checks if the contents of two objects
are equal.
6. Explain the difference between the logical "AND" (&&) and "OR" (||)
operators in Java.
The AND operator && returns true if both operands are true.
For example, if the "AND" operator && is used and the first operand is
false, then the second operand will not be evaluated and the result will be
false.
Conditional Statements
if statement
if-else statement
else if statement
switch statement
The breakstatement is used to exit the switch statement and prevent the
execution of any further cases.
If the break statement is not used in a switch statement, the code within
the true block and all subsequent blocks will be executed.
JAVA
11. What are the differences between if...else and switch statements?
If-else Switch
If the condition inside the if-statement is false, then the code block under
the else condition is executed If the condition inside switch statements
does not match any of the cases, the default statement is executed.
Either the code block in the if statement is executed or the code block in
the else statement. The switch case statement performs each case until a
break statement is encountered or the end of the switch statement is
reached.
Used for integer, character, floating-point type, or Boolean type. Used for
character expressions and integers.
12. What are the criteria for deciding whether to use a switch statement
or an if...else statement?
If there are only a few cases, using switch statements may not affect
speed. However, if there are more than five cases, a switch statement is
preferred for faster execution time.
Loops
while loop
do-while loop
for loop
for-each loop
Java consists of a for-each loop which can be used to iterate over an array.
During iteration with the for-each loop, we will get array elements, but no
index values.
Syntax
JAVA
3. What is the difference between a for loop and a while loop in Java?
Make sure to update the loop control variables in a way that ensures the
termination condition will eventually be met.
We can keep track of the number of iterations in the loop and exit the loop
when a certain number is reached.
The break statement is used to exit a loop The continue statement is used
to skip an iteration of a loop.
When a break statement is encountered, the loop terminates immediately
and the flow of control moves to the statement following the loop. When a
continuestatement is encountered, the current iteration of the loop
terminates and the flow of control moves to the next iteration.
7. What are the differences between for loop and for-each loop?
The differences between the for loop and for-each loop are:
Performance: The for loop is generally faster than the for-each loop, as the
for-each loop requires the creation of an Iterator object, which takes more
time. The for loop, on the other hand, can be optimized for performance
by using array indices, which makes it faster than the for-each loop.
Syntax: The syntax of the for loop is more complex than the syntax of the
for-each loop, as the for loop requires you to specify the start and end
conditions for the loop, whereas for-each loop is written for reading each
element in a collection, such as an array or list.
The while loop evaluates the condition first and only executes the code
block if the condition is true, while the do-while loop executes the code
block at least once and then evaluates the condition.
Strings
No, the string is not a primitive data type, but a non-primitive type.
Yes, the String is immutable in Java. Immutable means once the object is
created, its value cannot be changed.
4. How to compare two Strings in Java?
By compareTo() method.
5. What are the most widely used methods of Java String class?
These are the following most widely used methods of String class,
Method Description
trim() Returns the substring after removing any leading and trailing
whitespace from the specified string.
If the str1 value is "abc" then both statements will give the result true.
The main difference between the two statements arises when we pass
str1 value as null. If the str1 is null then str1.equals("abc") will throw a null
pointer exception while "abc".equals(str1) will return false.
Syntax
JAVA
The substring begins with the character from the startIndex and extends
up to endIndex-1. It means endIndex character is not included in the slice.
String class provides a split() method that split the string based on the
provided regular expression delimiter. This method returns an array of the
split substrings.
Method Decription
Syntax
JAVA
Example
10
11
class Main {
builder.append("Hello");
builder.append(" ");
builder.append("world!");
JAVA
Collapse
The
StringBuffer
Method Decription
Syntax
JAVA
Example
class Main {
buffer.append("Hello");
buffer.append(" ");
buffer.append("world!");
}
JAVA
Collapse
StringBuffer StringBuilder
String
class as it allows
simultaneous operations of
multiple threads.
String Pool
Heap Memory: This is where all the objects, including String objects, are
stored. The objects are created dynamically at runtime in this space.
String Pool: This is a special area within the heap memory where Java
stores all the unique String literals.
Question 2 of 2
When you create a string using double quotes(as a String Literal), Java
first checks the string pool to see if a string with the same value exists. If
it exists, it reuses that reference; otherwise, it creates a new string in the
pool.
For example, String str = "Hello";
When you create a string using the new keyword, which forces Java to
create a new string object in heap memory, irrespective of whether such a
value exists.
Code
JAVA
Output
Here, the output is false, because the references of the variable str1 and
the object str2 are not the same (str1 is stored in the String Pool, whereas
str2 is stored in the Heap Memory).
Question 3 of 3
3. Can we write int instead of String in the String[] args argument of the
main() method?
Question 1 of 1
You can replace String[] args with int[] args without any issues in a Java
application.
The JVM specifically looks for a main() method with the parameter String[]
args, to initiate the execution of the Java application.
Show Answ
An array in Java is a data structure that can store a fixed number of values
of the same data type. Arrays are used to store collections of data of the
same type, such as a list of integers or a list of strings.
The values in an array are stored in contiguous memory locations and can
be accessed using an index, which is an integer value that represents the
position of an element in the array.
ArrayList
HashSet
Arrays in Java are used to store collections of data, they are not
considered a part of the Java Collections Framework.
For example,
JAVA
For example,
JAVA
If the initial capacity of the array is exceeded, a new array with a larger
capacity is created automatically and all the elements from the current
array are copied to the new array.
When elements are removed from the ArrayList, the size of the ArrayList
can be shrunk automatically.
Advantages of an array:
We can store multiple elements of the same type under a single variable.
Disadvantages of an array:
Insertion and deletion operations are difficult because elements are stored
at contiguous memory locations.
No. The System.out.println(arr) does not print all the elements in the array
arr. It only prints the reference of the array in memory, not the values
stored in the array.
To print the elements of an array, we need to loop through the array and
print each element individually or use a method like Arrays.toString(arr) to
convert the array to a string representation, which can then be printed.
The following points are the differences between arrays and ArrayList:
Arrays ArrayLists
Declared with fixed size ArrayLists can dynamically grow and shrink in size
Arrays do not have built-in methods for adding, removing, and searching
ArrayLists have built-in methods for adding, removing and searching
Yes, we can join two or more ArrayLists in Java. The ArrayList has a
method addAll() to join two or more ArrayLists in Java.
If we have one ArrayList arrList1 and another arrList2, we can join them as
arrList1.addAll(arrList2) and the result will be stored in arrList1.
Method Description
15. Why can't we use primitive data types instead of their wrapper classes
to create ArrayLists in Java?
ArrayLists in Java store objects, not primitive data types. Primitive data
types, such as int, float, char etc., are not objects and therefore cannot be
stored in an ArrayList directly.
Methods
The main() method should be static in Java, so the JVM can directly invoke
it without instantiating the class's object.
HashSets
1. What is a HashSet?
Method Description
HashSet ArrayList
HashSet is generally faster for operations like add, remove, and contains
ArrayList is better for retrieving elements using index
Method Description
HashMaps
Method Description
HashSet HashMap
HashSet does not allow duplicates HashMap allows duplicates values, but
not duplicate keys
If we try to insert a key that already exists in the HashMap, the new value
will replace the old value for that key.
5. What is Hashing?
Contacts in mobile phone: name is the key and mobile number will be
value.
Books in library: type of book is the key and names of the books are
values.
Movies: type of movie is the key and the names of the movies are values.
There are many interfaces and classes in the Java Collections Framework.
ArrayList
LinkedList
HashSet
LinkedHashSet
TreeSet
PriorityQueue
LinkedList
HashMap
LinkedHashMap
TreeMap
Hashtable
All the above interfaces and classes are present in the java.util package.
Question 3 of 3
Set
Map
2. What is a List?
In Java, the List interface is a part of the Java Collections Framework and
extends the Collection interface. It represents an ordered collection of
elements, where each element can be inserted or accessed based on its
position in the list.
The List interface ensures that elements maintain a specific order, which
is the order of their insertion or any order imposed through methods like
sort(). It allows for the positional access of elements, meaning you can
access elements based on their index in the list.
The List interface inherits methods from the Collection interface and also
introduces list-specific methods. Here are some of the prominent methods
that it provides:
get(int index): Retrieves the element at the specified position in the list.
ArrayList
LinkedList
Vector
The List interface supports generics, allowing you to specify the type of
elements the list will hold, thereby providing type safety and avoiding
runtime type errors.
Question 3 of 3
Which of the following interfaces does the List interface extend in Java?
ArrayList
Collection
Set
Map
3. What is Set?
Being a subtype of the Collection interface, it inherits all methods from the
Collection interface and doesn’t introduce any new methods. However, it
adds the constraint of not allowing duplicate elements. Here are some
methods that you'll commonly use with a set:
add(E element): Adds the specified element to the set if it is not already
present.
contains(Object o): Returns true if the set contains the specified element.
HashSet
LinkedHashSet
TreeSet
Just like other collection types, the Set interface supports generics,
helping to maintain type safety. It allows you to restrict the type of
elements that you can add to the set.
Question 3 of 3
Map
Collection
ArrayList
4. What is a Map?
HashMap
LinkedHashMap
TreeMap
Hashtable
Question 2 of 2
The Collection interface forms the basis for working with groups of objects,
and the Collections class provides utility functions to perform common
operations on collections.
Collection Interface
Example:
JAVA
Collections Class
The Collections class, on the other hand, is a utility class containing static
methods that operate on or return collections. It provides various utility
functions to work with collections, such as sorting, searching, reversing,
and more.
Here are some typical operations and methods that the Collections class
provides:
Sorting: sort()
Searching: binarySearch()
Example:
JAVA
Question 4 of 4
add()
sort()
remove()
toArray()
Example
JAVA
Collapse
Output
Here, students are compared and sorted based on their roll numbers. We
can directly pass the list of students to sort based on the increasing order
of roll numbers since we are overriding the compareTo() method of the
Comparable interface.
Question 2 of 2
compare()
compareTo()
equals()
hashCode()
Example
JAVA
Collapse
Output
Here, students are compared and sorted based on their names. We can
pass the list of students and the StudentNameComparator object to sort
based on the alphabetical order of names since we are overriding the
compare() method of the Comparator interface.
Question 2 of 2
Usage Used to define a natural ordering for a class. Used to define custom
orderings for a class.
Null Handling Does not handle null values gracefully. Additional null
checks are needed. Can handle null values more gracefully with
Comparator.nullsFirst() and Comparator.nullsLast() methods.
Exception handling ensures that the program's flow does not break when
an exception occurs. For example, a program contains many statements,
and an exception occurs in the middle of executing some of them. In that
case, the statements after the exception will not be executed, and the
program will be terminated.
catch: this block catches all exceptions that were trapped in the try block.
4. What is the difference between the throw and throws keyword in Java?
The throws keyword is used with the method to declare the exceptions
that the method might throw.
5. What if the static modifier is removed from the signature of the main
method?
6. Can a single try block and multiple catch blocks co-exist in a Java
Program?
One or more catch blocks can follow a try block. Each catch block must
have a unique exception handler.
Errors in Java occur due to syntactical errors, infinite recursion, and many
other reasons. The most common are syntactical errors that occur when a
programmer violates the rules of Java programming language.
Exceptions are simply the errors detected at the execution of program. For
example, NullPointerException occurs when a program tries to access
memory through a null reference, which is a reference that does not point
to an instance of an object.
No, doing so will result in a compilation error. The catch or finally block
must always be used along with try block. We can remove either the final
block or catch block, but never both.
parse()
Code
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
System.out.println(date);
JAVA
Collapse
Output
2018-11-28
2. How to calculate difference between two dates and times in Java?
In Java, we have a
Period
class to find the difference between two dates in terms of years, months
and days.
We can get the period object as the difference between two dates using
between()
method.
Code
import java.time.Period;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
JAVA
Collapse
Output
Years: 1
Months: 8
Days: 1
b. calculating difference between two times
In Java, we have a
Duration
Code
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
class Main {
System.out.println(duration.getSeconds());
JAVA
Collapse
Output
60
The
LocalDate
class provides
now()
Code
import java.time.LocalDate;
class Main {
public static void main(String[] args) {
System.out.println(dateObj);
JAVA
Output
2022-12-20
java.time
package?
Class Description
The
DateTimeFormatter
class from
java.time.format
DateTimeForma
tter has a
ofPattern()
seconds.
Lambda Expressions
interface Runner {
void run();
JAVA
The main difference is that a lambda expression does not have a name
and does not belong to a class. Instead, it is an anonymous function that
can be passed around as a value.
Syntax
JAVA
4. What is a Predicate?
java.util.function.Predicate
Streams
1. What is a Stream?
It's important to note that a stream does not store the elements of an
array, etc, it simply provides a way to access them.
of()
method of the
Stream
interface.
Code
JAVA
The
Optional
java.util
NullPointerException
/home/rahul/documents/file.txt
Relative Path: A relative path is a path that specifies the location of a file
or directory relative to the current working directory. For example, a
relative path might be something like
documents\file.txt
file.txt
in the
documents
Submit Feedback
Threads
Multithreading
Thread class Methods
Introduction
1. Threads
When we click the “Run” button, the following steps take place:
Compile: The Java compiler (javac) compiles the source code (.java file)
into bytecode (.class file).
Load: The bytecode is loaded into the Java Virtual Machine (JVM) memory.
Check: The JVM checks the bytecode to make sure it is correct and safe.
Run: The JVM interprets or compiles the bytecode into machine code, and
the main thread starts running the main() method. In the following
sections, we will learn about the "main thread."
Finish: When the main() method is done, the JVM ends the program and
frees up resources.
When we run a Java program, the Java Virtual Machine (JVM) starts up and
allocates memory and resources for the program. One of the primary
actions it does is starting a thread – specifically, the main thread. This
main thread is responsible for invoking the main method of our Java class.
Every Java application has at least one thread, the main thread. However,
based on the needs of the application, additional threads can be spawned
to handle specific tasks, allowing for parallel execution and improved
efficiency.
10
11
12
13
14
15
16
17
18
19
20
21
class TicketBooking {
availableTickets -= numberOfTickets;
} else {
app.bookTicket("User1", 5);
app.bookTicket("User2", 6);
}
JAVA
Collapse
This delay might seem minor in this small example, but in real-world
applications with multiple users or
2. Multithreading
Benefits of Multithreading
Improved performance
Drawbacks of Multithreading
Complexity in code
The run() method is what defines the task or logic that the thread will
execute. It is the method that should be overridden from the Thread class.
The start() method of the Thread class is used to initiate a new thread of
execution, causing the run() method of the thread to execute in parallel. It
ensures the concurrent execution of tasks.
We can create a thread by extending the Thread class and overriding its
run() method. After creating the thread object, we can invoke the start()
method to execute the thread.
Syntax
JAVA
Here, the
Thread
MyThread
run()
Example
1
10
11
12
class Main {
thread.start();
JAVA
Collapse
Output
Output
start()
run()
method of the
MyThread
When
run()
is invoked directly, it runs within the current thread and not in a new
thread. This is because when we call the
start()
run()
run()
run()
Code
8
9
10
11
class Main {
thread.run();
JAVA
Expand
Output
Here,
the output seems to be as expected but the internal behavior of the code
is not as expected. We expect the execution of the RunnerThread class to
be done in a new thread, but it is executed in the main thread. So, we
should not call the run() method directly.
Syntax
JAVA
Example
10
11
12
13
class Main {
thread.start();
JAVA
Collapse
Output
Here,
Note
1. sleep()
The static sleep() method of the Thread class makes the current thread
pause its execution for a specified number of milliseconds, allowing other
threads to execute. It's useful for introducing deliberate delays.
Code
10
11
class Main {
try {
Thread.sleep(2000);
System.out.println("Awake now!");
} catch (InterruptedException e) {
JAVA
Collapse
Output
Here, the output Sleeping for 2 seconds... is printed first and after a two
seconds delay, the output Awake now! is printed.
2. currentThread()
Code
10
11
12
13
14
15
class Main {
public static void main(String[] args) {
obj.start();
JAVA
Collapse
Output
Here, we print the current thread's reference after starting the thread.
The
getName()
method of the
Thread
setName()
method assigns a new name to the thread. These methods aid in thread
identification.
Code
9
class Main {
thread.setName("MyMainThread");
JAVA
Output
Here, we are in main thread and we are changing the name of the thread
to
MyMainThread
Other Methods
Method Description
yield() Temporarily pauses the current thread, allowing other threads to exe
Makes the current thread wait until the specified thread completes i
join()
execution.
getPriorit
Retrieves the priority of the thread.
y()
setPriorit
Sets a new priority for the thread.
y()
thread group.
Causes the current thread to pause its execution and relinquish its l
wait()
the object's monitor until notified.
Wakes up all the threads that are waiting on the object's monitor, al
notifyAll()
them to proceed with their execution.
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
availableTickets -= numberOfTickets;
} else {
bookTicket(user, wantedTickets);
}
class BookingApp {
user1.setName("User1");
user2.setName("User2");
user1.start();
user2.start();
JAVA
Collapse
Output
Here,
start()
method on both
user1
and
user2
The class
TicketBooking
implements the
Runnable
bookTicket()
method in the
run()
method.
Runnable
Summary
The
Thread
The
main()
o Using the
Thread
class
o Using the
Runnable
interface
The
start()
The
run()
method is what defines the task or logic that the thread will execute.
The static
sleep()
method makes the current thread pause its execution for a specified time.
The static
currentThread()
The
getName()
setName()
1. Synchronization in Java
Types of Synchronization:
1. Synchronized Method:
Entire method is synchronized, so only one thread can execute it at
a time.
java
Copy code
2. Synchronized Block:
Synchronizes a specific block of code, which is more efficient than
synchronizing the entire method.
java
Copy code
synchronized (this) {
// critical section
3. Static Synchronization:
Synchronizes a static method or block, locking on the class object.
java
Copy code
// critical section
Example:
java
Copy code
class Counter {
count++;
counter.increment();
});
counter.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
2. Daemon Thread
Example:
java
Copy code
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
});
daemonThread.start();
System.out.println("Main thread finishing...");
java
Copy code
2. Runnable: The thread is ready to run but waiting for CPU allocation.
java
Copy code
t.start();
Example:
java
Copy code
System.out.println("Thread running...");
Summary:
4o