Java Notes
Java Notes
Types of Variables
2 Types: 1. Globally { [Link] Variable(Non-Static fields) ,ii. Class
Variable(Static Variable) }-( memory created in heap)
2. Locally { i. Local variables, ii. Parameters}
Instance Variables
Instance variables are declared in a class, but outside a method, constructor
or any block.
When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must
be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block in
the class. Normally, it is recommended to make these variables private
(access level). However, visibility for subclasses can be given for these
variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value is 0,
for Booleans it is false, and for object references it is null. Values can be
assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name
inside the class. However, within static methods (when instance variables are
given accessibility), they should be called using the fully qualified
name. [Link]
import [Link].*;
1
// salary variable is visible in Main class only.
name = empName;
salary = empSal;
[Link](1000);
[Link]();
Class/Static Variables
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
2
Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default
value is 0; for Booleans, it is false; and for object references, it is null. Values
can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class
name [Link].
When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and
final, the naming syntax is the same as instance and local variables.
import [Link].*;
public class Main {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
}
}
OutPut:Development average salary:1000
Note − If the variables are accessed from an outside class, the constant
should be accessed as [Link]
3
public class Main {
public void pupAge() {
int age = 0;
age = age + 7;
[Link]("Puppy age is : " + age);
}
public static void main(String args[]) {
Main test = new Main();
[Link]();
}
}
Output:
[Link]:variable number might not have been initialized
age = age + 7;
^
1 error
*****************************************************************
****
CONSTRUCTOR:
Java constructors are special types of methods that are used to initialize
an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit
return type.
All classes have constructors, whether you define one or not because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your constructor, the default
4
constructor is no longer used
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void as a return
type.
There can be multiple constructors in the same class, this concept is known
as constructor overloading.
The access modifiers can be used with the constructors, use if you want to
change the visibility/accessibility of constructors.
OutPut:
num1 : 0
num2 : 0
2. Explicit Constructor
2.1 No-args constructor
the No-argument constructor does not accept any argument. By using the
No-Args constructor you can initialize the class data members and perform
5
various activities that you want on object creation.
Output:
num1 : -1
num2 : -1
3. Parameterized Constructor
A constructor with one or more arguments is called a parameterized
constructor.
Most often, you will need a constructor that accepts one or more parameters.
Parameters are added to a constructor in the same way that they are added
to a method, just declare them inside the parentheses after the constructor's
name.
6
// Printing the objects values
[Link]("obj_x");
[Link]("num1 : " + obj_x.num1);
[Link]("num2 : " + obj_x.num2);
[Link]("obj_y");
[Link]("num1 : " + obj_y.num1);
[Link]("num2 : " + obj_y.num2);
}}
Output:
obj_x
num1 : 10
num2 : 20
obj_y
num1 : 100
num2 : 200
class Student {
String name;
int age;
// no-args constructor
Student() {
[Link] = "Unknown";
[Link] = 0;
}
// parameterized constructor having one parameter
Student(String name) {
[Link] = name;
[Link] = 0;
}
// parameterized constructor having both parameters
Student(String name, int age) {
[Link] = name;
[Link] = age; }
public void printDetails() {
[Link]("Name : " + [Link]);
[Link]("Age : " + [Link]);
}
7
}
public class Main {
public static void main(String[] args) {
Student std1 = new Student(); // invokes no-args constructor
Student std2 = new Student("Jordan"); // invokes parameterized constructor
Student std3 = new Student("Paxton", 25); // invokes parameterized constructor
// Printing details
[Link]("std1...");
[Link]();
[Link]("std2...");
[Link]();
[Link]("std3...");
[Link]();
}
}
OutPut:
td1...
Name : Unknown
Age : 0
std2...
Name : Jordan
Age : 0
std3...
Name : Paxton
Age : 25
************************************************************************
Jagged Array:
Here , each row have different column size
// Method 1
int arr_name[][] = new int[][] {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};
// Method 2
int[][] arr_name = {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};
// Method 3
int[][] arr_name = {
8
{10, 20, 30 ,40},
{50, 60, 70, 80, 90, 100},
{110, 120}
};
class Main {
public static void main(String[] args){
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];
// Making the above array Jagged
arr[0] = new int[3];
arr[1] = new int[2];
// Initializing array
int count = 0;
for (int i = 0; i < [Link]; i++)
for (int j = 0; j < arr[i].length; j++)
arr[i][j] = count++;
// Printing the Array Elements
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++)
[Link](arr[i][j] + " ");
[Link]();
}
}
}
output:
Contents of 2D Jagged Array
0 1 2
3 4
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
9
Strings: sequence of characters, String is a class in Java, but
considered as literal because its unique behavior(which means that
we prints the string then values are printed ,even though it is a
object. When we print objects it gives us or prints the hashcode or
address of the object . And another behavior is we directly assign
values to Stings whereas In other objects we cannot aasign the
values directly(by using new keyword only) ).
creation:
1. String s1 =”hello123”;
[Link] s2=new String(“hello456”);
Here,
=> String s3=’’hello’’; # it does not create new string Due to already
exists
=> String s4=new String(“hello”); # creates a new string in the heap
and here it does not checks in heap that it already exists or not.
Now,
*** s1==s2 # false
*** s1==s3 # True (# here s2 checks the same value is already
present in the string pool , if it already exists it assigns its Address
without creating new string.)
10
Heap String Pool
abc
abc
abc wel
S3
S1
String methods:
[Link](s2)
[Link]()
[Link]()
[Link]()
10. [Link]()
[Link](’string or char’’)
[Link](startidx,lastidx)
11
14. [Link]() # by default split by space and also use backslahes like “//%”
[Link]()
[Link](‘’old’’,”new”)
[Link]()
[Link]()
[Link]()
Memory allocation can be done by 2 ways : object creation and Static Keyword
When static concept is absent in java, then when we create class, then we again must create object
(instance of class) then only we got memory for that class members. So to avoid this problems,static
concept is raised,
The class file is loaded in to the class loader ,then it checks for the static related variales,methods,
blocks,subclasses and allocates memory by default by jvm.
12
Class Loader
Memory Management
Execution Engine
One block of memory is created only when you execute that particular
code by100 or any number of times .
Here , the objects uses Shared Memory : means any number of objects
uses the single Stack class memory.
Here , [Link];
import use non static variable, But we want to share the num field to all objects Lets try with
Static
publicvariable.
class Main
{
static int num;
public static void main(String[] args) {
Main m1= new Main();
[Link]=new Random().nextInt();
output:
1103874203
1103874203
1103874203
Here we have only one copy in the method area and there only data gets
14
updated there only, Memory is shared, only once it is created, overriding is
done here.
import [Link];
[Link]=new Random().nextInt();
[Link]=new Random().nextInt();
[Link]=new Random().nextInt();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
output:
12345678
12345678
12345678
Here when we call the static method ,with the [Link] , It gets executed.
Non-static methods must be call by creating object only.
import [Link];
public class Main
{
static int num;
public static void main(String[] args) {
15
[Link]();
}
public static void print(){
[Link](" Static method");
}
public void print1(){
[Link](" Non-Static method");
}
}
Output:
Static Method
*******************************************************************************/
import [Link];
public class Main
{
static int num;
public static void main(String[] args) {
[Link]();
Main m= new Main();
m.print1();
}
public static void print(){
[Link](" Static method");
}
public void print1(){
[Link](" Non-Static method");
}}
Output:
Static Method
Non-Static method.
Blocks Concept:
for initialization of variables , constructor uses indirectly static or non static blocks
import [Link];
public class Main
{
static{
[Link](" static block");
}
{
16
[Link](" non-static block");
}
public Main(){
[Link](" constructor");
}
public static void main(String[] args) {
[Link]("Main method");
}
}
Output:
Static block
Main method
from the above,first class loaders check the static block
then it allocates memory , and then entry point starts(main method)
constructors uses non static blocks for initialization internally.
[Link]("Main method");
new Main();
}
}
output:
Static block
main Method
17
Non-static block(1st priority than constructor)
Constructor
*******************************************************************************
public class Main
{
int num;
static{
[Link](" static block");
}
{
[Link](" non-static block");
}
public Main(){
[Link](" constructor");
}
public static void main(String[] args) {
[Link]("Main method");
}
}
output:
Static block
Main method
Here when the object is created then only non- static block and constuctor
executes
*******************************************************************************
18
}
public static void main(String[] args) {
[Link]("Main method");
new Main();
new Main();
new Main();
}
}
output:
Static block # calls only once
Main method
Non-static block
Constructor
Non-static block
Constructor
Non-static block
Constructor
** non- staic method ni static method lo direct gaa call cheyyalemu(object creation
compulsory)
** static method ni non- static method loo direct gaa call cheyyachu
19
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
[Link](count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}}
Output: 1 2 3
Type Inference:
It is a concept in which the compiler infers the type of the variable using the value
provided.
Example:
1. var i=20000(correct)
20
2. var j;
j=2000; (incorrect, var supports only for the single line initialization)
Rules:
OOPS CONCEPT:
Everything is Object.
Priciples of OOPS:
1. Inheritance
2. Encapsulation
3. Polymorphism
4. Abstraction
Java is not Fully 0r 100% OOP because Primitive data types and static keyword
Inheritance:
It is a mechanism in which one class acquires all the properties and behaviors
of another class with specific relationship.
Code Reusability
21
Method Overriding
Polymorphism
Types of Inheritance.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits
the properties and behavior of a single-parent class. Sometimes, it is also
known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is
a child class. The class ‘B’ inherits all the properties of the class ‘A’.
// Parent class
class One {
public void print_geek()
{
[Link]("Geeks");
}
}
// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
}}
Output
Geeks
22
For
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below
image, class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C. In Java, a class cannot directly access
the grandparent’s members if they are private.
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();
// Calling method from class One
g.print_geek();
// Calling method from class Two
g.print_for();
// Calling method from class Three
g.print_lastgeek();
}}
23
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the
derived classes B, C, and D .
class A {
public void print_A() { [Link]("Class A"); }
}
class B extends A {
public void print_B() { [Link]("Class B"); }
}
class C extends A {
public void print_C() { [Link]("Class C"); }
}
class D extends A {
public void print_D() { [Link]("Class D"); }
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();
24
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D
The problem occurs when there exist methods with the same signature in both the
superclasses and subclass. On calling the method, the compiler cannot determine
which class method to be called and even on calling which class method gets the
priority.
Note: Java doesn’t support Multiple Inheritance
25
@Override
public void testCode() {
[Link]("DevOps Engineer tests deployment pipelines.");
}
// Driver class
public class Main {
public static void main(String[] args) {
DevOpsEngineer devOps = new DevOpsEngineer();
[Link]();
[Link]();
[Link]();
}
}
Output
DevOps Engineer writes automation scripts.
DevOps Engineer tests deployment pipelines.
DevOps Engineer deploys code to cloud.
Super:
The super keyword in Java is a reference variable that is used to refer to the
parent class when we are working with objects
26
This ensures that the parent class is properly initialized before the subclass
does anything else.
Cannot be used in Static Context: We cannot use super in a static variable,
static method and static block .
Not Always Required: We know that the super keyword is used to call the
methods from the parent class. If a method is not overridden in the subclass,
then calling it without the super keyword will invoke the parent class’s
implementation.
// super keyword with variable
// Base class vehicle
class Vehicle {
int maxSpeed = 120;
}
// sub class Car extending vehicle
class Car extends Vehicle {
int maxSpeed = 180;
void display()
{
// print maxSpeed from the vehicle class
// using super
[Link]("Maximum Speed: "
+ [Link]);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}
Output
Maximum Speed: 120
// Demonstrating the use of super keyword
// with methods
// superclass Person
class Person {
void message()
{
[Link]("This is person class\n");
}}
27
// Subclass Student
class Student extends Person {
void message()
{
[Link]("This is student class");
}
28
the parent class constructor must be called before the child’s constructor finishes
it’s work.
// Demonstrating the use of
// super keyword with constructor
// superclass Person
class Person {
Person()
{
[Link]("Person class Constructor");
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Output
Person class Constructor
Student class Constructor
Access Modifiers
Define the scope or visibility of the members of a class(variables,
constructors and methods)
Types:’
1. Public (The code is accessible for all classes)
2. Private (The code is only accessible within the declared class)
3. Protected (The code is accessible in the same package and subclasses.)
4. Default / no-modifier/ package-private
29
For classes, you can use either public or default:
For attributes, methods and constructors, you canInuse
Different package we cannot
the one
Use all 4 : access subclass
-------------------------------------------------------------------------------
Non-Access Modifiers
For classes, you can use either final or abstract:
Modifier Description
For attributes and methods, you can use the one of the following:
30
Modifier Description
abstract Can only be used in an abstract class, and can only be used
on methods. The method does not have a body, for
example abstract void run();. The body is provided by the
subclass (inherited from).
31
Encapsulation:
32
}
Output
Name=> Geek
33
you can not provide implementation in public methods which effects all the
business logics.
Here Java provides default keyword in interfaces whereas in classes default
keyword is not used directly.
In Interfaces ,methods are public by predefined where as in classes ,methods
are default by predefined .
<Lenova>(class)
<<Laptop>>(Interface)
Public void copy(){ }
Public void copy();
Public void paste(){}
Public void paste();
Public void cut(){}
Public void cut();
@override
default void security(){
Public void security(){
sysout(“Laptop secure”);
Sout(“”Lenovo secure”)
}
}
Static void audio(){
Sysout(“Laptop audio”)
}
DEFAULT: In Lenova class we again create method for security, But
I want to execute the interface- security method write @override in
the Lenova class
we definetly create object , to call the security method {
[Link]()}.This method said that the as you provide
implementation it doesnot goes outside the world, but it goes to the
implemented classes, when the classes want to change the
implementation .
The output for above default methods is: ”Lenovo secure”(sub class
execute)
But some situations we want that does not create object, happened
through static keyword.
interface Animal {
34
void eat();
void sleep();
}
In other words, Interface fields are public, static and final by default, and
the methods are public and abstract.
Example
1. interface Drawable{
2. void draw();
3. default void msg(){[Link]("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){[Link]("drawing rectangle");}
7. }
8. public class Main{
9. public static void main(String args[]){
[Link] d=new Rectangle();
[Link]();
[Link]();
13.}
14.}
Output:
drawing rectangle
default method
35
Java 8 Static Method in Interface
Since Java 8, we can have static methods in the interface. Let's see an
example:
Example
1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){[Link]("drawing rectangle");}
7. }
8.
9. class Main{
[Link] static void main(String args[]){
[Link] d=new Rectangle();
[Link]();
[Link]([Link](3));
14.}}
Output:
drawing rectangle
27
Private Methods
<<Laptop>>
Public void copy();
Public void paste();
Public void cut();
default void security(){
sysout(“Laptop secure”);
}
Static void audio(){
Sysout(“Laptop audio”)
}
Private void commoncode(){
Sysout(“common code”);
}
36
Here , Private method is only accessible to that interface only. Then how we
access private method in interface. By calling in non-static methods.
<<Laptop>>
Public void copy();
Public void paste();
Public void cut();
default void security(){
commoncode()
sysout(“Laptop secure”);
}
Static void audio(){
Commoncode()
Sysout(“Laptop audio”)
}
Private static void commoncode(){
Sysout(“common code”);
} ++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++
Abstract class:
It is a class which contains abstract methods (unimplemented
methods) and is defined with the Keyword abstract
@overide
Public abstract void cut(){
Sysout(“cutting”)
}
@overide
Public abstract void keyboard(){
Sysout(“KB”)
When to use: When multiple classes
} are there , the common
code or implementation between all classes
// you are
write extra codeplaced
also in
abstract class, so that these classes extends abstract class.
Yes , we have
-----------------------------------------------------------------------------
--
Abstraction:
The process of hiding the implementation details and showing only
functionality to the user.
Security
Simplicity
38
How we achieve Abstraction?
Through Interfaces or abstract class.
How much percentage we achieve abstraction?
Through interfaces: ( 100% Abstraction) before java 8 , we achieve
100 % abstraction
After java 8, we can achieve abstraction may
be 100 % or may not be 100% . because its in the hands of user not
java.
Through Abstract class: (partial Abstraction) Similar to interefaces;
when the implemented classes increases, abstraction % gets
decreased.
// Working of Abstraction in Java
abstract class Geeks {
abstract void turnOn();
abstract void turnOff();
}
@Override
void turnOff() {
[Link]("TV is turned OFF.");
}
}
Polymorphism:
39
Many + Forms
2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It
is a process in which a function call to the overridden method is
resolved at Runtime. This type of polymorphism is achieved by Method
Overriding.
// Class 1
// Helper class
class Parent {
// Class 2
40
// Helper class
class subclass1 extends Parent {
// Method
void Print() {
[Link]("subclass1");
}
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print() {
[Link]("subclass2");
}
}
// Class 4
// Main class
class Geeks {
a = new subclass2();
[Link]();
}
}
Output
subclass1
subclass2
41
Exception Handling in Java:
Exception: An Exception is an unwanted or unexpected event
that occurs during the execution of a program (i.e., at runtime) and
disrupts the normal flow of the program’s instructions.
42
Difference Between Checked and Unchecked
Exceptions
Feature Checked Exception Unchecked Exception
Base
Derived from Exception Derived from RuntimeException
class
External factors like file I/O and Programming bugs like logical
database connection cause the errors cause unchecked
Cause checked Exception. Exceptions.
Finally is optional
Try is present then one catch block must be present or finally block
Try-Catch Block
A try-catch block in Java is a mechanism to handle exception.
The try block contains code that might thrown an exception and
the catch block is used to handle the exceptions if it occurs.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
43
// Code to handle the exception
}
finally Block
The finally Block is used to execute important code regardless of
whether an exception occurs or not.
Note: finally block is always executes after the try-catch block. It is also
used for resource cleanup.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}finally{
// cleanup code
}
44
ArithmeticException(“Error”); throws IOException {}
Java throw
Throws the exception for the java.
The lines or code after “ throw instance(exception) ” can not be
executed.
Whenever the code contains finally block, then the first : finally block
executes and then “ throw line ” gets execute.
throw is used to throw a single exception instance.
The throw statement must be followed by an instance of Throwable (like Exception,
RuntimeException, etc.).
class Geeks {
static void fun()
{
try {
throw new NullPointerException("demo");
}
catch (NullPointerException e) {
[Link]("Caught inside fun().");
throw e; // rethrowing the exception
}
}
Output
Caught inside fun().
Caught in main.
The flow of execution of the program stops immediately after the throw statement is
executed and the nearest enclosing try block is checked to see if it has
a catch statement that matches the type of exception. If it finds a match, controlled
is transferred to that statement otherwise next enclosing try block is checked, and
so on. If no matching catch is found then the default exception handler will halt the
program.
45
when an exception is thrown, Java looks for the nearest matching catch block. If it doesn’t
find one in the current method, it propagates upward through the call stack. If no matching
catch is found anywhere, the Java Virtual Machine (JVM) handles it and terminates the
program.
THROWS:
throws is a keyword in Java that is used in the signature of a method to
indicate that this method might throw one of the listed type exceptions.
The caller to these methods has to handle the exception using a try-catch
block.
In a program, if there is a chance of raising an exception then the compiler
always warns us about it and compulsorily we should handle that checked
exception, Otherwise, we will get compile time error saying unreported
exception XXX must be caught or declared to be thrown. To prevent
this compile time error we can handle the exception in two ways:
1. By using try catch
2. By using the throws keyword
46
throws keyword is required only for checked exceptions and usage
of the throws keyword for unchecked exceptions is meaningless.
throws keyword is required only to convince the compiler and usage
of the throws keyword does not prevent abnormal termination of the
program.
With the help of the throws keyword, we can provide information to
the caller of the method about the exception.
Hierarchy of Exception:
Other than RunTime Exception, all exceptions are called compiled Time or
hecked Exceptions.
47
Throwable : superclass => Object
=> [Link]()
=> [Link]()
=> [Link]()
Part –II
48
may constitute a resource leak and also the program could exhaust the
resources available to it.
By this, now we don’t need to add an extra finally block for just passing
the closing statements of the resources.
Syntax: Try-with-resources
try(declare resources here) {
// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
Exceptions:
When it comes to exceptions, there is a difference in try-catch-finally
block and try-with-resources block. If an exception is thrown in both try
block and finally block, the method returns the exception thrown in
finally block.
For try-with-resources, if an exception is thrown in a try block and in a
try-with-resources statement, then the method returns the exception
thrown in the try block. The exceptions thrown by try-with-resources are
suppressed, i.e. we can say that try-with-resources block throws
suppressed exceptions.
import [Link].*;
class GFG {
49
// Adding resource
FileOutputStream fos
= new FileOutputStream("[Link]"))
{
// Custom string input
String text
= "Hello World. This is my java program";
Output:
Resource are closed and message has been written into the
[Link]
50
try-with-resources With Multiple Resources
Resources that were defined/acquired first will be closed last. Let’s look at
an example of this behavior
51
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught an
ArrayIndexOutOfBoundsException: " + [Link]());
}
catch (ArithmeticException e) {
[Link]("Caught an ArithmeticException: " +
[Link]());
}
catch (Exception e) {
[Link]("Caught a generic Exception: " +
[Link]());
}
finally {
[Link]("Finally block executed.");
}
}
}
Multiple Exceptions in Single Catch block:
public class MultiCatchExample {
public static void main(String[] args) {
try {
String str = null;
[Link]([Link]()); // This will throw
NullPointerException
int result = 10 / 0; // This would throw ArithmeticException
if reached
}
catch (NullPointerException | ArithmeticException e) {
[Link]("Caught an exception: " +
[Link]().getSimpleName() + " - " + [Link]());
}
finally {
[Link]("Finally block executed.");
}
}
}
Output: Caught an exception: NullPointerException - Cannot invoke
"[Link]()" because "str" is null
If the JVM crashes or the process is forcefully killed, the finally block may not run.
try {
while(true) {} // Infinite loop
} finally {
[Link]("Finally block"); // Never reached
}
This class extends Exception, making it a checked exception. To make it an unchecked exception,
extend RuntimeException instead.
53
public class TestCustomException {
} else {
try {
} catch (InvalidAgeException e) {
Files
54
import [Link];
import [Link];
import [Link];
[Link]([Link]([Link]()));
55
File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays\\
[Link]");
// [Link]([Link]());
File f2 = new File([Link]()+"/[Link]");
[Link]();
}
}
1.
isFile() Boolean
isDirectory() Boolean
56
length() Long Returns the size of the file in bytes
EOF== -1 (here)
FileInputStream
Type – I:
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
57
}
}
Output:
Hello Prasanna
How are you?
Type-II
//Store in String and then print entire text.
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
}
[Link](textString);
}
}
Output:
Hello Prasanna
How are you?
Scanner
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
58
[Link]();
}
while( [Link]()) {
[Link]([Link]());
}
}
}
similarly if you want to take string
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws
IOException
{
}
[Link](textString);
}
}
Type _II
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
59
public static void main(String[] args)throws IOException
{
}
[Link](textString);
}
}
FileReader
Reads the data character by character similar to the
FileInputStream
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
int asciicode;
String textString = new String();
while((asciicode=[Link]())!=-1) {
textString +=[Link]((char)asciicode);
}
[Link](textString);
60
}
BufferReader
// reads by character
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
}
[Link](textString);
}
}
Type-2
// Read line by line because it has readLine()->
return type: String
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
61
[Link]();
}
BufferedReader bReader=new BufferedReader(new
FileReader(f));
String lineString=new String();
while((lineString= [Link]())!=null) {
[Link](lineString);
}
}
}
Type-3
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{
}
}
FileOutputStream
import [Link];
62
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws
IOException
{
63
FileWriter
Type-I:
public class Mains {
public static void main(String[] args)throws IOException
{
}
}
Type-II
public class Mains {
public static void main(String[] args)throws IOException
{
}
}
Type-III
public class Mains {
public static void main(String[] args)throws IOException
{
}
}
64
BufferdReader(similar to FileReader)
}
}
Update the file
public class Mains {
public static void main(String[] args)throws IOException
{
}
}
65
66