0% found this document useful (0 votes)
3 views61 pages

Java Student Note

This document provides an introduction to Object-Oriented Programming (OOP), detailing its principles, advantages, and evolution over the decades. It explains key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with the significance of Java as an OOP language. The document also covers the Java Virtual Machine (JVM) and the compilation process for Java programs.
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)
3 views61 pages

Java Student Note

This document provides an introduction to Object-Oriented Programming (OOP), detailing its principles, advantages, and evolution over the decades. It explains key concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction, along with the significance of Java as an OOP language. The document also covers the Java Virtual Machine (JVM) and the compilation process for Java programs.
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

Chapter 1:

Introduction to Object-Oriented Programming (OOP)


Programming Paradigm

A programming paradigm is a style, approach, or way of thinking about how to write and
organize a program. It is a model or pattern for writing programs that guides how problems
should be solved using code. Think of programming paradigms as different cooking styles of egg
(fried, boiled, scrambled ). Each has its own techniques, ingredients, and presentation styles, but
all produce food.

Types of Programming Paradigms


1. Imperative Programming (How to achieve the goal)
A programmer tells the computer exactly how to do something through a series of explicit steps
Procedural(Structured) Programming: Based on functions or procedures
The program is divided into smaller steps (functions) that operate on data. How to solve the
problem (step by step)
Example: C, Fortran

Object-Oriented Programming (OOP): Based on objects and classes


Data and behavior are bundled together.
Models real-world entities. Who is responsible for what (objects)
Example: Java, C++, C#, Python.

2. Declarative Programming (What is the goal)


The programmer describes what the desired result is,
but doesn't necessarily specify the step-by-step control flow
Focuses on what needs to be achieved, not how
Functional Programming: Based on mathematical functions
Uses pure functions
Example: Haskell (also supported in JavaScript, Python, etc.)
Logic Programming: provides a set of facts and rules, and the computer finds the solution.
Example: Prolog. used for Artificial Intelligence, expert systems, and natural language
processing
Database Query Languages (SQL): Describe what data you want
Example: SQL: used to interact with and manage data stored in a relational database

Evolution of Programming Paradigms


1950s: Machine Code → Assembly
(Imperative thinking begins)
1960s: FORTRAN
(Procedural/Structured programming)

1970s: Pascal, C
(Structured programming refined)

1980s: C++
(Object-Oriented Programming emerges)

1990s: Java, Python, JavaScript


(OOP dominance, multi-paradigm languages)

2000s: C#,, Go
(Multi-paradigm, functional revival)

2010s: Rust, Kotlin


(Safe concurrency, modern multi-paradigm)

How to Choose a Paradigm?

Business applications → OOP


Data processing → Functional
AI/Expert systems → Logic
System programming → Procedural/Imperative

No single paradigm is "best" for all problems


Understanding multiple paradigms makes you a more versatile programmer
Most modern languages are multi-paradigm

1.1. Overview of OOP?

Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to


model real-world entities and their interactions. Unlike procedural programming, which
focuses on functions and sequences of actions, OOP organizes code around data (objects) and
the methods that operate on that data. Its primary goal is to increase modularity, reusability,
and maintainability of code.
Think about the world around you. You don't see 'functions' and 'procedures';
You see objects – cars, people, buildings, orders.
OOP brings this intuitive view into programming. Instead of a program being a long list of
instructions acting on data, the program becomes a collection of these self-contained 'objects'
that interact with each other. It allows us to represent real-world entities (like a Student, a
BankAccount, or a Car) directly in our code.

Easier to understand
More modular
More reusable
Easier to maintain and extend
Example: A Student → has attributes (name, ID, grade) and behaviors ( takeExam).

1.2. Why Java?


Java is a popular, general-purpose programming language, designed around OOP principles
Platform Independent ("Write Once, Run Anywhere")
Object-Oriented: Everything in Java is treated as an object
Strongly Typed: Reduces runtime errors by catching type mismatches at compile time.
Automatic Memory Management: The Garbage Collector handles memory, so you don't have
to manually manage pointers (like in C++).
Rich Standard Library: Provides extensive APIs for data structures, networking, and GUI
Multi-threading Support: Built-in support for concurrent programming
Community and Ecosystem: Large community, extensive documentation, and wide use in
enterprise, Android development, and web applications. It's trusted by large enterprises like
banks and tech companies.

History

Java was originally named Oak in 1991 by James Gosling for the "Green Team" project at
Sun Microsystems, named after an oak tree outside his office. It was renamed to Java in
1994-1995 because "Oak" was already trademarked by Oak Technologies. The final name
was inspired by coffee from Indonesia during a team brainstorming session.

Example HelloWorld

public class Sample {


public static void main(String[] args) {
System. [Link]("Hello, World!");

}
}

1.3. The JVM and Byte Code


How does Java run on any computer?

JVM (Java Virtual Machine): This is the "translator." It reads the Byte Code and executes it as
machine code on your specific OS.

Source Code (.java) -> Compiler (javac) -> Bytecode (.class) -> JVM (Windows/Linux/Mac) ->
Running Program

Compiler (javac): Translates your .java file into .class files containing bytecode.
Bytecode (.class): An intermediate, platform-independent code. It's not machine code. Bytecode is
like a universal language
Java Virtual Machine (JVM): The heart of the "Write Once, Run Anywhere" concept. It interprets and
executes the bytecode.
When you write any Java program, it does not run directly on the operating system like C or C++, but
runs through the JVM.
Java follows the famous principle “Write Once, Run Anywhere”. As a result, Java programs are
highly portable, secure, and reliable.
Each platform (Windows, macOS, Linux) has its own specific JVM.
The JVM acts as an abstraction layer, so your bytecode runs the same way on all of them.

References: [Link]
[Link]
Share: [Link]

Java Virtual Machine (JVM) is a core component of the Java Runtime Environment (JRE) that allows
Java programs to run on any platform without modification. JVM acts as an interpreter between Java
bytecode and the underlying hardware

Java source (.java) -> compiled by javac -> bytecode (.class)


JVM loads the bytecode, verifies it, links it, and then executes it
Execution may involve interpreting bytecode or using Just-In-Time (JIT) compilation to convert “hot”
code into native machine code for performance
Garbage collection runs in the background to reclaim memory from unused objects

Component: What It Is Purpose


JVM Java Virtual Machine executes bytecode
JRE Java Runtime Environment provides an environment to run Java programs
JDK Java Development Kit provides tools and libraries to develop Java apps
JIT Just-In-Time Compiler Bytecode to machine code at runtime to speed up execution

JDK: to write and compile .java to .class.


JRE: provides the environment (libraries) to run it.
JVM: executes the code.
JIT: makes the execution fast.

1.4. Basic concepts of OOP

1.4.1 Class

A Class is a user-defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type.
Think of a class as a design of a real-world entity.
Think of a class as a cookie cutter. The cookie cutter itself is not a cookie—it's just a shape. But once
you have that cutter, you can create as many cookies as you want, all with the same basic shape. In
programming, a class defines the 'shape' of our data and behavior.

Example:
class Person {
private String name; // Private variable

// Getter method
public String getName() {
return name;
}
// Setter method
public void setName(String name) {
[Link] = name;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
[Link]("John"); // Set the name using setter
[Link]([Link]()); // Get the name using getter
}
}

1.4.2 Object
Object represents real-life entities. An object is an instance of a class. A physical entity. When you
use the new keyword, the JVM allocates memory for that specific object.

1.4.3 Members
Members are the components inside a class
Members define what an object has and does.
Variables (data members): Represent/Store the state or data of the object e.g., int speed.
Methods (member functions): Represent the behavior or actions the object e.g., accelerate()

1.4.4. class member visibility

Class Member Visibility (Access Modifiers) controls where members can be accessed.

Four Levels of Visibility

Modifier Accessible Same Subclass Everywhere


Within Class Package

private Yes​ No​ ​ No No

default Yes Yes ​ No No


(no
modifier)

protected Yes Yes Yes No

Public Yes Yes Yes Yes

1.4.5. encapsulation, inheritance, and polymorphism


The four pillars of OOP are Encapsulation, Inheritance, Polymorphism, and Abstraction.

1. Encapsulation: The Power of Hiding Data

What is Encapsulation?

Encapsulation is the process of wrapping data and methods into a single unit, usually a class,
and restricting direct access to the data. It acts as a protective shield that prevents data from
being accessed directly from outside the class.

●​ Data members are hidden using the private access modifier.


●​ Access to data is provided through public getter and setter methods.
●​ It improves data security, maintainability, and controlled access.

Encapsulation is like putting a lock on the box where your data is stored and only giving
access through a controlled key (getter and setter methods). It allows you to hide the internal
details of an object and only expose what is necessary to the outside world. This protects your
data from unauthorised access and changes.
In Java, encapsulation is achieved by making class variables private and providing public
getter and setter methods to access them.

2. Inheritance: Reusing Code for Better Design

Inheritance allows one class to inherit properties and behaviours from another class. It helps

avoid duplication of code by enabling a new class to reuse code from an existing class. In

Java, a subclass (child class) can inherit from a superclass (parent class) using the extends

keyword.

It represents an “is-a” relationship between classes.

●​ The class being inherited is called the superclass, and the inheriting class is the
subclass.
●​ A subclass can use existing features of the superclass and also add its own.
●​ Inheritance promotes code reusability and reduces redundancy.

Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
3. Polymorphism: One Method, Many Forms

Polymorphism means having many forms. Polymorphism allows objects of different


classes to be treated as objects of a common superclass. The specific method that gets called
is determined at runtime, depending on the object type. It means “many forms” and is mostly
achieved through method overriding and method overloading.

Method Overriding (Runtime Polymorphism): a subclass provides its own version of a


method already defined in the superclass.

Method Overloading (Compile-time Polymorphism): Achieved when multiple methods have

the same name but different parameters. The method call is resolved at compile time.

4. Abstraction: Hiding the Complexity


Abstraction is the concept of hiding the complex implementation details and showing only

the essential features. It allows you to focus on what an object does, rather than how it does

it.

In Java, abstraction is achieved using abstract classes and interfaces.

●​ Hides complexity: Internal implementation details are hidden from the user.
●​ Improves maintainability: Changes in implementation do not affect the user
code.
●​ Enhances flexibility: Supports loose coupling through abstract classes and
interfaces.

Example: An ATM represents abstraction, where the user interacts with simple operations
while the internal working and implementation details remain hidden.

●​ Encapsulation helps in hiding the internal data of an object.

●​ Inheritance allows you to reuse code and create a hierarchy.


●​ Polymorphism provides flexibility by allowing objects to behave differently.

●​ Abstraction simplifies complex systems by showing only the essential features.

Procedure-Oriented Programming Language

Advantages
●​ Code reusability: Classes and objects allow the reuse of existing code, reducing
duplication and improving efficiency.
●​ Better structure and maintainability: Programs are organized into logical units,
making code easier to understand, debug, and maintain.
●​ Supports DRY principle: Common functionality is written once and reused,
leading to cleaner and more maintainable code.
●​ Faster development: Modular and reusable components help in quicker and more
scalable application development.

Disadvantages

●​ Steep learning curve: Concepts like classes, objects, inheritance, and


polymorphism can be difficult for beginners.
●​ Overhead for small programs: OOP may require more code and structure than
necessary for simple applications.
●​ Debugging complexity: Code spread across multiple classes and layers can make
debugging more time-consuming.
●​ Higher memory usage: Creating many objects can consume more memory
compared to procedural programs.
Chapter 2:The inside of objects and classes: More on OOP
concepts

