0% found this document useful (0 votes)
14 views34 pages

JAVA_-_UNIT_2

The document provides an overview of Java's fundamental concepts including classes, objects, inheritance, methods, access specifiers, and modifiers. It explains how to create classes and subclasses, define data members and methods, and utilize access specifiers for data encapsulation. Additionally, it covers method and constructor overloading, the Java Class Library, control flow statements, arrays, strings, and inheritance, emphasizing their importance for structured and maintainable code.

Uploaded by

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

JAVA_-_UNIT_2

The document provides an overview of Java's fundamental concepts including classes, objects, inheritance, methods, access specifiers, and modifiers. It explains how to create classes and subclasses, define data members and methods, and utilize access specifiers for data encapsulation. Additionally, it covers method and constructor overloading, the Java Class Library, control flow statements, arrays, strings, and inheritance, emphasizing their importance for structured and maintainable code.

Uploaded by

SS GAMER
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

2️⃣

JAVA - UNIT 2
Summary of Pages 1-3 (Unit II: Classes, Objects, and Inheritance)

1. Creating a Class and Subclass


1. Declaring a Class:

Use the class keyword to define a class.

Example:

public class MyClass {


// Fields and methods
}

2. Naming a Class:

Must start with a letter or underscore, and it is case-sensitive.

Example: MyClass is different from myclass .

3. Creating a Subclass:

Subclasses inherit the properties and methods of a superclass using the


extends keyword.

Example:

public class SubClass extends SuperClass {


// Additional subclass features
}

2. Data Members (Fields)


Fields represent the state of an object, holding data within a class.

Example:

public class MyClass {


int myInt;
String myString;
double myDouble;
}

Naming Variables:

Use meaningful names, starting with a lowercase letter.

Constants should be in ALL_CAPS .

JAVA - UNIT 2 1
Using Class Members:

Access data members using the dot ( . ) operator.

Example:

MyClass obj = new MyClass();


int num = obj.myInt;

3. Methods
Invoking Methods:

Methods are functions that define behavior.

Example:

public class MyClass {


public void display() {
System.out.println("Hello");
}
}

Passing Arguments to Methods:

Methods can accept parameters to process data.

Example:

public void printValue(int value) {


System.out.println(value);
}

Method Overloading:

Define multiple methods with the same name but different parameters.

Example:

public int add(int a, int b) {


return a + b;
}
public double add(double a, double b) {
return a + b;
}

4. Access Specifiers and Modifiers


Default: Accessible within the same package.

Public: Accessible everywhere.

Private: Accessible only within the same class.

JAVA - UNIT 2 2
Protected: Accessible in the same package or subclasses.

5. Static and Final Modifiers


Static: Belongs to the class rather than an instance.

Final: Cannot be changed (for variables), cannot be overridden (for methods),


or subclassed (for classes).

6. Constructor Overloading
You can have multiple constructors with different parameters.

Example:

public class Person {


public Person() { ... }
public Person(String name) { ... }
}

7. Java Class Library


Abstract Classes: Cannot be instantiated and may contain abstract methods.

Interfaces: Contain only method signatures; classes implement them.

Conclusion
Mastering classes, objects, inheritance, access specifiers, and method
overloading is essential for Java programming. These foundational concepts
allow for structured, reusable, and maintainable code.

Summary of Pages 3-6 (Java Methods, Overloading, and Access


Specifiers)

3. Methods
In Java, methods define the behavior of an object. They are blocks of code that
perform a specific task and can be invoked when needed.

1. Using Data Members:

Data Members (fields or attributes) are variables declared within a class


that hold data associated with an object.

Example:

public class MyClass {


int myInt;
String myString;

public void printValues() {


System.out.println("Integer: " + myInt);
System.out.println("String: " + myString);

JAVA - UNIT 2 3
}
}

2. Invoking Methods:

Methods are called using the dot ( . ) operator on an instance of a class.

Example:

MyClass obj = new MyClass();


obj.printValues(); // Calls the method

3. Passing Arguments to Methods:

Methods can accept parameters (arguments) to perform actions on input


data.

Example:

public void printValue(int value) {


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

4. Calling a Method:

Create an object of the class and call the method using the dot ( . )
operator.

Example:

MyClass obj = new MyClass();


obj.printValue(20); // Calls method with argument 20

4. Access Specifiers and Modifiers


Access specifiers in Java control the visibility and accessibility of classes,
methods, and variables.

1. Default (Package-Private):

Members are accessible within the same package but not from outside the
package.

Example:

class MyClass { // Default access


int myVar; // Default access
}

2. Public:

The public access modifier allows access from anywhere, even outside
the package.

JAVA - UNIT 2 4
Example:

public class MyClass {


public int myVar;
}

3. Private:

The private access modifier restricts access to the same class only.

Example:

public class MyClass {


private int myVar;
}

4. Protected:

The protected access modifier allows access within the same package and
by subclasses, even if they are in different packages.

Example:

public class MyClass {


protected int myVar;
}

5. Static and Final Modifiers


1. Static:

The static keyword is used for class-level members (methods or


variables), which are shared among all instances of a class.

Example:

public class MyClass {


public static int myStaticVar;
public static void myStaticMethod() {
System.out.println("Static method");
}
}

2. Final:

The final keyword makes a class, method, or variable unchangeable.

Example:

Final class: A class that cannot be subclassed.

public final class MyFinalClass { }

JAVA - UNIT 2 5
Final variable: A variable that cannot be reassigned.

public final int MY_CONSTANT = 100;

6. Method Overloading
Method overloading allows multiple methods with the same name but different
parameters (number or types) in a class.

1. Example of Method Overloading:

public class MathUtils {


// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}

// Method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}
}

Here, the add method is overloaded with different parameter types and
numbers, allowing flexibility in its use.

7. Constructor Overloading
Constructor overloading allows multiple constructors with the same name but
different parameter lists.

1. Example of Constructor Overloading:

public class Person {


private String name;
private int age;

// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}

// Constructor with name


public Person(String name) {

JAVA - UNIT 2 6
this.name = name;
this.age = 0;
}

// Constructor with name and age


public Person(String name, int age) {
this.name = name;
this.age = age;
}
}

Conclusion
Methods, access specifiers, static/final modifiers, and overloading are core
concepts in Java for managing object behavior and visibility.

Overloading methods and constructors improves code flexibility and


reusability, while access control ensures proper encapsulation of data.

Summary of Pages 6-9 (Access Modifiers, Overloading, and


Inheritance)

6. Java Class Library


In Java, classes serve different purposes based on how they are defined and
used. Here are common types of classes in Java:

1. Regular Class:

A basic class with fields, methods, and constructors.

Example:

public class MyClass {


private int myField;

public MyClass(int value) {


myField = value;
}

public void doSomething() {


// Some action
}
}

2. Abstract Class:

Cannot be instantiated and often contains abstract methods that must be


implemented by subclasses.

Example:

JAVA - UNIT 2 7
public abstract class Shape {
abstract double area();
}

3. Interface:

Defines a contract for classes that implement it, specifying methods


without implementations.

Example:

public interface Drawable {


void draw();
}

4. Enum:

Represents a fixed set of constants.

Example:

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDA
Y, SATURDAY
}

5. Inner Class (Nested Class):

A class defined within another class, with access to the outer class's
members.

Example:

public class Outer {


private int outerField;

public class Inner {


public void doSomething() {
outerField = 42;
}
}
}

6. Static Nested Class:

A nested class without a reference to the outer class.

Example:

public class Outer {


private static int outerField;

JAVA - UNIT 2 8
public static class StaticNested {
public void doSomething() {
outerField = 42;
}
}
}

7. Decision Making & Loops


Java provides various control flow statements to manage the execution of code.

1. If-Then-Else:

Executes code based on a condition.

Example:

int number = 10;


if (number > 5) {
System.out.println("Number is greater than 5.");
} else {
System.out.println("Number is not greater than
5.");
}

2. Switch Statement:

Used for multi-branching based on the value of an expression.

Example:

int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
default:
System.out.println("Invalid day");
}

3. Ternary Operator:

A shorthand for the if-then-else statement.

Example:

int number = 10;


String result = (number > 5) ? "Greater than 5" : "Not

JAVA - UNIT 2 9
greater than 5";

4. While Loop:

Executes a block of code repeatedly as long as the condition is true.

Example:

int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}

5. Do-While Loop:

Executes the code at least once before checking the condition.

Example:

int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);

6. For Loop:

Iterates over a range of values.

Example:

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


System.out.println("Iteration: " + i);
}

7. For-Each Loop (Enhanced For Loop):

Used to iterate through collections like arrays or lists.

Example:

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


for (int number : numbers) {
System.out.println("Number: " + number);
}

8. Arrays
Arrays in Java are used to store collections of elements of the same type.

1. One-Dimensional Array:

JAVA - UNIT 2 10
A simple list of elements.

Example:

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

2. Two-Dimensional Array:

An array that represents a table with rows and columns.

Example:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3. Initializing Arrays:

You can initialize arrays during declaration or afterward.

Example:

int[] numbers = new int[5]; // Creates an array of size


5
numbers[0] = 1;

Conclusion
Java offers a variety of class types (regular, abstract, interfaces) and control
flow structures (if-else, loops, arrays) that enable structured and flexible
program development.

Mastering loops, arrays, and different types of classes will enhance your
ability to create more dynamic and efficient programs.

Summary of Pages 9-12 (Arrays, Strings, and Inheritance in Java)

8. Arrays (Continued)
Arrays in Java are a fundamental data structure that allows for storing multiple
elements of the same type.

1. Creating an Array:

Arrays can be created and initialized in one step or initialized after


declaration.

Example:

int[] numbers = {1, 2, 3, 4, 5}; // Declaration and in


itialization in one step
int[] numbers = new int[5]; // Declaration, then

JAVA - UNIT 2 11
initialization
numbers[0] = 1;
numbers[1] = 2;

2. Two-Dimensional Array:

A two-dimensional array represents a table (matrix) of rows and columns.

Example:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3. Initializing Arrays After Declaration:

Arrays can also be initialized using loops or by reading values from input.

Example:

int[] numbers = new int[5];


for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}

9. Strings in Java
A String in Java is an object that represents a sequence of characters. Strings are
widely used for handling textual data.

1. String Array:

A string array holds references to string objects.

Example:

String[] names = {"Alice", "Bob", "Charlie"};

2. Common String Methods:

length(): Returns the number of characters in the string.

String str = "Hello";


int length = str.length(); // 5

charAt(int index): Returns the character at the specified index.

char ch = str.charAt(0); // 'H'

JAVA - UNIT 2 12
substring(int beginIndex): Returns a substring starting from the specified
index.

String sub = str.substring(1); // "ello"

indexOf(String str): Returns the index of the first occurrence of the


specified substring.

int index = str.indexOf("l"); // 2

toUpperCase() and toLowerCase(): Converts all characters to upper or


lower case.

String upper = str.toUpperCase(); // "HELLO"

equals(String another) and equalsIgnoreCase(String another):


Compares two strings for equality.

boolean isEqual = str.equals("hello"); // false


boolean isEqualIgnoreCase = str.equalsIgnoreCase("hell
o"); // true

3. String Split:

The split(String regex) method splits a string into an array of substrings


based on a regular expression.

Example:

String str = "Hello,World";


String[] parts = str.split(","); // {"Hello", "World"}

10. Inheritance
Inheritance is a fundamental concept in Java's object-oriented programming,
allowing one class to inherit properties and behaviors from another class.

1. Single Inheritance:

In Java, a class can inherit from only one superclass (single inheritance).

Example:

class Parent {
// Parent class members
}

class Child extends Parent {


// Child class inherits from Parent
}

JAVA - UNIT 2 13
2. Multiple Inheritance through Interfaces:

While a class cannot extend more than one class, it can implement
multiple interfaces.

Example:

interface A {
void methodA();
}

interface B {
void methodB();
}

class MyClass implements A, B {


public void methodA() {
// Implementation for methodA
}

public void methodB() {


// Implementation for methodB
}
}

3. Hierarchical Inheritance:

Occurs when multiple classes inherit from the same superclass.

Example:

class Parent {
// Parent class members
}

class Child1 extends Parent {


// Child1 inherits from Parent
}

class Child2 extends Parent {


// Child2 inherits from Parent
}

4. Multilevel Inheritance:

A class inherits from a class, which in turn inherits from another class,
creating a chain.

Example:

JAVA - UNIT 2 14
class Grandparent {
// Grandparent class members
}

class Parent extends Grandparent {


// Parent class inherits from Grandparent
}

class Child extends Parent {


// Child inherits from Parent
}

5. Hybrid Inheritance (Not Supported by Java):

Hybrid inheritance combines multiple types of inheritance, such as single


and multiple inheritance. Java does not support hybrid inheritance directly
due to complexities and the "diamond problem."

Conclusion
Java arrays and strings are foundational tools for managing collections of data
and textual information.

Inheritance, whether single or multilevel, is key to promoting code reusability


and creating organized class hierarchies. Through inheritance, developers can
efficiently build upon existing code, leading to more scalable and maintainable
applications.

Summary of Pages 12-15 (Polymorphism, Abstract Classes,


Interfaces, and More on Inheritance)

11. Polymorphism in Java


Polymorphism is one of the core concepts of object-oriented programming (OOP)
in Java, allowing a single action to behave differently based on the object that
performs it.

1. Compile-Time Polymorphism (Method Overloading):

Achieved by defining multiple methods with the same name but different
parameters within a class.

Example:

public class Calculator {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;

JAVA - UNIT 2 15
}
}

2. Run-Time Polymorphism (Method Overriding):

Achieved when a subclass provides a specific implementation of a method


that is already defined in its superclass.

Example:

class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound(); // Output: Dog barks
}
}

3. Advantages of Polymorphism:

Flexibility: The same method can behave differently based on the object.

Reusability: Promotes code reuse by allowing methods to be shared


between classes through inheritance.

12. Abstract Classes


An abstract class in Java is a class that cannot be instantiated and may contain
abstract methods (methods without implementation).

1. Characteristics of Abstract Classes:

Abstract classes are declared with the abstract keyword.

They can have both abstract and non-abstract (concrete) methods.

A class that extends an abstract class must provide implementations for all
its abstract methods, or it must be declared abstract itself.

2. Example of an Abstract Class:

JAVA - UNIT 2 16
abstract class Animal {
abstract void makeSound(); // Abstract method

public void eat() {


System.out.println("This animal eats food");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Dog barks");
}
}

3. When to Use Abstract Classes:

When you want to define a base class with common functionality for its
subclasses, while some methods must be implemented by the subclasses.

13. Interfaces in Java


An interface in Java is a reference type that defines a contract for classes to
implement. It contains abstract methods and can contain constants.

1. Characteristics of Interfaces:

All methods in an interface are abstract (until Java 8, where default


methods were introduced).

A class can implement multiple interfaces, allowing for multiple inheritance


of behavior.

Interfaces are declared using the interface keyword.

2. Example of an Interface:

interface Flyable {
void fly(); // Abstract method
}

class Bird implements Flyable {


public void fly() {
System.out.println("Bird is flying");
}
}

3. Default Methods in Interfaces (Java 8 and later):

Default methods allow interfaces to provide method implementations.

Example:

JAVA - UNIT 2 17
interface Flyable {
void fly();
default void land() {
System.out.println("Landing safely");
}
}

4. Difference Between Abstract Class and Interface:

Abstract Class: Can have both abstract and concrete methods, and a
class can only extend one abstract class.

Interface: Can only have abstract methods (until Java 8), and a class can
implement multiple interfaces.

14. Super Keyword


The super keyword in Java refers to the superclass of the current object. It is used
to:

1. Call Superclass Methods: When a subclass overrides a method, super can


call the superclass version of the method.

Example:

class Animal {
public void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
public void sound() {
super.sound(); // Calls the Animal's sound met
hod
System.out.println("Dog barks");
}
}

2. Call Superclass Constructor: The super() call can be used to invoke the
constructor of the superclass.

Example:

class Animal {
Animal() {
System.out.println("Animal constructor");
}
}

JAVA - UNIT 2 18
class Dog extends Animal {
Dog() {
super(); // Calls Animal constructor
System.out.println("Dog constructor");
}
}

15. Final Keyword


The final keyword in Java is used to apply restrictions on classes, methods, and
variables.

1. Final Class: Cannot be subclassed.

Example:

public final class FinalClass { }

2. Final Method: Cannot be overridden by subclasses.

Example:

class Parent {
public final void display() {
System.out.println("Cannot override this metho
d");
}
}

3. Final Variable: The value cannot be changed once assigned.

Example:

public class Example {


public final int MAX_VALUE = 100;
}

Conclusion
Polymorphism and inheritance are crucial for designing flexible and reusable
Java applications.

Abstract classes and interfaces provide different ways of defining contracts


for other classes to follow, with interfaces being key for multiple inheritance of
behavior.

The super keyword allows subclasses to reuse functionality from their parent
class, and the final keyword provides important restrictions on inheritance and
modification in Java.

JAVA - UNIT 2 19
Summary of Pages 16-18 (Exception Handling and Packages in
Java)

16. Exception Handling in Java


Exception handling in Java is a mechanism to handle runtime errors, ensuring the
normal flow of the program. Exceptions are unexpected events that occur during
the execution of a program and can cause it to crash if not handled properly.

1. What is an Exception?

An exception is an event that disrupts the normal flow of the program's


instructions.

Java uses a combination of try , catch , throw , throws , and finally blocks
to handle exceptions.

2. Types of Exceptions:

Checked Exceptions: Exceptions that are checked at compile-time (e.g.,


IOException , SQLException ).

Unchecked Exceptions: Exceptions that occur at runtime (e.g.,


ArithmeticException , NullPointerException ).

3. Try-Catch Block:

The try block contains code that might throw an exception, while the
catch block contains code to handle that exception.

Example:

try {
int division = 10 / 0; // This will cause an Arith
meticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.ge
tMessage());
}

4. Finally Block:

The finally block is used to execute important code, such as closing


resources, and it runs whether an exception occurs or not.

Example:

try {
int data = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("Finally block executed");
}

JAVA - UNIT 2 20
5. Throwing Exceptions:

You can explicitly throw an exception using the throw keyword.

Example:

public void checkAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be
18 or older");
}
}

6. Using throws Keyword:

The throws keyword is used in method signatures to declare exceptions


that the method might throw.

Example:

public void readFile() throws IOException {


// Code that may throw an IOException
}

17. Java Packages


A package in Java is a namespace that organizes classes and interfaces.
Packages provide a way to avoid class name conflicts and manage code better.

1. Types of Packages:

Built-in Packages: Provided by the Java API (e.g., java.util , java.io ).

User-Defined Packages: Created by the programmer to group related


classes.

2. Creating a Package:

To create a package, use the package keyword at the top of your Java file.

Example:

package myPackage;

public class MyClass {


// Class code
}

3. Importing Packages:

To use classes from another package, you can import the package using
the import keyword.

Example:

JAVA - UNIT 2 21
import java.util.Scanner;

public class Example {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
}

4. Accessing a Package:

Classes in a package are accessed using the package name and class
name, or by importing the package.

Example:

package myPackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass");
}
}

Then, in another class:

import myPackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}

5. Package Naming Convention:

Package names are typically written in all lowercase to avoid conflicts with
class names. It is common to use reverse domain names for packages
(e.g., com.example ).

6. Advantages of Using Packages:

Avoids Naming Conflicts: Helps to organize classes with the same names
but in different packages.

Reusability: Grouping related classes and interfaces enhances reusability


and easier maintenance.

18. Built-in Packages in Java


Java provides a vast collection of built-in packages, which include:

JAVA - UNIT 2 22
1. java.lang:

Contains fundamental classes like Object , Math , String , and System . It is


automatically imported into every Java program.

Example:

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

2. java.util:

Contains utility classes, such as collections framework classes (e.g.,


ArrayList , HashMap ), date and time utilities, and more.

Example:

import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
System.out.println(list);
}
}

3. java.io:

Provides classes for input and output operations, including reading from
and writing to files.

Example:

import java.io.File;

public class FileExample {


public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File found");
} else {
System.out.println("File not found");
}
}
}

4. java.net:

Contains classes for networking, such as Socket and URL .

Example:

JAVA - UNIT 2 23
import java.net.URL;

public class URLExample {


public static void main(String[] args) throws Excep
tion {
URL url = new URL("<https://www.example.com>");
System.out.println("Protocol: " + url.getProtoc
ol());
}
}

Conclusion
Exception handling in Java allows you to handle runtime errors and ensure that
the program executes smoothly despite potential issues.

Packages in Java help in organizing classes, avoiding name conflicts, and


promoting code reusability. Java's built-in packages provide a vast range of
functionalities, from basic operations ( java.lang ) to more complex tasks like
I/O ( java.io ) and networking ( java.net ).

Understanding these core concepts is crucial for building robust and maintainable
Java applications.

Summary of Pages 19-22 (Input/Output Operations and Java I/O


Streams)

19. Input/Output Operations in Java


Input and output (I/O) operations in Java are handled through various classes in
the java.io package. These operations are essential for reading data from and
writing data to different sources like files, consoles, or network streams.

1. Types of I/O Streams:

Byte Streams: Handle I/O of raw binary data (e.g., InputStream ,


OutputStream ).

Character Streams: Handle I/O of character data (e.g., Reader , Writer ).

2. InputStream and OutputStream:

These are the fundamental classes for byte stream operations. InputStream

is used for reading data, while OutputStream is used for writing data.

Example:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileIOExample {


public static void main(String[] args) throws IOExc

JAVA - UNIT 2 24
eption {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

3. FileReader and FileWriter:

These classes are used to handle character streams. FileReader is used for
reading text files, while FileWriter is used for writing to text files.

Example:

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileReaderWriterExample {


public static void main(String[] args) throws IOExc
eption {
FileReader reader = new FileReader("input.tx
t");
FileWriter writer = new FileWriter("output.tx
t");

int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}

reader.close();
writer.close();

JAVA - UNIT 2 25
}
}

4. BufferedReader and BufferedWriter:

These classes buffer data to improve performance during read/write


operations.

BufferedReader allows for reading lines of text efficiently, while


BufferedWriter is used for writing lines of text.

Example:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedReaderWriterExample {


public static void main(String[] args) throws IOExc
eption {
BufferedReader reader = new BufferedReader(new
FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new
FileWriter("output.txt"));

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

reader.close();
writer.close();
}
}

20. File Class


The File class in Java is used to represent a file or directory path in the file
system.

1. Creating a File Object:

The File class can be used to check the existence, create, delete, and
modify files or directories.

Example:

JAVA - UNIT 2 26
import java.io.File;

public class FileExample {


public static void main(String[] args) {
File file = new File("example.txt");

if (file.exists()) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
}
}

2. Common Methods of the File Class:

createNewFile() : Creates a new, empty file.

delete() : Deletes the file or directory.

mkdir() : Creates a new directory.

list() : Returns an array of file names in the directory.

Example:

File dir = new File("newDirectory");


if (dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory creation failed");
}

3. Directory Listing:

The list() method returns an array of file and directory names within a
specified directory.

Example:

File directory = new File("exampleDir");


String[] files = directory.list();
for (String file : files) {
System.out.println(file);
}

21. Serialization in Java


Serialization is the process of converting an object into a byte stream, allowing it
to be saved to a file or sent over a network. Deserialization is the reverse
process, converting a byte stream back into an object.

JAVA - UNIT 2 27
1. Serializable Interface:

A class must implement the Serializable interface to be eligible for


serialization.

Example:

import java.io.Serializable;

public class Person implements Serializable {


private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}
}

2. ObjectOutputStream and ObjectInputStream:

These streams are used to serialize and deserialize objects.

Example (Serialization):

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeExample {


public static void main(String[] args) throws Excep
tion {
Person person = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream
("person.ser");
ObjectOutputStream out = new ObjectOutputStream
(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
}
}

Example (Deserialization):

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeExample {


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

JAVA - UNIT 2 28
FileInputStream fileIn = new FileInputStream("p
erson.ser");
ObjectInputStream in = new ObjectInputStream(fi
leIn);
Person person = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println(person.name + ", " + person.
age);
}
}

22. Data Streams


Data streams provide methods for reading and writing primitive data types (e.g.,
int , float , double ) as well as String objects.

1. DataInputStream and DataOutputStream:

These classes allow reading and writing of primitive data types from/to a
binary stream.

Example (Writing data):

import java.io.DataOutputStream;
import java.io.FileOutputStream;

public class DataStreamExample {


public static void main(String[] args) throws Excep
tion {
DataOutputStream out = new DataOutputStream(new
FileOutputStream("data.dat"));
out.writeInt(42);
out.writeDouble(3.14159);
out.writeUTF("Hello, Data Stream");
out.close();
}
}

Example (Reading data):

import java.io.DataInputStream;
import java.io.FileInputStream;

public class DataStreamExample {


public static void main(String[] args) throws Excep
tion {
DataInputStream in = new DataInputStream(new Fi
leInputStream("data.dat"));

JAVA - UNIT 2 29
int number = in.readInt();
double pi = in.readDouble();
String message = in.readUTF();
in.close();
System.out.println(number + ", " + pi + ", " +
message);
}
}

Conclusion
Java's I/O Streams are essential for reading and writing data, from simple text
files to complex objects and binary data.

The File class provides the ability to manipulate files and directories in the file
system.

Serialization allows objects to be saved to and restored from byte streams,


making it easy to store and transmit objects.

Data Streams are a convenient way to handle primitive data types and strings
in binary form. Mastering these concepts will allow for efficient handling of
data in Java applications.

Summary of Pages 23-25 (Multithreading in Java)

23. Multithreading in Java


Multithreading in Java allows concurrent execution of two or more parts of a
program, known as threads. Each thread runs independently, enabling efficient
utilization of CPU and improving the performance of applications that perform
multiple tasks simultaneously.

1. What is a Thread?

A thread is a lightweight process. Java provides built-in support for


multithreaded programming through the java.lang.Thread class.

A thread can be created in two ways: by extending the Thread class or by


implementing the Runnable interface.

2. Life Cycle of a Thread:

A thread in Java goes through several stages:

1. New: When a thread is created but not yet started.

2. Runnable: After the start() method is called, the thread is ready to


run.

3. Running: When the thread scheduler picks the thread to run.

4. Blocked/Waiting: When the thread is waiting for resources or other


threads.

5. Terminated: When the thread completes its execution.

JAVA - UNIT 2 30
3. Creating a Thread by Extending Thread Class:

One way to create a thread is by extending the Thread class and overriding
its run() method.

Example:

class MyThread extends Thread {


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

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}

4. Creating a Thread by Implementing Runnable Interface:

Another way to create a thread is by implementing the Runnable interface


and passing it to the Thread constructor.

Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Runnable thread is runnin
g");
}
}

public class Main {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

24. Thread Methods


Several important methods in the Thread class help manage thread behavior:

1. start():

Starts the execution of the thread by invoking the run() method.

Example:

JAVA - UNIT 2 31
thread.start();

2. run():

Contains the code that constitutes the new thread's task. It is overridden
when creating a thread.

Example:

public void run() {


System.out.println("Thread is running");
}

3. sleep(long millis):

Pauses the execution of the thread for a specified number of milliseconds.

Example:

try {
Thread.sleep(1000); // Pauses for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}

4. join():

Waits for the thread to finish execution before the next line of code is
executed.

Example:

thread.join(); // Waits until thread finishes

5. yield():

Temporarily pauses the currently executing thread to allow other threads


to run.

Example:

Thread.yield();

6. isAlive():

Checks if the thread is still running.

Example:

if (thread.isAlive()) {
System.out.println("Thread is still running");
}

JAVA - UNIT 2 32
25. Synchronization in Java
Synchronization in Java is a mechanism to control the access of multiple threads
to shared resources. It ensures that only one thread can access a resource at a
time, preventing data inconsistency and race conditions.

1. Why Synchronization is Needed:

When multiple threads try to access and modify shared resources (e.g.,
variables, files) simultaneously, it may lead to inconsistent data.
Synchronization helps avoid this by ensuring only one thread can access a
critical section of code at a time.

2. Synchronized Methods:

A method can be declared synchronized to allow only one thread at a time to


execute it.

Example:

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

JAVA - UNIT 2 33
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Final count: " + counter.ge


tCount());
}
}

3. Synchronized Block:

A synchronized block is used to synchronize a specific part of the code


instead of the entire method, providing more fine-grained control.

Example:

public void increment() {


synchronized (this) {
count++;
}
}

4. Static Synchronization:

Static synchronization is used to control access to static members of a


class.

Example:

public static synchronized void staticMethod() {


// Static synchronized code
}

Conclusion
Multithreading allows concurrent execution of multiple parts of a program,
improving performance for tasks like file operations, network calls, or large
computations.

Key thread control methods include start() , run() , sleep() , join() , and
yield() , which manage thread behavior.

Synchronization is crucial for ensuring data consistency in multithreaded


applications, especially when threads share resources.

Mastering multithreading and synchronization is essential for writing efficient,


high-performance Java applications.

JAVA - UNIT 2 34

You might also like