Java Student Note
Java Student Note
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.
1970s: Pascal, C
(Structured programming refined)
1980s: C++
(Object-Oriented Programming emerges)
2000s: C#,, Go
(Multi-paradigm, functional revival)
Easier to understand
More modular
More reusable
Easier to maintain and extend
Example: A Student → has attributes (name, ID, grade) and behaviors ( takeExam).
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
}
}
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
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()
Class Member Visibility (Access Modifiers) controls where members can be accessed.
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.
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.
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.
● 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
the same name but different parameters. The method call is resolved at compile time.
the essential features. It allows you to focus on what an object does, rather than how it does
it.
● 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.
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
Introduction
Hello World!
Step 1: open the cmd.(command prompt) and go to the directory where you save
Step 2: Type ‘javac [Link]’ and enter to compile the code. If no error it
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.
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.
/*
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.).
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.)
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
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
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
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:
String to Integer:
String to Double:
String to Boolean:
parseBoolean will convert any case-insensitive string that has the value “true”. For
example True, tRue, TRUE will all become true
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:
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
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
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
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
for Loop
while (condition) {
// loop body
}
do {
// loop body
} while (condition);
Example:
import [Link];
class DateApp {
public static void main (String args[]) {
Date today = new Date();
// three actions: declaration, instantiation, and initialization
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
Initializing an Object
For example
class Student {
int id;
String n;
public Student(int id, String n) {
[Link] = id;
this.n = 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 → class
s1 → reference variable
new → allocates memory
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.
class Hello{
// Default Constructor
Hello(){
[Link]("Default constructor");
}
public static void main(String[] args){
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;
}
}
// No-arg constructor
Rectangle() {
length = 1.0;
width = 1.0;
}
// Parameterized constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
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
//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).
return x+y;
Use Methods
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
2. User-defined Method
Example:
return a + b;
int x = 7, y = 9;
✅ ❌ ❌ ❌
Modifier Same Class Same Package Subclass (different package) Anywhere
✅ ✅ ❌ ❌
Private
(default)
✅ ✅ ✅ ❌
✅ ✅ ✅ ✅
protected
public
Mutator (Setter): "sets" or updates the value of a private variable, often including
logic to make sure the data is valid.
Method calling in Java means invoking a method to execute the code it contains.
first create an object of the class (if the method is non-static) and then call the
method using that object.
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.
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
Achieving Abstraction:
Better organization
Disadvantages of Inheritance
Complexity:
Tight Coupling:
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 {
String name;
class MyMain {
[Link] = "Buchu";
[Link]();
[Link]();
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.
[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.
class Animal {
void move() {
[Link](
"Animal is moving.");
void eat() {
[Link](
"Animal is eating.");
}
}
@Override
void move() {
void bark() {
[Link]("Dog is barking.");
}
}
class Parent {
// Parent class code
}
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.");
}
}
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.
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);
[Link](b);
}
use of super keyword is that it eliminates the confusion between the superclasses and
subclasses that have methods with same name.
class Animal {
void eat() {
[Link]("Animal 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");
}
}
// overriding method
@Override
public void display(){
[Link]("I am a dog");
}
class Test {
public static void main(String[] args) {
Dog dog1 = new Dog();
[Link]();
}
}
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.
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
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.
d) Error in coding: Accessing an array index out of bounds, calling a method on a null
reference
Examples
Basic try-catch
The try block contains code that might throw an exception,
The catch block handles the exception if it occurs.
Example:
try {
int x = 2, y = 0, z;
z = x / y;
[Link]("Z=" + z);
} catch (ArithmeticException e) {
[Link]("ArithmeticException / by zero");
try {
[Link](arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Index error");
} catch (Exception e) {
[Link]("General error");
Syntax:
throw Instance
Example:
throw statement is executed, the program flow immediately stops, and the
nearest try block is checked for a matching catch block.
Example
divide(10, 0);
} catch (ArithmeticException e) {
[Link]([Link]());
if (b == 0) {
[Link](a / b);
throws Keyword
Syntax:
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.
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");
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.
[Link]()
JVM crash,
try {
int x = 2, y = 0, z;
z = x / y;
[Link]("Z=" + z);
} catch (ArithmeticException e) {
[Link]("ArithmeticException / by zero");
} finally {
[Link]("Program continues...");
Best Practices
Avoid Overuse: Do not overuse exceptions for control flow. They should be used for
exceptional conditions, not for regular conditional checks.
Keywords
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.
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.
Types of Streams
Java I/O streams are categorized into two main types based on the type of data they
handle:
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.
Write to a File
We use the FileWriter class along with its write() method in order to write some text to
the file.
try {
// 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() 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.
[Link]();
}
// Exception Cases
catch (FileNotFoundException e) {
[Link]("An error has occurred.");
[Link]();
}
}
Delete a File
// Deleting File
if ([Link]()) {
[Link]("The deleted file is : " + [Link]());
}
else {
[Link](
"Failed in deleting the file.");
}
}
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
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
[Link]([Link]());
[Link]([Link]());
}
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
Best for Binary files, direct control Text files, efficient reading/writing
Reference
Web- [Link]
[Link]
[Link]
[Link]