Introduction
Hello World!

public class Main {


public static void main(String[] args) {
[Link]("Hello Java!");
}
}

Compile and Run java Program

Step 1: open the cmd.(command prompt) and go to the directory where you save

your HelloWorld program.

(Assume your file is save in below directory.


D:\java\[Link])

Step 2: Type ‘javac [Link]’ and enter to compile the code. If no error it

goes to next line.

Step 3: Type ‘java HelloWorld’ to run your HelloWorld program.

Now you will be able to see the output in command prompt.

When you run a Java program, the Java Virtual Machine (JVM) looks for this exact
method signature and executes it.

public

Access modifier public is accessible from anywhere b/c JVM needs to call this
method from outside the class. If you omit public, the JVM won’t find the entry point,
and you'll get a runtime error: Main method not public.

static

Indicates that the method belongs to the class itself, not to any particular instance
(object). When the program starts, no objects exist yet – the JVM cannot create an
object to call an instance method. By marking main as static, the JVM can invoke it
simply by using the class name (e.g., [Link](...)).

void

The return type. void means the method does not return any value to the caller (the
JVM). The main method completes and the program terminates; there is no
meaningful value to return.

main

The name of the method. This is the identifier the JVM looks for. It must be spelled
exactly main (case‑sensitive).

String[] args
A parameter that is an array of String objects. This array holds any command‑line
arguments passed to the program when it is [Link] can name the parameter
anything (e.g., String[] arguments), but the type must be String[] (or the varargs
equivalent String... args). If no arguments are given, the array is not null; it is an
empty array of length 0.

System

A final class in the [Link] package. It contains several useful static fields and
methods. You do not need to import it because [Link] is automatically imported.

out

A static field inside the System class of type PrintStream. It represents the standard
output stream (typically the console). Because it's static, you access it as
[Link].

println

A method of the PrintStream class. It prints the argument (here a String) to the
output stream and then terminates the line (moves the cursor to the next line).
overloaded versions for different data types (e.g., println(int), println(double), etc.).
[Link](...) sends the given text to the console followed by a newline.

print

prints the argument (here a String) to the output stream and doesn't add new line

[Link]

Important note: In Java, each statement must end with a semicolon (;) and it is
mandatory. Forgetting to add a semicolon will result in a compilation error. However,
note that code blocks enclosed in curly braces {} (like class and method
declarations) don't need semicolons.

Comments
Single-line comments: Use // to comment out a single line.
Multi-line comments: Use /* to start and */ to end a multi-line comment block.

public class Main {


public static void main(String[] args) {
// This is a single-line comment
[Link]("Hello, Coddy!"); // This is another single-line comment

/*
This is a multi-line comment.
It can span multiple lines.
*/
[Link]("Comments are useful for explaining code.");
}
}

Variables

A variable is like a memory unit that we can access by typing the name of the
variable.

Each variable has a unique name and a value that can be of different types. Java
has various built-in data types that define the type of value a variable can hold.
reserved keywords (e.g., class, public, static, void, if, else, for, while, etc.). You
cannot use them as identifiers (variable names, class names, etc.).

To initialize a variable, we use the following format:

variable_type variable_name = value;

Numbers

Numbers are typically represented using two main data types: int and double.
int is used to store whole numbers without any decimal point. double is used to store
numbers with a decimal point.
For example:
int age = 60;
double price = 99.99;
double pi = 3.14159;

String
A char is a single character (For example: 1, 6, %, b, p, ., T, etc.)

The String type is a special type that consists of multiple chars.


To initialize a string value in a variable, enclose it within double quotation marks:

String s1 = "This is a string";

Boolean
A Boolean type has only 2 possible values: true or false.
To assign a boolean value to a variable, use the keyword boolean followed by the
variable name:
boolean variable_true = true;
boolean variable_false = false;

Char

A char is a single character (For example: 1, 6, %, b, p, ., T, etc.)


The char type is a special type that consists of a single character.
To initialize a char value in a variable, enclose it within single quotation marks:
char c1 = 'h';

Type Declaration

Once a variable is declared with a certain type, it can only hold values of that type.
For instance, an int variable can only hold integer values, and a String variable can
only hold text.
For example:
int age = 25; // Can only hold whole numbers
String str = "abc"; // Can only hold text

These would cause errors:


age = "defg"; // Error: can't put text in an int variable
str = 25; // Error: can't put a number in a String variable

Constants
A constant is a special type of variable that cannot be changed once it is initialized.
To declare a constant use the keyword final followed by the variable type:
final int MAX_VALUE = 100;
MAX_VALUE = 200; // This will cause an error
result in an error because constant values cannot be changed.
Naming Conventions
Naming conventions to keep your code readable and maintainable. Here are some
key rules:
Variable Names: Use camelCase: Start with a lowercase letter, then capitalize the
first letter of each subsequent word (e.g., firstName, studentCount).
Choose descriptive names that indicate the variable's purpose (e.g., userAge instead
of ua).
Avoid single-letter names except for simple loop counters.
Constant Names: Use UPPER_SNAKE_CASE: Write in uppercase letters, with
words separated by underscores (e.g., MAX_VALUE, PI_VALUE).
Use for values that don't change throughout the program.
General Rules: Names can contain letters, digits, underscores, and dollar signs.
Names must start with a letter, an underscore _, or a dollar sign $.
Names are case-sensitive (myVariable is different from myvariable).
Avoid using Java's reserved keywords (like int, class, public, etc.).
Following these conventions helps make your code more understandable, especially
when working in teams or revisiting your code later.

