UNIT 1
Object-Oriented Programming Using
Java
Complete Study Guide with Code Examples
Topics Covered:
• Introduction to Java
• Data Types & Variables
• Operators
• Control Structures (Selection & Looping)
• Java Methods & Overloading
• Math Class
• Arrays
• Classes & Objects
• Constructors & Finalizer
• Visibility Modifiers
• Inbuilt Classes: String, Character, StringBuffer, File, this
1. Introduction to Java
Java is a high-level, object-oriented programming language created by
James Gosling at Sun Microsystems in 1991. Think of Java as a
universal language that can run on any device — Windows, Mac,
Linux, phones — without changing the code. That is what the phrase
'Write Once, Run Anywhere' means.
How Java Works
When you write Java code, it goes through two stages:
• You write code in a .java file and the Java Compiler converts it to Bytecode
(.class file).
• The JVM (Java Virtual Machine) reads that bytecode and runs it on your
computer.
• This is why Java is platform-independent — every OS has its own JVM.
💡 Note: JVM = Java Virtual Machine. It is the engine that runs Java
programs. Every OS has its own JVM, but all JVMs understand the same
bytecode.
Your First Java Program
Every Java program needs a class and a main() method. The main()
method is where execution begins — it is the starting point.
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
Output:
Hello, Java!
Breaking it down:
• public class HelloWorld — Defines a class named HelloWorld (file name
must match).
• public static void main(String[] args) — The main method; program starts
here.
• [Link](...) — Prints text to the screen followed by a new line.
2. Data Types in Java
A data type tells Java what kind of value a variable will hold. Java has
two categories of data types: Primitive and Non-Primitive.
Primitive Data Types
These are the basic building blocks. There are 8 primitive data types:
Type What it Size Default Example
Stores
byte Small 1 byte 0 byte age = 25;
whole
numbers
short Medium 2 bytes 0 short score = 1000;
whole
numbers
int Regular 4 bytes 0 int marks = 95;
whole
numbers
long Very large 8 bytes 0L long pop = 7800000000L;
whole
numbers
float Decimal 4 bytes 0.0f float pi = 3.14f;
numbers
Type What it Size Default Example
Stores
(less
precise)
double Decimal 8 bytes 0.0d double d = 3.14159;
numbers
(more
precise)
char A single 2 bytes \u0000 char grade = 'A';
character
boolean true or JVM false boolean pass = true;
false dep.
Code Examples for All Primitive Types
public class DataTypesDemo {
public static void main(String[] args) {
boolean isJavaFun = true;
char grade = 'A';
byte temperature = -10;
short students = 1000;
int marks = 95;
long worldPop = 7800000000L;
float pi = 3.14f;
double precise = 3.141592653589793;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Grade: " + grade);
[Link]("Temperature: " + temperature);
[Link]("Students: " + students);
[Link]("Marks: " + marks);
[Link]("World Population: " + worldPop);
[Link]("Pi (float): " + pi);
[Link]("Pi (double): " + precise);
}
}
Output:
Is Java fun? true
Grade: A
Temperature: -10
Students: 1000
Marks: 95
World Population: 7800000000
Pi (float): 3.14
Pi (double): 3.141592653589793
Non-Primitive Data Types
These are more complex types. They include Strings, Arrays, Classes,
and Interfaces. We will cover these in later sections. Unlike primitives,
they store references (memory addresses) to actual data.
3. Variables in Java
A variable is like a labelled box where you store a value. Every variable
has a name (identifier), a type, and a value.
How to Declare and Use Variables
public class VariablesDemo {
public static void main(String[] args) {
// Declaration and initialization
int age = 20;
String name = "Alice";
double cgpa = 8.75;
boolean isEnrolled = true;
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("CGPA: " + cgpa);
[Link]("Enrolled: " + isEnrolled);
// Changing a variable value
age = 21;
[Link]("Next year age: " + age);
}
}
Output:
Name: Alice
Age: 20
CGPA: 8.75
Enrolled: true
Next year age: 21
Java Identifiers (Naming Rules)
An identifier is the name you give to a variable, class, or method.
Rules:
• Can contain letters (A-Z, a-z), digits (0-9), $ and _ only.
• Cannot start with a digit. For example, 123name is invalid.
• Cannot be a Java keyword (like int, class, if).
• Java is case-sensitive: age and Age are different variables.
• No spaces allowed. Use camelCase like studentName.
💡 Note: Good naming convention: use camelCase for variables
(studentAge), PascalCase for classes (StudentRecord), and ALL_CAPS
for constants (MAX_SIZE).
4. Operators in Java
Operators are symbols that perform operations on values (called
operands). Java has several types of operators.
4.1 Arithmetic Operators
Used for basic math operations: +, -, *, /, %
public class ArithmeticDemo {
public static void main(String[] args) {
int a = 15, b = 4;
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b)); //
integer division
[Link]("Modulus: " + (a % b)); //
remainder
}
}
Output:
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3
4.2 Unary Operators
Operate on a single operand: +, -, ++, --, !
public class UnaryDemo {
public static void main(String[] args) {
int x = 5;
[Link]("Original: " + x);
[Link]("Post-increment x++: " + x++); //
prints 5, then x becomes 6
[Link]("After post-increment: " + x); // 6
[Link]("Pre-increment ++x: " + ++x); // x
becomes 7, then prints 7
boolean flag = true;
[Link]("Logical NOT: " + !flag); //
false
}
}
Output:
Original: 5
Post-increment x++: 5
After post-increment: 6
Pre-increment ++x: 7
Logical NOT: false
4.3 Assignment Operators
Used to assign values. The = is basic assignment. Others like +=, -=,
*= are shorthand.
public class AssignmentDemo {
public static void main(String[] args) {
int n = 10;
[Link]("Initial: " + n);
n += 5; // same as n = n + 5
[Link]("After n+=5: " + n);
n -= 3; // same as n = n - 3
[Link]("After n-=3: " + n);
n *= 2; // same as n = n * 2
[Link]("After n*=2: " + n);
n /= 4; // same as n = n / 4
[Link]("After n/=4: " + n);
}
}
Output:
Initial: 10
After n+=5: 15
After n-=3: 12
After n*=2: 24
After n/=4: 6
4.4 Relational Operators
Compare two values and return true or false: ==, !=, <, >, <=, >=
public class RelationalDemo {
public static void main(String[] args) {
int a = 10, b = 20;
[Link]("a == b: " + (a == b));
[Link]("a != b: " + (a != b));
[Link]("a < b: " + (a < b));
[Link]("a > b: " + (a > b));
[Link]("a <= b: " + (a <= b));
[Link]("a >= b: " + (a >= b));
}
}
Output:
a == b: false
a != b: true
a < b: true
a > b: false
a <= b: true
a >= b: false
4.5 Logical Operators
Combine boolean conditions: && (AND), || (OR), ! (NOT)
public class LogicalDemo {
public static void main(String[] args) {
int age = 20;
boolean hasID = true;
[Link]("Can enter (age>=18 AND hasID): " +
(age >= 18 && hasID));
[Link]("Can enter (age>=18 OR hasID): " +
(age >= 18 || hasID));
[Link]("Does NOT have ID: " + !hasID);
}
}
Output:
Can enter (age>=18 AND hasID): true
Can enter (age>=18 OR hasID): true
Does NOT have ID: false
4.6 Ternary Operator
A shortcut for if-else. Format: condition ? valueIfTrue : valueIfFalse
public class TernaryDemo {
public static void main(String[] args) {
int marks = 75;
String result = (marks >= 50) ? "Pass" : "Fail";
[Link]("Result: " + result);
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Max value: " + max);
}
}
Output:
Result: Pass
Max value: 20
4.7 Bitwise and Shift Operators
Operate directly on binary bits. Useful in low-level programming: &, |, ^,
~, <<, >>, >>>
public class BitwiseDemo {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
[Link]("AND (5&3): " + (a & b)); //
0001 = 1
[Link]("OR (5|3): " + (a | b)); //
0111 = 7
[Link]("XOR (5^3): " + (a ^ b)); //
0110 = 6
[Link]("Left shift (5<<1): " + (a << 1));
// 10
[Link]("Right shift (5>>1): " + (a >> 1));
// 2
}
}
Output:
AND (5&3): 1
OR (5|3): 7
XOR (5^3): 6
Left shift (5<<1): 10
Right shift (5>>1): 2
5. Control Structures — Selection
Control structures decide which part of code to execute based on
conditions. Java has several selection statements.
5.1 if Statement
Runs a block of code only if the condition is true.
public class IfDemo {
public static void main(String[] args) {
int temperature = 35;
if (temperature > 30) {
[Link]("It is hot outside!");
}
[Link]("Program continues...");
}
}
Output:
It is hot outside!
Program continues...
5.2 if-else Statement
Runs one block if true, another block if false.
public class IfElseDemo {
public static void main(String[] args) {
int num = 7;
if (num % 2 == 0) {
[Link](num + " is Even");
} else {
[Link](num + " is Odd");
}
}
}
Output:
7 is Odd
5.3 Nested if Statement
An if inside another if. Used to check multiple related conditions.
public class NestedIfDemo {
public static void main(String[] args) {
int marks = 85;
if (marks >= 50) {
[Link]("Passed!");
if (marks >= 90) {
[Link]("Excellent grade!");
} else if (marks >= 75) {
[Link]("Good grade!");
}
} else {
[Link]("Failed.");
}
}
}
Output:
Passed!
Good grade!
5.4 if-else-if Ladder
Used when you have multiple conditions to check one after another.
public class GradeCalc {
public static void main(String[] args) {
int marks = 72;
if (marks >= 90) {
[Link]("Grade: A");
} else if (marks >= 75) {
[Link]("Grade: B");
} else if (marks >= 60) {
[Link]("Grade: C");
} else if (marks >= 50) {
[Link]("Grade: D");
} else {
[Link]("Grade: F - Failed");
}
}
}
Output:
Grade: C
5.5 switch-case Statement
A cleaner way to choose from many fixed options. Works with int, char,
String, and enums.
public class SwitchDemo {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
default:
[Link]("Weekend");
}
}
}
Output:
Wednesday
💡 Note: Always use 'break' after each case in a switch, or execution will
'fall through' and run the next case too.
5.6 Jump Statements: break, continue, return
These alter the normal flow of loops and methods.
break — exits a loop or switch immediately
public class BreakDemo {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
[Link]("Breaking at i = " + i);
break;
}
[Link]("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 3
i = 4
Breaking at i = 5
continue — skips the current iteration
public class ContinueDemo {
public static void main(String[] args) {
// Print only ODD numbers from 1-10
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0)
continue; // skip even numbers
[Link](i + " ");
}
}
}
Output:
1 3 5 7 9
return — exits a method and optionally returns a value
public class ReturnDemo {
public static void main(String[] args) {
boolean done = true;
[Link]("Before return.");
if (done)
return;
[Link]("This line never runs.");
}
}
Output:
Before return.
6. Looping in Java
Loops let you repeat a block of code multiple times. Java has three
main types of loops.
6.1 for Loop
Best when you know exactly how many times to repeat. It has three
parts: init; condition; update.
public class ForLoopDemo {
public static void main(String[] args) {
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
// Print multiplication table of 3
[Link]("\nTable of 3:");
for (int i = 1; i <= 5; i++) {
[Link]("3 x " + i + " = " + (3 * i));
}
}
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Table of 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
6.2 while Loop
Best when you don't know in advance how many times to repeat. It
checks the condition before each iteration.
public class WhileDemo {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
[Link]("While: " + i);
i++; // don't forget to update, or it loops
forever!
}
}
}
Output:
While: 1
While: 2
While: 3
While: 4
While: 5
6.3 do-while Loop
Similar to while, but it always runs the body at least once, because the
condition is checked after the body.
public class DoWhileDemo {
public static void main(String[] args) {
int i = 1;
do {
[Link]("do-while: " + i);
i++;
} while (i <= 5);
// Even with false condition, runs once:
int x = 100;
do {
[Link]("Runs once even though x > 5. x
= " + x);
} while (x <= 5);
}
}
Output:
do-while: 1
do-while: 2
do-while: 3
do-while: 4
do-while: 5
Runs once even though x > 5. x = 100
💡 Note: for: use when loop count is known. while: use when condition-
driven. do-while: use when loop must run at least once.
7. Java Methods
A method is a named block of code that performs a specific task. You
define it once and call it multiple times. This avoids writing the same
code again and again.
Method Syntax
returnType methodName(parameter1, parameter2, ...) {
// body of the method
return value; // only needed if returnType is not void
}
Method Examples
public class MethodsDemo {
// A method that returns the sum of two numbers
static int add(int a, int b) {
return a + b;
}
// A method that prints a greeting (returns nothing -
void)
static void greet(String name) {
[Link]("Hello, " + name + "!");
}
// A method that checks if a number is even
static boolean isEven(int n) {
return (n % 2 == 0);
}
public static void main(String[] args) {
int result = add(10, 25);
[Link]("Sum: " + result);
greet("Alice");
[Link]("Is 8 even? " + isEven(8));
[Link]("Is 7 even? " + isEven(7));
}
}
Output:
Sum: 35
Hello, Alice!
Is 8 even? true
Is 7 even? false
8. Method Overloading
Method overloading means having multiple methods with the same
name, but different parameters (different number or types of
parameters). Java decides which one to call based on what arguments
you pass.
Think of it like the word 'draw': draw a circle, draw a rectangle, draw a
line — same word, different actions depending on context.
public class OverloadDemo {
// Version 1: Add two integers
static int add(int a, int b) {
return a + b;
}
// Version 2: Add three integers
static int add(int a, int b, int c) {
return a + b + c;
}
// Version 3: Add two doubles
static double add(double a, double b) {
return a + b;
}
// Version 4: Concatenate two Strings
static String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
[Link]("Two ints: " + add(5, 10));
[Link]("Three ints: " + add(5, 10, 15));
[Link]("Two doubles: " + add(3.5, 2.5));
[Link]("Two strings: " + add("Hello ",
"World"));
}
}
Output:
Two ints: 15
Three ints: 30
Two doubles: 6.0
Two strings: Hello World
💡 Note: Overloading is NOT done by changing only the return type. The
parameter list MUST be different.
9. Math Class in Java
Java provides a built-in Math class that has many useful mathematical
functions. You do not need to create an object — just call
[Link]() directly.
public class MathDemo {
public static void main(String[] args) {
// Absolute value
[Link]("abs(-9): " + [Link](-9));
// Square root
[Link]("sqrt(25): " + [Link](25));
// Power: 2^8
[Link]("pow(2,8): " + [Link](2, 8));
// Maximum and Minimum
[Link]("max(10,20): " + [Link](10, 20));
[Link]("min(10,20): " + [Link](10, 20));
// Floor, Ceil, Round
[Link]("floor(3.9): " + [Link](3.9));
[Link]("ceil(3.1): " + [Link](3.1));
[Link]("round(3.5): " + [Link](3.5));
// PI and E constants
[Link]("PI: " + [Link]);
[Link]("E: " + Math.E);
// Random number between 0.0 and 1.0
[Link]("random(): " + [Link]());
// Log and Exp
[Link]("log(10): " + [Link](10));
[Link]("exp(1): " + [Link](1)); //
e^1
}
}
Output:
abs(-9): 9
sqrt(25): 5.0
pow(2,8): 256.0
max(10,20): 20
min(10,20): 10
floor(3.9): 3.0
ceil(3.1): 4.0
round(3.5): 4
PI: 3.141592653589793
E: 2.718281828459045
random(): 0.7345231... (varies)
log(10): 2.302585092994046
exp(1): 2.718281828459045
10. Arrays in Java
An array is a container that stores multiple values of the same type. All
values are stored in consecutive memory locations. Once created, an
array's size is fixed.
Declaring and Using Arrays
public class ArrayDemo {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Access by index (index starts at 0)
[Link]("First element: " + numbers[0]);
[Link]("Third element: " + numbers[2]);
[Link]("Length of array: " +
[Link]);
// Loop through array
[Link]("\nAll elements:");
for (int i = 0; i < [Link]; i++) {
[Link]("Index " + i + ": " +
numbers[i]);
}
// Enhanced for-each loop
[Link]("\nUsing for-each:");
for (int num : numbers) {
[Link](num + " ");
}
}
}
Output:
First element: 10
Third element: 30
Length of array: 5
All elements:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50
Using for-each:
10 20 30 40 50
2D Arrays (Array of Arrays)
A 2D array is like a table with rows and columns.
public class TwoDArrayDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link]("Matrix:");
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
[Link]("Element at [1][2]: " + matrix[1]
[2]);
}
}
Output:
Matrix:
1 2 3
4 5 6
7 8 9
Element at [1][2]: 6
11. Basics of Objects and Classes
Java is an Object-Oriented language. Everything is built around
Classes and Objects.
A Class is like a blueprint or template. An Object is the actual thing
created from that blueprint.
Example: A class called Car defines properties like color, speed, and
actions like drive(), brake(). An object is an actual car like myCar = new
Car().
Defining a Class and Creating Objects
public class Car {
// Attributes (fields)
String color;
String brand;
int speed;
// Method
void displayInfo() {
[Link](brand + " | Color: " + color + " |
Speed: " + speed + " km/h");
}
void accelerate(int amount) {
speed += amount;
[Link](brand + " accelerated to " + speed
+ " km/h");
}
public static void main(String[] args) {
// Creating objects
Car car1 = new Car();
[Link] = "Red";
[Link] = "Toyota";
[Link] = 0;
Car car2 = new Car();
[Link] = "Blue";
[Link] = "Honda";
[Link] = 0;
[Link]();
[Link](60);
[Link]();
[Link]();
[Link]();
}
}
Output:
Toyota | Color: Red | Speed: 0 km/h
Toyota accelerated to 60 km/h
Toyota | Color: Red | Speed: 60 km/h
Honda | Color: Blue | Speed: 0 km/h
12. Constructors
A constructor is a special method that is automatically called when an
object is created. It is used to initialize the object's attributes. The
constructor has the same name as the class and no return type.
Default and Parameterized Constructors
public class Student {
String name;
int age;
double cgpa;
// Default constructor (no parameters)
Student() {
name = "Unknown";
age = 0;
cgpa = 0.0;
}
// Parameterized constructor
Student(String n, int a, double c) {
name = n;
age = a;
cgpa = c;
}
void display() {
[Link]("Name: " + name + ", Age: " + age +
", CGPA: " + cgpa);
}
public static void main(String[] args) {
Student s1 = new Student(); // calls
default constructor
Student s2 = new Student("Alice", 20, 8.5); // calls
parameterized
[Link]();
[Link]();
}
}
Output:
Name: Unknown, Age: 0, CGPA: 0.0
Name: Alice, Age: 20, CGPA: 8.5
Constructor Overloading
Just like methods, constructors can also be overloaded — same class
can have multiple constructors with different parameters.
public class Box {
double length, width, height;
Box() { length = width = height = 1; } //
cube default
Box(double side) { length = width = height = side; } //
equal sides
Box(double l, double w, double h) { length = l; width = w;
height = h; }
double volume() { return length * width * height; }
public static void main(String[] args) {
Box b1 = new Box();
Box b2 = new Box(5);
Box b3 = new Box(3, 4, 5);
[Link]("b1 volume: " + [Link]());
[Link]("b2 volume: " + [Link]());
[Link]("b3 volume: " + [Link]());
}
}
Output:
b1 volume: 1.0
b2 volume: 125.0
b3 volume: 60.0
13. Finalizer (finalize method)
The finalize() method is called by the garbage collector just before an
object is destroyed (removed from memory). It is used to perform
cleanup operations like releasing resources.
💡 Note: In modern Java, finalize() is deprecated (not recommended).
Use try-with-resources or explicit close() methods instead. However, it is
still in the syllabus, so here it is.
public class Resource {
String name;
Resource(String n) {
name = n;
[Link]("Resource created: " + name);
}
// This runs just before garbage collection
@Override
protected void finalize() {
[Link]("Resource being cleaned up: " +
name);
}
public static void main(String[] args) {
Resource r1 = new Resource("FileHandle");
Resource r2 = new Resource("DBConnection");
// Remove references - objects become eligible for GC
r1 = null;
r2 = null;
// Request garbage collection (not guaranteed to run
immediately)
[Link]();
[Link]("Main method ends.");
}
}
Output:
Resource created: FileHandle
Resource created: DBConnection
Resource being cleaned up: FileHandle
Resource being cleaned up: DBConnection
Main method ends.
14. Visibility Modifiers (Access Modifiers)
Visibility modifiers control who can access a class, method, or variable.
Think of them as permission levels.
Modifier Same Same Subclass Anywhere
Class Package
private Yes No No No
(default) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
public class BankAccount {
private double balance; // only this class can access
String owner; // default: package-level
access
protected String bank; // subclasses can access
public String accountNo; // everyone can access
public BankAccount(String owner, double bal) {
[Link] = owner;
[Link] = bal;
}
// Public getter for private field
public double getBalance() {
return balance;
}
// Public method to deposit
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: " + amount + " |
New Balance: " + balance);
}
}
public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 1000.0);
// [Link] = 5000; // ERROR! private - not
accessible here
[Link](500);
[Link]("Balance: " + [Link]());
}
}
Output:
Deposited: 500.0 | New Balance: 1500.0
Balance: 1500.0
15. The 'this' Reference
'this' is a keyword in Java that refers to the current object. It is used
inside a class to refer to the object's own attributes and methods. It is
especially useful when parameter names shadow field names.
public class Person {
String name;
int age;
// 'this' used to distinguish field from parameter
Person(String name, int age) {
[Link] = name; // [Link] = field, name =
parameter
[Link] = age;
}
// 'this' used to call another method of same object
void greet() {
[Link]("Hi, I am ");
[Link](); // calling own method
}
void introduce() {
[Link](name + " and I am " + age + " years
old.");
}
// 'this' used to call another constructor
Person(String name) {
this(name, 0); // calls Person(String, int)
constructor
[Link]("Single-arg constructor called.");
}
public static void main(String[] args) {
Person p1 = new Person("Alice", 22);
[Link]();
Person p2 = new Person("Bob");
[Link]();
}
}
Output:
Hi, I am Alice and I am 22 years old.
Single-arg constructor called.
Hi, I am Bob and I am 0 years old.
16. Inbuilt Classes in Java
Java provides many ready-made classes. Let us study the most
important ones in the syllabus.
16.1 String Class
String is used to store text. Strings in Java are immutable — once
created, they cannot be changed. Any modification creates a new
String object.
public class StringDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
// Basic operations
[Link]("Length: " + [Link]());
[Link]("Uppercase: " + [Link]());
[Link]("Lowercase: " + [Link]());
[Link]("Concatenation: " + [Link](" " +
s2));
[Link]("charAt(1): " + [Link](1));
[Link]("indexOf('l'): " +
[Link]('l'));
[Link]("substring(1,4): " +
[Link](1, 4));
[Link]("replace 'l'->'r': " +
[Link]('l', 'r'));
[Link]("trim ' hi ': " + " hi
".trim());
// Comparing strings
String a = "java";
String b = "JAVA";
[Link]("equals: " + [Link](b));
[Link]("equalsIgnoreCase: " +
[Link](b));
// Check contents
[Link]("startsWith 'He': " +
[Link]("He"));
[Link]("endsWith 'lo': " +
[Link]("lo"));
[Link]("contains 'ell': " +
[Link]("ell"));
}
}
Output:
Length: 5
Uppercase: HELLO
Lowercase: hello
Concatenation: Hello World
charAt(1): e
indexOf('l'): 2
substring(1,4): ell
replace 'l'->'r': Herro
trim ' hi ': hi
equals: false
equalsIgnoreCase: true
startsWith 'He': true
endsWith 'lo': true
contains 'ell': true
16.2 Character Class
The Character class is a wrapper for the primitive char type. It provides
useful utility methods to check and convert characters.
public class CharacterDemo {
public static void main(String[] args) {
char c1 = 'A';
char c2 = '5';
char c3 = ' ';
char c4 = 'z';
[Link]("isLetter('A'): " +
[Link](c1));
[Link]("isDigit('5'): " +
[Link](c2));
[Link]("isWhitespace(' '): " +
[Link](c3));
[Link]("isUpperCase('A'): " +
[Link](c1));
[Link]("isLowerCase('z'): " +
[Link](c4));
[Link]("toUpperCase('z'): " +
[Link](c4));
[Link]("toLowerCase('A'): " +
[Link](c1));
[Link]("isLetterOrDigit('A'): " +
[Link](c1));
// Count vowels in a String
String word = "Programming";
int vowels = 0;
for (char ch : [Link]()) {
if ("AEIOUaeiou".indexOf(ch) != -1) vowels++;
}
[Link]("Vowels in '" + word + "': " +
vowels);
}
}
Output:
isLetter('A'): true
isDigit('5'): true
isWhitespace(' '): true
isUpperCase('A'): true
isLowerCase('z'): true
toUpperCase('z'): Z
toLowerCase('A'): a
isLetterOrDigit('A'): true
Vowels in 'Programming': 3
16.3 StringBuffer Class
StringBuffer is like String but mutable — you can modify it without
creating a new object. This makes it much more efficient when you are
doing many string modifications. It is also thread-safe.
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
// append - add to end
[Link](" World");
[Link]("After append: " + sb);
// insert - insert at position
[Link](5, ",");
[Link]("After insert: " + sb);
// delete - remove characters
[Link](5, 6);
[Link]("After delete: " + sb);
// reverse
StringBuffer sb2 = new StringBuffer("JAVA");
[Link]();
[Link]("Reversed JAVA: " + sb2);
// replace
StringBuffer sb3 = new StringBuffer("Hello World");
[Link](6, 11, "Java");
[Link]("After replace: " + sb3);
// length and capacity
[Link]("Length: " + [Link]());
[Link]("Capacity: " + [Link]());
// charAt and setCharAt
[Link](0, 'h');
[Link]("After setCharAt: " + sb);
}
}
Output:
After append: Hello World
After insert: Hello, World
After delete: Hello World
Reversed JAVA: AVAJ
After replace: Hello Java
Length: 11
Capacity: 21
After setCharAt: hello World
💡 Note: Use String when content won't change. Use StringBuffer when
you need to frequently modify strings (building long text, loops, etc.).
16.4 File Class
The File class from [Link] package is used to work with files and
directories on the system. It does not read/write content — it handles
file metadata and creation.
import [Link];
import [Link];
public class FileDemo {
public static void main(String[] args) {
// Create a File object (does not create the file yet)
File f = new File("[Link]");
// Create the file
try {
if ([Link]()) {
[Link]("File created: " +
[Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("Error: " + [Link]());
}
// File info
[Link]("Name: " + [Link]());
[Link]("Absolute Path: " +
[Link]());
[Link]("Exists: " + [Link]());
[Link]("Is File: " + [Link]());
[Link]("Is Directory: " +
[Link]());
[Link]("Can Read: " + [Link]());
[Link]("Can Write: " + [Link]());
// Delete the file
[Link]();
[Link]("File deleted. Exists: " +
[Link]());
// Working with directories
File dir = new File("myFolder");
[Link]();
[Link]("Directory created: " +
[Link]());
[Link]();
}
}
Output:
File created: [Link]
Name: [Link]
Absolute Path: /home/user/[Link]
Exists: true
Is File: true
Is Directory: false
Can Read: true
Can Write: true
File deleted. Exists: false
Directory created: true
17. Quick Reference Summary
Data Types Summary
Type Size / Range When to Use
byte 1 byte, -128 to 127 Small numbers like age, small
counters
short 2 bytes, -32768 to Medium sized numbers
32767
int 4 bytes, ~-2 billion to General purpose integers (most
2 billion common)
long 8 bytes, very large Very large numbers (timestamps,
range populations)
float 4 bytes, ~6-7 decimal Decimal numbers when memory is
places limited
double 8 bytes, ~15-16 Default decimal type, more precise
Type Size / Range When to Use
decimal places
char 2 bytes, Unicode Single characters
character
boolean true or false Flags, conditions
Key Points to Remember
• Java is case-sensitive: int ≠ Int, main ≠ Main.
• Every program must have a main() method as the entry point.
• Use int for whole numbers, double for decimals by default.
• Strings are objects in Java, not primitive types. Use .equals() to compare
them, not ==.
• Arrays index starts at 0, not 1. An array of size 5 has indices 0-4.
• Constructor name must match the class name and has no return type.
• private = most restricted, public = accessible everywhere.
• StringBuffer is preferred over String for frequent modifications.
• Math class methods are static — call them as [Link](), not new
Math().sqrt().
• 'this' keyword refers to the current object inside a class.
End of Unit 2 — Java Programming Study Guide