You are on page 1of 68

JAVA

JAVA: WHAT? WHY? WHEN? WHERE?


 What is Java ?
• Programming Language: Java is a high-level, general-purpose programming language.
• Platform: It provides a runtime environment (Java Virtual Machine - JVM) for executing Java bytecode.
• Ecosystem: Java has a rich ecosystem with libraries, frameworks (e.g., Spring, Hibernate), and tools.
 Why Java?
• Platform Independence : Java is designed to be platform-independent, allowing developers to write
code once and run it anywhere (WORA).
• Object-Oriented : Java is an object-oriented programming language, promoting modular and reusable
code structures.
• Robust and Secure : Java's strong memory management and built-in security features contribute to
robust and secure applications.
• Community Support:: Java has a large and active community, providing extensive libraries,
frameworks, and resources for developers.
WHEN TO USE JAVA?
• Enterprise Applications: Java is commonly used for developing large-scale enterprise applications.

• Web Development: Java is used for server-side development in web applications.

• Mobile Applications: Android applications are often developed using Java.

• Big Data: Java is used in big data processing frameworks like Apache Hadoop.

 Where is Java Used?


• Web Development: Java is widely used for server-side development in web applications.

• Mobile Development: Android applications are primarily written in Java.

• Enterprise Systems: Java is extensively used in building large-scale enterprise applications.

• Cloud Computing: Many cloud-based services and platforms use Java.


 Platform Independence:  Memory Management:
• Java is designed to be platform-independent, • Java has automatic memory management
allowing the same code to run on different through garbage collection, reducing the risk of
platforms. memory leaks and improving application
robustness.
• This is achieved through the use of the Java
Virtual Machine (JVM). TECHNOLOGIES
 Object-Oriented:  Security:
FROM OTHER
• Java emphasizes security features, such as the
• Java follows the principles of object-oriented sandboxing of applets and a security manager,
programming (OOP), emphasizing DIFFERENT making it suitable for building secure
encapsulation, inheritance, and polymorphism. applications.
HOW JAVA IS
 Strong Typing:  Portability:
• Java is a statically-typed language, meaning • Java's "write once, run anywhere" philosophy
variable types are explicitly declared at compile contributes to its portability across different
time. This helps catch type-related errors early operating systems and devices.
in the development process.
PHASES OF A JAVA PROGRAM
• Edit:
Write the Java source code using a text editor or an integrated development environment (IDE).

• Compile:
Use the javac compiler to convert the source code into bytecode.

• Load:
The class loader loads the bytecode into memory.

• Verify:
The bytecode verifier checks the code for integrity and security.

• Execute:
The Java Virtual Machine (JVM) executes the bytecode.

• Unload:
When the program finishes, the class unloader unloads the classes from memory.
MEMORY TYPES IN JAVA
 Class (Method) Area :
The class method area is the memory block that stores the class code, variable code(static variable, runtime constant), method code, and
the constructor of a Java program.

 Class
The Heap area is the memory block where objects are created or objects are stored.
Heap memory allocates memory for class interfaces and arrays

 Stack
Each thread has a private JVM stack, created at the same time as the thread.
It is used to store data and partial results which will be needed.
Each thread in a Java program has its own stack, which stores local variables and partial results.

 Method Area (Non-Heap):


Also known as the "PermGen" (Permanent Generation) in older Java versions, or "Metaspace" in Java 8 and later versions.
It stores class metadata, constant pool, and static variables.

 Heap:
The heap is the runtime data area where objects are allocated.
It is divided into two regions: the Young Generation and the Old Generation.
The Young Generation is further divided into three areas: Eden space, and two survivor spaces (S0 and S1).
Garbage collection primarily occurs in the Young Generation, where short-lived objects are collected.
JAVA PROGRAMMING ENVIRONMENT
1. How to Install & set Path.

2. A Simple Java Program.

3. Phases of Java Program.

4. Runtime Exception.

5. Name of a Java Source File.

6. Platform Independent.

7. Java Technology (JDK, JRE, JVM, JIT)


JDK JRE JVM JIT
• JDK (Java Development Kit) :
The JDK is a software development environment that provides the
necessary tools and libraries to develop and run Java applications.

• JRE (Java Runtime Environment) :


The JRE is an environment that allows you to run Java applications. It includes the JVM and other necessary libraries.

• JVM (Java Virtual Machine) :


The JVM is the runtime engine that executes Java bytecode. It provides platform independence and memory management.

• JIT (Just-In-Time Compilation)


JIT is a technique used by the JVM to improve performance by dynamically compiling Java bytecode into native machine code.
SYNTAX RULES
• Java follows a strict set of rules for constructing statements and expressions, including rules for naming conventions and semicolons.

 Data Types
Java supports primitive data types like integers, floating-point numbers, characters, and boolean values, along with non primitive data types like
Class, Interface,String, arrays and objects.

 Byte:
Size: 1byte (8bits)
Maxvalue: +127
Minvalue:-128

• Example:
byte b=10;
byte b2=130;//C.E:possible loss of precision
byte b=10.5;//C.E:possible loss of precision
CODING STANDARD
• Whenever we are writing any component the name of the component should reflect the purpose or functionality.
Like package, classname, methodname

 Coding standards for classes:


• Should starts with uppercase letter and if it contains multiple words every inner word should starts with upper case letter.

 Coding standards for interface :


• Should starts with upper case letter and if it contains multiple words every inner word should start with upper case letter.
Exa Serializable,Runnable ,Cloneable

 Coding standards for interface :


• Should starts with lowercase character and if it contains multiple words every inner word should starts with upper case letter.
 Coding standards for methods:
 Should starts with lowercase character and if it contains multiple words every inner word should starts with upper case letter.

 Exa; run() or getMethod()

 Coding standards for variables:


• Should starts with lowercase alphabet symbol and if it contains multiple words every inner word should starts with upper case character. Exa :
length, name, salary

 Coding standards for constants:


• Should contain only uppercase characters and if it contains multiple words then these words are separated with underscore symbol. Exa:
MAX_VALUE
CLASS AND OBJECT AND CONSTRCUTOR
 Class:
• A blueprint or template for creating objects.

• Defines attributes (fields) and behaviors (methods) of objects.

 Object:
• An instance of a class. Represents a real-world entity and has a state and behavior.

 Constructor:
• A special method that is called when an object is created.

• Initializes the object's state.

 Constructor overloading and use of this keyword

Types of Constructors:

• Default Constructor (No-argument)

• Parameterized Constructor
 Short:
The most rarely used data type in java is short.
Size: 2 bytes
Range: -32768 to 32767
Example :
short s=130;
short s=32768;//C.E:possible loss of precision
short s=true;//C.E:incompatible types

 Int:
This is most commonly used data type in java.
Size: 4 bytes
Range:-2147483648 to 2147483647
• Example:
int i=130;
int i=10.5;//C.E:possible loss of precision
int i=true;//C.E:incompatible types

 long:
Whenever int is not enough to hold big values then we should go for long data type.
Example:
To hold the no. Of characters present in a big file int may not enough hence the return type of length() method is long.
long l=f.length(); //f is a file
Size: 8 bytes
 Float
If we want to 5 to 6 decimal places of accuracy then we should go for float.
We can specify explicitly floating point literal as double type by suffixing with d or D.
Size:4 bytes. float follows single precision.
Example :float height = 167.7f (valid)
float f=123.456;//C.E:possible loss of precision(invalid)
double d=123.456;(valid)

 Double
If we want to 14 to 15 decimal places of accuracy then we should go for double.
Size:8 bytes. double follows double precision.
Example : double price = 987.90D / double price = 987.90d / double price = 987.90
 Char :
In java we are allowed to use any worldwide alphabets character and java is Unicode based to represent all these characters one byte is not
enough compulsory we should go for 2 bytes.
Size: 2 bytes
Range: 0 to 65535
Example:
char ch=97;(valid)
char ch2=65536;//C.E:possible loss of precision

 Boolean
Size: Not applicable (virtual machine dependent)
Range: Not applicable but allowed values are true or false.
Which of the following boolean declarations are valid?
Example 1:
boolean b=true;
boolean b=True;//C.E:cannot find symbol
boolean b="True";//C.E:incompatible types
boolean b=0;//C.E:incompatible types
LITERALS
• Integer Literals: 10, 0x1A, 077.

• Floating-Point Literals: 3.14, 2.0f, 1.0e10.

• Character Literals: 'A', '1'.

• String Literals: "Hello, World!".

• Boolean Literals: true, false.

• Null Literal: null.


VARIABLES & IT'S TYPES
1) Instance Variable(non- static variable)
If the value of a variable is varied from object to object such type of variables are called instance variables.
Instance variables will be created at the time of object creation and destroyed at the time of object destruction hence the scope of instance variables is exactly
same as scope of objects.
Instance variables should be declared with in the class directly but outside of any method or block or constructor.
Instance variables can be accessed directly from Instance area. But cannot be accessed directly from static area. But by using object reference we can access
instance variables from static area. Example

2) Static Variable (Global Variable)

static variables it is not required to perform initialization explicitly, JVM will always provide default values.

Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the
scope of the .class file.

Static variables will be stored in method area. Static variables should be declared with in the class directly but outside of any method or block or constructor.

Static variables can be accessed from both instance and static areas directly.

We can access static variables either by class name or by object reference but usage of class name is recommended.Example :
3) Local Variable

• Declare variables inside a method or block or constructors such type of variables.

• The local variables will be created as part of the block execution in which it is declared and destroyed once that block execution completes. The local
variables will be stored on the stack.

• scope of the local variables is exactly same as scope of the block in which we declared.

• Example :

4) final variable

5) transient variable

6) Reference Variable : Reference variables can be used to refer objects.


Example: Student s=new Student()
NAMING CONVENTION OF JAVA LANGUAGE
Classes: CamelCase (e.g., MyClass).

Methods: CamelCase (e.g., myMethod()).

Variables: CamelCase (e.g., myVariable).

Constants: UPPERCASE_WITH_UNDERSCORES (e.g., MAX_VALUE).

Packages: Lowercase (e.g., com.example.package)


ACCESS MODIFIER- PUBLIC,PRIVATE,DEFAULT PROTECTED
• When we apply With variable

• When we apply With method

• When we apply With constructor

• When we apply With class

 Final Modifier:
• Final is the modifier applicable for classes, methods and variables.

• Final Methods:
Whatever the methods parent has by default available to the child.
If the child is not allowed to override any method, that method we have to declare with final in parent class. That is final methods cannot
overridden.

• The main advantage of final keyword is we can achieve security. Whereas the main disadvantage is we are missing the key benefits of oops

 Abstract Modifier: applied on class and method


IMPORT AND PACKAGE
• Implicit - Implicit means that its done by the complier

• It is never recommended to use because it reduces readability of the code. ( import java.util.*; )

• Explicit - Explicit means something is done by the programmer

• This type of import is highly recommended to use because it improves readability of the code. Import java.util.arraylist;

• Package structure

• com.icicibank.loan.houseingloadn.Account

• com.healthcare.doctor.doctorappointment

• Rule of the package - package name start with lowercase (pack com.class)
MAIN METHOD IN JAVA
Whether the class contains main() method or not and whether it is
properly declared or
not these checking’s are not responsibilities of the compiler, at
runtime JVM is
responsible for this. If jvm unable to find the required main()
method then we will get
runtime exception saying NoSuchMethodError: main.
ARRAY
• An array is a collection of elements of the same type stored in contiguous memory locations.

• Arrays may be stored in contiguous memory.

• The variables in the array are ordered, and each has an index beginning with 0.

Syntax : datatype_name[] arr_name = new datatype_name[size];

• Int[] arr; //declare an Array of integers.

• Arr = new int[5]; //allocating memory for 5 integers.also int[] myNum = {10, 20, 30, 40};

• int[] a;//valid

• int[5] a;//invalid

• Arr[0] =10 ; // initialize the first elements of the array.

• Length of an Array: int length = numbers.length;


RULES IN ARRAY
At the time of array creation compulsory we should specify the size otherwise we will get compile time error.

It is legal to have an array with size zero in java.

If we are taking array size with -ve int value then we will get runtime exception saying NegativeArraySizeException.

The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any other type we will get compile time error.

The maximum allowed array size in java is maximum value of int size [2147483647].

Example:
int[] a1=new int[2147483647];(valid)
int[] a2=new int[2147483648];//C.E:integer number too large: 2147483648(invalid)
INTERFACE
 Introduction

• If we don’t’ know anything about implementation just we have requirement specification then we should go for interface.Every method present
inside interface
is always public and abstract whether we are declaring or not.We can’t declare interface methods with the modifiers private, protected, final,
static, synchronized, native, strictfp.Every interface variable is always
public static final whether we are declaring or not.Inside interface we can’t take constructor.

• Interface declarations and implementations.


Extends vs implements
Interface methods
Interface variables
Interface naming conflicts
Method naming conflicts, Marker interface
• Any service requirement specification (srs) is called an interface.

• Example1: Sun people responsible to define JDBC API and database vendor will provide implementation for that.

• ATM GUI screen describes the set of services what bank people offering, at the same time the same GUI screen the set of
services what customer his excepting hence this GUI screen acts as a contract between bank and customer.

• Def3: Inside interface every method is always abstract whether we are declaring or not hence interface is considered as
100% pure abstract class.

• Any service requirement specification (SRS) or any contract between client and
service provider or 100% pure abstract classes is considered as an interface.
TYPE CASTING
 Auto up casting ( implicit casting) - compiler (JVM) converts

Example : Byte to int

 Down casting ( explicit casting ) - programmer is responsible

Example : Long to int(long)

Float to int
OPERATORS IN JAVA
 Arithmetic Operators:
• + (Addition)

• - (Subtraction)

• * (Multiplication)

• / (Division)

• % (Modulus)

• int a = 10, b = 3;
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
System.out.println("Remainder: " + (a % b));
 Comparison Operators:
• == (Equal to)

• != (Not equal to)

• < (Less than)

• > (Greater than)

• <= (Less than or equal to)

• >= (Greater than or equal to)

• int x = 5, y = 10;

System.out.println(x == y); // false


System.out.println(x != y); // true
System.out.println(x < y); // true
System.out.println(x > y); // false
System.out.println(x <= y); // true
System.out.println(x >= y); // false
 Logical Operators:
• && (Logical AND)

• || (Logical OR)

• ! (Logical NOT)

• boolean isJavaFun = true;


boolean isJavaHard = false;

System.out.println(isJavaFun && isJavaHard); // false


System.out.println(isJavaFun || isJavaHard); // true
System.out.println(!isJavaFun); // false
 Assignment Operators:
• = (Assignment)

• += (Addition assignment)

• -= (Subtraction assignment)

• *= (Multiplication assignment)

• /= (Division assignment)

• %= (Modulus assignment)

• int num = 5;
num += 3; // num = num + 3;
System.out.println(num); // 8
 Increment and Decrement Operators:
• ++ (Increment)

• -- (Decrement)

• int counter = 10;


counter++; // Increment by 1
System.out.println(counter); // 11

counter--; // Decrement by 1
System.out.println(counter); // 10

 Conditional (Ternary) Operator:


• ? : (Conditional)
int number = 7;

• String result = (number % 2 == 0) ? "Even" : "Odd";

• System.out.println(result); // Odd
FLOW CONTROL IN THE JAVA

 1 selection statement - if else , switch

 2 iterative statement - while loop, do, for loop, for each

 3 transfer statement - break, continue, return, try - catch - finally.


1 SELECTION STATEMENT -
 if else

if-else statement is used for decision-making. It executes a block of code if a specified condition is true, and another block if the condition is false.

Example :

int num = 10;

if (num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
1 SELECTION STATEMENT -
 switch

The switch statement is used for multiple branching based on the value of an expression..

Example :

int dayOfWeek = 3;
String dayName;

switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
// ... other cases
default:
dayName = "Invalid day";
}
System.out.println("Day: " + dayName);
2 ITERATIVE STATEMENT
 while loop

The while loop repeatedly executes a block of code as long as a specified condition is true.

Example :

int i = 0;
while (i < 5) {
System.out.println("Value of i: " + i);
i++;
}

 do-while loop

Similar to while loop, but it ensures that the block of code is executed at least once before checking the condition.

int j = 0;
do {
System.out.println("Value of j: " + j);
j++;
} while (j < 5);
2 ITERATIVE STATEMENT
 For loop

The for loop provides a concise way to iterate over a range of values.

for (int k = 0; k < 5; k++) {


System.out.println("Value of k: " + k);
}

 for-each loop:

Introduced in Java 5, it simplifies the process of iterating over arrays or collections.

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


for (int num : numbers) {
System.out.println("Value: " + num);
}
3 TRANSFER STATEMENT
 Break statement
• Used to terminate the loop or switch statement it is in.

• for (int m = 0; m < 10; m++) {


if (m == 5) {
break; // exits the loop when m is 5
}
System.out.println("Value of m: " + m);
}
3 TRANSFER STATEMENT
 continue statement
• Skips the rest of the code inside a loop and proceeds with the next iteration.

• for (int n = 0; n < 5; n++) {


if (n == 2) {
continue; // skips the iteration when n is 2
}
System.out.println("Value of n: " + n);
}

 return statement
• Exits the current method and returns a value to the calling code.

• public int add(int a, int b) {


return a + b;
}
EXCEPTION HANDLING
• An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.Exception is an abnormal condition

• Exception handling in Java is a mechanism that allows developers to deal with runtime errors or exceptional situations in a structured and controlled way.

• Java has a comprehensive exception-handling mechanism based on the concepts of try, catch, and finally blocks.

 a. Checked Exceptions:
• Checked exceptions are exceptions that are checked at compile-time.

• The programmer is required to either handle them using try-catch blocks or declare that the method throws the exception using the throws clause.
• Example :

• import java.io.FileReader;
import java.io.IOException;

public class CheckedExample {


public static void main(String[] args) {
try {
// Code that might throw a checked exception
FileReader fileReader = new FileReader("example.txt");
// Additional code...
} catch (IOException e) {
// Handling the checked exception
e.printStackTrace();
}
}
}
 b. Unchecked Exceptions (Runtime Exceptions):
• Unchecked exceptions are not checked at compile-time.

• They are subclasses of RuntimeException and typically represent programming errors or conditions that are beyond the programmer's control.

 public class UncheckedExample {


public static void main(String[] args) {
// Code that might throw an unchecked exception
int result = 10 / 0; // ArithmeticException (division by zero)
// Additional code...
}}

 c. Error:
• Errors are exceptional situations that are typically beyond the control of the programmer.

• Unlike exceptions, errors are not meant to be caught or handled by the program, and they usually indicate serious issues

• public class ErrorExample {


public static void main(String[] args) {
// Code that might cause an error
int[] array = new int[Integer.MAX_VALUE]; // OutOfMemoryError
// Additional code...
}
}
.
2. TRY, CATCH, AND FINALLY BLOCKS:
 a. Try Block:
• The try block encloses the code that might throw an exception.

• It is followed by one or more catch blocks to handle specific exceptions.

 b. Catch Block:
• A catch block handles a specific type of exception.

• Multiple catch blocks can be used to handle different types of exceptions.

 c. Finally Block:
• The finally block contains code that is always executed, whether an exception occurs or not.

• It is optional but is often used for cleanup operations.


• import java.io.FileReader;
import java.io.IOException;

public class TryCatchFinallyExample {


public static void main(String[] args) {
FileReader fileReader = null;
try {
// Code that might throw a checked exception
fileReader = new FileReader("example.txt");
// Additional code...
} catch (IOException e) {
// Handling the checked exception
e.printStackTrace();
} finally {
// Cleanup code or code that must be executed regardless of exceptions
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
e.printStackTrace();
} } } }
4. CUSTOM EXCEPTIONS:
• Developers can create their own exception classes by extending the Exception class or its subclasses.

• Custom exceptions allow for more specific and meaningful error handling.

• class MyCustomException extends Exception {


public MyCustomException(String message) {
super(message);
}
}

public class CustomExceptionExample {


public static void main(String[] args) {
try {
// Code that might throw a custom exception
throw new MyCustomException("This is a custom exception");
} catch (MyCustomException e) {
// Handling the custom exception
System.out.println("Custom Exception: " + e.getMessage());
}
}
}
THROW AND THROWS
• The throw keyword is used to explicitly throw an exception in a program. It is used to signal that an exceptional situation has occurred, and the
program should take appropriate action.

• Used inside a method or a block to explicitly throw an exception.

• Typically used when a specific condition is met and an exceptional situation needs to be signaled.

• The throw statement is followed by an instance of an exception or a subclass of Throwable.

• public static void validateAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older.");
} else {
System.out.println("Age is valid.");
}
}
THROWS

• The throws keyword is used in a method signature to indicate that the method might throw certain types of exceptions.

• It is part of the method declaration and is followed by a list of exception classes.

• Used in the method signature to declare the types of exceptions that might be thrown by the method.

• Indicates that the method does not handle the exceptions itself but expects the calling code to handle them.

• import java.io.FileNotFoundException;

public class ThrowsExample {


public static void main(String[] args) {
try {
readFile("example.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
}

// Method that declares it might throw a checked exception


public static void readFile(String filename) throws FileNotFoundException {
// Code that might throw a FileNotFoundException
// ...
}
}
Checked Exceptions Unchecked exceptions

• Checked exceptions are Checked at Compile Time. • Checked exceptions are not Checked at Compile Time.

• • ArithmeticException, NullPointerException,
IOException ,SQLException FileNotFoundException
ArrayIndexOutOfBoundsException
OOPS
• Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes for organizing code.
• Java is an object-oriented programming language, an OOP principles play a fundamental role in Java development.

 Class
• A class is a blueprint or template that defines the structure and behavior of objects.
It encapsulates data (attributes) and methods (functions) that operate on the data.

 object
An object is an instance of a class, representing a real-world entity.
Objects have state (attributes) and behavior (methods).

Abstraction
Abstraction is the process of simplifying complex systems by modeling classes based on their essential properties and behaviors.
It hides the implementation details and exposes only relevant features.
Abstract classes and interfaces are used to achieve abstraction.

Abstract Class: Shape with abstract methods like draw() and calculateArea() .
• ENCAPSULATION
Encapsulation is the bundling of data (attributes) and methods that operate on the data within a single unit (class).
It restricts direct access to some of an object's components and can prevent unintended interference.

Encapsulation: Private attributes like accountNumber and public methods like deposit() and withdraw() .
• // Class representing a Bank Account
class BankAccount {
private String accountNumber;
private double balance;

// Constructor
public BankAccount(String accountNumber) {
this.accountNumber = accountNumber;
this.balance = 0.0;
}

// Getter and Setter methods


public String getAccountNumber() {
return accountNumber;
}

public double getBalance() {


return balance;
}

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposit successful. New balance: " + balance);
} else {
System.out.println( "
INHERITANCE
• Inheritance is a mechanism that allows a new class (subclass or derived class) to inherit properties and behavior from an existing class (superclass or
base class).
It promotes code reuse, extensibility, and the creation of a hierarchy of classes.
Superclass: Vehicle
Subclass: Car (inherits from Vehicle)

• We will see this() and super()

POLYMORPHISM
• Polymorphism allows objects to be treated as instances of their parent class rather than their actual class.
It enables methods to be invoked on objects of different types, leading to flexibility and extensibility.

• Two types of polymorphism:

• compile-time (method overloading) and runtime (method overriding).

 Compile-time Polymorphism:

• Method Overloading in a class, e.g., calculateArea(int side) and calculateArea(int length, int width).

 Runtime Polymorphism:
Method Overriding in a subclass, e.g., draw() in Shape overridden in Circle and Square.
MULTITHREADING
• a thread is the smallest unit of execution.

• It represents an independent path of execution within a program.

• Java provides built-in support for multithreading, allowing you to create and manage multiple threads within a single program.

• This allows for concurrent execution of tasks, which can improve program efficiency by utilizing the available CPU resources more effectively.

• creation of thread in java


Threads in Java can be created by extending the Thread class or implementing the Runnable interface.
Extending the Thread class involves creating a new class that inherits from Thread and overriding the run() method.
Implementing the Runnable interface requires creating a class with a run() method and then passing an instance of that class to the Thread
constructor .
THREAD LIFE CYCLE
• New:A thread is in this state when it is created, but the start() method has not been called yet.

• Runnable:The thread is ready to run and is waiting for CPU time.

• Blocked:The thread is blocked, waiting for a monitor lock. This occurs when a thread attempts to access an object that another thread has
locked.

• Waiting:The thread is waiting indefinitely for another thread to perform a particular action. It enters this state when using methods like wait() or
join().

• Timed Waiting:Similar to the waiting state, but the thread can wait for a specified period. Methods like sleep() or wait(timeout) put a thread in
this state.

• Terminated:The thread has exited, either by completing its execution or by throwing an uncaught exception.
MULTITHREADING
• Multithreading allows multiple threads to execute concurrently.
Each thread runs independently, and the operating system manages their execution.
Multithreading is beneficial for tasks that can be performed concurrently, improving program responsiveness and efficiency.

class MyThread extends Thread {


public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value " + i);
}
}
}
USE OF MULTITHREADING
 Web Server:

In a Spring Boot web application, the web server handles multiple incoming requests simultaneously. Each incoming request is typically
processed in a separate thread, allowing the server to handle multiple clients concurrently without blocking.

 Parallel Processing:

Imagine a Spring Boot application that needs to perform a complex computation or data processing task. By dividing the task into smaller units
and processing them concurrently using threads, the application can achieve parallel processing, improving performance.

 Background Tasks:

Spring Boot applications often have tasks that run in the background, such as sending emails, updating caches, or performing periodic cleanup.
Using threads, you can run these tasks concurrently without affecting the main application flow.

 File Upload/Download:

When handling file uploads or downloads, multithreading can be beneficial. For instance, in a Spring Boot application serving file downloads,
each download request can be processed in a separate thread, allowing multiple users to download files concurrently.
 Asynchronous Processing:
Spring Boot supports asynchronous processing, where tasks can be executed asynchronously using threads. This is commonly used in scenarios
like handling long-running operations, such as making external API calls or processing large data sets, without blocking the main application
thread.

 Database Operations:
In a Spring Boot application interacting with a database, multithreading can be employed to handle concurrent database operations. For example,
multiple database queries or updates can be executed simultaneously, improving overall database access performance.

 Microservices Communication:
In a microservices architecture implemented with Spring Boot, individual microservices may communicate with each other. Multithreading can be
used to handle parallel communication with multiple microservices, improving the responsiveness of the overall system.

 Web Scraping or API Integration:


When integrating with external APIs or performing web scraping, multithreading can be used to fetch data from multiple sources concurrently.
This can significantly reduce the time required to gather information from various endpoints.
STRING CONCEPTS
• string is basically an object that represents sequence of char values.

 Immutable string

• string references are used to store various attributes like username, password, etc.

• In Java, String objects are immutable. Immutable simply means unmodifiable or unchangeable.

• String object is created its data or state can't be changed but a new String object is created.
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
} }
JAVA STRING COMPARE
 By Using equals() Method

 By Using == Operator

 By compareTo() Method
STRING METHODS
1. CharAt()
2. CompareT0()
3. Concat()
4. EndsWith()
5. Equals()
6. EqualsgnoreCase()
7. IndexOf()
8. IsEmpty()
9. LastIndexOf()
10. Length()
11. Replace()
12. ReplaceAll()
13. Split()
14. StartsWith()
15. ToCharArray
16. ToLowerCase()
17. ToUpperCase()
18. Trim()
19. valueOf()
OBJECT CLASS
• Object class is an parent class of all class.

 equals(Object obj):
• Indicates whether some other object is "equal to" this one.

• By default, it checks for reference equality.

 hashCode():
• Returns a hash code value for the object.

• Used for hash-based data structures like HashMap.

 toString():

• Returns a string representation of the object.

• By default, it returns a string consisting of the class name followed by "@" and the object's hashcode.
 getClass():
• Returns the runtime class of an object.

• Useful for obtaining information about the class.

 clone():
• Creates and returns a copy of this object.

• The class must implement the Cloneable interface.

 finalize():
• Called by the garbage collector before the object is reclaimed.

• Deprecated in recent Java versions. Use try-with-resources or AutoCloseable instead.

 notify(), notifyAll(), wait():


• Used for inter-thread communication and synchronization.
GENERICS
• Generics in Java provide a way to create classes, interfaces, and methods with parameters that can work with any data type.

• They allow you to write code that is more flexible, reusable, and type-safe. Here's an example to illustrate the use of generics
EXAMPLE
• // Generic class with a type parameter T
class Box<T> {
private T value;

// Constructor
public Box(T value) {
this.value = value;
}

// Getter and Setter


public T getValue() {
return value;
}

public void setValue(T value) {


this.value = value;
}
}

public class Main {


public static void main(String[] args) {
// Creating a Box for Integer
Box<Integer> intBox = new Box<>(42);
System.out.println("Integer Value: " + intBox.getValue());

// Creating a Box for String


Box<String> strBox = new Box<>("Hello, Generics!");
System.out.println("String Value: " + strBox.getValue());
}
}
GARBAGE COLLECTIONS
• Automatic Memory Management:
Java's garbage collector automatically manages the memory allocated for objects.
Developers do not need to explicitly free up memory as the JVM takes care of deallocating memory for unreachable objects.

• Object Reachability:
Garbage collection identifies objects that are no longer reachable or referenced by any part of the program.
Reachable objects are those that can be accessed directly or indirectly from the application's roots (e.g., local variables, static variables, method
parameters).

• Mark and Sweep Algorithm:


A common garbage collection algorithm is the "Mark and Sweep" algorithm.
It involves two phases: marking reachable objects and sweeping away unreferenced objects .
• public class GarbageCollectionExample {
public static void main(String[] args) {
// Creating two objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();

// Nullifying the reference to obj1


obj1 = null;

// At this point, obj1 is unreachable and can be garbage collected


// obj2 is still reachable, and its memory is not eligible for collection

// Explicitly requesting garbage collection (Note: This is just for demonstration)


System.gc();
}
}

class MyClass {
// Class definition
}

You might also like