Type Casting
Type casting is the process of converting a value from one data type to another.
In Java, we can convert integers to doubles, doubles to integers, and more. There
are two types of casting: implicit (automatic) and explicit (manual) casting.
For example integer to double:
Implicit (automatic) casting:
int number = 5;
double decimal = number; // automatically becomes 5.0
// with calculation
int x = 7;
double result = x / 2.0; // result is 3.5

Explicit (manual) Casting double to integer:


double decimal = 9.7;
int number = (int) decimal; // becomes 9 (decimal part is truncated)
// with calculation
double price = 19.99;
int roundedPrice = (int) price; // becomes 19

It is also possible to convert number and booleans to string and vice versa. To
convert a value to string we can use the [Link]() function:

int number1 = 789;


double number2 = 789;
boolean isValid = true;
String text1 = [Link](number1); // becomes "789"
String text2 = [Link](number2); // becomes "789.0"
String text3 = [Link](isValid); // becomes "true"

To convert a string to a different type is a bit more complicated:

String to Integer:

String numberText = "123";


int number = [Link](numberText); // becomes 123

String to Double:

String decimalText = "45.67";


double decimal = [Link](decimalText); // becomes 45.67

String to Boolean:

String boolText = "true";


boolean bool = [Link](boolText); // becomes true

parseBoolean will convert any case-insensitive string that has the value “true”. For
example True, tRue, TRUE will all become true

Trying to convert a string to an invalid type will result in an error:

String invalidNumber = "abc";


int number = [Link](invalidNumber); // This will cause a
NumberFormatException

Arithmetic Operators

Most basic arithmetic operators, they may be familiar from math classes.
Operator
Operation
Example
+
Addition
3+2=5
-
Subtraction
3-2=1
*
Multiplication
3*2=6
/
Division
4/2=2
Let's see usage example,
int a = 3;
int b = 5;
int c = a + b; // c holds 8

When working with decimal numbers in Java, we use the double data type, which
can store numbers with decimal points. The same arithmetic operators (+, -, *, /)
work with doubles just like they do with integers:
double x = 3.3;
double y = 4.1;
double z = x + y; // z holds 7.4

Modulo Operator
The modulo operator % gives the remainder of a division. In Java, it's used with a
simple syntax:

result = dividend % divisor;

Increment/Decrement

Increment and decrement operators are used to increase or decrease the value of a
variable by 1. These operators are widely used in programming, especially in loops
and counters.
The increment operator is represented by two plus signs ++, and the decrement
operator is represented by two minus signs --.
For example, to increment a variable named count, you can use the increment
operator like this:
int count = 5;
count++; // count is now 6

int value = 10;


value--; // value is now 9
Post Increment/Decrement

Increment (++) and Decrement (--) operators can be used in two ways:
Pre-increment/decrement (++x or --x):
The operator goes BEFORE the variable
The value changes IMMEDIATELY
The new value is used in the expression
int x = 5;
int y = ++x;
// x is increased to 6 first, then y becomes 6

Post-increment/decrement (x++ or x--):


The operator goes AFTER the variable
The original value is used first
The value changes AFTER the expression
int x = 5;
int y = x++;
// y becomes 5 first, then x increases to 6

Relational (Comparison) Operators


Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal a >= b
<= Less than or equal a <= b

Logical Operators
Operator Meaning Example
&& Logical AND (a > 0) && (b < 10)
|| Logical OR (a > 0) || (b < 10)
! Logical NOT !(a > 0)

Control Flow

if-else

if (speed > 60) {


[Link]("Slow down!");
} else {
[Link]("Speed is fine.");
}

switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}

for Loop

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


[Link]("class: " + i);
}

while (condition) {
// loop body
}

do {
// loop body
} while (condition);

2.1. member methods and their components

A member method (or instance method) belongs to an object of a class.


Components of a method:
Access modifier (e.g., public, private)
Return type (e.g., void, int, String)
Method name (e.g., calculateTotal)
Parameter list (zero or more parameters)
Method body (enclosed in {})

Example:

public class Calculator {


// Method
public int add(int a, int b) {
int sum = a + b;
return sum;
}
}

import [Link];
class DateApp {
public static void main (String args[]) {
Date today = new Date();
// three actions: declaration, instantiation, and initialization

[Link]("Today: " + today);


}
}

2.2. instantiation and initializing class objects

Declaring an Object
Either way, a declaration takes the form of
type name

Date today;

where type is either a simple data type, such as int, float, or boolean,
or a complex data type, such as a class like the Date class. name

Declarations simply notify the compiler that you will be using name
to refer to a variable whose type is type. Declarations do not instantiate objects.

Instantiating an Object

"new" operator instantiates a new object by allocating memory for it


new requires a single argument: a constructor method for the object to be created.
The constructor method is responsible for initializing the new object.

Initializing an Object

Classes provide constructor methods to initialize a new object of that type.


In a class declaration, constructors can be distinguished from other methods
because they have the same name as the class and have no return type.

For example
class Student {
int id;
String n;
public Student(int id, String n) {
[Link] = id;
this.n = n;
}
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student(10, "Abebe");
[Link]([Link]);
[Link](s1.n);
}
}

2.3. constructors
Constructor: Runs automatically when the object is created. It has the same name as
the class and no return type.
Example initializing object

Student s1 = new Student();

Student → class
s1 → reference variable
new → allocates memory

2.3.1. default and parameterized

A constructor that takes no arguments is known as the default constructor. Like Date,
most classes have at least one constructor, the default constructor. However, classes
can have multiple constructors, all with the same name but with a different number or
type of arguments.

For example, the Date class supports a constructor that requires three integers:
Date(int year, int month, int day)

Default Constructor
Provided automatically if no constructor is defined, or explicitly coded.

Has the same name as the class


Has no return type
class Car {
String model;
// Default constructor (implicitly provided)
}

