Java Interview

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

Intro to Java

1. What is Java?

Java is a popular object-oriented programming language. It was created in


1995 and is owned by Oracle.

Java is a secure, fast, and powerful programming language. Java works on


different platforms (Windows, Mac, Linux, etc.). It has huge community
support (tens of millions of developers).

2. What is meant by a statically typed language and a dynamically typed


language?

A programming language is statically typed if the type of a variable is


known at compile-time. Some examples of statically-typed languages are
Java, C, C++, etc.

A language is dynamically typed if the type of a variable is checked during


run-time. Most modern programming languages are dynamically typed.
Some examples of dynamically-typed languages are Python, Javascript,
etc.

3. What are the concepts of Object-oriented programming?

Inheritance

Encapsulation

Polymorphism

Abstraction

4. What are JDK, JRE, and JVM?

JDK JRE JVM

It refers to Java Development Kit. It refers to Java Runtime Environment. It


refers to Java Virtual Machine.

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 contains JRE + development tools. It consists of many components like a


Java class library, tools, and a separate JVM JVM is a very important part of
both JDK and JRE

5. How a Java program is executed?

Execution of a Java Program consists of a series of steps,


Compilation: We can compile Java programs using the Java compiler,
which is a command-line tool called javac provided by the JDK.

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.

Executing machine code: The JVM creates machine code that is


understandable for the specific processor(CPU) or operating system(OS).
Finally, the machine code is executed and the output is produced.

6. What is a Bytecode?

Bytecode is a low-level code that is executed by a virtual machine, such


as the Java Virtual Machine (JVM). In Java, it is the compiled form of a Java
program. It is platform-independent. For example, we can share the
bytecode that is compiled in a Linux system and run it on a Windows
system (if it consists of JVM).

7. What is a Class?

A class in Java is a blueprint that defines the variables/attributes and


methods common to objects of a certain kind. Classes are used to create
objects which represent instances of the class and to define the behavior
and properties of these objects. Classes are like a template or a blueprint
for creating objects.

8. What is an instance of a class?

An instance of a class is called an object. An object is simply a collection


of attributes and methods that act on those data.

The new keyword is a Java operator that is used to create the object.

The new operator is followed by a call to a constructor, which initializes


the new object.

Inheritance

1. What is Inheritance?

Inheritance is the mechanism by which one class is allowed to inherit the


features(fields and methods) of another class.

The extends is the keyword used to perform inheritance in Java.

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).

2. Can a class extend more than one class?

No, one class can extend only a single class.

3. How will you restrict a member of a class from inheriting to its


subclass?

We can restrict members of a class by declaring them private because the


private members of the superclass are not available to the subclass
directly. They are only available in their own class.

4. Can we access subclass members if we create an object of superclass?

No, we can access only superclass members but not the subclass
members.

But we can access both subclass and superclass members if we create an


object of the subclass.

5. What is the IS-A relationship in OOPs?

The IS-A relationship is related to the Inheritance property of OOPs.

For example, Apple is a Fruit, Car is a Vehicle, etc.

Inheritance is uni-directional. For example, House is a Building. But


Building is not a House.

6. Explain why inheritance is less useful than composition in OOPs.

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.

Let us understand this: Let's say we want to create a Manager class, so we


end up with the below syntax, which is not allowed in Java (multiple
Inheritance is not allowed in Java)

JAVA

But we can write the above code easily using composition as follows:

class Manager {

public string title;

public Manager(Person p, Employee e) { // objects as parameters


this.title = e.title;

JAVA

Composition assists in attaining high flexibility and prevents breaking of


encapsulation.

7. Why is multiple inheritance not supported in Java?

To reduce the complexity and simplify the language, multiple inheritance


is not supported in Java. Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from the child class object, there will be a
confusion whether to call the method of A or B class.

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.

8. What is super keyword in Java?

The super keyword in Java is a reference variable that is used to refer to


the immediate parent class object.

Whenever you create the instance of a subclass, an instance of the parent


class is created implicitly which is referred by a super reference variable.

Usage of Java super keyword:

super can be used to refer immediate parent class instance variable.

super can be used to invoke the immediate parent class method.

super() can be used to invoke the immediate parent class constructor.

9. What are the main uses of this keyword?

These are the following uses of this keyword.

this can be used to refer to the current class instance variable.

this can be used to invoke the current class method (implicitly)

this() can be used to invoke the current class constructor.

this can be passed as an argument in the method call.

this can be passed as an argument in the constructor call.

this can be used to return the current class instance from the method.
10. Why do we need to use inheritance?

These are the following reasons to use inheritance in Java.

We can reuse the code from the base class.

Using inheritance, we can increase features of class or method by


overriding.

Inheritance is used to use the existing features of the class.

It is used to achieve runtime polymorphism i.e., method overriding.

11. What are the advantages of inheritance in Java?

The advantages of inheritance in Java are as follows:

We can minimize the length of duplicate code in an application by putting


the common code in the superclass and sharing it amongst several
subclasses.

Due to reducing the length of code, the redundancy of the application is


also reduced.

Inheritance can also make application code more flexible to change.

12. Are static members inherited to subclasses?

Yes, static members are inherited to subclass.

13. Can we overload a static method in Java?

Yes, we can overload a static method in Java. Overloading has nothing to


do with runtime but the signature (i.e, return type, arguments, etc) of
each method must be different. In Java, to change the method signature,
we must change either number of arguments, type of arguments, or order
of arguments.

14. What is the difference between Inheritance and Encapsulation?

Inheritance is a relationship between classes in object-oriented concepts.


It is useful to implement the responsibility of the code while programming.
We can use the members of the superclass by extending to the subclass,
which also has the basis of polymorphism.

Whereas Encapsulation is also an object-oriented concept in Java that is


being used to hide the internal details of a class like methods, and
attributes.

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.

16. What is the order of calling constructors in the case of inheritance?

In the case of inheritance, constructors are called from the top to down
hierarchy.

17. Can a class extend itself?

No, a class cannot extend itself.

18. What is Single inheritance and Multilevel inheritance?

Single inheritance involves extending a single superclass from a single


subclass.

In Java, a subclass can have only one superclass.

single inheritance

In multilevel inheritance, a subclass extends from a superclass and then


the same subclass acts as a superclass for another class.

multilevel inheritance

19. Can we pass an object of a subclass to a method that accepts an


object of the superclass?

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.

20. What is Method Hiding?

Method hiding is a concept in object-oriented programming where a


subclass provides its own implementation of a static method that is
already defined in its superclass. When a static method is defined in both
the superclass and the subclass with the same name and signature, the
method in the subclass hides the method in the superclass.

In method hiding, the static method in the subclass is not an override of


the static method in the superclass because static methods cannot be
overridden. Instead, the subclass method is a new method that simply has
the same name as the superclass method.

Code

class Superclass {

public static void display() {

System.out.println("Superclass display method");


}

class Subclass extends Superclass {

public static void display() {

System.out.println("Subclass display method");

public class Main {

public static void main(String[] args) {

Superclass.display(); // "Superclass display method"

Subclass.display(); // "Subclass display method"

Superclass ref = new Subclass();

ref.display(); // "Superclass display method"

JAVA

Collapse

Output

Superclass display method

Subclass display method

Superclass display method

Access Modifiers

1. What are Access Modifiers in Java?

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.

Protected: The access level of a protected modifier is up to the


class/subclass of the same package and also to a different package
through the subclass. A subclass is required to access it from a different
package.

Public: The access level of a public modifier is everywhere in the program.


It means that it is accessible from the class/subclass of the same/different
package.

2. Can we have a private constructor in Java?

Yes, we can have a private constructor in Java. The private constructor is


used when we do not want to create the object of that class.

3. What are commonly used non-access modifiers in Java?

Some of the most commonly used non-access modifiers in Java include:

static: Used to define a class method or attribute that belongs to the class
and not to any particular instance of the class.

final: Used to declare a constant attribute, method, or class that cannot be


changed.

abstract: Used to declare an abstract method that does not have a body
and must be implemented by a subclass.

4. Can a method or a class be final and abstract at the same time?

No, it is not possible. A class or a method cannot be final or abstract at the


same time because the final method or final class cannot be further
modified whereas an abstract class or an abstract method must be
modified further.

5. Explain the use of final keyword in attribute, method and class.

The final is a non-access modifier,

final attribute:

When an attribute is declared as final in Java, the value can't be modified


once it has been assigned.

If any value has not been assigned to that attribute, then it can be
assigned only by the constructor of the class.

final method:

A method declared as final cannot be overridden by its children classes.


A constructor cannot be marked as final because whenever a class is
inherited, the constructors are not inherited. Hence, marking it final
doesn't make sense. Java throws a compilation error.

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

1. What is Encapsulation? How can it be achieved?

Encapsulation in Java is a process of wrapping related code and data


together into a single unit. By this, we can achieve data hiding as given
below,

Declaring the attributes of the class as private.

Providing public setter and getter methods to modify the values of


attributes.

2. What is the difference between Abstraction and Encapsulation?

Abstraction focuses on hiding complexity and presenting a simplified view


of a system, while encapsulation focuses on wrapping data and behavior
within an object and controlling access to it.

Abstraction provides a high-level view of a system, hiding low-level details


and exposing only the essential information.

Encapsulation, on the other hand, provides a low-level mechanism for


managing the internal state of an object and protecting it from outside
access.

3. How the final class related to Encapsulation?

A final class as it relates to encapsulation is a class that a programmer


cannot extend. No subclass within the code can inherit any attributes or
methods from a final class.

It is advisable to write a final class when we want to create a class that is


impossible to expand. For example, imagine we have a class that has
sensitive data relating to a customer's payment and billing information.
We can establish this class as a final class so that no subclasses can
access it.

4. What are some real-world applications of Encapsulation?


Encapsulation is used in banking systems to control access to sensitive
financial data and enforce data validation. For example, a bank account
class might be designed to hide the implementation of a customer's
account balance, and only expose methods for making deposits and
withdrawals.

Encapsulation is used in automotive systems to control access to critical


systems and ensure data consistency. For example, a car's engine
management system might be encapsulated within an object that exposes
methods for controlling the engine but restricts direct access to the
internal data and components.

5. What are the getter(get) and setter(set) methods in Java? Why are they
used?

A getter method is used to retrieve/collect private data from an


encapsulated class.

A setter method is used to update private data/values of an encapsulated


class.

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.

Polymorphism in Java refers to an object’s capacity to take several forms.


Polymorphism allows us to perform the same action in multiple ways in
Java.

2. What are the types of polymorphism?

Polymorphism is of two types:

Compile-time polymorphism

Runtime polymorphism

A polymorphism that occurs during the compilation stage is known as a


Compile-time polymorphism. Method overloading is an example of
compile-time polymorphism.

A polymorphism that occurs during the execution stage is called Runtime


polymorphism. Method overriding is an example of Runtime
polymorphism.
3. How is polymorphism different from method overloading and
overriding?

Polymorphism refers to the ability of an object to take on many forms. It


includes method overloading/overriding as one of its implementation
techniques.

4. What is the difference between polymorphism and inheritance?

Inheritance allows a subclass to inherit behavior from a superclass,


providing code reusability.

Polymorphism allows the subclass to redefine and provide its own


implementation of inherited behavior through overloading and overriding.

5. What is Method overloading?

Method overloading in Java is a feature that allows a class to have more


than one method with the same name, but with different parameters.

Java supports method overloading through two mechanisms: By changing


the number of parameters, by changing the data type of parameters i.e.,
methods with the same names and same parameters with different data
types.

6. What is Method overriding?

In Java, declaring a method in a subclass that is already present in a


superclass is called method overriding. The main purpose of having
overriding methods in the subclass is to have a different implementation
for a method that is present in the superclass.

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.

8. Can the static methods be overridden?

No, we can't override the static methods because they are part of the
class, not the object.

9. Can we change the scope of the overridden method in the subclass?

Yes, we can change the scope of the overridden method in the subclass.
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.

private -> default -> protected -> public

However, the private methods cannot be overridden.

10. What are the differences between method overriding and overloading?

Method Overriding Method 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

Runtime polymorphism Compile-time polymorphism

11. When will the runtime polymorphism fail?

Runtime polymorphism may not work as expected when we try to override


a method that is declared as final in the superclass.

Abstraction

1. What is Abstraction?

Abstraction is the process of hiding certain details and showing only


essential information to the user.

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.

2. Can we make the abstract methods static in Java?

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.

3. What is the difference between abstract class and concrete (normal)


class?

The differences between abstract class and concrete class are:

We cannot create an object of an abstract class. Only objects of its non-


abstract (or concrete) subclasses can be created.
An abstract class can have zero or more abstract methods, but abstract
methods are not allowed in a non-abstract class (concrete class).

4. What are the differences between final and abstract methods?

Differences between final and abstract methods are as follows:

Final Method Abstract Method

A final method cannot be overridden An abstract method must be


overridden

A final method has a body An abstract method does not have a body

A final method can be invoked An abstract method cannot be invoked


directly

5. What is an Abstract method in Java? When it is used?

A method that is declared with an abstract modifier and has no


implementation (means no body) is called as an abstract method in Java.

It does not contain any body. It simply has a method declaration followed
by a semicolon(;).

An abstract method can be used,

when the same method has to perform different tasks depending on the
object calling it.

when it needs to be overridden in its non-abstract subclasses.

6. Can we define an abstract method inside non-abstract class (concrete


class)?

No, we cannot define an abstract method in a non-abstract class.

7. Is it compulsory for a class which is declared as abstract to have at


least one abstract method?

No, an abstract class may or may not have abstract methods.

8. We can't instantiate an abstract class. Then why constructors are


allowed in abstract class?

It is because we can’t create objects of abstract classes but we can create


objects of their subclasses. From the subclass constructor, there will be an
implicit call to the superclass constructor. That’s why abstract classes
should have constructors.

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?

No, we cannot create an abstract attribute. The abstract keyword is used


to declare methods that must be implemented by subclasses, but
attributes cannot be overridden, as they represent a state that is stored in
memory and is not meant to be changed by subclasses.

Therefore, declaring an abstract attribute would be meaningless and don't


make sense in the context of object-oriented programming.

10. What will happen if we do not override all abstract methods in


subclass?

Java compiler will generate a compile-time error. We have to override all


abstract methods in the subclass.

Interfaces

1. What is an Interface in Java?

An interface is similar to an abstract class. It cannot be instantiated and


consists of abstract methods.

The interfaces act as a blueprint for a class. The interface keyword is used
to create an interface.

2. What is the use of Interface in Java?

Interfaces are used in Java to achieve abstraction. By using the


implements keyword, a Java class can implement an interface.

In general terms, an interface can be defined as a container that stores


the methods without bodies to be implemented in the class. It improves
the levels of Abstraction.

3. Can we define private and protected modifiers for data members


(attributes) in interfaces?

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.

4. How to use interfaces in classes?

The class uses implements keyword to implement the interfaces.

5. Can a single class in Java implement multiple interfaces?

Yes, a class can implement multiple interfaces.

6. Can an interface extend multiple interfaces?


Yes, an interface in Java can extend multiple interfaces using the extends
keyword. This allows for multiple inheritance of behavior and abstract
methods from multiple interfaces in a single interface.

7. Can an interface implement another interface?

No, an interface cannot implement another interface. It only extend


another interface.

8. What happens if a class has implemented an interface but has not


provided implementation for that method defined in an Interface?

If a class implements an interface but fails to provide an implementation


for a method defined in the interface, the class must be declared as
abstract. This is because an abstract class can provide an implementation
for some methods and leave others for subclasses to implement.

If a non-abstract class fails to provide an implementation for an interface


method, the compiler will throw an error. So all methods in the interface
should be overridden in the class which implements an interface.

9. What is the difference between abstract class and interface in Java?

Abstract class Interface

Abstract class can have abstract and non-abstract methods. Interface can
have abstract, static, default and final methods

Abstract class doesn't support multiple inheritance. Interface supports


multiple inheritance.

Abstract class can have final, non-final, static and non-static attributes.
Interface has only static and final attributes.

Abstract class can provide the implementation of interface. Interface can't


provide the implementation of abstract class.

The abstract keyword is used to declare an abstract class. The interface


keyword is used to declare an interface.

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.

10. When to use an abstract class and when to use an interface?

We can use an abstract class when we want to provide a default


implementation for some of the methods, or when we want to share
attributes between the subclasses.
We can use an interface when we want to define a group of classes can
adhere to, without specifying any implementation details. Also, we can
use an interface when we want to allow multiple inheritance, since a class
can implement multiple interfaces, but can only inherit from one class.

11. Can we create non-static attributes in an interface?

No. We cannot create non-static attributes in an interface. If we try to


create non-static attributes compile-time error occurs.

By default, they will be treated as public, static, and final. So, it expects
some value to be initialized.

12. Can we declare constructor inside an interface?

No. Interfaces do not allow constructors. The attributes inside interfaces


are static, and final attributes, means constants, and we cannot create the
object for an interface.

So, there is no need for a constructor in the interface that is the reason
interface doesn't allow us to create a constructor.

13. Can we override an interface method in subclass with access modifier


other than public?

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.

14. Can we declare an interface with abstract keyword?

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.

15. Can we re-assign a value to the attributes of interfaces?

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.

It is mandatory to initialize them in the interface.

16. If same method is defined in two interfaces, can we override this


method in class implementing these interfaces?

Yes, implementing the method once is enough in class.

A class cannot implement two interfaces that have methods with the
same name but different return type.

Variables & Arithmetic Operations

1. Can a static method access instance variables?


A static method cannot access a class's instance variables and instance
methods, because a static method can be called even when no objects of
the class have been instantiated.

2. What are the differences between variables and keywords in Java?

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.

Specifies the type/kind of entity. Identify the name of a particular entity.

It always starts with a lowercase letter. First character can be a uppercase,


lowercase letter or underscore.

A keyword should be in lowercase. An identifier can be in uppercase or


lowercase.

A keyword contains only alphabetical characters. An identifier can consist


of alphabetical characters, digits and underscores.

No special symbol, punctuation is used No punctuation or special symbol


except underscore is used.

3. How many data types are there in Java?

Java has two types of data types.

Primitive Data Types, there are 8 primitive data types in Java.

short

byte

int

long

float

double

boolean

char

Non-primitive Data Types

array

class

interface and etc


If noticed, String is not the primitive data type in Java. A string is the
name of the class. Similarly, we can also define our own custom class
types like Student, User, etc.

4. What are the rules for naming Java variables?

These are some rules related to Java variable names:

Java variable names are case-sensitive. Variables declared as bankBalance


is different than BankBalance or BANKBALANCE.

Variable name must start with a letter, or $ or _ character. No other


special characters or digits are allowed as the first character of a variable
name.

After the first character, the Java variable name can have digits as well
along with a letter, $ and _

Variable name cannot be equal to reserved keyword in Java. For example,


we cannot give variable name as int, if, or boolean as they are reserved
keywords in Java.

5. What are some common naming conventions used in Java?

Naming Variables Rule #1

Use only the below characters

- Capital Letters ( A – Z )

- Small Letters ( a – z )

- Digits ( 0 – 9 )

- Underscore(_), this is used only for variables storing a constant value


(i.e, variables

Examples:

age, canLearn, currentGear, MAX_PRICE, etc.

Naming Variables Rule #2

Below characters cannot be used

Blanks ( )

Commas ( , )

Special Characters

( ~ ! @ # % ^ . ?, etc. )

Naming Variables Rule #3


Variable names must begin with small letters, except for the variables
storing a constant value

Naming Variables Rule #4

Cannot use keywords, which are reserved for a special meaning.

int

if, etc

In addition to this, programmers generally use camel case (Eg: canLearn,


ageLimit, etc) notation for naming variables in Java.

6. What are the default or implicitly assigned values for data types in
Java?

Data type Default value

boolean false

byte 0

short 0

int 0

long 0L

char /u0000

float 0.0f

double 0.0d

Any object reference (ex: String) null

7. Explain the difference between int and Integer in Java.

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.

8. What is an Operator in Java?

An operator is a special symbol that tells the compiler to perform specific


mathematical or logical operations. It is generally used in a program to
perform a particular function on operands.

9. What are the types of operators in Java?

Arithmetic operators

Relational operators
Logical operators

Assignment operators

Increment and decrement operators

Conditional/Ternary operators

10. What are Arithmetic operators in Java?

Operators that are used to perform fundamental arithmetic operations


such as addition, subtraction, multiplication, and division on numeric data
types are called arithmetic operators.

+ Addition

– Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder)

11. What is the precedence of operators in Java?

The following is the precedence of operators in Java from highest to


lowest:

Priority Operator Precedence

1 Parentheses ()

2 Unary operators ++, --, +, -, !

3 Multiplicative operators *, /, %

4 Additive operators +, -

5 Relational operators <, >, <=, >=

6 Equality operators ==, !=

7 Logical and operator &&

8 Ternary operator ?:

9 Assignment operators =, +=, -=, *=, /=, %=

12. What is the difference between x += y and x = x + y expressions?

There is no difference between the expressions. Both are equal.

13. What are the sizes of the primitive data types in Java?

The sizes of the primitive data types in Java are:


Data Type Size (in bits) Range of Values Example

boolean 1 true, false true, false

byte 8 -128 to 127 100, -126

char 16 ASCII values from 0 to 255 'a', '7'

short 16 -215 to 215-1 -24456, 4532

int 32 -231 to 231-1 -2036372537, 4500

long 64 -263 to 263-1 3847539L, 8589934592L

float 32 up to 7 decimal points 1.23f, 5.67F

double 64 up to 16 decimal points 1.23456d, 5.6789D

14. Explain the purpose of the Math class in Java.

The Java Math class provides different methods for performing


mathematical operations such as exponentiation, rounding off, etc.

15. What does the Math.pow() method do in Java?

The Math.pow() method is similar to ** operator in Python. It accepts two


numbers and returns the value of the first number raised to the second
number (exponentiation).

The Math.pow() method in Java returns a double value, even if both the
arguments are of type int.

BigInteger

1. What is the use of BigInteger class in Java?

The BigInteger class is used for representing and performing operations


on very large integers that are outside the range of the int and long
primitive data types.

2. What are the various methods available in the BigInteger class for
performing arithmetic operations in Java?

The BigInteger class provides various methods for performing arithmetic


operations such as add() method for addition, subtract() method for
subtraction, multiply() method for multiplication, divide() method for
division, etc.

3. Can we use +, -, * , % operators on BigIntegers?

No, we can't use arithmatic operators on BigIntegers. There are


predefined methods to perform those operations.

4. Compare two BigInteger objects in Java.


The BigInteger class provides a compareTo() method that can be used to
compare two BigIntegers. This method returns an int value of 0 if the two
BigInteger objects are equal, a negative value if the first BigInteger is less
than the second, and a positive value if the first BigInteger is greater than
the second.

5. Where do we use BigInteger in Java?

The BigInteger class is useful in many real-world scenarios where large


number calculations are required. Some common examples include
financial calculations, and scientific applications.

In financial calculations, the BigInteger class can be used to represent and


perform calculations on large amounts of money.

In scientific applications, the BigInteger class can be used to represent


and perform calculations on large numbers in simulations and
calculations. For example, measuring distance between two planets.

I/O Basics

1. How to get input from the user in java?

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.

2. Why do we use System.in as an argument in Scanner class?

By using System.in in a Scanner, we are instructing the scanner to read


the input from the keyboard.

3. How to get different data types as inputs from the user?

The Scanner class provides various methods, such as

nextInt() to read integer

nextDouble() to read double type value

nextLine() to read a sentence as string

next() to read word as a string

nextFloat() to read the float value

4. How to get character as input from the user?

We use next().charAt(0) to read the character, where charAt(0) gets the


first character from the string.

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.

Java provides two types of type conversion :

Implicit Type Conversion

Explicit Type Conversion (Type Casting)

2. How to convert BigIntegers to Integers and Strings?

BigIntegers can be converted to Integers and Strings by using the


following methods:

Let us assume bigNum is BigInteger value.

To Data Type BigInteger Method

int bigNum.intValue()

float bigNum.floatValue()

long bigNum.longValue()

double bigNum.doubleValue()

String bigNum.toString()

int to BigInteger :

JAVA

3. What are some basic type castings?

From Data Type To Data Type Syntax

int float (float) num

int double (double) num

int char (char) num

float int (int) f

double int (int) d

4. How to convert any primitive data type to String?

The valueOf() method is used to convert any primitive data type to String.

From Data Type To Data Type Syntax

int String String.valueOf(num)

float String String.valueOf(floatNum)


char String String.valueOf(ch)

5. How to convert int to char and char to int?

From Data Type To Data Type Syntax

char int Character.getNumericValue(ch)

int char Character.forDigit(num, 10)

6. How to convert String to int, float, long , and double?

From Data Type To Data Type Syntax

String int Integer.parseInt()

String float Float.parseFloat()

String double Double.parseDouble()

Relational & Logical Operators

1. What is the use of logical operators in Java?

The logical operators are used to perform logical operations on boolean


values. These will also produce a true or false result.

2. What are the types of logical operators in Java?

Java supports three types of logical operators. They are,

AND(&&) operator

OR(||) operator

NOT(!) operator

3. What is the use of relational operators in Java?

Relational Operators are used for comparing values. It returns true or false
as the result of a comparison.

4. What are the types of relational operators?

Relational Operators in Java are,

== (equals to)

!= (not equal to)

> (greater than)

>= (greater than or equal to)

< (less than)

<= (less than or equal to)


Relational Operators return boolean results (true/false)

5. Explain the difference between '==' and '.equals()'.

The == is a comparison operator that compares the memory addresses of


two objects to check if they are equal.

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.

The OR operator || returns true if any one of the operands is true.

7. Explain the short-circuit evaluation in Java.

Short-circuit evaluation in Java refers to the behavior of the logical


operators where the second operand is not evaluated if the first operand
determines the result of the expression.

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

1. What is a conditional statement in programming?

A conditional statement is a type of control flow statement that allows a


program to make a decision based on a specified condition.

2. How many types of conditional statements are there in Java?

There are 4 types of conditional statements. They are,

if statement

if-else statement

else if statement

switch statement

3. What is an if...else statement and what is its purpose?

When an if...else conditional statement is used, the if block of code


executes when the condition is true, otherwise the else block of code is
executed.

4. Can we use the else statement without if?


No, an else statement must be associated with an if statement and cannot
exist on its own. The else statement provides an alternative action to be
executed if the condition in the if statement evaluates to false.

5. What is the purpose of an else if statement?

Java provides an else if statement to have multiple conditional statements


between if and else.

The else if statement is optional.

We can add any number of else if statements after if conditional block.

6. What is a switch statement in programming and what is its purpose?

A switch statement is used to perform different actions based on different


conditions. It is often used when multiple conditions need to be evaluated.

The switch statement is more readable when compared to if...else


statement. The body of a switch statement is known as a switch block. A
switch block can have multiple case labels and a default label. The switch
statement allows us to execute a block of code among many cases.

7. What is the purpose of the break statement in a 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.

8. What is a ternary operator and what is its purpose?

A ternary operator is a simple way of writing an if-else statement. It is


used to perform a conditional operation in a single line of code.

JAVA

In the above expression, expression1 is executed if the condition is true,


and expression2 is executed if the condition is false.

9. What is the purpose of the default case in a switch statement?

The default case provides a default action to be executed if the expression


in the switch statement does not match any of the cases.

10. Can we use conditional statements and loops inside a switch


statement?

Yes, conditional statements and loops can be used inside a switch


statement.

11. What are the differences between if...else and switch statements?
If-else Switch

The if...else blocks are executed depending on the condition in the if


statement The switch statement has multiple cases, and the code block
corresponding to that case is executed.

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.

Tests both logical expressions and equality Tests only equality

It has multiple statements for multiple decisions It has single statement


for multiple decisions

12. What are the criteria for deciding whether to use a switch statement
or an if...else statement?

A switch statement is more efficient for selecting among a large group of


fixed data values, as the compiler creates a jump table to select the path
of execution. The if...else statements are better for testing expressions
based on ranges of values or conditions, and for variable conditions that
result in a boolean.

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.

Combining cases and adding/removing labels is easier with a switch


statement, making the code easier to read and maintain.

Loops

1. What is a loop and why is it important in programming?

Loops allow us to execute a block of code several times. It is important in


programming as it enables efficient and automated processing of data.

2. What are the types of loops in Java?

The different types of loops in Java are,

while loop
do-while loop

for loop

for-each loop

2. What is for-each loop in Java?

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?

A for loop is a control structure that allows a programmer to repeat a set


of instructions a specified number of times.

A while loop is a control structure that allows a programmer to repeat a


set of instructions as long as a certain condition is true.

4. What is an infinite loop and how can we avoid it in Java?

An infinite loop is a loop that continues to execute indefinitely because its


termination condition is never met. It can be caused by a logic error in the
loop condition or by incorrect updates to the loop control variables.

We can avoid it in the following ways:

Make sure to update the loop control variables in a way that ensures the
termination condition will eventually be met.

We can use a breakstatement to exit the loop if a certain condition is met.

We can keep track of the number of iterations in the loop and exit the loop
when a certain number is reached.

5. What is the use of the continue statement in Java?

The continue statement in Java is used to skip the current iteration of a


loop and move on to the next iteration. When a continue statement is
encountered inside a loop, the current iteration of the loop is immediately
terminated, and control is transferred to the next iteration of the loop.

6. What is the difference between break and continue statements?

Break Statement Continue Statement

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:

Modification of Elements: The for loop allows elements to be modified


within the loop, but the for-each loop does not. The for-each loop is
designed to only read the elements.

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.

8. What is the difference between a while loop and a do-while loop in


Java?

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

1. What are the different ways to create string objects?

String objects can be created in two ways:

Using the new operator.

Using double quotes.

2. Is String a primitive or non-primitive type in Java?

No, the string is not a primitive data type, but a non-primitive type.

The string is a class in the Java Standard Library that represents a


sequence of characters.

3. Is String immutable in Java?

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?

In Java, two strings can be compared based on content and reference.


There are three general ways by which we can compare strings.

Using equals() method

By == operator (double equal operators)

By compareTo() method.

It is suggested to use equals() or compareTo() methods to compare two


strings as those methods compares string values.

Whereas, using == operator compares the reference in the memory.

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

split() Split/divide the string at the specified regular expression.

compareTo() Compares two strings based on the Unicode value of each


string character.

compareToIgnoreCase() Similar to compareTo, but it also ignores case


differences.

length() Returns the length of the specified string.

substring() Returns the substring from the specified string.

equalsIgnoreCase() Compares two strings ignoring case differences.

contains() Checks if a string contains a substring.

trim() Returns the substring after removing any leading and trailing
whitespace from the specified string.

charAt() Returns the character at the specified index.

toLowerCase() Converts string characters to lowercase.

toUpperCase() Converts string characters to uppercase.

concat() Concatenates two strings.

6. Explain the difference between str1.equals("abc") and


"abc".equals(str1), where str1 is any String object.

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.

7. What is the use of the substring() method in Java?

The substring() method can be used to access a part of the string.

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.

8. How do we check whether a string is empty in Java?

The isEmpty() method can we used to determine whether the string is


empty or not. If the length of the string is zero, it returns true, or else it
returns false.

9. What is the split() method?

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.

10. Is it possible to get a Character Array from String in Java?

String class provides toCharArray() method, which converts this string to a


new character array. This method returns a copy of its internal char array,
whose length is the length of that string.

11. What is StringBuilder?

The StringBuilder is a class in Java that provides a mutable sequence of


characters. It is used to represent a string of characters that can be
modified and is often used when we need to build or manipulate strings in
our code.

Unlike String, StringBuilder allows us to modify a string without creating a


new object each time we make a change, which is more memory-efficient
than creating new objects for each modification. It provides different
methods,

Method Decription

append() used to add a sequence of characters

insert() used to insert a sequence of characters

replace() used to replace a sequence of characters


delete() used to delete a sequence of characters

Syntax

StringBuilder builder = new StringBuilder();

JAVA

Example

10

11

class Main {

public static void main(String[] args) {

StringBuilder builder = new StringBuilder();

builder.append("Hello");

builder.append(" ");

builder.append("world!");

String result = builder.toString();

System.out.println(result); // Hello world!

JAVA
Collapse

12. What is StringBuffer?

The

StringBuffer

is a class in Java that is similar to StringBuilder but is designed to be


thread-safe. This means that multiple threads can access the same
StringBuffer object simultaneously without causing synchronization issues.
It provides methods for modifying and manipulating strings.

Method Decription

append() used to add a sequence of characters

insert() used to insert a sequence of characters

replace() used to replace a sequence of characters

delete() used to delete a sequence of characters

Syntax

StringBuffer buffer = new StringBuffer();

JAVA

Example

class Main {

public static void main(String[] args) {

StringBuffer buffer = new StringBuffer();

buffer.append("Hello");

buffer.append(" ");

buffer.append("world!");

String result = buffer.toString();

System.out.println(result); // Hello world!

}
JAVA

Collapse

13. What are the differences between StringBuffer and StringBuilder?

StringBuffer StringBuilder

StringBuffer can be used by StringBuilder cannot be used by multiple


multiple threads threads

It is faster than the

String

class due to mutability but


It is the fastest among all as it allows
slower than the
mutability and does not allow multiple
StringBuilder threads to operate at the same time.

class as it allows
simultaneous operations of
multiple threads.

String Pool

1. How does Java allocate memory for Strings?

In Java, memory is primarily divided into two regions:

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

2. What is a String Pool?

String pooling is Java's optimization technique to save memory by reusing


common String literals. String Pool is a special area within the heap
memory where Java stores all the unique String literals. This means that
we can assume the heap memory is a large container that stores all the
objects used in a program, and the String pool is a small container, inside
the large container, which stores unique String literals.

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.

For example, String str = new String("Hello");

As we know in the case of String comparison with ==, the reference is


compared instead of values. We can use this comparison to understand
memory allocation from the below code,

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?

We cannot replace String[] args with an array of integers(like int[] args).


The JVM specifically looks for a main() method with the exact signature
including String[] args to initiate the execution of the Java application.

The String[] args parameter in the main() method is used to handle


command-line arguments. It is an array of String types that captures any
arguments that you pass at the command line while initiating the
application. These arguments are stored as strings and can be converted
to other types within the main() method if necessary.

Question 1 of 1

Which of the following statements is true?

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.

We cannot convert the elements of the String[] args to other datatypes.

Show Answ

Arrays and ArrayLists


1. What is an array in Java?

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.

2. What are the different collections available in Java?

Java consists of various types of collections like,

ArrayList

HashSet

HashMap and etc.

Arrays in Java are used to store collections of data, they are not
considered a part of the Java Collections Framework.

3. What is the single-dimensional and multi-dimensional array in Java?

The single-dimensional array is an array with only one dimension, similar


to a linear list of elements.

For example,

JAVA

The above code declares a single-dimensional array of integers with a size


of 7.

On the other hand, a multi-dimensional array is an array that contains


arrays as elements.

For example,

JAVA

The above code declares a two-dimensional array of integers with 2 rows


and 3 columns.

4. How to access the elements of an array in Java?

To access elements in a single-dimensional array in Java, we can use the


index number of the element in square brackets. For example, if we have
an array named arr and we want to access the 3rd element, we can
access it as arr[2] (arrays in Java are 0-indexed).
To access elements in a multi-dimensional array in Java, use multiple sets
of square brackets. For example, if we have a 2-dimensional array named
arr2d, and we want to access the element in the 2nd row and 3rd column,
we can access it as arr2d[1][2].

5. What is an ArrayList in Java?

The ArrayList is a class from the package java.util, that is used to


implement the functionality of resizable arrays.

6. Why is an ArrayList called a dynamically growing array in Java?

ArrayList is called a dynamically growing array in Java because ArrayList


uses a dynamic array internally for storing a group of elements.

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.

7. What happens if we declare an array without assigning the size?

It is not possible to declare an array without knowing the length. When we


declare an array without assigning the size, like bills = new int[], it results
in a compile-time error.

8. When an ArrayIndexOutOfBoundsException occurs?

The ArrayIndexOutOfBoundsException occurs when we try to access an


invalid index of an array. For example, when the index is higher than the
size of the array or the index is negative.

9. What are the advantages and disadvantages of an array?

Advantages of an array:

We can store multiple elements of the same type under a single variable.

We can retrieve elements using the index at run time.

Disadvantages of an array:

Before using an array, it is mandatory to declare its size.

It is a static structure, so we cannot increase or decreases memory


allocation.

Insertion and deletion operations are difficult because elements are stored
at contiguous memory locations.

Allocating more memory than required is a waste of memory.


10. Does System.out.println(arr) prints all elements in the array arr?

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.

11. What is the difference between Arrays and Arraylists?

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 accept primitive data types ArrayLists accept an object of primitive


data types

Arrays do not have built-in methods for adding, removing, and searching
ArrayLists have built-in methods for adding, removing and searching

12. What are the benefits of Arrays over ArrayLists?

Efficiency: Arrays are more efficient than ArrayLists in terms of memory


usage and runtime performance. This is because ArrayLists use an
underlying array to store elements, and require additional memory and
processing overhead for managing dynamic resizing and insertion/deletion
operations.

Simplicity: Arrays are simpler to use and understand than ArrayLists,


especially for basic operations such as iterating over elements or
accessing elements by index.

13. Is it possible to join two or more ArrayLists in Java?

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.

14. What are the methods commonly used in ArrayList in Java?

The following are the methods commonly used in ArrayList in Java.

Method Description

add(element) Adds an element to the end of the ArrayList

add(index, element) Adds an element at a specific index in the ArrayList


get(index) Returns the element at a specific index in the ArrayList

remove(index) Removes the element at a specific index in the ArrayList

remove(Object) Removes the first occurrence of an object from the


ArrayList

size() Returns the number of elements in the ArrayList

clear() Removes all elements from the ArrayList

contains(Object) Returns a boolean indicating if the ArrayList contains a


specified element.

indexOf(Object) Returns the index of the first occurrence of a specified


element in the ArrayList

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.

Wrapper classes, such as Integer, Float, etc., provide a way to wrap


primitive data types as objects. This allows us to store primitive data
types in an ArrayList, as the ArrayList can store objects.

If we try to store a primitive data type directly in an ArrayList, we will


receive a compile-time error, as the ArrayList only accepts objects.

Methods

1. Why the main() method should be public and static?

The main() method should be static in Java, so the JVM can directly invoke
it without instantiating the class's object.

If the main() method is non-static, then JVM needs to create an instance of


the class, and there would be confusion if the constructor of that class
takes an argument, which constructor should be called by JVM, and what
parameters should be passed? We know that JVM can’t instantiate a Java
class without calling a constructor method.

2. What is the method in Java?

A method in Java is a named block of code that performs a specific task. It


can take inputs, process them, and return a result. Methods make code
more organized, readable, and reusable.

3. What is a return type of a method and how is it used?


The return type of a method specifies what type of value the method
returns. The return type can be any valid Java data type, including void.
The return type is used to specify the expected output of the method. If
the return type is void then the method should not return any value.

4. What is a recursion in Java?

Recursion is a method calling itself repeatedly until a certain condition is


met. It is used to solve problems by breaking them down into smaller,
easier-to-solve subproblems.

5. What is a constructor in Java?

A constructor is a special type of method that is called when an object is


created. It has the same name as the class and is used to initialize the
object's instance variables.

6. What is the difference between an argument and a parameter in Java?

In Java, an argument refers to the value that is passed to a method during


a method call, while a parameter refers to the variable in the method
definition that receives the argument. Simply, when we call a method, we
pass values to it as arguments, and the method then uses these
arguments as parameters.

HashSets

1. What is a HashSet?

The HashSet is an unordered collection of elements. The HashSet stores


only unique elements and duplicate elements are not allowed.

2. What happens when we remove an element from a HashSet that


doesn’t exist?

If we try to remove an element from a HashSet that doesn’t exist, nothing


happens. The HashSet will remain unchanged.

3. What are the methods commonly used in HashSet?

Method Description

add() adds a single element to a HashSet

remove() removes an element from a given HashSet. It returns true if a


HashSet contains the specified element, otherwise false

clear() removes all the elements from a HashSet

contains(element) checks if an element is present in a given HashSet. It


returns true if the element is found, otherwise false
size() finds the size of a HashSet

4. What are the differences between HashSets and ArrayLists?

The differences between the HashSets and ArrayLists are as follows:

HashSet ArrayList

HashSet stores only unique elements ArrayList can store duplicate


elements

The order of elements in HashSet is not maintained ArrayList maintains


the order of elements as they are inserted and removed

HashSet is generally faster for operations like add, remove, and contains
ArrayList is better for retrieving elements using index

5. How do HashSets perform different set operations?

HashSets uses the following methods to perform operations like: union,


intersection, etc.

Method Description

addAll() used to perform the union of two HashSets

retainAll() used to perform the intersection of two HashSets

removeAll() used to find the difference between two HashSets

containsAll() this method can be used to check if a given set is a superset


or subset of another set

6. How to sort elements in a HashSet?

To perform operations like sorting, we can convert HashSet to ArrayList,


and perform the operations on the respective ArrayList.

HashMaps

1. What is HashMap in Java?

The HashMap is an unordered collection of elements. HashMap stores the


data in key/value pairs. Here, keys should be unique and a value is
mapped with the key. HashMaps can have duplicate values.

In HashMap, each key/value pair is known as an element.

2. What are the methods commonly used in HashMap?

Method Description

put() used to add elements to a HashMap

get() used to access values of a HashMap


replace() used to update values of a HashMap

remove() used to remove a single element of a HashMap

clear() used to remove all the elements of a HashMap

keySet() used to get all the keys of a HashMap

values() used to get all the values of a HashMap

entrySet() used to get all the elements of a HashMap

3. What are the differences between HashSet and HashMap?

The differences between HashSet and HashMap are as follows:

HashSet HashMap

HashSet is used to store a collection of unique elements HashMap is used


to store key-value pairs, where each key is unique

HashSet does not allow duplicates HashMap allows duplicates values, but
not duplicate keys

The order of elements in HashSet is not guaranteed The order of elements


in a HashMap is determined by the order of their keys

4. Is it possible to store a key that is already present in HashMap?

Yes, it is possible to store a key that is already present in a HashMap, but


it will overwrite the previous value associated with that key. The HashMap
in Java stores key-value pairs, and the keys must be unique.

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?

Hashing in Java is a way of mapping data to a key, so that it can be used


to identify data uniquely. These keys are generated by a function called
the Hash-function, which provides output known as Hash-values (keys).
The data is stored in pairs of key(Hash values) and value(real data) in an
array called HashMap, which uses keys as indexes and values as data to
be stored at each index location.

6. What are some of the practical applications of HashMap in real world?

The following are some practical applications of HashMaps:

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.

Java Collections Framework

1. Explain about Java Collections Framework

In Java, the Collections Framework is a set of classes and interfaces that


implement commonly reusable collection data structures. It is a unified
architecture for representing and manipulating collections. It resides in the
java.util package and its subpackages.

There are many interfaces and classes in the Java Collections Framework.

Collection interface: It is extended by the below interfaces,

List interface: It is implemented by the below classes,

ArrayList

LinkedList

Vector: The Vector class is extended by the Stack class.

Set interface: It is implemented by the below classes,

HashSet

LinkedHashSet

TreeSet

Queue interface: It is implemented by the below classes,

PriorityQueue

LinkedList

Map interface: It is implemented by the below classes,

HashMap

LinkedHashMap

TreeMap

Hashtable

All the above interfaces and classes are present in the java.util package.

Question 3 of 3

Which of the following interfaces is implemented by the HashMap class in


Java?
List

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:

add(E element): Adds an element to the end of the list.

add(int index, E element): Inserts an element at the specified position in


the list.

remove(int index): Removes the element at the specified position in the


list.

get(int index): Retrieves the element at the specified position in the list.

set(int index, E element): Replaces the element at the specified position


with the specified element.

indexOf(Object o): Returns the index of the first occurrence of the


specified element in the list, or -1 if the list does not contain the element.

Several classes in Java implement the List interface, each offering


different characteristics:

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?

In Java programming, the Set interface is a part of the Java Collections


Framework and it extends the Collection interface. A set represents a
collection that does not allow duplicate elements. It models the
mathematical set abstraction and has classes that implement this
interface to provide the functionalities of a set collection.

A prominent characteristic of a set is that it does not allow duplicate


elements. It ensures that all elements in the set are unique. It does not
preserves the insertion order of elements.

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.

remove(Object o): Removes the specified element from the set if it is


present.

contains(Object o): Returns true if the set contains the specified element.

clear(): Removes all elements from the set.

The Set interface has various implementations, each having its


characteristics:

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

Which of the following interfaces is extended by the Set interface in Java?


List

Map

Collection

ArrayList

4. What is a Map?

In Java, the Map interface is a part of the Java Collections Framework,


though not extending the Collection interface; it stands a bit apart from
the typical collection types. The Map interface facilitates the storage of
associations between keys and values, allowing for quick retrieval of a
value using its key.

The fundamental characteristic of a map is to store data in key-value


pairs. Each key is associated with exactly one value. Keys are unique, but
values can be duplicated.

The Map interface provides a variety of methods to manipulate and access


data stored in a map. Some prominent methods include:

put(K key, V value): To associate a specific value with a key.

get(Object key): To retrieve the value associated with a key.

remove(Object key): To remove the key-value pair associated with a key.

containsKey(Object key): To check if a key is present in the map.

containsValue(Object value): To check if a value is present in the map.

keySet(): To retrieve a set of all keys in the map.

values(): To retrieve a collection of all values in the map.

Several classes implement the Map interface, providing various


characteristics and functionalities. Here are some of the well-known
implementations:

HashMap

LinkedHashMap

TreeMap

Hashtable

Question 2 of 2

Which of the following is not a characteristic of the Map interface in Java?

Storing data in key-value pairs


Each key is associated with exactly one value

Keys can be duplicated

Values can be duplicated

5. Difference between the Collections Class and Collection Interface?

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

The Collection interface is a member of the Java Collections Framework


and serves as the root interface for most collection types in Java, including
List, Set, and Queue. It defines the essential methods that all collections
will have, which include operations such as addition, removal, and
inspection of elements in a collection.

Here is a broad classification of the methods that the Collection interface


provides:

Basic Operations: add, remove, contains, etc.

Bulk Operations: containsAll, addAll, removeAll, etc.

Array Operations: toArray()

Iterative Operations: iterator()

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()

Synchronization Wrappers: synchronizedCollection()

Unmodifiable Wrappers: unmodifiableCollection()


Singleton and Empty Collections: singleton(), emptyList(), emptySet(),
emptyMap()

Example:

JAVA

Aspect Collection Collections

Package java.util java.util

Type Interface Class

Implementation Implemented by classes like ArrayList, HashSet, etc.


Utility class providing static methods to operate on collections

Usage To work with groups of objects; a high-level representation of a


collection of objects To provide utility functions to work with and
manipulate collections.

Methods Methods like add(), remove(), etc., which are to be implemented


by classes that implement the Collection interface Contains static
methods like sort(), reverse(), etc., to work on collections

Extensibility Can be extended by implementing the interface in a custom


class Cannot be extended in a custom class

Performance Aspect Depends on the specific implementing class Offers


optimized, ready-to-use static methods to manipulate collections
effectively

Question 4 of 4

Which of the following methods is available in the Collections class?

add()

sort()

remove()

toArray()

6. Explain about the Comparable interface.

The Comparable interface is a part of the java.lang package, and it is used


to impose a natural ordering on the objects of the class that implements
it. Classes implementing this interface must override the
compareTo(Object o) method, which compares the current object with the
specified object for order. It aids in sorting the elements of collections like
arrays and array lists.
Imagine you have a list of students, and each student has a roll number
assigned. It is generally accepted that roll numbers should be in
ascending order, from smallest to largest. This natural and generally
accepted ordering is what the Comparable interface helps us to achieve.

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

Which of the following methods must be overridden in a class that


implements the Comparable interface?

compare()

compareTo()

equals()

hashCode()

7. Explain about the Comparator interface.

The Comparator interface is part of the java.util package and it provides a


way to define custom sorting orders for collections of objects. Classes that
implement this interface must override the compare(T o1, T o2) method to
dictate how two objects should be compared for ordering. It also has a
default and several static methods such as reversed(), thenComparing(),
etc., which facilitate more complex comparator logic. It is often used with
data structures such as trees and arrays to perform sorted operations or
to maintain a sorted order.

Now, what if we want to sort students based on different criteria at


different times? For instance, once based on their names and another time
based on their roll numbers. This is where the Comparator interface
comes in handy, as it allows us to create different rules for sorting.

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

What is the purpose of the Comparator interface in Java?

To define custom sorting orders for collections of objects.

To create a map of key-value pairs.

To impose a natural ordering on the objects of the implementing class.

To allow storage of duplicate elements in a collection.

8. What is the difference between Comparable and Comparator


interfaces?

Aspect Comparable interface Comparator interface

Package java.lang java.util

Method to Override compareTo(T o) compare(T o1, T o2)

Usage Used to define a natural ordering for a class. Used to define custom
orderings for a class.

Flexibility Less flexible as it forces an object to have only one natural


ordering. More flexible as it allows an object to have multiple ordering
criteria.

Method Parameters A single parameter representing the object to be


compared with. Two parameters representing the objects to be compared.

Implementation Implemented in a class of objects to be sorted and


overrides the compareTo() method. Can be implemented in a separate
class or as an anonymous inner class, and overrides the compare()
method.

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.

Errors and Exceptions

1. What is an Exception Handling in Java?

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.

2. How do exceptions affect the program if we don't handle them?

Exceptions are runtime errors. Suppose we are making a web application


with Java. And it all works fine but there is an exceptional case when the
application tries to get the file from storage and the file doesn’t exist (this
is the case of exception in Java). And if this case is not handled properly
then the application will crash.

3. How can you handle exceptions in Java?

Exception handling can be performed using:

try: the set of statements or code which requires monitoring for an


exception is kept under this block.

catch: this block catches all exceptions that were trapped in the try block.

finally: this block is always performed irrespective of the catching of


exceptions in the try or catch 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.

The throw keyword is used to throw an exception explicitly.

5. What if the static modifier is removed from the signature of the main
method?

The program compiles. But, at runtime, it throws an error


NoSuchMethodError.

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.

So, if we want to perform multiple tasks in response to various exceptions,


we can use multiple catch blocks.

7. What is the difference between exception and error in Java?

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.

8. Can we just use try instead of finally and catch blocks?

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.

Dates and Times

1. How to convert a string to date in Java?

The DateTimeFormatter class has a

parse()

method which creates the respective object (date, time, or date-time)


from the give string.

Code

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

class Main {

public static void main(String[] args) {

String dateStr = "28 November 2018";

DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd


MMMM yyyy");

LocalDate date = LocalDate.parse(dateStr, format1);

System.out.println(date);

JAVA

Collapse

Output

2018-11-28
2. How to calculate difference between two dates and times in Java?

a. calculating difference between two dates

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 {

public static void main(String[] args) {

LocalDate startDate = LocalDate.of(2020, 2, 20);

LocalDate endDate = LocalDate.of(2021, 10, 21);

Period period = Period.between(startDate, endDate);

System.out.println("Years: " + period.getYears());

System.out.println("Months: " + period.getMonths());

System.out.println("Days: " + period.getDays());

JAVA

Collapse

Output

Years: 1

Months: 8

Days: 1
b. calculating difference between two times

In Java, we have a

Duration

class to find the difference between two times in seconds.

Code

import java.time.Duration;

import java.time.LocalTime;

import java.time.format.DateTimeFormatter;

class Main {

public static void main(String[] args) {

LocalTime startTime = LocalTime.of(10, 30, 30);

LocalTime endTime = LocalTime.of(10, 31, 30);

Duration duration = Duration.between(startTime, endTime);

System.out.println(duration.getSeconds());

JAVA

Collapse

Output

60

3. How do we get today's date?

The

LocalDate

class provides

now()

method which returns the date object with today's date.

Code

import java.time.LocalDate;

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

LocalDate dateObj = LocalDate.now();

System.out.println(dateObj);

JAVA

Output

2022-12-20

4. What are the commonly used classes in

java.time

package?

Class Description

It allows us to create a date object and represent a valid


LocalDate
date (year, month and day)

It allows us to create a time object and represent a valid


LocalTime
time (hours, minutes and seconds).

It allows us to create a date-time object and represent a


LocalDateTime
valid date and time together.

The

DateTimeFormatter

class from

java.time.format
DateTimeForma
tter has a

ofPattern()

method that creates an instance of the


DateTimeFormatter for the given pattern of the date,
time and date-time.

It is used to find the difference between two dates in


Period
terms of years, months and days.

Duration It is used to find the difference between two times in


Class Description

seconds.

Lambda Expressions

1. What is a Functional Interface?

A functional interface is an interface that has a single abstract method


(SAM). A functional interface can have any number of default methods
(methods with a default implementation) or static methods, but it must
have only one abstract method.

Sample Functional Interface

interface Runner {

void run();

JAVA

2. What is a Lambda Expression?

A lambda expression consists of a list of parameters, an arrow, and a


body. They provide a way to represent a function as an object.

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

(parameters) -> lambda body

JAVA

3. What are the main features of a Lambda Expression?

 A lambda expression can be passed as a parameter to another


method.

 There is no need to declare the parameter type because the


compiler can fetch the type from the parameter's value.
 We can use parentheses when using multiple parameters but there
is no need to have parenthesis when we use a single parameter.

 If the body of expression has a single statement then there is no


need to include curly braces.

 A lambda expression can exist standalone without belonging to a


class.

4. What is a Predicate?

Predicate is a Functional Interface. It belongs to the

java.util.function.Predicate

package. It returns a boolean value. It is used in several Stream methods.

Streams

1. What is a Stream?

A stream is a sequence of elements that supports various operations for


processing the elements.

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.

2. What is the difference between Intermediate and Terminal operations?

An intermediate operation is a stream operation that produces a new


stream as output after performing the specified operations.

A terminal operation is a stream operation that consumes the elements of


a stream and produces a result. It doesn't produce a new stream.

3. Convert an array to Stream.

We can create a stream directly using the

of()

method of the

Stream

interface.

Code

String[] animals = {"Cat", "Dog", "Rat"};


Stream numbers = Stream.of(animals);

JAVA

4. What are an Optional?

The

Optional

class from the

java.util

package is designed to be used as a return type for methods that may or


may not return a value. It provides several methods to help prevent the

NullPointerException

5. What is the difference between Absolute path and Relative path?

Absolute Path: An absolute path is a path that specifies the exact


location of a file or directory in the file system, starting from the root
directory. For example, on a Unix-based system, an absolute path might
be something like

/home/rahul/documents/file.txt

for Linux systems.

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

, which specifies the location of the file

file.txt

in the

documents

folder in the current working directory.

Submit Feedback

Multithreading in Java | Part - 1

Threads

Multithreading
Thread class Methods

Introduction

In the world of computing, imagine a task as a worker. Normally, we might


have a single worker handling everything, from making coffee to
answering emails. This is like a single-threaded application: one task after
another. But what if we could have multiple workers, each doing a
different job at the same time? That's where multithreading comes in!

In Java, multithreading allows a program to perform multiple operations


simultaneously, making tasks efficient and quick. Consider a busy
restaurant: instead of one chef preparing all dishes one by one, multiple
chefs work together, cooking several dishes at once. This is similar to how
multi-threaded applications operate, with multiple threads (or "chefs")
working concurrently.

1. Threads

In Java, a thread is a lightweight sub-process or the smallest unit of


processing. Assume a thread as a worker within a program, carrying out a
specific task. We can assume a program is a process that contains
multiple threads.

Referring to our previous example, if our restaurant represents a running


Java program, each chef represents a thread. Each chef (or thread) carries
out specific tasks within the restaurant (the program). Just like chefs work
concurrently in a kitchen, threads in Java allow multiple operations to be
executed simultaneously, making the overall process efficient.

To understand the concept of threads, it’s important to know what


happens when we run a Java program.

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.

What is a main thread?


The main thread is the entry point of any Java application. It's the thread
from which other "child" threads are spawned. The main() method in a
Java class is invoked by the main thread. If we don't create any additional
threads in our application, only the main thread will execute, sequentially
performing all tasks.

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.

Need for Multithreading

In the world of applications, waiting can lead to inefficiencies. The time it


takes to process one task before moving on to the next might seem trivial,
but when magnified over thousands or millions of tasks, it can result in
significant delays. Let's delve into our ticket booking scenario to
understand this better.

Imagine a high-demand concert where thousands of audiences are trying


to book tickets simultaneously. In our current application setup without
multithreading, if two audiences (let's call them User1 and User2) attempt
to book at the same moment, User2 would be left waiting until User1
completes their booking. This sequential processing could lead to
potential ticket unavailability for User2 if tickets run out while they wait.

run out while they wait.

10
11

12

13

14

15

16

17

18

19

20

21

class TicketBooking {

private int availableTickets = 10;

public void bookTicket(String user, int numberOfTickets) {

if (availableTickets >= numberOfTickets && numberOfTickets > 0) {

availableTickets -= numberOfTickets;

System.out.println(user + " successfully booked " +


numberOfTickets + " tickets.");

} else {

System.out.println("Sorry " + user + ", tickets not available or


invalid booking request!");

public class BookingApp {

public static void main(String[] args) {

TicketBooking app = new TicketBooking();

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

tasks, these delays accumulate, leading to inefficiencies. By introducing


multithreading, we can allow User1 and User2 to book tickets at the same
time, making the system faster and more responsive.

2. Multithreading

In Java, multithreading is the process of executing multiple threads


simultaneously.

Multithreading refers to the concurrent(at the same time) execution of


multiple threads within a program. By using multiple threads, different
parts of a program can be executed concurrently, allowing multiple tasks
to run at the same time.

In Java, multithreading is the capability of a CPU, or a single core in a


multi-core processor, to provide multiple threads of execution
concurrently. This simultaneous execution leads to optimal utilization of
CPU resources, making our applications faster and more responsive.

Drawing from our restaurant example, think of multithreading as having


multiple chefs (threads) working in a kitchen (program) simultaneously. If
each chef is dedicated to a specific task, like chopping vegetables or
frying, then meals (tasks) get prepared much faster than if one chef were
to handle every task sequentially. Similarly, with multiple threads working
concurrently in a program, tasks get executed more efficiently.

Benefits of Multithreading

Improved performance

Better resource utilization

More responsive applications

Drawbacks of Multithreading

Complexity in code

Potential for thread interference and deadlocks


In Java, we can create a thread in two ways:

Using the Thread class

Using the Runnable interface

2.1 Using the Thread Class

The Thread class is predefined in Java. It is part of the java.lang package


and provides methods for creating and managing threads in Java
programs. The two most important methods of the Thread class are the
start() and run() methods.

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

class MyThread extends Thread {

public void run() {

// Code to be executed by the thread

JAVA

Here, the

Thread

class is extended by the

MyThread

class so that it is considered a thread. We write the code in the

run()

method that needs to be executed when the thread is started.

Example
1

10

11

12

class MyThread extends Thread {

public void run() {

System.out.println("Thread using Thread class.");

class Main {

public static void main(String[] args) {

MyThread thread = new MyThread();

thread.start();

JAVA

Collapse

Output

Output

Thread using Thread class.

Here, we have created a


MyThread

object and invoked its

start()

method to initiate a new thread of execution. Then the

run()

method of the

MyThread

object is invoked implicitly.

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()

method, a new thread is instantiated and the

run()

method is invoked implicitly. But when we call the

run()

method directly, a new thread is not instantiated, so the

run()

method is executed in the current thread.

Code

8
9

10

11

class RunnerThread extends Thread {

public void run() {

System.out.println("Inside run() method.");

class Main {

public static void main(String[] args) {

RunnerThread thread = new RunnerThread();

thread.run();

JAVA

Expand

Output

Inside run() method.

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.

Extending the Thread class has some limitations, such as inflexibility in


extending other classes. In Java, any class can only extend a single class,
so we can't extend another class after extending the Thread class. In such
cases, we have to use the Runnable interface.

2.2 Using the Runnable interface

Another way to create a thread is by implementing the Runnable interface


and implementing its run() method. The Runnable interface is predefined
in Java. It is part of the java.lang package and is used to define the
behavior of a thread.
As similar to the Thread class, the Runnable interface contains only one
method, called run(), which is implemented by a class to define the
behavior of the thread when it is executed.

A class object that implements Runnable can be passed to a Thread


object's constructor and executed using the start() method.

Syntax

class MyRunnable implements Runnable {

public void run() {

// Code to be executed by the thread

JAVA

Example

10

11

12
13

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread using Runnable interface.");

class Main {

public static void main(String[] args) {

MyRunnable myRunnable = new MyRunnable();

Thread thread = new Thread(myRunnable);

thread.start();

JAVA

Collapse

Output

Thread using Runnable interface.

Here,

we have created a MyRunnable object and invoked its start() method to


initiate a new thread of execution. Then the run() method of the
MyRunnable object is invoked implicitly.

Note

In multithreading, when multiple threads are running concurrently, the


exact order and frequency of execution can vary each time you run the
code. The reason behind this is threads run independently and share the
CPU, which is managed by the operating system. The operating system
manages the CPU and determines how much time each thread gets to use
it.

So the output may vary each time we run the code.

3. Thread class Methods

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 {

public static void main(String[] args) {

try {

System.out.println("Sleeping for 2 seconds...");

Thread.sleep(2000);

System.out.println("Awake now!");

} catch (InterruptedException e) {

System.out.println("Error: " + e);

JAVA

Collapse

Output

Sleeping for 2 seconds...


Awake now!

Here, the output Sleeping for 2 seconds... is printed first and after a two
seconds delay, the output Awake now! is printed.

2. currentThread()

The static currentThread() method of the Thread class returns the


currently executing thread's reference. It's helpful when we need details
or to manipulate the current thread.

Code

10

11

12

13

14

15

class MyThread extends Thread {

public void run() {

Thread threadReference = Thread.currentThread();

System.out.println("Current thread: " + threadReference);

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

MyThread obj = new MyThread();

obj.start();

JAVA

Collapse

Output

Current thread: Thread[Thread-0,5,main]

Here, we print the current thread's reference after starting the thread.

3. getName() & setName()

The

getName()

method of the

Thread

class retrieves the name of the thread, while the

setName()

method assigns a new name to the thread. These methods aid in thread
identification.

Code

9
class Main {

public static void main(String[] args) {

Thread thread = Thread.currentThread();

System.out.println("Original thread name: " + thread.getName());

thread.setName("MyMainThread");

System.out.println("Updated thread name: " + thread.getName());

JAVA

Output

Original thread name: main

Updated thread name: MyMainThread

Here, we are in main thread and we are changing the name of the thread
to

MyMainThread

Other Methods

Method Description

getId() Returns the unique identifier of the thread.

isAlive() Determines if the thread is still running.

yield() Temporarily pauses the current thread, allowing other threads to exe

destroy() Destroy a thread without ensuring proper resource release.

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()

toString() Returns a string representation of the thread, including its name, pr


Method Description

thread group.

Causes the current thread to pause its execution and relinquish its l
wait()
the object's monitor until notified.

Wakes up one thread that is waiting on the object's monitor, allowin


notify()
proceed with its execution.

Wakes up all the threads that are waiting on the object's monitor, al
notifyAll()
them to proceed with their execution.

Let's adapt our ticket booking example to utilize multithreading.

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

class TicketBooking implements Runnable {

private int availableTickets = 10;

public void bookTicket(String user, int numberOfTickets) {

if (availableTickets >= numberOfTickets && numberOfTickets > 0) {

availableTickets -= numberOfTickets;

System.out.println(user + " successfully booked " +


numberOfTickets + " tickets.");

} else {

System.out.println("Sorry " + user + ", tickets not available or


invalid booking request!");

public void run() {

String user = Thread.currentThread().getName();

int wantedTickets = (user.equals("User1")) ? 5 : 6;

bookTicket(user, wantedTickets);
}

class BookingApp {

public static void main(String[] args) {

TicketBooking app = new TicketBooking();

Thread user1 = new Thread(app);

Thread user2 = new Thread(app);

user1.setName("User1");

user2.setName("User2");

user1.start();

user2.start();

JAVA

Collapse

Output

Sorry User2, tickets not available or invalid booking request!

User1 successfully booked 5 tickets.

Here,

 To initiate the threads, we call the

start()

method on both

user1

and

user2

. Both users begin their ticket booking processes almost simultaneously.

 The class

TicketBooking
implements the

Runnable

interface and calls the

bookTicket()

method in the

run()

method.

 By setting a name to the threads, we can have distinct behavior or


processing to different threads within the same

Runnable

implementation, providing flexibility and distinction in concurrent


execution scenarios.

Summary

 Threads are the smallest units of a program that can run


concurrently in Java.

 Multithreading allows multiple threads to execute simultaneously,


making better use of system resources.

 The

Thread

class in Java provides built-in methods for managing and controlling


threads.

 The

main()

method in a Java class is invoked by the main thread.

 We can create a thread in Java in two ways:

o Using the

Thread

class

o Using the

Runnable

interface
 The

start()

method is used to initiate a new thread of execution.

 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()

method returns the currently executing thread's reference.

 The

getName()

method retrieves the name of the thread, while the

setName()

method assigns a new name to the thread.

Multithreading in Java | Part - 2

1. Synchronization in Java

Why Synchronization is Needed?


When multiple threads access a shared resource simultaneously, it can
lead to data inconsistency. Synchronization ensures that only one thread
accesses a shared resource at a time.

Types of Synchronization:

1. Synchronized Method:
Entire method is synchronized, so only one thread can execute it at
a time.

java

Copy code

public synchronized void display() {


// critical section

2. Synchronized Block:
Synchronizes a specific block of code, which is more efficient than
synchronizing the entire method.

java

Copy code

public void display() {

synchronized (this) {

// critical section

3. Static Synchronization:
Synchronizes a static method or block, locking on the class object.

java

Copy code

public static synchronized void display() {

// critical section

Example:

java

Copy code

class Counter {

private int count = 0;

public synchronized void increment() {

count++;

public int getCount() {


return count;

public class Main {

public static void main(String[] args) {

Counter counter = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

counter.increment();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

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

What is a Daemon Thread?


A daemon thread is a low-priority background thread that runs in the
background to perform tasks such as garbage collection. It does not
prevent the JVM from exiting when all user threads are complete.

How to Create a Daemon Thread?

 Use the setDaemon(true) method before starting the thread.

Example:

java

Copy code

public class Main {

public static void main(String[] args) {

Thread daemonThread = new Thread(() -> {

while (true) {

System.out.println("Daemon thread running...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

});

daemonThread.setDaemon(true); // Set the thread as a daemon

daemonThread.start();
System.out.println("Main thread finishing...");

3. Life Cycle of a Thread

States in Thread Life Cycle:

1. New: A thread object is created but not started.

java

Copy code

Thread t = new Thread();

2. Runnable: The thread is ready to run but waiting for CPU allocation.

java

Copy code

t.start();

3. Running: The thread is actively running.

4. Blocked/Waiting: The thread is waiting for a monitor lock or to be


notified.

5. Terminated: The thread finishes execution.

Example:

java

Copy code

class MyThread extends Thread {

public void run() {

System.out.println("Thread running...");

public class Main {


public static void main(String[] args) {

MyThread t = new MyThread(); // NEW state

t.start(); // Runnable state

// Thread moves to Running state when scheduled

Summary:

 Synchronization ensures data consistency.

 Daemon threads support background tasks.

 A thread transitions through various states during its lifecycle.

Let me know if you need further details or examples!

4o

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy