[Go to site: main page, start]

0% found this document useful (0 votes)
24 views66 pages

Java Notes

This document provides comprehensive notes on Java programming, covering topics such as variable types (instance, class/static, and local variables), constructors (default and parameterized), and jagged arrays. It explains the characteristics and behaviors of different variable types, the concept of constructor overloading, and includes code examples for clarity. Additionally, it discusses string handling, static vs non-static elements, and memory management in Java.

Uploaded by

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

Java Notes

This document provides comprehensive notes on Java programming, covering topics such as variable types (instance, class/static, and local variables), constructors (default and parameterized), and jagged arrays. It explains the characteristics and behaviors of different variable types, the concept of constructor overloading, and includes code examples for clarity. Additionally, it discusses string handling, static vs non-static elements, and memory management in Java.

Uploaded by

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

JAVA NOTES

 Java is a Statical-typed Language.


---> which means when we declared or initialized a variable it must be
assign data types.

 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].*;

public class Main {

// this instance variable is visible for any child class.

public String name;

1
// salary variable is visible in Main class only.

private double salary;

// The name variable is assigned in the constructor.

public Main (String empName) {

name = empName;

// The salary variable is assigned a value.

public void setSalary(double empSal) {

salary = empSal;

// This method prints the employee details.

public void printEmp() {

[Link]("name : " + name );

[Link]("salary :" + salary);

public static void main(String args[]) {

Main empOne = new Main("Ransika");

[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]

Java Local Variables

 Local variables are declared in methods, constructors, or blocks.


 Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
 Access modifiers(Static) cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or
block.

 Local variables are implemented at stack level internally.


 There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.

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]();
}
}

public class Test {


public void pupAge() {
int age; age = age + 7;
[Link]("Puppy age is : " + age);
}
public static void main(String args[])
{ Test test = new Test(); [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.

Types of Java Constructors


2 Types
(1. Default Constructor or Implicit Constructor and
2. Explicit Constructor(No-args constructor, Parameterized Constructor) )

1. Default Constructor or Implicit Constructor


If you do not create any constructor in the class, Java provides a
default constructor that initializes the object.
Example:
public class Main {
int num1;
int num2;
public static void main(String[] args) {
// We didn't created any structure
// a default constructor will invoke here
Main obj_x = new Main();
// Printing the values
[Link]("num1 : " + obj_x.num1);
[Link]("num2 : " + obj_x.num2);
}}

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.

public class Main {


int num1;
int num2;
// Creating no-args constructor
Main() {
num1 = -1;
num2 = -1;
}
public static void main(String[] args) {
// no-args constructor will invoke
Main obj_x = new Main();
// Printing the values
[Link]("num1 : " + obj_x.num1);
[Link]("num2 : " + obj_x.num2);
}
}

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.

public class Main {


int num1;
int num2;
// Creating parameterized constructor
Main(int a, int b) {
num1 = a;
num2 = b;
}
public static void main(String[] args) {
// Creating two objects by passing the values
// to initialize the attributes.
// parameterized constructor will invoke
Main obj_x = new Main(10, 20);
Main obj_y = new Main(100, 200);

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

Constructor Overloading in Java


Constructor overloading means multiple constructors in a class. When you
have multiple constructors with different parameters listed, then it will be
known as constructor overloading.

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}
};

// Program to demonstrate 2-D jagged array in Java

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

--------------------------------------------------------------------------------------------

For Each Loop:


for(datatype varName: array or Collection){

// Only increments always…….

--------------------------------------------------------------------------------------------

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 s1=”hello”; # creates this string in String Pool (which is


one part of Heap )

=> String s2=new String(“hello”); # creates in heap, which is outside


the string pool.

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

*** s2==s4 # false


Heap Memory

10
Heap String Pool
abc
abc

abc wel

S3
S1

String methods:
[Link](s2)

[Link](“ string or char”) # True or False

[Link](“ string or char”) # True or False

[Link](“ string or char”) # True or False


[Link]() # ignore cases

[Link]()

[Link]() # leading and ending spaces are removed.

[Link]()

[Link]()

10. [Link]()

11. [Link](‘’string or char’’) # if sting or char not present it returns -1

[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] Class .valueOf(s1) #int a=[Link](s1)

[Link]()

[Link]()

Static and Non- Static:


The static keyword in Java is used for memory management mainly.

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 we do experiment with the non- static member


import [Link];
public class Main
{ 13
int num;
public static void main(String[] args) {
Main m1= new Main();
output:
-1265694953
-886828179
1770642822

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

Main m2= new Main();


[Link]=new Random().nextInt();

Main m3= new Main();


[Link]=new Random().nextInt();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}

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.

when static is there , there is no object creation concept


then above code as follows:

import [Link];

public class Main

static int num;

public static void main(String[] args) {

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

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");
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

*******************************************************************************

public class Main


{
int num;
static{
[Link](" static block");
}
{
[Link](" non-static block");
}
public Main(){
[Link](" constructor");

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

Program of the counter without static variable


class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
[Link](count);
}
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}}
Output: 1 1 1

Program of counter by static variable

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

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


• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it

Type Inference:
It is a concept in which the compiler infers the type of the variable using the value
provided.

. This type Inference is restricted(use) to local variables

. After java 10 , var keyword is valid.

Example:

1. var i=20000(correct)

20
2. var j;

j=2000; (incorrect, var supports only for the single line initialization)
Rules:

1. Used with local variables only.


2. Can not be used for only declaration purpose
3. When Used with arrays , should not use [] bracket
Int var=10; ( valid this keyword used as variable name)
var var=10;(valid)
var[] arr=new int[5]; (Invalid)
var arr=new int[5]; (valid)

var arr={1,2,3} (Invalid)


var arr=new int[]{1,2,3} (Valid)
4. Cannot used in In-Line array initialization specifying datatype
5. Don’t use var in parameters.

OOPS CONCEPT:

Everything is Object.
Priciples of OOPS:

1. Inheritance

2. Encapsulation

3. Polymorphism

4. Abstraction

Java is Object Oriented Programming not Object Based( absence of


inheritance).

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");
}
}

class Two extends One {


public void print_for() { [Link]("for"); }
}

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

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
[Link]("Geeks");
}}
// Child class Two inherits from class One
class Two extends One {
// Method to print "for"
public void print_for() {
[Link]("for");
}}
// Child class Three inherits from class Two
class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
[Link]("Geeks"); }}

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

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();

24
}
}
Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.

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

// Interface 1 that defines coding behavior


interface Coder {
void writeCode();
}

// Interface 2 that defines testing behavior


interface Tester {
void testCode();
}

// Class implementing both interfaces


class DevOpsEngineer implements Coder, Tester {
@Override
public void writeCode() {
[Link]("DevOps Engineer writes automation scripts.");
}

25
@Override
public void testCode() {
[Link]("DevOps Engineer tests deployment pipelines.");
}

// Additional method specific to DevOpsEngineer


public void deploy() {
[Link]("DevOps Engineer deploys code to cloud.");
}
}

// 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

The characteristics of the super keyword are listed below:


 Calling the Parent Class Constructor: When we create an object of the
subclass, its constructor needs to call the constructor of the parent class. This
can be done with the help of the super keyword, and it calls the constructor of
the parent class.
 Accessing Parent Class Methods: If the subclass wants to access the
methods of the parent class, it can also be done with the help of the super
keyword.
 Accessing Parent Class Fields: Fields from the parent class can also be
accessed using the super keyword in the subclass.
 First Statement in a Constructor: When calling a superclass constructor, the
super() statement must be the first statement in the constructor of the subclass.

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");
}

// Note that display() is


// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();
// will invoke or call parent
// class message() method
[Link]();
}
}
// Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
[Link]();
}
}
Output

This is student class


This is person class
Firstly , it checks message() method in the sub class, if it is not there then it looks for
Parent class message(). Even though we have message() in both parent and child, when
we put super keyword then it checks in Parent class only.
Use of super with Constructors
The super keyword can also be used to access the parent class constructor. One
more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending on the situation.

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");
}
}

// subclass Student extending the Person class


class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();

[Link]("Student 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

final The class cannot be inherited by other classes

abstrac The class cannot be used to create objects (To access an


t abstract class, it must be inherited from another class.

For attributes and methods, you can use the one of the following:

30
Modifier Description

final Attributes and methods cannot be overridden/modified

static Attributes and methods belongs to the class, rather than an


object

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

transient Attributes and methods are skipped when serializing the


object containing them

synchronize Methods can only be accessed by one thread at a time


d

volatile The value of an attribute is not cached thread-locally, and is


always read from the "main memory"

31
Encapsulation:

It is a mechanism of wrapping the data (variables) and code acting on the


data (methods) together as a single unit
The ability of an object hide its data and methods from the rest of the
world
Real time example: class(wraps variables and methods),object.
// Java program demonstrating Encapsulation
class Programmer {
private String name;
// Getter and Setter for name
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
}
public class Geeks {
public static void main(String[] args) {
Programmer p = new Programmer();
[Link]("Geek");
[Link]("Name=> " + [Link]());
}

32
}
Output
Name=> Geek

Interfaces(em cheyyalo(What todo)( is-a)


relation:
it cannot be instantiated.
It is blueprint of a Class(em cheyyalo +ela cheyyalo(how to do)).
Business Document(how to do)
Implementation is absent.
Defined or unimplemented methods are known as abstract methods.
All methods in interface are public abstract by default.
Public,private,static,default keywords are used .
interface Drawable{
void draw();
default void msg(){[Link]("default method");}
}
class Rectangle implements Drawable{
public void draw(){[Link]("drawing rectangle");}
}
public class Main{
public static void main(String args[]){
Drawable d=new Rectangle();
[Link]();
[Link]();
}
}
Output:
drawing rectangle
default method

Here , Until java 7, we have interfaces(“how to do only”: Method


declaration)which contains unimplemented methods and abstract methods
and variables only.
Then java 8:” What to do” concept also introduced in interfaces.( due tlo
Stream API and Collection(List Interface,..)) which means you can implement
the method in interfaces.
Whenever you add new declared method in the interface(business document)
then all the classes (extended the interface) are effected(got errors)because
you did not provide any implementation for the new declared method in any
classes.
This can be done by using [Link] method and 2. Static method.

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.

STATIC: [Link](). This method chooses that implementation


also uses outside the world .

In Interfaces, non-static methods are not call in static methods.


Whereas static methods are call in non-static methods just like
classes.

o Since Java 9, we can have private methods in an interface.


o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple
inheritance.
o It is used to achieve loose coupling.

interface Animal {

34
void eat();
void sleep();
}

Internal Addition by The Compiler


The Java compiler adds the public and abstract keywords before the
interface method. Moreover, it adds public, static and final keywords
before data members.

In other words, Interface fields are public, static and final by default, and
the methods are public and abstract.

Java 8 Default Method in Interface


Since Java 8, we can have method body in interface. But we need to make
it default method. Let's see an example:

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

In Java 9, Interfaces have introduced Private methods:


Avoid code duplication ,allows reusability
Inside the Interfaces, private methods are used for code Reuseability
which means the commaon code between defaut methods and static methods
are written in 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.

Can we call private methods in static method in interface?

Yes, By using Private Static

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

Abstract class Requirement is occurred, before Java 8 we have


interfaces

Which contains only abstract methods not contains


implemented methods. So that y we can provide some
implemented methods in abstract class.
It is not a fully class and fully interface, this is called abstract
class

Non Access Modifier-----abstract keyword

Code reuseability <<Laptop>>


Void copy();
Void paste();
Abstract class<Sampleabst> Void cut();
implements Laptop{ 37
Void keyboard();
Public void copy(){ sysout(“copy in
laptop”) }
Public void paste(){ sysout(“paste
Class <Lenovo> extends Sampleabst{

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

Can we create an instance of a abstract class?


No ,we cannot, because it contains abstract methods and non- abstract
methods

Can we have non-abstract methods inside abstract class?

Yes , we have

Can we extend multiple abstract classes into a single class?

No, we cannot because multiple inheritance is not applicable at class


level

Class Lenovo extends Sampleabs,Sampleabs2: (error)

Can we implement the abstract class like an interface?

No,because we use extends keyword.

-----------------------------------------------------------------------------
--

Abstraction:
The process of hiding the implementation details and showing only
functionality to the user.

 Security
 Simplicity

In Encapsulation , hide only “data” , but in abstraction Implementation is


hiding.

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

// Concrete class implementing the abstract methods


class TVRemote extends Geeks {
@Override
void turnOn() {
[Link]("TV is turned ON.");
}

@Override
void turnOff() {
[Link]("TV is turned OFF.");
}
}

// Main class to demonstrate abstraction


public class Main {
public static void main(String[] args) {
Geeks remote = new TVRemote(); here Geeks is
abstract class
[Link](); we use object type
with abstract
[Link](); class
}
}
Output
TV is turned ON.
TV is turned OFF.

Polymorphism:
39
Many + Forms

Ability of an object to take on many forms.

Types of Polymorphism in Java


In Java Polymorphism is mainly divided into two types:
1. Compile-Time Polymorphism (Static)
2. Runtime Polymorphism (Dynamic )
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism and
also known as method overloading or early binding. This happens when multiple
methods in the same class have the same name but different parameters.
But Java doesn’t support the Operator Overloading.
Achieved at compilation time.
We can Change method type or number of parameters, order of
parameters; not focus on parameter name.

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 {

// Method of parent class


void Print() {
[Link]("parent class");
}
}

// 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 {

// Main driver method


public static void main(String[] args) {

// Creating object of class 1


Parent a;

// Now we will be calling print methods


// inside main() method
a = new subclass1();
[Link]();

a = new subclass2();
[Link]();
}
}
Output
subclass1
subclass2

Is it necessary to use @override ?


No, it is not: but it is used to identify errors at compiler time.

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.

It occurs when something unexpected happens, like accessing an


invalid index, dividing by zero, or trying to open a file that does not
exist.
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
int ans = n / m;
[Link]("Answer: " + ans);
}
}

Stack trace : it contains exception name,message,line number,


method info

 Checked Exception: These exceptions are checked at compile time,


forcing the programmer to handle them explicitly.
 Unchecked Exception: These exceptions are checked at runtime and
do not require explicit handling at compile time.

42
Difference Between Checked and Unchecked
Exceptions
Feature Checked Exception Unchecked Exception

Behavi Checked exceptions are Unchecked exceptions are


our checked at compile time. checked at run time.

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.

Checked exceptions must be


handled using a try-catch
block or must be declared using
the throws keyword. If a
method throws a checked
Exception, then the No handling is required
exception must be handled
Handlin using a try-catch block and
g declared the exception in
Requir the method signature using
ement the throwS keyword.

Exampl IOException, SQLException, Fil NullPointerException, ArrayIndex


es eNotFoundException. OutOfBoundsException.

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
}

Feature throw throws

It is used to declare that a


It is used to explicitly throw an
method might throw one
exception.
Definition or more exceptions.

It is used inside a method or a It is used in the method


Location block of code. signature.

It is only used for


It can throw both checked and checked exceptions.
unchecked exceptions. Unchecked exceptions do
Usage not require throws

The method’s caller is


The method or block throws the
responsible for handling
exception.
Responsibility the exception.

It forces the caller to


Flow of Stops the current flow of
handle the declared
execution immediately.
Execution exceptions.

Example throw new public void myMethod()

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
}
}

public static void main(String args[])


{
try {
fun();
}
catch (NullPointerException e) {
[Link]("Caught in main.");
}
}
}

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

// Demonstrating how to throw an exception


class Geeks {
static void fun() throws IllegalAccessException
{
[Link]("Inside fun(). ");
throw new IllegalAccessException("demo");
}

public static void main(String args[])


{
try {
fun();
}
catch (IllegalAccessException e) {
[Link]("Caught in main.");
}
}
}
Output
Inside fun().
Caught in main.

The above example throwing a IllegalAccessException from a method


and handling it in the main method using a try-catch block.

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:

In Exception we have , RuntimeException…

Other than RunTime Exception, all exceptions are called compiled Time or
hecked Exceptions.

47
Throwable : superclass => Object

Interface => Serializable.

=> [Link]()

=> [Link]()

=> [Link]() # returns the array

=> [Link]()

Part –II

Try with resources:


In Java, the "try-with-resources" statement is a feature introduced in Java 7
that simplifies resource management, ensuring that resources like files or
network connections are properly closed after use. It automatically closes
resources that implement the AutoCloseable interface, eliminating the need
for explicit finally blocks.

In Java, the Try-with-resources statement is a try statement


that declares one or more resources in it. A resource is an object that
must be closed once your program is done using it. For example, a File
resource or a Socket connection resource.

The try-with-resources statement ensures that each resource is closed


at the end of the statement execution. If we don’t close the resources, it

48
may constitute a resource leak and also the program could exhaust the
resources available to it.

You can pass any object as a resource that


implements [Link],(Interface) which includes all
objects which implement [Link].(Inteface)

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 {

public static void main(String[] args)


{
// Try block to check for exceptions
try (

// Creating an object of FileOutputStream


// to write stream or raw data

49
// Adding resource
FileOutputStream fos
= new FileOutputStream("[Link]"))
{
// Custom string input
String text
= "Hello World. This is my java program";

// Converting string to bytes


byte arr[] = [Link]();

// Text written in the file


[Link](arr);
}

// Catch block to handle exceptions


catch (Exception e) {

// Display message for the occurred exception


[Link](e);
}

// Display message for successful execution of


// program
[Link](
"Resource are closed and message has been written
into the [Link]");
}
}

Output:
Resource are closed and message has been written into the
[Link]

50
try-with-resources With Multiple Resources

try (Scanner scanner = new Scanner(new File("[Link]"));


PrintWriter writer = new PrintWriter(new
File("[Link]")))
{
while ([Link]()) { [Link]([Link]());
} }

A Custom Resource With AutoCloseable


To construct a custom resource that will be correctly handled by a try-with-
resources block, the class should implement
the Closeable or AutoCloseable interfaces and override the close method:

public class MyResource implements AutoCloseable {


@Override
public void close() throws Exception {
[Link]("Closed MyResource");
}
}

Resource Closing Order(stack)

Resources that were defined/acquired first will be closed last. Let’s look at
an example of this behavior

Try with multiple Catch Block:


public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
[Link]("Number: " + numbers[5]); // This will
throw ArrayIndexOutOfBoundsException
int result = 10 / 0; // This would throw ArithmeticException
if executed not executed.

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

Finally block executed.

When will Finally block is not executed ?

1 [Link]() is called before finally executes:


52
public class Example {
public static void main(String[] args) {
try {
[Link]("Inside try block");
[Link](0); // Terminates the JVM
} finally {
[Link]("Inside finally block"); //
This won't execute
}
}
}

3. JVM crashes (e.g., fatal error, power loss):

 If the JVM crashes or the process is forcefully killed, the finally block may not run.

4. Infinite loop or hang in try block:

try {
while(true) {} // Infinite loop
} finally {
[Link]("Finally block"); // Never reached
}

[Link] gets killed abruptly:

o If a thread running the try-finally block is forcefully terminated (e.g., using


[Link]() — now deprecated), finally may not execute.

Throw custom(user defined) exceptions using throw Keyword

Type-I: using Throw Keyword


Step 1: Create a Custom Exception Class
// Custom exception class
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);// here Exception extends
Throwable(constructor)
}
}

This class extends Exception, making it a checked exception. To make it an unchecked exception,
extend RuntimeException instead.

Step 2: Use throw to Throw the Custom Exception

53
public class TestCustomException {

public static void validateAge(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age must be 18 or older.");

} else {

[Link]("Access granted – age is valid.");

public static void main(String[] args) {

try {

validateAge(15); // Change the value to test different cases

} catch (InvalidAgeException e) {

[Link]("Caught custom exception: " + [Link]());

Output::Caught custom exception: Age must be 18 or older.

Files
54
import [Link];

import [Link];
import [Link];

public class Mains {


public static void main(String[] args)throws IOException
{
File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays\\
[Link]");# absolute path
File f=new File("./[Link]"); # relative path

[Link]( [Link]());//Here File is not


created yet, Instance of File class created
[Link]( [Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](true); // true--- writable, false--- not writable
# Folder Creation.
File f=new File("./Resources/");
[Link]([Link]());

## Multiple folder creations.


File f=new File("./Resources/Test1");
[Link]([Link]());

## Returns list of files as well as folders. Return type is array


File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays");
for(String filename:[Link]()){
[Link](filename+ " ");
}
Or

[Link]([Link]([Link]()));

## Returns full path name of each file in the directorys


File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays");
[Link]([Link]([Link]()));

## Returns file name


File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays\\
[Link]");
[Link]([Link]());

## Create new file with existing file using getParent()

55
File f=new File("C:\\Users\\HP\\Desktop\\Java_Prep\\Arrays\\
[Link]");
// [Link]([Link]());
File f2 = new File([Link]()+"/[Link]");
[Link]();

}
}

Some other methods:

1.

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

isFile() Boolean

isDirectory() Boolean

getAbsolutePath() String Returns the absolute pathname of the file

getParent() String Returns the parent folder of the file

56
length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

listFiles() String[] Returns full path of each files in the directory

mkdir() Boolean Creates a directory

mkdirs() Boolean Creates more than one directorys

lastModified() Boolean Lasts time modified the file(date and time)

EOF== -1 (here)

Different ways of reading the data from text files

 FileInputStream : (same as FileReader due to character reading)


 Scanner :
 FileReader : This class extends Reader class( Same as
FileInputStream due to character reading)
 BufferedReader : This class extends Reader class

FileInputStream
Type – I:
import [Link];
import [Link];
import [Link];
import [Link];
public class Mains {
public static void main(String[] args)throws IOException
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
FileInputStream fis = new FileInputStream(f);
int asciicode;
while((asciicode=[Link]())!=-1)
[Link]((char)asciicode);

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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
FileInputStream fis = new FileInputStream(f);
int asciicode;
String textString = new String();
while((asciicode=[Link]())!=-1) {
textString +=[Link]((char)asciicode);

}
[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
{

File f= new File("./[Link]");


if(![Link]()){

58
[Link]();
}

Scanner scanner=new Scanner(f);

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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}

Scanner scanner=new Scanner(f);


String textString=new String();
while( [Link]()) {
textString += [Link]()+ "\n";

}
[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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}

Scanner scanner=new Scanner(new FileInputStream(f));


String textString=new String();
while( [Link]()) {
textString += [Link]()+ "\n";

}
[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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
FileReader fReader = new FileReader(f);

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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
BufferedReader bReader=new BufferedReader(new
FileReader(f));
// Because FileReader indirectly extends Reader class.
// Performance is decrease in FileInputStream and
FileReader due to reads character at a time only
// Here The perforamance is high due to its internally
reads the lines .
int asciicode;
String textString = new String();
while((asciicode=[Link]())!=-1) {
textString +=[Link]((char)asciicode);

}
[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
{

File f= new File("./[Link]");


if(![Link]()){

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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
FileInputStream fis=new FileInputStream(f);
InputStreamReader inputStreamReader=new
InputStreamReader(fis);
BufferedReader bReader=new
BufferedReader(inputStreamReader);

String lineString=new String();


while((lineString= [Link]())!=null) {
[Link](lineString);
}

}
}

Different ways of writing the data into text files


 FileOutputStream
 FileWriter
 BufferedWriter
Flush() common method for all.

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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
FileOutputStream fileOutputStream=new
FileOutputStream(f);
[Link](75);
[Link](80);
}
}
Type-II
import [Link];
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
{

File f= new File("./[Link]");


if(![Link]()){
[Link]();
}
String string="Good Evening ";
FileOutputStream fileOutputStream=new
FileOutputStream(f);
for(char a: [Link]()) {
[Link]((int)a); # If we pass
integer , then it converts to char.
}
}}

63
FileWriter
Type-I:
public class Mains {
public static void main(String[] args)throws IOException
{

FileWriter myWriter = new FileWriter("[Link]");


[Link]("Files in Java might be tricky, but
it is funny enough!");
[Link]();
[Link]("Successfully wrote to the
file.");

}
}
Type-II
public class Mains {
public static void main(String[] args)throws IOException
{

FileWriter myWriter = new FileWriter("[Link]");


String string=" I am Prasanna..";
[Link](string);;
[Link]();
[Link]("Successfully wrote to the file.");

}
}

Type-III
public class Mains {
public static void main(String[] args)throws IOException
{

FileWriter myWriter = new FileWriter("[Link]");


String string=" I am Prasanna..";
[Link]([Link]());;
[Link]();
[Link]("Successfully wrote to the
file.");

}
}

64
BufferdReader(similar to FileReader)

public class Mains {


public static void main(String[] args)throws IOException
{

File f= new File("./[Link]");


if([Link]()){
[Link]();
}
[Link]();
String string="Good Night ";
BufferedWriter bwriter=new BufferedWriter(new FileWriter(f));
[Link](string);
[Link]();
[Link]();

}
}
Update the file
public class Mains {
public static void main(String[] args)throws IOException
{

File f= new File("./[Link]");


String existingTextString=new String();
String lineString="";
BufferedReader bReader=new BufferedReader(new
FileReader(f));
while((lineString=[Link]())!=null) {
existingTextString +=lineString+"\n";
}
String string=" Good Night ";
BufferedWriter bwriter=new BufferedWriter(new FileWriter(f));
[Link](existingTextString+string);
[Link]();
[Link]();

}
}

65
66

You might also like