class Hello{

// Default Constructor
Hello(){

[Link]("Default constructor");

}
public static void main(String[] args){

Hello hi = new Hello();


}
}

Note: It is not necessary to write a constructor for a class because the Java compiler
automatically creates a default constructor (a constructor with no arguments) if your
class doesn’t have any.

Parameterized Constructor
Allows to pass data, an object is created, and to initialize fields of the class with own
values, then use a parameterized constructor.

class Car {
String model;
int year;

// Parameterized constructor
Car(String m, int y) {
model = m;
year = y;
}
}

2.3.2. overloaded constructors

Having multiple constructors in the same class with different parameters.


This gives the user "options" on how to create the object.
class Rectangle {
double length, width;

// No-arg constructor
Rectangle() {
length = 1.0;
width = 1.0;
}

// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}

// Constructor with one parameter (square)


Rectangle(double side) {
length = side;
width = side;
}
}

2.4. methods

Java Methods are blocks of code that perform a specific task. A method allows us to
reuse code, improving both efficiency and organization. All methods in Java must
belong to a class. A method is a block of code that only runs when it is called.

Syntax of a Method

modifier return type name(parameters){

//body

}
Non-access Modifiers provide information about the behavior of the method to the
Java Virtual Machine (JVM). The modifier static means the method belongs to the
class, and it can be accessed without creating an object (an object is an instance of
a class).

public int add(int x, int y){

return x+y;

●​ Multi-word names should follow camelCase format.

Use Methods

●​ Methods help improve readability, reusability, Modularity, and maintainability

Types of Methods in Java

1. Predefined Method
method that is already defined in the Java class libraries. It is also known as the
standard library method or built-in method.

[Link]()

Example

Use import [Link].*;

[Link]() // returns random value​


[Link] // return pi value

[Link](9.3333) // return round number

2. User-defined Method

method written by a programmer and modified according to the requirement.

Example:

public class Main {

public int add(int a, int b) {

return a + b;

public static void main(String[] args) {

int x = 7, y = 9;

Main m = new Main();

[Link]("add:" + [Link](x, y)); }

2.5. access specifiers

Control the visibility of classes, methods, and fields.

✅ ❌ ❌ ❌
Modifier Same Class Same Package Subclass (different package) Anywhere​

✅ ✅ ❌ ❌
Private ​
(default) ​
✅ ✅ ✅ ❌​
✅ ✅ ✅ ✅
protected
public

2.6. accessors and mutators


In oop usually make data private for safety, to interact with that data needs special
methods.

Accessor (Getter): "gets" or reads the value of a private variable.

Mutator (Setter): "sets" or updates the value of a private variable, often including
logic to make sure the data is valid.

public class Main {


private int age;

public int getAge() {


return age;
}

public void setAge(int a) {


[Link] = a;
}
public static void main(String[] args) {
[Link](23);
[Link]("Age: " + [Link]());
}
}

2.7. calling and returning methods


Calling Different Types of Methods in Java

Method calling in Java means invoking a method to execute the code it contains.

1. Calling a User-Defined Method

first create an object of the class (if the method is non-static) and then call the
method using that object.

2. Calling an Abstract Method


Abstract methods have no body and must be overridden in a subclass. They are
called using an object of the subclass.

3. Calling the Predefined Methods


Java provides many built-in methods via the Java Standard Library,

4. Calling a Static Method


Static methods belong to the class, not the object. They can be called without
creating an object.

2.8. static and instance members

Different Ways to Create Java Method

1.​ Instance Method: Access the instance data using the object name. Declared
inside a class.

// Instance Method​
void method_name() {​
// instance method body​
}

2. Static Method: Access the static data using class name. Declared inside class with
static keyword.

It belongs to the class rather than any specific object.

Can be called without creating an instance of the class.

Since static methods are not object-specific, they can access only static members
(data and methods), and cannot access non-static members.

// Static Method​
static void method_name() {​
// static method body​
}

[Link]

Chapter 3: Inheritance
3.1. Concept of inheritance
Inheritance is a core OOP concept. Inheritance is a process where one class
acquires the properties (methods and attributes) of another. With the use of
inheritance, the information is made manageable in a hierarchical order.

Need of Inheritance

Code Reusability: reuse the features

Extensibility: extend the functionalities of a class

Achieving Abstraction:

Better organization

Implantation of Method Overriding: Subclasses can override the methods of the


superclass, which allows them to change their behavior in different ways.

Disadvantages of Inheritance

Complexity:

Tight Coupling:

3.2. Super classes and subclasses

The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).

A subclass can reuse the fields and methods of the parent class without rewriting
the code

A subclass can add its own fields and methods or modify existing ones to extend
functionality

It inherits all public and protected members of the superclass, but not private
members. Constructors are not inherited.

Example:

class Animal {

// field and method of the parent class

String name;

public void eat() {


[Link]("I can eat");

// inherit from Animal

class Dog extends Animal {

// new method in subclass

public void display() {

[Link]("My name is " + name);

class MyMain {

public static void main(String[] args) {

// create an object of the subclass

Dog myDog = new Dog();

// access field of superclass

[Link] = "Buchu";

[Link]();

// call method of superclass

// using object of subclass

[Link]();

Types of Inheritance in Java


1. Single Inheritance

A subclass is derived from only one superclass. It inherits the properties and
behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
2. 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.

3. Hierarchical Inheritance

More than one subclass is inherited from a single base class. i.e. more than one
derived class is created from a single base class. For example, cars and buses
both are vehicle
4. Multiple Inheritance (Through Interfaces)

Java does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces.

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can
achieve hybrid inheritance only through Interfaces if we want to involve multiple
inheritance to implement Hybrid inheritance.

3.3. Protected members

The methods or data members declared as protected can be accessed from


Within the same class.
Subclasses of the same packages.
Different classes of the same packages.
Subclasses of different packages.
.
This is useful when you want to give subclasses direct access to certain fields or
methods while still hiding them from unrelated classes.

[Link]
3.4. Overriding methods

When a subclass provides a specific implementation for a method that is already defined in
its parent class, it is called method overriding. The overridden method in the subclass must
have the same name, parameters, and return type as the method in the parent class.

Rules for Method Overriding


Name, parameters, and return type must match the parent method.
Java picks which method to run at run time, based on the actual object type, not just the
reference variable type.
Static methods cannot be overridden.

class Animal {

void move() {
[Link](
"Animal is moving.");

void eat() {

[Link](
"Animal is eating.");

}
}

class Dog extends Animal {

@Override
void move() {

// move method from Base class is overriden in this


// method
[Link]("Dog is running.");
}

void bark() {

[Link]("Dog is barking.");
}
}

public class MyMain {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
[Link]();
}
}

3.5. Using this() and super()


extends keyword in Java code enables inheritance through which child classes
automatically obtain attributes and behaviors from parent classes.

general syntax for creating inheritance in Java is:

class Parent {
// Parent class code
}

class Child extends Parent {


// Child class inherits from Parent class
}

The Child class inherits all non-private members of the Parent class, including fields and
methods.

example to inheritance:

class Animal {
void eat() {
[Link]("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
[Link]("The dog barks.");
}
}

public class TestInheritance {


public static void main(String[] args) {
Dog dog = new Dog();
[Link](); // Inherited from Animal class
[Link](); // Method defined in Dog class
}
}
The extends keyword is used when a class inherits from another class, enabling the
reuse of fields and methods.
On the other hand, the implements keyword is used by a class to adhere to a particular
interface, which means it must provide implementations for all abstract methods defined
in the interface.

constructors are not inherited by subclasses, but they can be invoked using super(). The
constructor of the superclass is called before the subclass's constructor.

super keyword is used to access methods of the parent class while this is used to
access methods of the current class.

this keyword is a reserved keyword and can't use it as an identifier.


It is used to refer current class's instance as well as static members.
It can be used in

to refer instance variable of current class


to invoke or initiate current class constructor
can be passed as an argument in the method call
can be passed as argument in the constructor call
can be used to return the current class instance
It must be the first statement in the constructor.

Example :
class Test {
// instance variable
int a = 10;

// static variable
static int b = 20;
void display()
{
// referring current class(i.e, class Test)
// instance variable(i.e, a)
this.a = 100;

[Link](a);

// referring current class(i.e, class Test)


// static variable(i.e, b)
this.b = 600;

[Link](b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new Test().display();
}
}

super keyword is used in subclasses to access superclass members (attributes, constructors


and methods).
Both this() and super() cannot be used together in the same constructor (only one can be the
first line).
If a constructor does not call this(), Java automatically inserts super() if no explicit call is
present.

use of super keyword is that it eliminates the confusion between the superclasses and
subclasses that have methods with same name.

Uses of super keyword


To call methods of the superclass that is overridden in the subclass.
To access attributes (fields) of the superclass if both superclass and subclass have attributes
with the same name.
To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.
Example

class Animal {
void eat() {
[Link]("Animal eats");
}
}

class Dog extends Animal {


void eat() {
[Link](); // Calls the eat method of the Animal class
[Link]("Dog eats");
}
}

class Test {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]();
}

class Animal {

// overridden method
public void display(){
[Link]("I am an animal");
}
}

class Dog extends Animal {

// overriding method
@Override
public void display(){
[Link]("I am a dog");
}

public void printMessage(){

// this calls overriding method


display();

// this calls overridden method


[Link]();
}
}

class Test {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]();
}
}

3.6. Use of final with inheritance

The final keyword can be applied to classes, methods, and variables to restrict modification
in inheritance.

final Class
A final class cannot be extended (no subclass).
Used to prevent inheritance for security or design reasons.

final class A {
// class body
}
// class A extends B {} // Compilation error

final Method
A final method cannot be overridden in a subclass.
Useful to lock the implementation of a critical method.

final Variable
A final variable can be assigned only once (constant).
For instance variables, they must be initialized either at declaration or in every constructor.

3.7. Constructors in subclasses

When a subclass object is created, the superclass constructor is always executed first
(either explicitly or implicitly).
If the superclass has a parameterized constructor without a default no‑arg constructor, the
subclass must explicitly call a superclass constructor using super

Chapter 4: Polymorphism

4.1. Introduction
4.2. Relationships among objCP in an inheritance hierarchy
4.3. Assigning reference of subclass to superclass-type variable
4.4. Assigning a superclass reference to subclass-type variable
4.5. Subclass method calls via superclass-type variable
4.6. Summary of allowed assignments between superclass and subclass variables
4.7. Multiple inheritance and interfaces

Read from your Assignment


This chapter is also included in your final exam

Chapter 5: Exception Handling

5.1. Exception handling overview

Exceptions to handle errors and other exceptional events. An exception is an event that
occurs during the execution of a program that disrupts the normal flow of instructions.

Exception Handling is a mechanism used to handle both compile-time (checked) and


runtime (unchecked) exceptions, allowing a program to continue execution smoothly even in
the presence of errors.

Handles abnormal conditions that occur during program execution.​


Helps maintain program stability by preventing unexpected termination.

Exception handling plays an important role in software development.


What is an Exception?​
An expectation is an unexpected event that occurs while executing the program, which
disturbs the normal flow of the code.

5.2. The causes of exceptions

Some of the major reasons why Exceptions occur

a) Invalid input by the user: entering a string when a number is expected

b) Physical limitations: Exceeding available memory or disk space

c) Device failure: Disk full, network timeout, printer offline

d) Error in coding: Accessing an array index out of bounds, calling a method on a null
reference

e) Weak or no network connection

f) Opening an unavailable file

Examples

Division by zero → ArithmeticException

Invalid array index → ArrayIndexOutOfBoundsException

Null reference → NullPointerException

Invalid input → InputMismatchException

File handling issues → IOException

5.3. The Throwable class hierarchy


5.4. Handling of an exception

Basic try-catch
The try block contains code that might throw an exception,
The catch block handles the exception if it occurs.
Example:

public class MyMain {


public static void main(String[] args) {

try {

int x = 2, y = 0, z;

z = x / y;

[Link]("Z=" + z);

} catch (ArithmeticException e) {

[Link]("ArithmeticException / by zero");

try {

int[] arr = new int[2];

[Link](arr[3]);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Index error");

} catch (Exception e) {

[Link]("General error");

5.5. The throw statement

The throw statement allows you to create a custom error.


throw Keyword

The throw keyword is used to explicitly throw an exception from a method


or any block of code. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:

throw Instance

Where instance is an object of type Throwable (or its subclasses, such as


Exception).

Example:

throw new ArithmeticException("/ by zero");

throw statement is executed, the program flow immediately stops, and the
nearest try block is checked for a matching catch block.

If a matching catch block is found, control is transferred to that block.

If no match is found, the default exception handler terminates the


program.

Example

public static void main(String[] args) {


try {

divide(10, 0);

} catch (ArithmeticException e) {

[Link]([Link]());

static void divide(int a, int b) {

if (b == 0) {

throw new ArithmeticException("Division by zero is not allowed.");

[Link](a / b);

throws Keyword

throws is a keyword 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.

Syntax:

type method_name(parameters) throws exception_list


where exception_list is a comma separated list of all the exceptions which
a method might throw.

If a method can throw a checked exception, the compiler requires it to be


either handled using a try-catch block or declared using the throws
keyword; otherwise, a compile-time error occurs.

The exception can be handled using a try-catch block.

The throws keyword can be used to declare the exception and delegate
the handling responsibility to the caller (method or JVM).

throw Vs throws

The main differences between throw and throws in Java are as follows:

throw throws
It is used to explicitly throw It is used to declare that a method might
an exception. throw one or more exceptions.

It is used inside a method or a


It is used in the method signature.
block of code.

It is mainly used for checked exceptions.


It can throw both checked and
Unchecked exceptions can also be declared
unchecked exceptions.
using throws, but it is not mandatory.

The method or block throws The method's caller is responsible for handling
the exception. the exception.
Stops the current flow of It forces the caller to handle the declared
execution immediately. exceptions.

throw new
public void myMethod() throws IOException {}
ArithmeticException("Error");

5.6. The finally clause


Finally Block

The finally block executes after the try and catch blocks in most situations, whether
an exception arose or not. It is typically used for closing resources such as database
connections, open files, or network connections.

Finally may not execute in cases like:

[Link]()

JVM crash,

infinite loop before finally

public class MyMain {

public static void main(String[] args) {

try {
int x = 2, y = 0, z;

z = x / y;

[Link]("Z=" + z);

} catch (ArithmeticException e) {

[Link]("ArithmeticException / by zero");

} finally {

[Link]("This block always executes.");

[Link]("Program continues...");

5.7. User-defined exceptions


A user-defined custom exception is an exception class created by the programmer to
represent application-specific or business-specific error scenarios.

Examples of User-defined Exception:

Invalid bank transaction


Insufficient balance
Age not eligible for registration
Invalid login attempt

Steps to Create a User-Defined Exception:

Create a class that extends Exception or RuntimeException.


Define a constructor and call the superclass constructor.
Write the code that might generate the defined exception inside the try-catch block.
Use ‘throw’ to raise the exception.
Handle it using try-catch.

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class MyMain {


public static void main(String[] args) {
try {
validate(0);
[Link]("sucess");
} catch (CustomException e) {
[Link]([Link]());
}
}

static void validate(int number) throws CustomException {


if (number <= 0) {
throw new CustomException("Number must be greater than zero.");
}
}

Best Practices

Use Meaningful Messages: Always provide meaningful and descriptive messages


When throwing exceptions to make debugging easier.

Custom Exceptions: Create custom exceptions to represent specific error conditions in


your application. This makes your code more readable and maintainable.

Avoid Overuse: Do not overuse exceptions for control flow. They should be used for
exceptional conditions, not for regular conditional checks.

Keywords

try catch finally


throw throws
Chapter 6: Files and Streams

6.1. Introduction
File handling means working with files like creating them, reading data, writing data or
deleting them. It helps a program save and use information permanently on the computer.

Why is file handling required?


To store data permanently instead of keeping it only in memory.
To read and write data from/to files for later use.
To share data between different programs or systems.
To organize and manage large data efficiently.
To support file handling, Java provides the File class in the [Link] package.

File Class
File class in Java (from the [Link] package) is used to represent the name and path of a
file or directory. It provides methods to create, delete, and get information about files and
directories.

The File class (from [Link]) is used to get information about files and directories:Does
the file exist?
What is its name or size?
Create or delete files and folders
But: the File class does not read or write the contents of the file.

6.2. I/O classes


I/O Streams are more flexible, work with text and binary data (like images, audio, PDFs).
I/O streams are the fundamental mechanism for handling input and output operations.
They provide a uniform way to read data from various sources (files, network, memory)
and write data to different destinations.

Types of Streams
Java I/O streams are categorized into two main types based on the type of data they
handle:

Byte Streams and Character Streams

1/ Byte Streams

Work with raw binary data (like images, audio, and PDF files).
used to perform input and output of 8-bit bytes.
Examples: FileInputStream, FileOutputStream.

2/ Character Streams

Work with text (characters and strings). These streams automatically handle character
encoding.
Examples: FileReader, FileWriter, BufferedReader, BufferedWriter.

public static void main(String[] args) {


// Create a File object
File file = new File("[Link]");

// Check if file exists


if ([Link]()) {
[Link]("File exists!");
[Link]("File name: " + [Link]());
[Link]("Path: " + [Link]());
[Link]("Absolute path: " + [Link]());
[Link]("File size: " + [Link]() + " bytes");
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());
} else {
[Link]("File does not exist. Creating now...");
try {
if ([Link]()) {
[Link]("File created successfully!");
}
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
}
// Create a directory
File directory = new File("myFolder");
if ([Link]()) {
[Link]("Directory created: " + [Link]());
}

// List files in current directory


File currentDir = new File(".");
String[] files = [Link]();
[Link]("\nFiles in current directory:");
for (String f : files) {
[Link](" - " + f);
}
}

Write to a File

We use the FileWriter class along with its write() method in order to write some text to
the file.

public static void main(String[] args)


{

try {

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

// Writing File
[Link]("Files in Java are seriously good!!");
[Link]();

[Link]("Successfully written.");
}

// Exception Thrown
catch (IOException e) {
[Link]("An error has occurred.");
[Link]();
}
}

Read from a File

read() method is used with classes like FileReader or InputStream to read data from a
file one character or byte at a time.
It returns an integer value representing the character or byte read.
When the end of the file is reached, the method returns -1 indicating no more data is
available.

public static void main(String[] args)


{
try {
File Obj = new File("[Link]");
Scanner Reader = new Scanner(Obj);

// Traversing File Data


while ([Link]()) {
String data = [Link]();
[Link](data);
}

[Link]();
}

// Exception Cases
catch (FileNotFoundException e) {
[Link]("An error has occurred.");
[Link]();
}
}

Delete a File

public static void main(String[] args)


{
File Obj = new File("[Link]");

// Deleting File
if ([Link]()) {
[Link]("The deleted file is : " + [Link]());
}
else {
[Link](
"Failed in deleting the file.");
}
}

Character Stream Byte Stream


For reading or writing characters to For reading or writing bytes to files
text-based files like XML, HTML, JSON like images, videos or files in
etc. low-level formats like .exe, .obj,
.class, etc.

Deals with 16-bit Unicode characters Deals with bytes (8-bit data)

Streams are called as readers and Streams are called as input streams
writers and output streams

Abstract base classes are Reader and Abstract base classes are
Writer InputStream and OutputStream

6.3. File and FileDialog objects


File class
Represents a file or directory (does NOT read/write content).

public static void main(String[] args) {


File file = new File("[Link]");

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

FileDialog (GUI – AWT)

The [Link] class is a subclass of [Link] used for choosing a file to


open or save.

There are three steps to using a FileDialog:

Create the FileDialog


Make the FileDialog visible.
Get the directory name and file name of the chosen file

FileDialog fd = new FileDialog(new Frame(),


"Please choose a file:", [Link]);
[Link]();
if ([Link]() != null) {
File f = new File([Link](), [Link]());
}

public static void main(String[] args) {


Frame f = new Frame();
FileDialog fd = new FileDialog(f, "Select a file", [Link]);
[Link](true);

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

6.4. Low-Level File I/O

The package for Java I/O API is [Link].


A stream is a collection of data or a flow of data.
Reading data from an input source requires an input stream, and writing data to a target
requires an output stream.

Low-Level File I/O (Byte-Oriented)

Works with bytes and used for binary files (images, videos)
classes: FileInputStream and FileOutputStream

Low-level file I/O for raw byte I/O, similar to [Link]() and [Link]()
InputStream — Abstract class whose subclasses read raw bytes
OutputStream — Abstract class whose subclasses write raw bytes
FileInputStream — reads raw bytes
FileOutputStream — writes raw bytes

6.5. High-Level File I/O

support text data through characters instead of bytes.


Character-oriented I/O: use FileReader/FileWriter for text data;
wrap in BufferedReader/BufferedWriter for efficiency.

Common high-level classes include


BufferedInputStream, BufferedOutputStream,
BufferedReader, BufferedWriter, PrintWriter,
DataInputStream and DataOutputStream.

public static void main(String[] args) {


try (BufferedWriter writer = new BufferedWriter(new FileWriter("[Link]"))) {
[Link]("Hello, Java I/O!");
[Link]();
[Link]("This is high-level file handling.");
[Link]("Text written successfully.");
} catch (IOException e) {
[Link]("I/O error: " + [Link]());
}
}

Feature Low-Level I/O High-Level I/O

Data type Bytes Bytes or characters

Speed Basic, direct Usually faster with buffering

Ease of use More manual Easier and more convenient

Best for Binary files, direct control Text files, efficient reading/writing

FileInputStream, FileOutputStream, BufferedReader, BufferedWriter,


Examples
RandomAccessFile PrintWriter

6.6. Object I/O

ObjectInputStream/ObjectOutputStream classes can be used to read/write serializable


objects.
DataInputStream/DataOutputStream enables you to perform I/O for primitive-type values
and strings.
ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition to
primitive-type values and strings.
Since ObjectInputStream/ObjectOutputStream contains all the functions of
DataInputStream/DataOutputStream,
You can replace DataInputStream/DataOutputStream completely with
ObjectInputStream/ObjectOutputStream.

6.7. Random Access files


RandomAccessFile class to allow data to be read from and written to at any location in
the file.
A file that is opened using the RandomAccessFile class is known as a random-access
file.

The RandomAccessFile class implements the DataInput and DataOutput interfaces,

[Link] Class works like an array of byte storted in the File.


Declaration :
public class RandomAccessFile
extends Object
implements DataOutput, DataInput, Closeable

Reference
Web- [Link]
[Link]
[Link]
[Link]

You might also like