0% found this document useful (0 votes)
22 views78 pages

Java Programming Concepts Explained

The document provides an overview of Java programming, highlighting its platform independence, object-oriented features, and various data types. It explains the execution flow of Java programs, the significance of the main method, and the concept of type casting, along with details on methods, arrays, strings, and method overloading. Additionally, it discusses the Java Runtime Environment (JRE) and the differences between primitive and wrapper classes.

Uploaded by

Cmv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views78 pages

Java Programming Concepts Explained

The document provides an overview of Java programming, highlighting its platform independence, object-oriented features, and various data types. It explains the execution flow of Java programs, the significance of the main method, and the concept of type casting, along with details on methods, arrays, strings, and method overloading. Additionally, it discusses the Java Runtime Environment (JRE) and the differences between primitive and wrapper classes.

Uploaded by

Cmv
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Java Flashcards

(Core)
Program Execution flow :-

Platform Independent (Platform means Operating System)

a)Not platform independent B)Platform Independent


•Features of JAVA:

•Platform Independence: Java code can run on any platform with a compatible JVM.

•Object-Oriented: Java is based on the object-oriented programming paradigm,


promoting concepts like encapsulation, inheritance, and polymorphism.

•Portability: Java's platform independence and Write Once, Run Anywhere (WORA)
principle make it highly portable across different devices and platforms.

•Platform for Web Development: Java supports server-side programming through


technologies like Servlets, JSP, and frameworks like Spring and Java EE.

•How JAVA achieved Platform Independence:


Java achieves platform independence by compiling source code into bytecode,
which can run on any device with compatible JVM, as the JVM interprets
bytecode into machine-specific instructions, abstracting away platform-specific
details.

•JVM is platform dependent and Java is platform independent.


Object Orientation :- The perspective of looking at this world, as a collection of objects is known as object orientation.

Rules :-
➢ The first rule of object orientation is the world is a collection of objects.
➢ Every object in this world belongs to a category or Type.
➢ Type is only known as Class in Java.
➢ Type is imaginary but objects are real.
➢ A Java program is a collection of objects and classes.
➢ Every object has two parts i.e.,
1. State/Properties or what an object has.
2. Behavior or what an object does(actions).
➢ In Java state/properties are handled using Data types.
➢ Behavior is handled using methods or functions.

➢ To create an object in Java, we require JVM.


➢ When “new” keyword, JVM creates an object of a Car class
Main Method :-

➢ for any program to execute, the operating system (OS) should give control of execution (COE) to the programming
language
➢ public: It is an access specifier, which makes the main
method visible to the operating system.
➢ static: It is a keyword, where the operating system can
access the main method without creating an object.
➢ void: It is a return type, where the main method returns
nothing.
➢ main: It is the name of the method.
➢ String [] args: Are command line arguments. It is an array of
strings that can be used to pass the arguments to execute before
the main method.

Signature of the main method: public staticstatic


public voidvoid
main(String [ ] args)
main(String [ ] args)
Flow of execution of methods
When a class is loaded into memory it will first look for JRE
 Static variables
 Static blocks
 Static method(Precisely Static method)
Variables
For the classes that are loaded later i.e., for non-main method classes Blocks
 Static variables In main
 Static blocks

After executing these only other members are executed. Loaded


class
Instance members follows after the object creation of the class else will not be executed. Variables
Instance variables blocks
 Instance blocks
 Instance methods
Instance
methods
Data Types :-

a) Integer type data:

1) Byte: Size is 1 byte: 8-bit signed Integer.


➢ For example, Byte can be used to store the age of the person.
➢ Range: -128 to 127
E.g.: byte a = 127;
2) Short: Size is 2 bytes: 16-bit signed Integer.
➢ For example, Short can be used to store the salary of a fresher.
➢ Range: -32768 to 32767
E.g.: short a = 32768;

3) Int: Size is 4 bytes: 32-bit signed Integer.


➢ For example, Int can be used to store a mobile number, the distance between two planets.
➢ Range: -2,147,483,648 to 2,147,483,647
E.g.: int b = 9433222;

4) Long: Size is 8 bytes: 64-bit signed integer


➢ For example, long can be used to store the distance between two galaxies.
➢ Range: -9,223,372,036,854,775,80 to +9,223,372,036,854,775,807
E.g.: long a= 9,223,372,036,854,775,807L;

Note: In Java, to store a long value, at the end of the value a suffix ‘L’ or ‘l’ is added.

Literals: Values are known as literals in JAVA


➢ Depending on the prefix of the literal, the value of the literal changes
Double: Size is 8 Bytes (8 bytes of memory is allocated).
b) Real number type data : ➢ Double is used to store double precision (up to 15-16 decimal points) real
number data.
➢ Example: double a = 9.34324;

Float: Size is 4 Bytes (4 bytes of memory is allocated).


➢ Float is used to store single precision (up to 6-7 decimal points) real number
data.
➢ While representing float-type data, we need to attach a suffix “f” at the end of
the real number value.
➢ Example: float a = 13.4f;

Note: If the suffix ‘f’ is not present, by default Java will consider it as a double
value.

c) Character type Data:


Character type data represents characters such as letters, digits, and symbols.
➢ In Java, a char data type is used to store characters. Char: Size is 2 Bytes.
➢ Characters are enclosed in single quotes. Example: char ch = ‘A’;
➢ In Java, char is 2 Bytes because it follows UNICODE (16-bit code).
d) Yes/No type Data: Boolean data type is used to store yes/no or true/false type data.

➢ Boolean data type does not have a specified size & it is dependent on JVM.

Type Casting in JAVA:


Typecasting is a process of converting one datatype into another datatype.
There are two types of typecasting.
1) Implicit typecasting
➢ Conversion of a smaller data type into a larger data type.
➢ This conversion is automatically performed by the Java compiler.
➢ The advantage of implicit typecasting is there is
no loss of precision.

2) Explicit typecasting
➢ Conversion of a larger data type into a smaller data type.
➢ This conversion is not automatically performed by the Java compiler.
➢ Explicit typecasting must be done by the programmer explicitly.
➢ Explicit typecasting results in a loss of precision, where
some data is lost.
Wrapper classes
➢ Primitive data types are not treated as objects in java
➢ The wrapper class in Java is a class provides the mechanism to convert primitive data types into object and
object into primitive data type

Advantage of Wrapper class: The program becomes pure object oriented.


Disadvantage of wrapper class: Execution speed decreases.
Advantage of Primitive data type: Faster in execution.
Disadvantage of Primitive data type: The program becomes impure object oriented.
•JRE (Java Runtime Environment) :-
➢ JRE is a software package that provides the
necessary runtime components for execution of Java
applications.
➢ When a Java program is loaded onto the RAM, a
region is created where the Java program executes,
known as JRE.
➢ JRE is divided into 4 segments.
1) Code Segment
2) Static Segment
3) Heap Segment
4) Stack Segment

Variable :- It is an identifier for the memory location.

•Types of variables:

1) Instance Variables
•➢ Instance variables are declared within a class but
outside of a method.
➢ Instant variables are a part of an object's state and
are created when an object is instantiated.
➢ Each instance of a class has its copy of instance
variables.
➢ Memory for instance variables is allocated in the
heap segment.
•Default values of primitive data
types:
1. Integers (byte, short, int, long) :
0
2. Real numbers (float, double): 0.0
3. Boolean: false
4. Character (char): empty
character
5. Objects (Arrays, Strings): null

•2. Local Variables


➢ Local variables are declared
within a method.
➢ They are temporary and exist
only during the execution of the
method.
➢ Local variables must be
initialized before using them.
➢ Local variable memory gets
allocated in the stack segment.
➢ No default values are provided
by JVM.
Pass by Value:
➢ Data/Value present in a variable is passed to another variable. Data is passed by copying its value to a method.
➢ Changes made to the parameter inside the method do not affect the original variable.
Pass by Reference/address:
➢ Reference (address) of one variable passed to another variable.
➢ When two reference variables have the same address, both variables will refer to the same object.
➢ Object reference (memory address of data) is passed to a method.
➢ Changes made to the parameter inside the method affect the original object.
➢ It allows for more memory efficiency.
METHODS
➢ The signature of a method in Java is,

Types of methods: There are four types of methods.


1. No input and no output method
2. No input and output method:

3. Input and no output method:


A method that has parameters (input) & will not return any value (no output).
4. Input
and
output
method
ARRAYS : An Array is a data structure that allows storage of multiple values of the same datatype under a single variable
name.
➢ Array is an object (non-primitive data type) in Java.
➢ The minimum value we can give is “0” and max value is “Integer.MAX_VALUE – 5”

➢ There are two types of arrays.

1. Regular Array:
➢ An array, where all rows have the same number of columns, is also known as a rectangular array.
➢ [Link] will give the number of blocks in a 3-D array.
➢ a[i].length will give the number of rows in ith block of a 3-D array. (Variable “i” is used for the count of the number of
blocks)
➢ a[i][j].length will give the number of columns in a 3-D array.(Variable “i” is used for the count of the number of blocks)
•2. Jagged Array: An array of
arrays where each row has a
different number of columns
is also known as an irregular
or non-rectangular array.
STRINGS
➢ A string is a collection of a sequence of characters enclosed within double quotes “ ”.
➢ Strings are classified into two types.

1) Mutable strings: String whose values can be changed.

2) Immutable strings: String whose value cannot be changed


Different ways to create an Immutable String in Java:
➢ Like arrays, Strings are also objects in JAVA. So, one can use a new keyword to create a string.
➢ Since strings are objects, memory is allocated in the heap segment of JRE.

1) String s = new String(“JAVA”);


2) String s = “JAVA”; Where are strings created in memory?
3) char [ ] c = {‘J’, ‘A’, ‘V’, ‘A’}; The heap Segment further classified into two pools:
String s = new String(c); 1. Constant pool
2. Non-Constant pool.
String Concatenation in JAVA
1) By + (string concatenation) operator 
2) By concat( ) method

NOTE :- If concatenation is performed between a


literal and reference, or even if a single
reference is involved in a concatenation always
memory is allocated in a non - constant pool.
2) String Concatenation by concat( ) method:
String comparison using compareTo( ) method:

➢ Returns zero, if the strings are equal.


➢ Returns a +ve number, if the first string is greater than the second string.
➢ Returns a -ve number, if the first string is less than the second string.

String comparison using compareToIgnoreCase( ) method:


Let, s1 = JAVA & s2 = java, compare the strings s1 & s2
ignoring the case

String Tokenizer:
In Java, the String class has a split( ) method that can be used to tokenize a string into an array of substrings based on a
specified delimiter.
➢ The nextToken( ) method returns the next token and the hasMoreTokens( ) method returns true if there are more tokens.
•Built-In Methods in Strings:
➢ length( ) - Returns the length of the string.
➢ charAt(int index) - Returns the character at the specified index in the string.
➢ substring(int startIndex, int endIndex) - Returns a new string that is a substring of the original
string, starting from the startIndex and ending at endIndex- 1.
➢ indexOf(String str) - Returns the index of the first occurrence of the specified str in the original
string.
➢ lastIndexOf(String str) - Returns the index of the last occurrence of the specified str in the original
string.
➢ replace(char oldChar, char newChar) - Replaces all occurrences of oldChar with newChar in the
original string.
➢ replaceAll(String regex, String replacement) - Replaces all occurrences of the regular expression
regex with replacement in the original string.
➢ toLowerCase( ) - Returns a new string that is the lowercase version of the original string.
➢ toUpperCase( ) - Returns a new string that is the uppercase version of the original string.
➢ trim( ) - Returns a new string with all leading and trailing whitespace removed from the original
string.
➢ split(String regex) - Splits the original string into an array of strings based on the specified regular
expression regex.
➢ toCharArray( ) - Converts a string into an array of characters.
➢ contains(String) – Returns whether the string present in the main String.
➢ repeat(int count) - provides a concise way to create a new string by concatenating the original
string a specified number of times
Mutable Strings: Strings whose values can be changed.
➢ To create a mutable string in Java, there are two classes
1) String Buffer : The default capacity of StringBuffer is 16.

➢ append(String str) - Adds the specified string to the end of the current string.
➢ capacity( ) - Returns the current capacity of the buffer or builder, which is the amount of memory allocated for storing the
string.
➢ length( ) - Returns the length of the string.
➢ trimToSize( ) - Trims the buffer or builder to the current length of the string, freeing up any unused memory.

➢ Initially, the capacity was 16, but now the size will
automatically increase.
➢ To calculate the capacity of a String Buffer, there is a
formula.
METHOD OVERLOADING :-
Method overloading is a It is also called as Static
process of creating Binding OR Early
multiple methods with Binding OR Compile –
the same name inside a Time Polymorphism OR
class but with different Virtual Polymorphism.
parameters.

➢ There are three ways to achieve method overloading:


➢ To overload a method, the argument lists of the methods must differ in either of these:
1) Number of parameters.
For example: Consider a method to calculate area. This is a valid case of overloading.
area(int, int)
area(int, int, int)
2) Data type of parameters.
For example: area(int, float)
area(int, int)
3) Sequence/Order of Data type of parameters.
For example: area(int, float)
area(float, int)
Note :- If two methods have the same name, the same parameters, and have different return types, then this is not a valid
method overloading example. This will give a compilation error.
For example: int area(int, int)
float area(int, int)
➢ Method overloading, also known as virtual(false) polymorphism Although to the user it appears as if there is only one
method performing multiple tasks (1:Many operations), there are separate methods for each task (1:1 operations)

class MainOverload {
public static void main(String[] args) {
➢ Main method can also be overrided  [Link]("Main method with String[] args");
main(10);
main("Hello", 20);
}
Output:- public static void main(int num) {
Main method with String[] args [Link]("Main method with int: " + num);
Main method with int: 10 }
Main method with String and int: Hello 20 public static void main(String str, int num) {
[Link]("Main method with String and int: " + str + " " + num);
}
}
ENCAPSULATION
➢ Encapsulation is a process of providing security & controlled access to the most important component of an object. i.e.,
data members of an object.
➢ Security can be provided by two steps.
1. Preventing direct access by declaring data members as private.
2. Providing controlled access by using public setters and public getters.
➢ Variables with private keyword can be accessible only within the same class and cannot be accessed outside the class.
➢ Setter is a public method that updates or sets the value of data members.
➢ Setter is also known as a mutator in Java
➢ Getter is a public method that reads or returns the value of data members.
➢ Getter is also known as accessor in Java.
Reason :- There is a name clash between instance variable and
Public void setData(int cId, String cName){
local variables as variable names are same.
cId = cId;
➢ This is known as the shadowing problem, that is a name
cName = cName;
clash that occurs inside a setter when the names of instance
}
and local variables are the same.
➢ To avoid the shadowing problem, we should attach the
Public void setData(int cId, String cName){ “this” keyword to the names of instance variables.
[Link] = cId;
[Link] = cName;
}
Constructors in Java:
➢ Constructor is a built-in setter or special method that is automatically called during object creation.
➢ Constructors do not have a return type (not even void).
Differences between a method and a constructor:
Method Constructor
This method name can be anything Should be same as class name
Must have return type No return type
Called after object creation Called during object creation
No default method is provided by java A default constructor is provided by java
compiler compiler
Methods can be overloaded and Can only be overloaded
overridden
Can be static Cannot be static
➢ Constructors are of two types.
1. Zero parameterized (No-argument) constructor: This constructor does not take any arguments and it is used to
initialize the default values for the objects.
2. Parameterized constructor: This constructor takes one or more arguments, and it is used to initialize the object with
specific values.
Constructor chaining: Constructor chaining can be achieved in two ways.
1. Within the same class (Local chaining).
2. Child class to parent class.

Local chaining:
➢ If a constructor calls another constructor within the same class,then it is known as local chaining.
➢ Local chaining can be achieved using this( ) method.
Child
class to
parent
class :-
STATIC : The static keyword in Java is a powerful tool that can be used to improve the efficiency and readability of code. A class
in Java consists of the following members,

Static members belong to a class and non-static members (Instance) belong to objects.

1) Static Variables can be accessed by static as well as instance


members.
Rules of static: 2) Instance variables can be accessed by only instance
members.
3) Static members cannot access instance variables (non-static
members).
•Static Variables:
➢ Static variables in Java belong to the class, not to an object, and they are initialized only
once when the class is loaded into the memory.
➢ These variables will be initialized first, before the initialization of any instance variables.
➢ A single copy is to be shared by all instances of the class.
➢ A static variable can be accessed directly by the class name and doesn’t need an object.
Syntax: <class-name>.<variable-name>

•Static Method:
➢ A static method in Java is a method that belongs to the class and not to the object.
➢ A static method can access only static data. It cannot call non-static data (instance
variables).
➢ A static method can call only other static methods and cannot call a non-static method
from it.
➢ A static method can be accessed directly by class name and does not need any object.

•Static Block:
➢ The static block in Java is a code segment within a class that runs just once when the class
is loaded into memory.
➢ Its primary purpose is to initialize static variables.
➢ The static block executes even before the main method begins its execution.
INHERITANCE
➢ Inheritance is the process of acquiring the properties and behaviour of a class by another class.
➢ Inheritance can be implemented using the “extends” keyword.
Advantages of Inheritance: Rules
➢ Code reusability. ➢ Private members do not participate in inheritance
➢ Reduce development time and effort. ➢ Multilevel (Hierarchical Inheritance) Inheritance is
➢ Increases profitability. permitted in Java
Types (Supported by java) ➢ Multiple Inheritance is not permitted in Java as it leads to
➢ Single diamond shaped problem which results in ambiguity.
➢ Multilevel ➢ Constructors do not participate in inheritance.
➢ Hierarchical ➢ Cyclic Inheritance is not permitted.
➢ Hybrid (Single + Hierarchical OR Multilevel + Hierarchical)
Note :- If a class explicitly doesnot extend any other class then it is implicitly extending Object class

Types of methods :-
➢ Inherited Methods
➢ Specialized methods
➢ Overridden methods Note:- Use @Override annotation before overriding method in childclass
Rules of overriding
➢ The overridden method of child class must either maintain the same access modifier as the parent class method or
provide greater access; however, it can never be reduced.
➢ The overridden method of child class must maintain the same return types as the parent class method.
➢ In the overridden method of child class, the return types can be different, provided the relationship between the return types
is ‘is-a’ relationship. Such return types between which “is-a” relationship exists are called as covariant return types.

Polymorphism
Polymorphism is derived from two Greek words: poly and morphs. The word ‘poly’ means many and ‘morphs’ means forms.
Creating parent-type references to child objects is called loose
coupling, through which we have achieved polymorphism.
There is one limitation of parent type reference to child type.
That is using parent type reference we cannot directly access
the specialized methods of child class
In order to access the specialised methods of a child class
using a parent type reference, it is necessary to downcast the
reference to the child type.

Advantages of Polymorphism:
1. Code reusability
2. flexibility
3. Reduction in complexity
 This is second method of polymorphism
Method overriding is also called as dynamic binding,
late binding
Naming , dynamic method dispatch
conventions
•Packages: lowercase (e.g., [Link]).
•Classes and Interfaces: CamelCase, starting with an uppercase letter
(e.g., MyClass, MyInterface).
•Methods: camelCase, starting with a lowercase letter
(e.g., calculateArea()).
•Variables: camelCase, starting with a lowercase letter
(e.g., userName, totalCount).
•Constants: uppercase with underscores separating words
(e.g., MAX_VALUE, DEFAULT_NAME).

Final Keyword
The final keyword in Java is used to restrict the user.
1. Variable (Cannot be changed)
2. Method (Cannot be overriden)
3. Class (Cannot be extended)
Aggregation and Composition:
➢ Aggregation is “has-a” relationship between two objects where one object contains a reference to another object, but the
two objects can exist independently.
➢ Composition is a “part-of” relationship where one object is composed of one or more other objects, and the component
objects cannot exist independently without the parent object.
➢ Aggregation is a loose bound has-a relationship.
➢ Composition is a tight bound has-a relationship.

➢ Charger can exist without a phone and therefore it is aggregation. (loosely bound)
➢ An OS cannot exist without a phone and therefore it is composition. (tightly bound)
ABSTRACTION
➢ Abstraction in Java is a mechanism for hiding implementation details and exposing only the necessary information to the
user.
➢ Abstract classes cannot be instantiated and can only be used as a base class for other classes.
➢ The abstract keyword is a non-access modifier.
➢ It is only used for classes and methods.
Abstract class: It’s a restricted class, that cannot be used to create objects (to access, it must be inherited from another class).
Abstract method: It's a method with just a signature, no body. If a class has even one abstract method, you need to mark the
whole class as abstract.
An abstract class can have both abstract and regular methods.
Abstract methods can only exist in abstract classes only
➢ An abstract class can contain both abstract methods as well as concrete methods.
➢ A normal class can inherit from an abstract class.
➢ An abstract class can inherit from another abstract class.
➢ An abstract class can inherit from a normal class.
➢ If a class contains even a single abstract method, then the class should be declared as abstract.
➢ Abstract class objects cannot be created/instantiated. If you want to create it then it must be inherited from another class.
➢ Abstract and final keywords cannot be used together.
➢ Abstract cannot go with variables
INTERFACE
An interface is a collection of pure abstract methods; inside an interface, you have only Rules of interface
Rule 1: An interface is like a contract which when implemented helps to achieve standardization.
Rule 2: Interfaces promote polymorphism. An interface type reference can point to implementing class objects. This achieves
loose coupling, code reduction and code flexibility.
Rule 3: Methods within an interface are automatically public, abstract.
Rule 4: Specialized methods cannot be accessed directly using interface type reference.
Rule 5: If a class partially implements interface, it must declare itself as abstract.
Rule 6: A class can implement multiple interfaces because diamond shape problem does not exist as interfaces will not have
parents.
Rule 7: An interface cannot implement another interface, because interface cannot provide methods with bodies inside it.
Rule 8: An interface can extend another interface. Not only this it can inherit from multiple interfaces because the diamond
shape problem does not exist.
Rule 9: A class can both extend another class as well as implement an interface. However, order should be extend first and
implemented later.
Rule 10: An interface can contain constant variables and method signatures. A variable within an interface is automatically
public static final.
Rule 11: An empty interface in Java is referred to as a Marker interface or Tagged interface. It is used to provide special
properties to the object of the class.
➢ To use concrete methods in interfaces we need to use default(Not an access specifier) keyword before concreate methods. It
is used to achieve backward competability
➢ We use static methods in interfaces , to use them before implementation
➢ We can use private methods in interface for creating concrete methods
Functional Interfaces
➢ To specify an interface as functional interface we need to use “@functionalInterface” annotation
➢ To provide security we use a nested class and to access the functional interface and it can be done in four ways
i) Normal class
ii) Nested class
iii) Anonymus class EX :- Runnable is an example of functional interface.
iv) Lambda expressions
Note :- If a class is inside main method it can be used normally if it is outside main method we need to use it after making it
static only otherwise it will throw an error.

Interface Vehicle{ Interface Vehicle{


void ride(); void ride();
} }
Class H1{ Class H1{
public static void main(String args[]){ public static void main(String args[]){
Vehicle v = new Vehicle(){ Vehicle v = ()  {[Link](“Riding”);};
@Override [Link]();
public void ride(){Sysout(“Riding”);} }
}; }
[Link]();
}
}
EXCEPTION HANDLING
The process of avoiding the abrupt termination of the program is only called Exception Handling.
During the execution of a Java program, if the user gives faulty
inputs, then an exception object is generated. This causes the
program to lose control and the flow of execution is handed over
to the Runtime System. Next, the Runtime System checks
whether the programmer has provided any specific code to
handle the exception. In this case, if no special code is present,
the Runtime System passes the exception object to the default
exception handler. As a result, the program crashes.

➢ Whenever there are multiple methods, if within a method an exception object gets
generated, it is handled by the run-time system,
➢ And the run-time system checks if there is any try-catch block to handle the
exception. If it is not there, then the exception object does not directly go to the default
exception handler, instead, it gets propagated below the stack.
➢ If none of the methods handle the exception, then it reaches the default exception
handler, and abrupt termination happens.
➢ Once an exception is caught it does not gets propagate down to the caller methods
and normal termination of the program happens.
Different Ways to Handle Exception.
1) Handling the Exception(try-catch)
2) Re-throwing the Exception(try-catch-throw-throws-finally)
3) Ducking the Exception(throws)
Case-2: Re-throwing the Exception (try-catch-throw-throws-finally)
➢ If an exception occurs within a method and is also handled in the same method, but the same exception object must also
propagate to the caller of the method, then it is referred to as re-throwing the exception.
➢ Throw keyword is used to explicitly throw an exception from a method or anyblock of code.
➢ The disadvantage of the throw keyword is that statements below the throw keyword do not execute. This can be overcome
by placing the statements within the finally block.
Case-3: Ducking the Exception(throws)
➢ If an exception occurs within a method and the method does not want to handle it, instead it wants to hand over the
responsibility of handling the exception to the caller of the method, it is referred to as ducking an exception.
➢ To achieve this, the throws keyword is used.
Custom Exception
1. Create a class.
2. Make that class extend from the built-in Exception or RuntimeException class.
3. Override the getMessage() method.

Note :-

PrintStackTrace():- This method in the exception class provide detailed information about where an exception is included
It includes the name of the exception and where it is generated.

getMessage() :- This method in the exception class retrives the desriptive message associated with the exception

Runtime errors can also be handled using the generic exceprions

Ex:-
Main(){ Note :- A generic catch block can never be placed on top of specific catch
try{ blocks. It would result an error.
int arr[] = new int[Integer.MAX_VALUE];
}
catch(Error e){
[Link](“Error handled”);
}
}
•Exceptions are further subdivided into two types
1. Checked Exceptions (compile-time)
2. Unchecked Exceptions (run-time)

•All subclasses of RuntimeException are unchecked exceptions, whereas all subclasses


of Exception besides RuntimeException are checked exceptions.

• Checked Exception:
•➢ Checked Exceptions, also referred to as compiler-known exceptions.
➢ These are identified by the compiler during the compilation process.
➢ The compiler enforces the handling of checked exceptions since it can predict their
occurrence.
➢ Errors related to these exceptions must be addressed immediately.
Example: FileNotFoundException, SocketException etc

•2. Unchecked Exceptions:


➢ Unchecked Exceptions, also known as compiler-unknown exception or
runtime exceptions.
➢ These are unidentified by the compiler during the compilation process.
➢ The compiler does not enforce the handling of unchecked exceptions, as it
cannot predict their occurrence.
➢ Errors related to these exceptions must be addressed subsequently.
Example: ArrayIndexOutBoundsException, NegativeArraySizeException etc
➢ Multithreading is a programming concept that allows a computer or software
application to execute multiple threads (independent units of a program) concurrently.
➢ The stack created by Java automatically is called the Main Stack.
➢ The thread scheduler automatically creates a line of execution called the Main
Thread to execute the contents of the main stack.

MULTI ➢ A thread is part of a process or the path followed when executing a program.
➢ Thread scheduler in Java is a software that decides which thread should run.
➢ Only one thread can run in a single process at a time.

THREADI •Note:
➢ When the currentThread method is invoked, a reference is created for the currently

NG
executing thread.
➢ If we print the reference of the thread, it will display three pieces of information:
the thread's name, its priority, and the name of the method in which the thread is
currently executing.
➢ Here, you can modify the thread's name and priority using the setName() method
to change the thread's name and the setPriority() method to adjust the thread’s
priority. However, it's important to note that you cannot modify the method name
associated with the thread
➢ The default priority of the main thread is 5, and the priorities of these threads
typically lie between 1 and 10
•There are two ways to achieve multithreading:
1. Extending Thread class
2. Implementing Runnable Interface
1. Extending the Thread class:
➢ This involves creating a class that extends the Thread class
➢ Overriding the run() method to define the task that will be executed in a separate thread.
➢ Then, create an instance of the class and call its start() method to start the execution of the task in a new thread.
Note:
➢ The programmer must never directly call the run() method.
➢ It must always be indirectly called using start().
•When start() is called, a new thread is created and code inside run() method is executed in new thread while if you call run() directly no new
thread is created and code inside run() will execute on the current thread or main thread.
•[Link] Runnable Interface
➢ Create a class that implements the Runnable interface. The Runnable interface has a single method called run().
➢ Override the run() method in your class to include the code that you want to run in the new thread.
➢ Create an instance of your class.
➢ Create an instance of the Thread class and pass the instance of your class as a parameter to the constructor.
➢ Call the start() method on the Thread instance to start the new thread.
➢Implementing from runnable interface will not allow us to create a new small stack frame to do so we need to use thread class
Thread v/s Runnable:
There are several differences between the Thread class and Runnable interface based on their performance, memory usage, and
composition.
➢ By extending the thread, there is the overhead of additional methods, i.e. they consume excess or indirect memory,
computation time, or other resources.
➢ Since in Java, we can only extend one class, and therefore if we extend the Thread class, then we will not be able to extend
any other class. That is why we should implement Runnable interface to create a thread.
➢ Runnable makes the code more flexible, if we are extending a thread, then our code will only be in a thread whereas, in the
case of runnable, one can pass it in various executor services, or pass it to the single-threaded environment.
➢ Maintenance of the code is easy if we implement the Runnable interface.

User Thread:
➢ User Thread is a Thread that is created by the user
➢ It is the normal thread that runs in the foreground to perform a task.
➢ When all the user threads are completed, the program will be terminated automatically.
Daemon Thread:
➢ It is a low-priority thread that runs in the background to perform specific tasks such as garbage collection, finalization, etc.
➢ The JVM automatically terminates a daemon thread if all the user threads are completed
➢ To create a daemon thread in Java, you simply need to call the setDaemon(true) method on a Thread object before starting
the thread.
The life cycle of thread:
The moment the thread is created till the thread finishes its execution, a thread goes through different phases or states.
New State:
➢ The thread is created but not yet started. Created using the new keyword.
➢ It's waiting for the start() method to be invoked to transition to the "Runnable" state.

Runnable State:
➢ Once the thread's start() method has been invoked, it transitions to the "Runnable" state,
indicating that it is ready to run.
➢ However, it may not immediately start executing as the thread scheduler has not yet
selected it to be the running thread.
•Running State:
➢ The thread transitions to the "Running" state when the thread scheduler has selected it to run, and it is currently
executing its code.
Blocked State:
➢ Threads enter the "Blocked" state when they are temporarily inactive.
➢ This typically occurs when a thread is waiting for a specific resource, such as I/O operations or synchronization.
Waiting State:
➢ In the "Waiting" state, a thread pauses its execution, anticipating another thread to perform a certain action.
➢ The thread can remain in this state until it is notified and transitions back to the "Runnable" state.
Sleep State:
➢ Threads can enter the "Sleep" state voluntarily using the [Link]() method, introducing a pause in their
execution.
➢ After the specified time elapses, the thread automatically transitions back to the "Runnable" state, ready to resume
its tasks.
Dead State:
➢ A thread enters the "Dead" state when it completes its task or is terminated due to an error or being forcefully
killed.
➢ Once a thread is in the dead state, it cannot be restarted.

•Threads from runnable, running, sleep, blocked and wait state can be moved to dead state by calling interrupt()
method.

•Synchronization
•➢ To prevent this, statements that only a single thread should access at a time are referred to as Semaphores.
➢ Locks can be used to implement Semaphores in Java, and they can be achieved by using the synchronized keyword.
➢ This is achieved by synchronizing access to the resource using the synchronized keyword.
➢ If you aim to lock an entire method, incorporate the synchronized keyword into the method's signature.
➢ If the need is to lock only specific lines within a method, utilize a synchronized block.
DeadLock: A deadlock in Java occurs when two or more threads are stuck in the blocked state, each waiting for the other to
release resources.
➢ Deadlock is caused by the synchronized keyword, which causes a thread to block while waiting for a lock associated with a
particular object.

Join() in Java
➢ In Java, the Thread class provides the join() method, which allows one thread to wait for another thread to complete its
execution.
➢ This is useful when the output of one thread is dependent on the execution of another thread.
➢ When a Thread object, let's say t, is currently executing, then calling [Link]() will ensure that t is terminated before the next
instruction is executed by the program.
•Producer-Consumer problem in Java:
➢ The producer-consumer problem is a well-known multi-process
synchronization issue
➢ in computer science that is also referred to as the bounded-
buffer problem.
➢ It involves two distinct processes, the producer and the
consumer, which share a fixed-size buffer that functions as a queue.
➢ The producer's primary responsibility is to create data, put it into
the buffer, and repeat the process.
➢ On the other hand, the consumer is in charge of taking the data
out of the buffer one piece at a time.
➢ This situation creates a challenge because the producer must
ensure that the buffer is not full before adding more data,
➢ while the consumer must make sure that the buffer is not empty
before taking data from it.
➢ As a result, the producer and consumer must cooperate to
ensure that the buffer is not overloaded or underutilized.
COLLECTIONS
The Collection Framework is a group of classes and interfaces that provide a standard way to manage a group of objects in Java.

• boolean add(Object o) - Adds an element to the collection and returns true if the element was successfully added.
• boolean addAll(Collection c) - Adds all of the elements in the specified collection to the current collection and returns true if
the collection was modified as a result of the call.
• boolean remove(Object o) - Removes the first occurrence of the specified element from the collection and returns true if the
element was successfully removed.
• boolean removeAll(Collection c) - Removes all of the elements in the specified collection from the current collection and
returns true if the collection was modified as a result of the call.
• boolean retainAll(Collection c) - Retains only the elements in the collection that are also in the specified collection and returns
true if the collection was modified as a result of the call.
• void clear() - Removes all elements from the collection.
• boolean contains(Object o) - Returns true if the collection contains the specified element.
• boolean containsAll(Collection c) - Returns true if the collection contains all of the elements in the specified collection.
• Iterator iterator() - Returns an iterator over the elements in the collection.
• Object[] toArray() - Returns an array containing all of the elements in the collection
• boolean isEmpty() - Returns true if the collection is empty (i.e., contains no elements).
• int size() - Returns the number of elements in the collection.

LIST:
➢ The List interface is a sub interface of the Collection interface in the Java Collection framework.
➢ A List is an ordered collection of elements and is used to store a collection of elements that can be accessed in order.
Properties: Ordered collection, Index-based access, Duplicates allowed, Multiple implementations, Inherits from Collection,
Resizable, Null allowed.
Methods
• add(int index, Object element): Adds the specified element at the specified position in the list.
• addAll(int index, Collection c): Adds all of the elements in the specified collection to the list, starting at the specified position.
• get(int index): Returns the element at the specified position in the list.
• indexOf(Object o): Returns the index of the first occurrence of the specified element in the list.
• lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list.
• remove(int index): Removes the element at the specified position in the list.
• set(int index, Object element): Replaces the element at the specified position in the list with the specified element.
ArrayList:
ArrayList is a commonly used implementation of the List interface in Java. It provides a dynamic array, which automatically
resizes as elements are added or removed from the list.
Different ways of creating ArrayList:
1. Using the default constructor: The simplest way to create an ArrayList is to use the default constructor, which creates an
empty ArrayList.
ArrayList< > list = new ArrayList< >();
2. Specifying the initial capacity: you can also create an initial capacity, which is number of elements that ArrayList can hold
without resizing.
ArrayList< > list = new ArrayList< >(100);

3. Initializing with a collection: you can create arrayList from exisiting collection by passing a collection.

ArrayList< > list = new ArrayList< >(Collection c);


Properties:
➢ Underlying data structure: The underlying data structure of an ArrayList is an array.
➢ Heterogeneous elements: An ArrayList can store elements of different data types.
➢ Default capacity: The default capacity of an ArrayList is 10.
➢ Dynamic resizing: When the internal array is full, ArrayList creates a new array of a larger size.
➢ New capacity calculation formula: The size of the new array is calculated using the formula.
newCapacity = currentCapacity * 3/2 + 1
➢ Duplicate elements: ArrayList allows duplicates.
➢ Order of elements: The order of elements is preserved as they are added to the list.
➢ Null elements: ArrayList allows null elements.
LinkedList:
The LinkedList class is collection in Java Collection Framework that implements the List interface.
Properties:
➢ Underlying Data Structure: The underlying data structure of a LinkedList is a doubly linked list.
➢ Nodes: A LinkedList is made up of a series of nodes, each of which contains an element and a reference to the next node in the
list.
➢ Head and Tail: The first node in the list is called the head, and the last node is called the tail. The tail node refers to null,
indicating the end of the list.
➢ Efficiency of Insertion and Deletion: LinkedList provides efficient insertion and deletion operations, with O(1) time complexity.
➢ Dynamic Size: LinkedList does not have a fixed size and can change dynamically to accommodate the elements, making it a
good choice for applications with changing number of elements.

Different ways of creating LinkedList:


1. Default constructor: The default constructor creates an empty LinkedList object.
LinkedList list = new LinkedList();
2. LinkedList constructor that accepts a collection: You can create a LinkedList from an existing collection object, such as another
List, set, or Queue.
LinkedList list = new LinkedList(Collection c);

1. void addFirst(Object o) - This method inserts an element at the beginning of the list.
2. void addLast(Object o) - This method inserts an element at the end of the list.
3. Object getFirst() - This method returns the first element in the list.
4. Object getLast() - This method returns the last element in the list.
5. Object removeFirst() - This method removes and returns the first element in the list.
6. Object removeLast() - This method removes and returns the last element in the list.
Stack:
Stack is a data structure that operates on the Last-In-First-Out (LIFO) principle. It is an abstract data type that provides two main
operations, namely, push and pop, which add or remove elements from the top of the stack, respectively.
Methods of stack:
1. Object push(Object o): Adds specified object o to the top of stack and returns the same object as a result.
2. Object pop(Object o): The pop() method pops(removes and returns) the top elements of stack.
3. Object peek(Object o): peek() method that returns the object at top of stack without removing it.
4. Int search(Object o): search(Object o) method provided by the stack class in Java that is used to search for the occurrence of
an object in the stack and returns its position (counted from the top of the stack) if it is found.
If the object is not found in the stack, the method returns -1.
5. Boolean empty(): empty() method in Java’s Stack class is a boolean method that returns a boolean value of true if the stack
is empty and false if it contain elements.
Different ways of traversing a Collection:
Iterator:
➢ Iterator is a Java interface used to traverse a collection and retrieve its elements one by one. The iterator allows sequential
access to the elements of the collection.
➢ It is widely used in the Java collections framework for traversing and manipulating the collections.
Methods of Iterator:
➢ hasNext(): this method returns true is the iterator has more elements to traverse, and false otherwise.
➢ next(): This method returns the next element in the collection and advance the iterator. If there are no more elements, a
NoSuchElementException is thrown.
➢ remove(): This method removes the last element returned by the iterator from the underlying collection. This method can onoy
be called once per call to next(), otherwise an IllegalStateException is thrown.
ListIterator:
ListIterator is an interface in Java that provides a way to iterate over a list (or any List implementation) and allows for both
forward and backward traversal of the list.
Methods Of ListIterator:
➢ hasNext() - returns true if the iteration has more elements in the forward direction.
➢ next() - returns the next element in the list and advances the cursor position.
➢ hasPrevious() - returns true if the iteration has more elements in the reverse direction.
➢ previous() - returns the previous element in the list and moves the cursor position backward.
➢ nextIndex() - returns the index of the next element.
➢ previousIndex() - returns the index of the previous element.
➢ remove() - removes the last element returned by the iterator from the list.
➢ set(E e) - replaces the last element returned by the iterator with the specified element
Set:
The Set interface is a part of [Link] pakage and represents a collection of the unique element, meaning that no two elements in
Set can be equal.
➢ HashtSet
➢ LinkedHashSetTreeSet
HashSet:
HashSet is a class that implements the Set interface and provides an implantation of a set that uses a hash table for storage. A
HashSet is similar to an array or a List, but with the added feature that it does not allow duplicate elements.
Properties:
➢ It follows Hashing Algorithm internally Different ways of creating Hashset:
➢ Efficient Data Structure is Hashing Algorithm new HashSet()
➢ Default capacity = 16 new HashSet(Collection c)
➢ LoadFactor = 0.75 new HashSet(int initalCapacity)
➢ newCapacity = oldCapacity *2 new HashSet(int initalCapacity, float loadfactor)
➢ Duplicates are not allowed
➢ Insertion order not maintained
➢ Majorly used for searching

Linked HashSet:
LinkedHashSet is a class that extends the HashSet class and provides a set that maintains the insertion order of its elements. It
does this by using a doubly-linked list to keep track of order in which elements were added to set, in addition to hash table used
by HashSet class.

TreeSet:
TreeSet is a class that implements the SortedSet interface and provides set that is sorted in natural ascending order.
Properties: Different ways of creating TreeSet:
➢ Insertion order is not preserved. new TreeSet()
➢ Duplicates are not allowed. new TreeSet(Collection c)
➢ Heterogenous objects not allowed. new TreeSet(SortedSet s)
➢ Null insertion not allowed. new Tree set(Comparator c)
➢ Elements are in sorted order.
Methods of TreeSet:
➢ First(): Returns the first (lowest) elements currently in the set.
➢ Last(): Returns the last (highest) elements currently in the set.
➢ headset(E toElement): Returns a view of the portion of the set whose elements are strictly less than toElement.
➢ tailSet(E fromElement): Returns a view of the portion of the set whose elements are greater than or equal to fromElement.
Queue:
➢ A queue is linear data structure in which elements are added at one end (called the rear or trail) and removed from the other
(called the front or head).
➢ It follows the First-In-First-Out (FIFO) principle, meaning that the elements that is added first is the one that will be
removed first.
Methods Of Queue:
1. offer(Object e): Insert the specified elements into the queue. If the task is successful, offer() returns true, if not it returns
false.
2. remove(): Retrieves and removes the head of the queue. Throws NoSuchElementException is the queue is empty.
3. Poll(): Retrieves and removes the head of the queue, or returns is empty.
4. element(): Retrives, but does not remove, the head of the queue. Throws NoSuchElementException if the queue is empty.
5. peek(): Retrives, but does not remove, the head of the queue, or returns null if the queue is empty.
PriorityQueue:
➢ PriorityQueue is a special kind of queue in Java's Collection framework where each element is associated with a priority
value.
➢ The elements in a PriorityQueue are ordered based on their priority, with the highest priority elements appearing at the front
of the queue.
Some common operations that can be performed on a PriorityQueue include:
• add(E e): Inserts the specified element into the queue based on its priority.
• Remove(): Retrieves and removes the head of the queue.
• peek(): Retrieves, but does not remove, the head of the queue.
• size(): Returns the number of elements in the queue.
Comparable Interface:
➢ A comparable interface is a generic interface that defines a single method, compareTo()
➢ Which is used to compare two objects of the same class.
➢ By implementing the Comparable interface, a class indicates that its instances can be ordered or sorted in some natural way.
➢ compareTo() method takes a single argument, which is the object to be compared to the current object.
➢ It returns a negative integer if the current object is less than the argument, zero if they are equal, or a positive integer if the
current object is greater than the argument.
Comparator Interface:
➢ The comparator interface is a generic interface that provides a way to define custom ordering or sorting for objects of a
particular class.
➢ The Comparator interface defines a single method, compare()
➢ which takes two arguments of the type we want to compare, and returns a negative integer if the first argument is less than the
second, zero if they are equal, or a positive integer if the first argument is greater than the second.

public int compare(Object o1, Object o2)


MAP:
➢ Map is an interface that represents a collection of key-value pairs, where each key is associated with a value.
➢ The Map interface is part of the Java Collections Framework and provides a way to store and manipulate data in a way that
allows fast retrieval of the values using the keys.

Constructors of Map Properties of Map:


new HashMap(); ➢ Duplicates are not allowed in key
new HashMap(int initialCapacity); ➢ Duplicates are allowed in values
new HashMap(int initialCapacity, float loadFactor); ➢ Single null insertion is allowed in key
new HashMap(Map m); ➢ Null insertion is allowed in values
➢ Insertion order is not maintained
➢ Underlying data structure is hash table
➢ Majorly used for search operations
➢ Default value=16, load factor=0.75
Methods of Map:
1. put(key, value)
➢ To add a key-value pair to the map.
➢ If the specified key is already available then the old value will be replaced with new value and old value will be returned.
➢ If the key is not present then the method will return null.
2. putAll(Map m)
➢ This method is used to add the group of key-value pairs.
3. get( key)
➢ This method will return the value associated with the specified key.
➢ If the key is not available then we will get null.
4. remove(key)
➢ To remove the key-value pair associated with the specified key from the map.
➢ Returns the value associated with the key or null if the key is not present.
5. clear()
➢ To remove all key-value pairs from the map.
6. size()
➢ Returns the number of entries present in the map.
7. contains(key)
➢ To check if the map contains a specific key.
➢ Returns true if the key present or else returns false.
8. contains(value)
➢ To check if the map contains a specific value.
➢ Returns true if the value is present or else returns false.
9. keySet()
➢ To get a set view of all the keys present in the map.
10. values()
➢ To get a collection view of all the values present in the map.
11. entrySet()
➢ To get a set view of all key-value pairs(entries) present in the map.
12. replace(key, new value)
➢ To replace the value associated with a specific key with a new value.
➢ Returns the previous value associated with the key or null if the key is not present.
13. isEmpty()
➢ Returns true if the map is empty else returns false.
Some common implementations of Map interface in Java includes:
➢ HashMap: A map that uses a hash table to store the key-value pairs. It offers constant-time performance for the basic
operations (get, put, contains Key, and remove) on average.
➢ TreeMap: A map that stores the key-value pairs in sorted order based on the natural ordering of the keys or specified
comparator. It offers O(log n) time performance for basic operations.
➢ LinkedHashMap: A map that maintain the order in which the key-value pairs were added. It offers predictable iteration
order and slightly slower performance than HashMap.
Identity HashMap:
➢ Uses reference equality(‘==’) for comparing keys and values, rather than the ‘equals’ method.
➢ Two keys or values are considered equal if and only if they refer to the same object in memory.
➢ Does not consider the ‘equals’ and ‘hashcode’ methods for key comparison
➢ Allows multiple keys that are equal according to ‘equals’, as long as they are distinct objects.
➢ Useful in scenarios where you want to distinguish between objects based on their identity in memory, rather than their content.
Weak HashMap:
➢ Allows keys to be garbage-collected if there are no other references to them.
➢ Weakly referenced keys are automatically removed from the map when the garbage collector determines that there are no
strong references to the key.
➢ Uses weak references for keys, making them eligible for garbage collection if there are no strong references to them.
➢ Useful in scenarios where you want to associate additional information with objects that should not prevent those objects
from being garbage-collected.
File Handling
File handling in Java implies reading from and writing data to a file.
➢ The File class from [Link] package, allows us to work with different formats of files.
➢ To use the File class, need to create an object of the class and specify the file name or directory name

import [Link];
public class Alpha{
public static void main(String[] args){
String path = "c:\\Users\\Megha\Desktop\\Myfiles\\[Link]";
File file = new File(path);
[Link]([Link]());
}
}

Different Methods of File class


1. canRead() and canWrite():
➢ canRead() method will check whether the file is readable or not. It returns true if it readable else false.
[Link]([Link]());

➢ canWrite() method will check whether the file is writable or not. It returns true if it readable else false.
[Link]([Link]());
2. getName(): This method returns the Name of the file object. The function returns a string object which contains the Name of
the given file object.
[Link]([Link]());
3. getParent(): This method returns a string that denotes the pathname string of the parent directory named by this abstract
pathname, or null if this pathname does not name a parent.
[Link]([Link]());
4. getAbsolutePath(): The getAbsolutePath() method is a part of the file class. This function returns the absolute pathname of
the given file object. If the pathname of the file object is absolute then it simply returns the path of current file object.

[Link]([Link]());

5. isFile(): The isFile() function is a part of the File class in Java. This function determines whether the file or directory denoted
by the abstract filename is a File or not. The function returns true if the abstract file path is File else returns false.

[Link]([Link]());
6. isDirectory(): This function determines whether the file or directory denoted by the abstract filename is a directory or not.
The function returns true if the abstract file path is Directory else returns false.
[Link]([Link]());
7. createNewFile(): The createNewFile() method creates a new and empty file with specified name. this operation
succeeded when the name did not yet exist. Checking for the existence of the file and creation of the file are atomic operations.

[Link]()
The createNewFile() will throw IOException so you need to handle this exception using throw or try catch

8. mkdir(): The mkdir() function used to create new directory denoted by the abstract pathname. The function returns if the
directory is created else returns false.

[Link]([Link]())
9. list(): Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.

String[] list = [Link]();


for (String string : list)
[Link](string);

10. delete(): Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the
directory must be empty in order to be deleted.

[Link]([Link]())
File Writer:
Java FileWriter class is used to write character-oriented data to file. It is character-oriented class which is used for file
handling in java.
➢ Create an object of file writer.
➢ Call write () and pass the string to be written inside the file.
➢ Now call the flush () to push the data to the file form the stream.
import [Link];
import [Link];
import [Link];
public class Alpha {
public static void main(String[] args) {
String path = "C:\\Users\\TAP\\Desktop\\MyFiles\\[Link]";
File file = new File(path);
FileWriter writer;
try {
writer = new FileWriter(file);
[Link]("Hello World");
[Link]();
}
catch (IOException e) {
[Link]();
}
}
}
File Reader: Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
It is a character-oriented class which is used for file handling in java.
➢ Store path of the file in a string.
➢ Create an object of file reader and this will throw an exception of FileNotFoundException if the file is not present in that
directory so need to handle that exception.
➢ Call read() which will read the characters present in that file and this method will throw IO Exception need to handle that.
➢ The read() will return -1 if there are non characters in the file.
public class Alpha {
public static void main(String[] args) {
String path = "C:\\Users\\TAP\\Desktop\\MyFiles\\[Link]";
FileReader reader = null;
try {
reader = new FileReader(path);
[Link]([Link]());
}
catch (FileNotFoundException e) {
[Link]();
}
catch(IOException e1) {
[Link]();
}
}
}
BufferedReader:- Now let’s see how to read the data from the file using BufferedReader. BufferedReader reads line by line.
➢ Create an object of file reader
➢ Convert file reader to BufferedReader by creating an object of the buffered reader.
➢ Call readLine() to read the each line present inside the file.
➢ This readLine() will also take the cursor to the next line.
➢ When there are no next line of characters readLine() method will return default value of String i.e null.
public class Alpha {
public static void main(String[] args) {

String path = "C:\\Users\\TAP\\Desktop\\MyFiles\\[Link]"; catch (FileNotFoundException e) {


FileReader reader = null; [Link]();
BufferedReader reader2 = null; }
try { catch(IOException e1) {
reader = new FileReader(path); [Link]();
reader2 = new BufferedReader(reader); }
String line = [Link](); }
[Link](line); }
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
How the JVM works
we can use the Java Printer tool (javap) to print a decompiled
version of our bytecode
javap [Link]
javap -c [Link] Here is the output from running the
javap command with the -c parameter
javap -sysinfo [Link]
javap -verbose [Link]

JVM has 3 main components:


 A class loader that initializes and
loads classes and interfafces
 Runtime data which includes
memory allocation
 Execution engine.
Garbage collection algorithms
The JVM has several garbage collection algorithms at its disposal, and which one is used depends upon the version
of Java and the specific use case. There are a few garbage collection algorithms worth mentioning:
 Serial Collector
 Parallel Collector
 Concurrent Mark-Sweep Collector (CMS)
 Garbage-First (G1) Collector
 Z Garbage Collector (ZGC)
Serial Collector : It is used for small heaps and single-threaded applications.

Parallel Collector : The parallel garbage collector, also referred to as the throughput garbage collector, was the default for early
Java releases through Java 8. Its capabilities exceed that of the serial collector in that it was designed for medium- to large-
sized heaps and multithreaded applications.

CMS : The CMS garbage collector was deprecated in Java 9 and removed from the Java platform in Java 14. Its purpose was to
minimize the amount of time an application was paused for garbage collection. The reasons for deprecation and removal
included high resource consumption, failures due to lag, difficulty in maintaining the code base, and that there were better
alternatives.

G1 Collector : The G1 Collector became the default garbage collector in Java 9. The G1 Collector can be considered the
primary and default garbage collector.
ZGC : Java 11 was released with the ZGC garbage collector as an experimental feature. ZGC’s aim was to provide a low-latency
garbage collector that was scalable. The intention was for ZGC to handle a wide range of heap sizes, from very small to very
large (for example, terabytes). ZGC delivered on these goals without sacrificing pause times. This success led to ZGC being
released as a Java 15 feature.

Execution Engine : There are 3 primary Implementations of this process


• Interpretation
• Ahead-of-Time (AOT) compilation
• JIT compilation
Interpretation : Read and execute byte code without converting it into native machine code. Only advantage is it saves time.
java [Link]
Ahead-of-Time (AOT) compilation : We can compile our bytecode into native machine code in advance of application
execution.
JIT compilation : We invoke the JVM and have it convert our bytecode into machine code specific to the current host machine.
This machine code is referred to as native machine code because it is native to the local CPU. This compilation occurs just in
time, or just before execution. This means the entirety of the bytecode is not compiled at once

You might also like