You are on page 1of 35

*introduction to java:

->Java has been one of the most popular programming languages for many years.

->Java is Object Oriented. However, it is not considered as pure object-oriented as it provides


support for primitive data types (like int, char, etc)

->The Java codes are first compiled into byte code (machine-independent code). Then the byte code
runs on Java Virtual Machine (JVM) regardless of the underlying architecture.

->Java syntax is similar to C/C++. But Java does not provide low-level programming functionalities
like pointers. Also, Java codes are always written in the form of classes and objects.

->Java is used in all kinds of applications like Mobile Applications (Android is Java-based), desktop
applications, web applications, client-server applications, enterprise applications, and many more.

->When compared with C++, Java codes are generally more maintainable because Java does not
allow many things which may lead to bad/inefficient programming if used incorrectly. For example,
non-primitives are always references in Java. So we cannot pass large objects (like we can do in C++)
to functions, we always pass references in Java. One more example, since there are no pointers, bad
memory access is also not possible.

->When compared with Python, Java kind of fits between C++ and Python. The programs are written
in Java typically run faster than corresponding Python programs and slower than C++. Like C++, Java
does static type checking, but Python does not.

Example:

public class GFG {

public static void main(String args[])

System.out.println("Hello World");

* Java programming language is named JAVA. Why?


->After the name OAK, the team decided to give a new name to it and the suggested words were
Silk, Jolt, revolutionary, DNA, dynamic, etc.
->These all names were easy to spell and fun to say, but they all wanted the name to reflect the
essence of technology. In accordance with James Gosling, Java the among the top names along with
Silk, and since java was a unique name so most of them preferred it.

->Java is the name of an island in Indonesia where the first coffee(named java coffee) was produced.
And this name was chosen by James Gosling while having coffee near his office. Note that Java is just
a name, not an acronym.

* Java Terminology
Before learning Java, one must be familiar with these common terms of Java.

1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution
phases of a program. They are written, compile and run the program.

Writing a program is done by a java programmer like you and me.

The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes the Java program as input and generates bytecode as output.

In the Running phase of a program, JVM executes the bytecode generated by the compiler.

Now, we understood that the function of Java Virtual Machine is to execute the bytecode produced
by the compiler. Every Operating System has a different JVM but the output they produce after the
execution of bytecode is the same across all the operating systems. This is why Java is known as a
platform-independent language.

2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the java
source code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler.
To view the bytecode, a disassembler like javap can be used.

3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode
and JVM. So, as the name suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program
to execute in java, we need to install JDK on our computer in order to create, compile and run the
java program.

4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the
java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet supports,
and plugins. For running the java program, a computer needs JRE.

5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that
memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the objects
that are not referenced. So Java makes the life of a programmer easy by handling memory
management. However, programmers should be careful about their code whether they are using
objects that have been used for a long time. Because Garbage cannot recover the memory of objects
being referenced.

6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class
files to load. By default, JDK provides many libraries. If you want to include external libraries they
should be added to the classpa

Primary/Main Features of Java


1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes
the bytecode generated by the compiler. This bytecode can run on any platform be it Windows,
Linux, or macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa. Each operating system has a different JVM, but the output produced by all the OS is the
same after the execution of bytecode. That is why we call java a platform-independent language.

2. Object-Oriented Programming Language: Organizing the program in the terms of collection of


objects is a way of object-oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:

Abstraction

Encapsulation

Inheritance

Polymorphism

3. Simple: Java is one of the simple languages as it does not have complex features like pointers,
operator overloading, multiple inheritances, and Explicit memory allocation.

4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a
lot of effort into checking errors as early as possible, that is why the java compiler is able to detect
even those errors that are not easy to detect by another programming language. The main features
of java that make it robust are garbage collection, Exception Handling, and memory allocation.

5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack
corruption or buffer overflow are impossible to exploit in Java. Also java programs run in an
environment that is independent of the os(operating system) environment which makes java
programs more secure .

6. Distributed: We can create distributed applications using the java programming language.
Remote Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are connected to
each other through an internet connection.

7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilization of the CPU.

8. Portable: As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform-independent bytecode can be taken to
any platform for execution makes java portable.

9. High Performance: Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code
on-demand basics where it only compiles those methods that are called making applications to
execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes,
new methods to existing classes and even create new classes through sub-classes. Java even
supports functions written in other languages such as C, C++ which are referred to as native
methods.

11. Sandbox Execution: Java programs run in a separate space that allows user to execute their
applications without affecting the underlying system with help of a bytecode verifier. Bytecode
verifier also provides additional security as its role is to check the code for any violation of access.

12. Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file which
corresponds to our applications(program) but contains code in binary format. It provides ease t
architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the
primary reason java is used in the enterprising IT industry globally worldwide.

13. Power of compilation and interpretation: Most languages are designed with purpose either they
are compiled language or they are interpreted language. But java integrates arising enormous power
as Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine
OS-dependent executable code.

Example

2. import java.io.*: This means all the classes of io package can be imported. Java io package
provides a set of input and output streams for reading and writing data to files or other input or
output sources.

3. class: The class contains the data and methods to be used in the program. Methods define the
behavior of the class. Class GFG has only one method Main in JAVA.

4. static void main(): static keyword tells us that this method is accessible without instantiating the
class.
5. void: keywords tell that this method will not return anything. The main() method is the entry
point of our application.

6. System.in: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.

7. System.out: This is the standard output stream that is used to produce the result of a program on
an output device like the computer screen.

8. println(): This method in Java is also used to display text on the console. It prints the text on the
console and the cursor moves to the start of the next line at the console. The next printing takes
place from the next line.

9. String []args: This is the argument passed to the main function which is an array of strings with
the array name args. One can choose their own flexible name but this name is used by many
developers.

*Advantages of Java:
1) Platform independent: Java code can run on any platform that has a Java Virtual Machine (JVM)
installed, which means that applications can be written once and run on any device.

2) Object-Oriented: Java is an object-oriented programming language, which means that it follows


the principles of encapsulation, inheritance, and polymorphism.

3) Security: Java has built-in security features that make it a secure platform for developing
applications, such as automatic memory management and type checking.

4) Large community: Java has a large and active community of developers, which means that there is
a lot of support available for learning and using the language.

5) Enterprise-level applications: Java is widely used for developing enterprise-level applications, such
as web applications, e-commerce systems, and database systems.
*Disadvantages of Java:
1)Performance: Java can be slower compared to other programming languages, such as C++, due to
its use of a virtual machine and automatic memory management.

2) Memory management: Java’s automatic memory management can lead to slower performance
and increased memory usage, which can be a drawback for some applications.

Features C++ Java

Abstraction Yes Yes

Encapsulation Yes Yes

Single Inheritance Yes Yes

Multiple Inheritance Yes No

Polymorphism Yes Yes

Static Binding Yes Yes

Dynamic Binding Yes Yes

Operator Overloading Yes No

Header Files Yes No

Pointers Yes No

Global Variables Yes No

Template Class Yes No

Interference and Packages No Yes

API No Yes
#include <iostream>

using namespace std;

int main() {

cout << "GFG!";

return 0;

import java.io.*;

class GFG {

public static void main (String[] args) {

System.out.println("GFG!");

* feature of java:

Simple

Object-Oriented

Portable

Platform independent

Secured

Robust
Architecture neutral

Interpreted

High Performance

Multithreaded

Distributed

Dynamic

* c++ vs java:

*Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

-->class keyword is used to declare a class in Java.

-->public keyword is an access modifier that represents visibility. It means it is visible to all.

-->static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method.

-->The main() method is executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.

-->void is the return type of the method. It means it doesn't return any value.

-->main represents the starting point of the program.

-->String[] args or String args[] is used for command line argument. We will discuss it in coming
section.

-->System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class. We will discuss the internal working
of System.out.println() statement in the coming section.
*At compile time, the Java file is compiled by Java Compiler (It does not interact with OS) and
converts the Java code into bytecode.

* java variable:

-->A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

1) local

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable
exists.

A local variable cannot be defined with "static" keyword.

2)instance

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among
instances.

3)static
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the memory.

example:

public class A

static int m=100;//static variable

void method()

int n=90;//local variable

public static void main(String args[])

int data=50;//instance variable

* data type:
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
*operator:

->Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

Unary Operator,

Arithmetic Operator,

Shift Operator,

Relational Operator,

Bitwise Operator,

Logical Operator,

Ternary Operator and

Assignment Operator.

1)Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

-incrementing/decrementing a value by one

-negating an expression

-inverting the value of a boolean

2)Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
* java keywords:
-->Java keywords are also known as reserved words. Keywords are particular words that act as a key
to a code. These are predefined words by Java so they cannot be used as a variable or object name
or class name.

1)abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide
the implementation of the interface. It can have abstract and non-abstract methods.

2)boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True
and False values only.

3) break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.

4)extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.

5)final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.

6)implements: Java implements keyword is used to implement an interface.

7)throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.

* java control statements:


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used to
control the flow of Java code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.

1)Decision Making statements

if statements

switch statement

2)Loop statements

do while loop

while loop

for loop

for-each loop

3)Jump statements

break statement

continue statement

*Object
Java Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or
code. The only necessary thing is the type of message accepted and the type of response returned
by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors
like wagging the tail, barking, eating, etc.
*Class
Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

*Polymorphism in Java
Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

*Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we
don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

*Encapsulation in Java OOPs Concepts


Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
*method
A method is a block of code or collection of statements or a set of code grouped together to perform
a certain task or operation. It is used to achieve the reusability of code. We write a method once and
use it many times. We do not require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code. The method is
executed only when we call or invoke it.

The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: When we use a private access specifier, the method is accessible only in the classes in which
it is defined.

Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.

Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

-->Types of Method

There are two types of methods in Java:

Predefined Method

User-defined Method

* constructor
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

There are two rules defined for the constructor.

Constructor name must be the same as its class name

A Constructor must have no explicit return type

A Java constructor cannot be abstract, static, final, and synchronized

* static keyword
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.

The static can be:

Variable (also known as a class variable)

Method (also known as a class method)

Block

Nested class

1)Java static variable

If you declare any variable as static, it is known as a static variable.


The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.

The static variable gets memory only once in the class area at the time of class loading.

2)Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than the object of a class.

A static method can be invoked without the need for creating an instance of a class.

A static method can access static data member and can change the value of it.

* this keyword:
In Java, this is a reference variable that refers to the current object.

Here is given the 6 usage of java this keyword.

this can be used to refer current class instance variable.

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

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

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

this can be passed as argument in the constructor call.

this can be used to return the current class instance from the method.

*super keyword:
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by 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 immediate parent class method.

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

*final keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

variable

method

class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will have
detailed learning of these. Let's first learn the basics of final keyword.

* inheritance:

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

*Why use inheritance in java

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.

The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

* aggregation
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It
contains one more object named address, which contains its own informations such as city, state,
country, zipcode etc. as given below.

class Employee{

int id;

String name;

Address address;//Address is a class

...

}
*polymorphism:
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

* method overloading:

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

There are two ways to overload the method in java

By changing number of arguments

By changing the data type

* method overriding:

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.

Method overriding is used for runtime polymorphism

class Vehicle{

//defining a method

void run(){System.out.println("Vehicle is running");}

//Creating a child class

class Bike2 extends Vehicle{


//defining the same method as in the parent class

void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){

Bike2 obj = new Bike2();//creating object

obj.run();//calling method

*abstract clasS:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

Abstraction is a process of hiding the implementation details and showing only functionality to the
user.

There are two ways to achieve abstraction in java

Abstract class (0 to 100%)

Interface

1)

An abstract class must be declared with an abstract keyword.

It can have abstract and non-abstract methods.

It cannot be instantiated.

It can have constructors and static methods also.

It can have final methods which will force the subclass not to change the body of the method.
*interface:
n interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have
a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in
the interface.

*package:
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
-->advantage:

Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

There are three ways to access the package from outside the package.

import package.*;

import package.classname;

fully qualified name.

*access modifier:
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.

Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.

Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
*encapsulation:
Encapsulation in Java is a process of wrapping code and data together into a single unit, for example,
a capsule which is mixed of several medicines.

encapsulation in java

We can create a fully encapsulated class in Java by making all the data members of the class private.
Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.

*Array:
Java array is an object which contains elements of a similar data type. Additionally, The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array

*wrapper class:
The wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive.
*String:
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.

There are two ways to create String object:

By string literal

String s="welcome";

By new keyword

String s=new String("Welcome");

*exception handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

Checked Exception
Unchecked Exception

Error

Java provides five keywords that are used to handle the exception.

try

catch

finally

throws

*thread:
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of
execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It
uses a shared memory area.

Java provides Thread class to achieve thread programming. Thread class provides constructors and
methods to create and perform operations on a thread. Thread class extends Object class and
implements Runnable interface.

*lifecycle:

In Java, a thread always exists in any one of the following states. These states are:

New-Whenever a new thread is created, it is always in the new state

Active-When a thread invokes the start() method, it moves from the new state to the active state.
The active state contains two states within it: one is runnable, and the other is running.

Blocked / Waiting-Whenever a thread is inactive for a span of time (not permanently) then, either
the thread is in the blocked state or is in the waiting state.

Timed Waiting-

Terminated-A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.

Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.

*creating a thread:

There are two ways to create a thread:

By extending Thread class

By implementing Runnable interface.

Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

Thread()

Thread(String name)

Thread(Runnable r)

Thread(Runnable r,String name)

Commonly used methods of Thread class:

public void run(): is used to perform action for a thread.

public void start(): starts the execution of the thread.JVM calls the run() method on the thread

public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.

public void join(): waits for a thread to die.

*multithreading:
Multithreading in Java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

-->Advantage:

-doesn't block the user

-can perform many operations together, so it saves time.

-independent

*deamon thread:
Daemon thread in Java is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides
information about the loaded classes, memory usage, running threads etc.

1) public void setDaemon(boolean status) is used to mark the current thread as daemon
thread or user thread.

2) public boolean isDaemon() is used to check that current is daemon.


Java Garbage Collection
In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.

It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.

*synchronization:
Synchronization in Java

Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the shared
resource.

Why use Synchronization?

The synchronization is mainly used to


To prevent thread interference.

To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

Process Synchronization

Thread Synchronization

class Table{

synchronized void printTable(int n){//synchronized method

for(int i=1;i<=5;i++){

System.out.println(n*i);

try{

Thread.sleep(400);

}catch(Exception e){System.out.println(e);}

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose we have 50 lines of code in our method, but we want to synchronize only 5 lines, in such
cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

synchronized (object reference expression) {

//code block

}
*deadlock:
Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for an
object lock that is acquired by first thread. Since, both threads are waiting for each other to release
the lock, the condition is called deadlock.

How to Avoid Deadlock in Java?

Deadlocks cannot be completely resolved. But we can avoid them by following basic rules mentioned
below:

Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason for a
deadlock condition. It normally happens when you give locks to multiple threads.

Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks to the
unnecessary threads that cause the deadlock condition.

Using Thread Join: A deadlock usually happens when one thread is waiting for the other to finish. In
this case, we can use join with a maximum time that a thread will take.

*collection:
The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces
(Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

ArrayList

The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed.

LinkedList

LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.

Deque Interface

Deque interface extends the Queue interface. In Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended queue which enables us to perform the operations
at both the ends.

HashSet

HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet.
*jdbc:
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to
connect with the database. There are four types of JDBC drivers:

JDBC-ODBC Bridge Driver,

Native Driver,

Network Protocol Driver, and

Thin Driver

The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC
API are given below:

Driver interface

Connection interface

Statement interface

PreparedStatement interface

CallableStatement interface

ResultSet interface

ResultSetMetaData interface

DatabaseMetaData interface

RowSet interface

We can use JDBC API to handle database using Java program and can perform the following
activities:

Connect to the database

Execute queries and update statements to the database

Retrieve the result received from the database.

You might also like