JAVA_-_UNIT_2
JAVA_-_UNIT_2
JAVA - UNIT 2
Summary of Pages 1-3 (Unit II: Classes, Objects, and Inheritance)
Example:
2. Naming a Class:
3. Creating a Subclass:
Example:
Example:
Naming Variables:
JAVA - UNIT 2 1
Using Class Members:
Example:
3. Methods
Invoking Methods:
Example:
Example:
Method Overloading:
Define multiple methods with the same name but different parameters.
Example:
JAVA - UNIT 2 2
Protected: Accessible in the same package or subclasses.
6. Constructor Overloading
You can have multiple constructors with different parameters.
Example:
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.
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.
Example:
JAVA - UNIT 2 3
}
}
2. Invoking Methods:
Example:
Example:
4. Calling a Method:
Create an object of the class and call the method using the dot ( . )
operator.
Example:
1. Default (Package-Private):
Members are accessible within the same package but not from outside the
package.
Example:
2. Public:
The public access modifier allows access from anywhere, even outside
the package.
JAVA - UNIT 2 4
Example:
3. Private:
The private access modifier restricts access to the same class only.
Example:
4. Protected:
The protected access modifier allows access within the same package and
by subclasses, even if they are in different packages.
Example:
Example:
2. Final:
Example:
JAVA - UNIT 2 5
Final variable: A variable that cannot be reassigned.
6. Method Overloading
Method overloading allows multiple methods with the same name but different
parameters (number or types) in a class.
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.
// Default constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
JAVA - UNIT 2 6
this.name = name;
this.age = 0;
}
Conclusion
Methods, access specifiers, static/final modifiers, and overloading are core
concepts in Java for managing object behavior and visibility.
1. Regular Class:
Example:
2. Abstract Class:
Example:
JAVA - UNIT 2 7
public abstract class Shape {
abstract double area();
}
3. Interface:
Example:
4. Enum:
Example:
A class defined within another class, with access to the outer class's
members.
Example:
Example:
JAVA - UNIT 2 8
public static class StaticNested {
public void doSomething() {
outerField = 42;
}
}
}
1. If-Then-Else:
Example:
2. Switch Statement:
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:
Example:
JAVA - UNIT 2 9
greater than 5";
4. While Loop:
Example:
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
5. Do-While Loop:
Example:
int count = 0;
do {
System.out.println("Count: " + count);
count++;
} while (count < 5);
6. For Loop:
Example:
Example:
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:
2. Two-Dimensional Array:
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
3. Initializing Arrays:
Example:
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.
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:
Example:
JAVA - UNIT 2 11
initialization
numbers[0] = 1;
numbers[1] = 2;
2. Two-Dimensional Array:
Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Arrays can also be initialized using loops or by reading values from input.
Example:
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:
Example:
JAVA - UNIT 2 12
substring(int beginIndex): Returns a substring starting from the specified
index.
3. String Split:
Example:
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
}
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();
}
3. Hierarchical Inheritance:
Example:
class Parent {
// Parent class members
}
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
}
Conclusion
Java arrays and strings are foundational tools for managing collections of data
and textual information.
Achieved by defining multiple methods with the same name but different
parameters within a class.
Example:
JAVA - UNIT 2 15
}
}
Example:
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
3. Advantages of Polymorphism:
Flexibility: The same method can behave differently based on the object.
A class that extends an abstract class must provide implementations for all
its abstract methods, or it must be declared abstract itself.
JAVA - UNIT 2 16
abstract class Animal {
abstract void makeSound(); // Abstract method
When you want to define a base class with common functionality for its
subclasses, while some methods must be implemented by the subclasses.
1. Characteristics of Interfaces:
2. Example of an Interface:
interface Flyable {
void fly(); // Abstract method
}
Example:
JAVA - UNIT 2 17
interface Flyable {
void fly();
default void land() {
System.out.println("Landing safely");
}
}
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.
Example:
class Animal {
public void sound() {
System.out.println("Animal sound");
}
}
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");
}
}
Example:
Example:
class Parent {
public final void display() {
System.out.println("Cannot override this metho
d");
}
}
Example:
Conclusion
Polymorphism and inheritance are crucial for designing flexible and reusable
Java applications.
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)
1. What is an Exception?
Java uses a combination of try , catch , throw , throws , and finally blocks
to handle exceptions.
2. Types of Exceptions:
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:
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:
Example:
Example:
1. Types of Packages:
2. Creating a Package:
To create a package, use the package keyword at the top of your Java file.
Example:
package myPackage;
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;
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;
import myPackage.MyClass;
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 ).
Avoids Naming Conflicts: Helps to organize classes with the same names
but in different packages.
JAVA - UNIT 2 22
1. java.lang:
Example:
System.out.println("Hello, World!");
2. java.util:
Example:
import java.util.ArrayList;
3. java.io:
Provides classes for input and output operations, including reading from
and writing to files.
Example:
import java.io.File;
4. java.net:
Example:
JAVA - UNIT 2 23
import java.net.URL;
Conclusion
Exception handling in Java allows you to handle runtime errors and ensure that
the program executes smoothly despite potential issues.
Understanding these core concepts is crucial for building robust and maintainable
Java applications.
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;
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();
}
}
}
}
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;
int data;
while ((data = reader.read()) != -1) {
writer.write(data);
}
reader.close();
writer.close();
JAVA - UNIT 2 25
}
}
Example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}
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;
if (file.exists()) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
}
}
Example:
3. Directory Listing:
The list() method returns an array of file and directory names within a
specified directory.
Example:
JAVA - UNIT 2 27
1. Serializable Interface:
Example:
import java.io.Serializable;
Example (Serialization):
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
Example (Deserialization):
import java.io.FileInputStream;
import java.io.ObjectInputStream;
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);
}
}
These classes allow reading and writing of primitive data types from/to a
binary stream.
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
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.
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.
1. What is a Thread?
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:
Example:
1. start():
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:
3. sleep(long millis):
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:
5. yield():
Example:
Thread.yield();
6. isAlive():
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.
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:
Example:
class Counter {
private int count = 0;
t1.start();
t2.start();
JAVA - UNIT 2 33
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
3. Synchronized Block:
Example:
4. Static Synchronization:
Example:
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.
JAVA - UNIT 2 34