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

Oops Java Manual (1)

This laboratory manual for the IV Semester of the CSE Department at Atria Institute of Technology outlines various programming experiments in Java, including grade calculation, stack implementation, employee management, and shape modeling. It covers both conventional experiments and open-ended projects, emphasizing concepts like polymorphism, exception handling, and file operations. Each section includes aims, code examples, and explanations to facilitate understanding of object-oriented programming principles.

Uploaded by

shivamchilkoti64
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 views68 pages

Oops Java Manual (1)

This laboratory manual for the IV Semester of the CSE Department at Atria Institute of Technology outlines various programming experiments in Java, including grade calculation, stack implementation, employee management, and shape modeling. It covers both conventional experiments and open-ended projects, emphasizing concepts like polymorphism, exception handling, and file operations. Each section includes aims, code examples, and explanations to facilitate understanding of object-oriented programming principles.

Uploaded by

shivamchilkoti64
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

LABORATORY MANUAL
IV Semester

(Academic Year: 2025-26)

DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024

​ ​ ​ ​ ​

PART A: CONVENTIONAL EXPERIMENTS


1 a. Write a program to display the grade

above 90=grad A1
between 80 to 90-grade a2
between 70 to 79-grade b1
between 60 to 69-grade b2
between 50 to 59-grade c1
between 40 to 49-grade c2
below 40-grade d

b. Write a program to generate multiplication table for a given number


in the format

3*1=3
3*2=6

2 Develop a stack class to hold a maximum of 10 integers with suitable


methods. Develop a JAVA main method to illustrate Stack
operations.

3 A class called Employee, which models an employee with an ID,


name and salary, is designed as shown in the following class
diagram. The method raiseSalary (percent) increases the salary by
the given percentage. Develop the Employee class and suitable main
method for demonstration.

4 A class called MyPoint, which models a 2D point with x and y


coordinates, is designed as follows:

●​ Two instance variables x (int) and y (int).

DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024

●​ A default (or "no-arg") constructor that construct a point at the
default location of (0, 0).

●​ A overloaded constructor that constructs a point with the given


x and y coordinates.

●​ A method setXY() to set both x and y.

●​ A method getXY() which returns the x and y in a 2-element int


array.

●​ A toString() method that returns a string description of the


instance in the format "(x,y)".

●​ A method called distance(int x, int y) that returns the distance


from this point to another point at the given (x, y) coordinates.

●​ An overloaded distance(MyPoint another) that returns the


distance from this point to the given MyPoint instance (called
another)

●​ Another overloaded distance() method that returns the distance


from this point to the origin (0,0)

Develop the code for the class MyPoint. Also develop a JAVA
program (called TestMyPoint) to test all the methods defined in the
class.

5 Develop a JAVA program to create a class named shape. Create three


sub classes namely: circle, triangle and square, each class has two
member functions named draw () and erase (). Demonstrate
polymorphism concepts by developing suitable methods, defining
member data and main program.

6 Develop a JAVA program to create an abstract class Shape with

DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024

abstract methods calculateArea() and calculatePerimeter(). Create
subclasses Circle and Triangle that extend the Shape class and
implement the respective methods to calculate the area and
perimeter of each shape.

7 Develop a JAVA program to create an interface Resizable with


methods resizeWidth(int width) andresizeHeight(int height) that
allow an object to be resized. Create a class Rectangle that
implements the Resizable interface and implements the resize
methods.

8 Develop a JAVA program to create a package named mypack and


import & implement it in a suitable class.

9 Develop a JAVA program to raise a custom exception (user defined


exception) for DivisionByZero using try, catch, throw and finally.

10 Write a program to illustrate creation of threads using runnable


Interface. (start method start each of the newly created
thread. Inside the run method there is sleep() for suspend the
thread for 500 milliseconds).

PART B: TYPICAL OPEN-ENDED EXPERIMENTS


1 Write a java program that simulates a traffic light. The program
lets the user select one of three lights: red, yellow, or green
with radio buttons. On selecting a button, an appropriate message
with “stop” or “ready” or “go” should appear above the buttons in a
selected color. Initially there is no message shown.

2 Suppose that a table named [Link] is stored in a text file. The


first line in the file is the header, and the remaining lines
correspond to rows in the table. The elements are separated by
commas. Write a java program to display the table using Labels in

DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024

Grid Layout.

3 Write a Java program that reads on file name from the user, then
displays information about whether the file exists, whether the
file is readable, whether the file is writable, the type of file
and the length of the file in bytes?

4 Write a Java program that reads a file and displays the file on the
screen, with a line number before each line?

5 Write a Java program that displays the number of characters, lines


and words in a text?

DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024
BAJAVB407 OOPS with JAVA Lab 1

PART A: CONVENTIONAL EXPERIMENTS

Computer Science and Engineering 1 of 63


BAJAVB407 OOPS with JAVA Lab 2

1 Expt 1

a. Write a program to display the grade

above 90=grad A1
between 80 to 90-grade a2
between 70 to 79-grade b1
between 60 to 69-grade b2
between 50 to 59-grade c1
between 40 to 49-grade c2
below 40-grade d

b. b. Write a program to generate multiplication table for a given number in the


format

3*1=3
3*2=6

1.1 a.

1.2 Aim

In Java, we handle this using a Scanner for input and a series of if-else if statements.
I have structured the conditions to match your specific ranges.

1.3 Java Grade Program

import [Link];

Computer Science and Engineering 2 of 63


BAJAVB407 OOPS with JAVA Lab 3

public class GradeCalculator {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter your marks: ");
// Check if the input is a valid number
if ([Link]()) {
double marks = [Link]();

if (marks > 90) {


[Link]("Grade: A1");
} else if (marks >= 80) {
[Link]("Grade: A2");
} else if (marks >= 70) {
[Link]("Grade: B1");
} else if (marks >= 60) {
[Link]("Grade: B2");
} else if (marks >= 50) {
[Link]("Grade: C1");
} else if (marks >= 40) {
[Link]("Grade: C2");
} else {
[Link]("Grade: D");
}
} else {
[Link]("Error: Please enter a valid number.");
}

[Link]();
}
}

Computer Science and Engineering 3 of 63


BAJAVB407 OOPS with JAVA Lab 4

1.4 How it Works

The program uses a "falling" logic. Since we start checking from the highest possible
score (> 90), we don’t need to specify the upper bound for the following checks.

The Scanner: We use import [Link] to read what the user types in the
console.

The Conditions: Each else if only runs if the ones above it were false. For example,
if a user enters 85, the first check (> 90) is false, but the second check (≥ 80) is
true, so it prints A2 and skips the rest.

Data Type: I used double for the marks variable so the program can handle
decimals (like 75.5).

Java follows this "ladder" when mixing types in a calculation or comparison. The
value moves up the ladder to avoid losing data:

1. double (Highest precision)

2. float

3. long

4. int (Lower precision)

Since double is higher than int, the integer 90 is temporarily treated as a double.

1.5 Results

1>javac -g *.java

Computer Science and Engineering 4 of 63


BAJAVB407 OOPS with JAVA Lab 5

1>java GradeCalculator
Enter your marks: 50
Grade: C1

1>java GradeCalculator
Enter your marks: 91
Grade: A1
1>

1.6 b.

1.7 Aim

To generate a multiplication table in Java, we use a for loop. This allows the
program to repeat the multiplication process from 1 up to 10 (or any limit you
choose) without writing the same line of code over and over.

1.8 Java Multiplication Table Program

import [Link];

public class MultiplicationTable {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);

[Link]("Enter a number to generate its table: ");

if ([Link]()) {
int num = [Link]();
[Link]("Multiplication Table for " + num + ":");

Computer Science and Engineering 5 of 63


BAJAVB407 OOPS with JAVA Lab 6

// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// Format: number * multiplier = result
[Link](num + "*" + i + "=" + (num * i));
}
} else {
[Link]("Please enter a valid integer.");
}

[Link]();
}
}

1.9 How the for loop works

• The for loop is the engine of this program. It follows a specific three-step
logic to ensure it runs exactly 10 times.

• Initialization (int i = 1): We create a counter variable i and start it at 1.

• Condition (i <= 10): The loop keeps running as long as i is less than or
equal to 10.

• Update (i++): After every multiplication, we add 1 to i.

In the line [Link](num + "" + i + "=" + (num * i));, we use


the + operator. In Java, when you add a String (like "") to a number,
Java converts the number to text and joins them together. This is called String
Concatenation.

Computer Science and Engineering 6 of 63


BAJAVB407 OOPS with JAVA Lab 7

1.10 Results

1>javac -g *.java
1>java MultiplicationTable
Enter a number to generate its table: 5
Multiplication Table for 5:
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
5*10=50
1>

2 Expt 2

Develop a stack class to hold a maximum of 10 integers with suitable methods.


Develop a JAVA main method to illustrate Stack operations.

In computer science, a Stack is a linear data structure that follows the LIFO (Last-
In, First-Out) principle. Imagine a stack of plates: the last one you put on top is
the first one you take off.

Computer Science and Engineering 7 of 63


BAJAVB407 OOPS with JAVA Lab 8

2.1 Aim

To implement this in Java, we use an array to store the integers and a top variable
to keep track of the current index.

2.2 The Stack Class Implementation

public class MyStack {


private int[] stackArray;
private int top;
private int maxSize;

// Constructor to initialize the stack with a fixed size of 10


public MyStack() {
[Link] = 10;
[Link] = new int[maxSize];
[Link] = -1; // Stack is empty when top is -1
}

// Push: Add an element to the top


public void push(int value) {
if (isFull()) {
[Link]("Stack Overflow! Cannot push " + value);
} else {
stackArray[++top] = value;
[Link]("Pushed: " + value);
}
}

// Pop: Remove and return the top element


public int pop() {

Computer Science and Engineering 8 of 63


BAJAVB407 OOPS with JAVA Lab 9

if (isEmpty()) {
[Link]("Stack Underflow! No elements to pop.");
return -1;
} else {
return stackArray[top--];
}
}

// Peek: Look at the top element without removing it


public int peek() {
if (isEmpty()) {
return -1;
}
return stackArray[top];
}

public boolean isEmpty() {


return (top == -1);
}

public boolean isFull() {


return (top == maxSize - 1);
}
}

2.3 The Main Method (Demonstration)

public class Main {


public static void main(String[] args) {
MyStack stack = new MyStack();

Computer Science and Engineering 9 of 63


BAJAVB407 OOPS with JAVA Lab 10

// Illustrating Push operations


[Link](10);
[Link](20);
[Link](30);

[Link]("Top element (Peek): " + [Link]());

// Illustrating Pop operations


[Link]("Popped element: " + [Link]());
[Link]("Popped element: " + [Link]());

// Check if empty
[Link]("Is stack empty? " + [Link]());

// Illustrating Stack Overflow


[Link]("Filling the stack...");
for(int i = 1; i <= 10; i++) {
[Link](i * 5);
}
}
}

2.4 Key Concepts Explained

• LIFO Principle: The last element added (e.g., 30) is the first one removed.

• Top Pointer: We start top at -1 because array indices start at 0. When we


push the first item, ++top moves the index to 0.

• Overflow vs. Underflow: Overflow occurs when you try to push into a full
array. Underflow occurs when you try to pop from an empty array.

• Pre-increment (++top) vs Post-decrement (top–): In the code, stackAr-

Computer Science and Engineering 10 of 63


BAJAVB407 OOPS with JAVA Lab 11

ray[++top] moves the pointer first then assigns the value. stackArray[top–]
returns the value first then moves the pointer down.

2.5 Results

2>javac *.java
2>java Main
Pushed: 10
Pushed: 20
Pushed: 30
Top element (Peek): 30
Popped element: 30
Popped element: 20
Is stack empty? false
Filling the stack...
Pushed: 5
Pushed: 10
Pushed: 15
Pushed: 20
Pushed: 25
Pushed: 30
Pushed: 35
Pushed: 40
Pushed: 45
Stack Overflow! Cannot push 50
2>

Computer Science and Engineering 11 of 63


BAJAVB407 OOPS with JAVA Lab 12

3 Expt 3

A class called Employee, which models an employee with an ID, name and salary,
is designed as shown in the following class diagram. The method raiseSalary
(percent) increases the salary by the given percentage. Develop the Employee
class and suitable main method for demonstration.

3.1 The Employee Class Design

To build this Employee class, we will use encapsulation. This means keeping the
data (fields) private and providing public methods (getters and setters) to interact
with that data.

public class Employee {


// Private fields (Data Hiding)
private int id;
private String name;
private double salary;

// Constructor
public Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}

// Method to increase salary by a percentage


public void raiseSalary(double percent) {
if (percent > 0) {
double increase = salary * (percent / 100);

Computer Science and Engineering 12 of 63


BAJAVB407 OOPS with JAVA Lab 13

salary += increase;
[Link]("Salary raised by " + percent + "%. New Salary: " +
} else {
[Link]("Invalid percentage.");
}
}

// Getters to access private data


public int getId() { return id; }
public String getName() { return name; }
public double getSalary() { return salary; }

// toString method for easy printing


@Override
public String toString() {
return "Employee[ID=" + id + ", Name=" + name + ", Salary=" + salary + "]";
}
}

3.2 The Main Method (Demonstration)

The Main class tests the logic by creating an object and applying the raiseSalary
method.

public class Main {


public static void main(String[] args) {
// Create an Employee object
Employee emp = new Employee(101, "Alice Smith", 50000.0);

// Display initial details


[Link]("Before Raise: " + [Link]());

Computer Science and Engineering 13 of 63


BAJAVB407 OOPS with JAVA Lab 14

// Raise salary by 10%


[Link](10);

// Display updated details


[Link]("After Raise: " + [Link]());
}
}

3.3 How it Works

1. The Constructor
When we call new Employee(. . . ), it sets the initial values for that specific
"instance."

2. The this Keyword


In the constructor, [Link] = id tells Java to take the local parameter id and
assign it to the class’s field id.

3. Math Logic
To increase a value by a percent, the formula is:

P ercent
N ewSalary = CurrentSalary + (CurrentSalary × )
100
4. Encapsulation
By making fields private, we prevent other classes from accidentally changing
the salary to a negative number or changing the ID without permission.

Tip: In Java, using @Override on the toString() method is a best practice. It


allows you to print the object directly using [Link](emp) and get a
readable string instead of a memory address.

Computer Science and Engineering 14 of 63


BAJAVB407 OOPS with JAVA Lab 15

3.4 Results

3>java Main
Before Raise: Employee[ID=101, Name=Alice Smith, Salary=50000.0]
Salary raised by 10.0%. New Salary: 55000.0
After Raise: Employee[ID=101, Name=Alice Smith, Salary=55000.0]
3>

Computer Science and Engineering 15 of 63


BAJAVB407 OOPS with JAVA Lab 16

4 Expt 4

A class called MyPoint, which models a 2D point with x and y coordinates, is


designed as follows:

• Two instance variables x (int) and y (int).

• A default (or "no-arg") constructor that construct a point at the default


location of (0, 0).

• A overloaded constructor that constructs a point with the given x and y


coordinates.

• A method setXY() to set both x and y.

• A method getXY() which returns the x and y in a 2-element int array.

• A toString() method that returns a string description of the instance in the


format "(x,y)".

• A method called distance(int x, int y) that returns the distance from this
point to another point at the given (x, y) coordinates.

• An overloaded distance(MyPoint another) that returns the distance from


this point to the given MyPoint instance (called another)

• Another overloaded distance() method that returns the distance from this
point to the origin (0,0)

Develop the code for the class MyPoint. Also develop a JAVA program (called
TestMyPoint) to test all the methods defined in the class.

Computer Science and Engineering 16 of 63


BAJAVB407 OOPS with JAVA Lab 17

4.1 Aim

This is a classic exercise in Method Overloading and the use of the Pythagorean
Theorem in programming. By defining multiple distance() methods with different
parameters, we allow the class to be flexible.

4.2 The MyPoint Class

We use [Link]() and [Link]() for the distance calculations.

The formula used for distance between (x1 , y1 ) and (x2 , y2 ) is:


d= (x2 − x1 )2 + (y2 − y1 )2

public class MyPoint {


private int x = 0;
private int y = 0;

// Default Constructor
public MyPoint() {
}

// Overloaded Constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}

public void setXY(int x, int y) {


this.x = x;

Computer Science and Engineering 17 of 63


BAJAVB407 OOPS with JAVA Lab 18

this.y = y;
}

public int[] getXY() {


return new int[] {this.x, this.y};
}

@Override
public String toString() {
return "(" + x + "," + y + ")";
}

// Distance to given (x, y) coordinates


public double distance(int x, int y) {
int xDiff = this.x - x;
int yDiff = this.y - y;
return [Link](xDiff * xDiff + yDiff * yDiff);
}

// Distance to another MyPoint instance


public double distance(MyPoint another) {
return distance(another.x, another.y); // Reusing the method above
}

// Distance to the origin (0,0)


public double distance() {
return distance(0, 0); // Reusing the first method
}
}

Computer Science and Engineering 18 of 63


BAJAVB407 OOPS with JAVA Lab 19

4.3 The Test Program (TestMyPoint)

This program initializes points and triggers every method to ensure the logic is
sound.

public class Main {


public static void main(String[] args) {
// Test Constructors
MyPoint p1 = new MyPoint(); // (0,0)
MyPoint p2 = new MyPoint(3, 4);

// Test setXY() and getXY()


[Link](1, 1);
int[] coords = [Link]();
[Link]("P1 coords from getXY: (" + coords[0] + "," + coords[1]

// Test toString()
[Link]("Point 1: " + p1);
[Link]("Point 2: " + p2);

// Test Overloaded distance() methods


[Link]("Distance from P2 to (7,1): " + [Link](7, 1));
[Link]("Distance from P2 to P1: " + [Link](p1));
[Link]("Distance from P2 to Origin: " + [Link]());
}
}

4.4 The Test Program (TestMyPoint)

This program initializes points and triggers every method to ensure the logic is
sound.

Computer Science and Engineering 19 of 63


BAJAVB407 OOPS with JAVA Lab 20

public class Main {


public static void main(String[] args) {
// Test Constructors
MyPoint p1 = new MyPoint(); // (0,0)
MyPoint p2 = new MyPoint(3, 4);

// Test setXY() and getXY()


[Link](1, 1);
int[] coords = [Link]();
[Link]("P1 coords from getXY: (" + coords[0] + "," + coords[1]

// Test toString()
[Link]("Point 1: " + p1);
[Link]("Point 2: " + p2);

// Test Overloaded distance() methods


[Link]("Distance from P2 to (7,1): " + [Link](7, 1));
[Link]("Distance from P2 to P1: " + [Link](p1));
[Link]("Distance from P2 to Origin: " + [Link]());
}
}

4.5 Key Technical Concepts

• Method Overloading
We have three distance() methods. Java knows which one to call based on
the arguments you pass (e.g., passing nothing calls the origin version; passing
two ints calls the coordinate version).

• Code Reused
Notice how distance(MyPoint another) simply calls distance(another.x, an-
other.y). This is a "dry" (Don’t Repeat Yourself) coding practice that makes

Computer Science and Engineering 20 of 63


BAJAVB407 OOPS with JAVA Lab 21

maintenance easier.

• Arrays as Return Types


The getXY() method creates a "new" array on the fly. This is a common
way to return multiple related values from a single function call.

4.6 Results

4>javac -g *.java
4>java Main
P1 coords from getXY: (1,1)
Point 1: (1,1)
Point 2: (3,4)
Distance from P2 to (7,1): 5.0
Distance from P2 to P1: 3.605551275463989
Distance from P2 to Origin: 5.0

Computer Science and Engineering 21 of 63


BAJAVB407 OOPS with JAVA Lab 22

5 Expt 5

Develop a JAVA program to create a class named shape. Create three sub classes
namely: circle, triangle and square, each class has two member functions named
draw () and erase (). Demonstrate polymorphism concepts by developing suitable
methods, defining member data and main program.

5.1 Aim

This program demonstrates Runtime Polymorphism (or Method Overriding). We


define a general behavior in the Shape class and then allow each specific subclass
to provide its own unique implementation.

5.2 The Shape Hierarchy

In Java, we use the extends keyword for inheritance. By marking the methods in
the parent class, we ensure that every shape "knows" how to draw and erase itself.

class Shape {
// Member data
String color;

Shape(String color) {
[Link] = color;
}

void draw() {
[Link]("Drawing a generic shape");
}

Computer Science and Engineering 22 of 63


BAJAVB407 OOPS with JAVA Lab 23

void erase() {
[Link]("Erasing a generic shape");
}
}

class Circle extends Shape {


Circle(String color) { super(color); }

@Override
void draw() {
[Link]("Drawing a " + color + " Circle.");
}

@Override
void erase() {
[Link]("Erasing the Circle.");
}
}

class Triangle extends Shape {


Triangle(String color) { super(color); }

@Override
void draw() {
[Link]("Drawing a " + color + " Triangle.");
}

@Override
void erase() {
[Link]("Erasing the Triangle.");
}
}

Computer Science and Engineering 23 of 63


BAJAVB407 OOPS with JAVA Lab 24

class Square extends Shape {


Square(String color) { super(color); }

@Override
void draw() {
[Link]("Drawing a " + color + " Square.");
}

@Override
void erase() {
[Link]("Erasing the Square.");
}
}

5.3 The Main Program (Polymorphism Demo)

The power of polymorphism is that we can treat a group of different objects as if


they are all the same type (Shape), and Java will automatically call the correct
version of the method at runtime.

public class Main {


public static void main(String[] args) {
// Creating an array of Shape references
Shape[] shapes = new Shape[3];

// Upcasting: Storing subclasses in parent class references


shapes[0] = new Circle("Red");
shapes[1] = new Triangle("Green");
shapes[2] = new Square("Blue");

Computer Science and Engineering 24 of 63


BAJAVB407 OOPS with JAVA Lab 25

[Link]("--- Demonstrating Polymorphism ---");

for (Shape s : shapes) {


[Link](); // Calls the specific subclass version
[Link](); // Calls the specific subclass version
[Link]("--------------------");
}
}
}

5.4 Key Concepts

• Inheritance
The subclasses (Circle, Triangle, Square) inherit the properties of Shape.

• Method Overriding
The @Override annotation tells the compiler that we are redefining the
draw() and erase() methods specifically for that subclass.

• Upcasting
We can store a Circle object inside a Shape variable. This is what allows us
to loop through an array of different shapes and treat them uniformly.

• Dynamic Method Dispatch


This is the "magic" of polymorphism. Even though the variable type is
Shape, Java looks at the actual object in memory to decide which draw()
method to execute.

Computer Science and Engineering 25 of 63


BAJAVB407 OOPS with JAVA Lab 26

5.5 Results

5>javac -g *.java
5>java Main
--- Demonstrating Polymorphism ---
Drawing a Red Circle.
Erasing the Circle.
--------------------
Drawing a Green Triangle.
Erasing the Triangle.
--------------------
Drawing a Blue Square.
Erasing the Square.
--------------------
5>

Computer Science and Engineering 26 of 63


BAJAVB407 OOPS with JAVA Lab 27

6 Expt 6

Develop a JAVA program to create an abstract class Shape with abstract methods
calculateArea() and calculatePerimeter(). Create subclasses Circle and Triangle
that extend the Shape class and implement the respective methods to calculate
the area and perimeter of each shape.

6.1 Aim

Using an Abstract Class is the perfect way to handle this. An abstract class acts as
a "blueprint" or a contract. It tells the subclasses: "I don’t know how to calculate
your area yet, but I am forcing you to define that logic yourself."

In this program, we use the following mathematical formulas:

• Circle Area: πr2

• Circle Perimeter (Circumference): 2πr



• Triangle Area (Heron’s Formula): s(s − a)(s − b)(s − c) where s is the
semi-perimeter.

• Triangle Perimeter: a + b + c

6.2 The Abstract Shape Hierarchy

abstract class Shape {


// Abstract methods (no body)
abstract double calculateArea();
abstract double calculatePerimeter();

Computer Science and Engineering 27 of 63


BAJAVB407 OOPS with JAVA Lab 28

// Concrete method (shared logic)


void displayShapeType(String type) {
[Link]("\n--- " + type + " ---");
}
}

class Circle extends Shape {


private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
double calculateArea() {
return [Link] * [Link](radius, 2);
}

@Override
double calculatePerimeter() {
return 2 * [Link] * radius;
}
}

class Triangle extends Shape {


private double sideA, sideB, sideC;

public Triangle(double a, double b, double c) {


[Link] = a;
[Link] = b;
[Link] = c;
}

Computer Science and Engineering 28 of 63


BAJAVB407 OOPS with JAVA Lab 29

@Override
double calculateArea() {
// Using Heron's Formula
double s = (sideA + sideB + sideC) / 2;
return [Link](s * (s - sideA) * (s - sideB) * (s - sideC));
}

@Override
double calculatePerimeter() {
return sideA + sideB + sideC;
}
}

6.3 The Main Program (Demonstration)

public class Main {


public static void main(String[] args) {
// You cannot do: Shape s = new Shape(); // This would cause a compile erro

Shape myCircle = new Circle(5.0);


Shape myTriangle = new Triangle(3.0, 4.0, 5.0);

// Circle Calculations
[Link]("Circle");
[Link]("Area: %.2f%n", [Link]());
[Link]("Perimeter: %.2f%n", [Link]());

// Triangle Calculations
[Link]("Triangle");
[Link]("Area: %.2f%n", [Link]());

Computer Science and Engineering 29 of 63


BAJAVB407 OOPS with JAVA Lab 30

[Link]("Perimeter: %.2f%n", [Link]());


}
}

6.4 Key Takeaways

• Abstract Keyword
By using abstract, you prevent anyone from creating a generic Shape object.
A "Shape" is an idea; a "Circle" is a reality.

• Mandatory Implementation
If a class extends Shape, it must provide the code for calculateArea() and
calculatePerimeter(), or the code will not compile.

• Math Utility
We use [Link] for high precision and [Link]() for the square root cal-
culations required by Heron’s formula.

• Printf Formatting
I used %.2f in the print statement to round the decimal results to two places
for better readability.

6.5 Results

6>javac -g *.java
6>java Main

--- Circle ---


Area: 78.54
Perimeter: 31.42

Computer Science and Engineering 30 of 63


BAJAVB407 OOPS with JAVA Lab 31

--- Triangle ---


Area: 6.00
Perimeter: 12.00
6>

Computer Science and Engineering 31 of 63


BAJAVB407 OOPS with JAVA Lab 32

7 Expt 7

Develop a JAVA program to create an interface Resizable with methods resizeWidth(int


width) andresizeHeight(int height) that allow an object to be resized. Create a
class Rectangle that implements the Resizable interface and implements the resize
methods.

7.1 Aim

In Java, an Interface is a way to achieve absolute abstraction. While an abstract


class can have some finished methods, an interface is purely a contractit tells a
class what it must do, but not how to do it.

By implementing Resizable, our Rectangle class gains the ability to change its
dimensions dynamically.

7.2 The Resizable Interface and Rectangle Class

In this design, we use the implements keyword. Unlike inheritance (extends), a


class can implement multiple interfaces at once.

// Define the interface


interface Resizable {
void resizeWidth(int width);
void resizeHeight(int height);
}

// Implement the interface in a class


class Rectangle implements Resizable {

Computer Science and Engineering 32 of 63


BAJAVB407 OOPS with JAVA Lab 33

private int width;


private int height;

// Constructor
public Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}

// Implementing the interface method for Width


@Override
public void resizeWidth(int width) {
[Link] = width;
[Link]("Width resized to: " + [Link]);
}

// Implementing the interface method for Height


@Override
public void resizeHeight(int height) {
[Link] = height;
[Link]("Height resized to: " + [Link]);
}

public void displayDimensions() {


[Link]("Current Dimensions: " + width + "x" + height);
}
}

Computer Science and Engineering 33 of 63


BAJAVB407 OOPS with JAVA Lab 34

7.3 The Main Program (TestResizable)

This program demonstrates how an object of type Rectangle can be treated as a


Resizable typeanother form of polymorphism.

public class Main {


public static void main(String[] args) {
// Create a Rectangle object
Rectangle myRect = new Rectangle(100, 50);

[Link]("Initial Status: ");


[Link]();

// Using interface methods to resize


[Link](150);
[Link](80);

[Link]("Final Status: ");


[Link]();
}
}

7.4 Key Concepts to Remember

• Contractual Obligation
When Rectangle implements Resizable, it must provide code for both re-
sizeWidth and resizeHeight. If you miss one, the code won’t compile.

• Public by Default
In an interface, all methods are implicitly public and abstract. You don’t

Computer Science and Engineering 34 of 63


BAJAVB407 OOPS with JAVA Lab 35

need to write those keywords, but you must use public when implementing
them in your class.

• Flexibility
If you later created a Window class or an Image class, they could also im-
plement Resizable. This allows you to create a list of Resizable objects and
resize them all, regardless of whether they are Rectangles or Images.

7.5 Results

7>javac -g *.java
7>java Main
Initial Status: Current Dimensions: 100x50
Width resized to: 150
Height resized to: 80
Final Status: Current Dimensions: 150x80
7>

Computer Science and Engineering 35 of 63


BAJAVB407 OOPS with JAVA Lab 36

8 Expt 8

In Java, a package is used to group related classes together. It works like a folder
on your computer, helping you avoid "naming conflicts" (having two classes with
the same name) and making your project easier to manage.

8.1 AIm

To implement this, we need to create two separate files: one for the package and
one to import and use it.

8.2 Create the Package ([Link])

This file must have the package keyword at the very top. We will save this in a
folder named mypack.

package mypack; // Defining the package name

public class MyClass {


public void displayMessage() {
[Link]("Hello from the 'mypack' package!");
}
}

8.3 Import and Implement ([Link])

This file will be located outside the mypack folder. We use the import keyword to
gain access to MyClass.

Computer Science and Engineering 36 of 63


BAJAVB407 OOPS with JAVA Lab 37

import [Link]; // Importing the specific class from our package

public class Main {


public static void main(String[] args) {
// Create an instance of the class from the package
MyClass obj = new MyClass();

// Call the method


[Link]();
}
}

8.4 How to Compile and Run

Because packages rely on the folder structure, you must follow these specific steps
in your terminal/command prompt:

• Create the directory: Create a folder named mypack.

• Save the files: * Put [Link] inside the mypack folder.

• Put [Link] in the parent folder (outside mypack).

• Compile the package: javac mypack/[Link]

• Compile the main program: javac [Link]

• Run the program: java TestPackage

8.5 Key Rules for Packages

The Folder Rule: The package name must match the folder name exactly. If your
package is [Link], your file must be inside com/math/logic/.

Computer Science and Engineering 37 of 63


BAJAVB407 OOPS with JAVA Lab 38

The Public Rule: Only public classes can be accessed from outside their package.
If you remove public from MyClass, TestPackage will throw a compilation error.

Importing All: If you had many classes in mypack, you could import them all at
once using import mypack.*;.

8.6 Results

8>javac -g *.java
8>java Main
Hello from the 'mypack' package!
8>

Computer Science and Engineering 38 of 63


BAJAVB407 OOPS with JAVA Lab 39

9 Expt 9

Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionByZero using try, catch, throw and finally.

9.1 Aim

In Java, while there is a built-in ArithmeticException for division by zero, creating


a Custom Exception (User-Defined Exception) is a common way to handle specific
business logic or more descriptive error reporting.

To do this, we create a class that extends the Exception class.

9.2 Defining the Custom Exception

We create a class called DivisionByZeroException. By extending Exception, we


make it a "checked" exception, meaning the compiler will force us to handle it.

// Custom Exception Class


class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message); // Pass the message to the parent Exception class
}
}

Computer Science and Engineering 39 of 63


BAJAVB407 OOPS with JAVA Lab 40

9.3 The Main Program (Implementation)

We use a method that "throws" our custom exception if the divisor is zero. We
then handle it using the try-catch-finally block.

public class Main {

// Method that uses the 'throw' keyword


public static double divide(int numerator, int denominator) throws DivisionByZe
if (denominator == 0) {
// Manually raising our custom exception
throw new DivisionByZeroException("Error: You cannot divide " + numerat
}
return (double) numerator / denominator;
}

public static void main(String[] args) {


int a = 10;
int b = 0;

try {
[Link]("Attempting division...");
double result = divide(a, b);
[Link]("Result: " + result);
}
catch (DivisionByZeroException e) {
// Handling the custom exception
[Link]("Caught Custom Exception: " + [Link]());
}
finally {
// This block always executes
[Link]("Execution of division attempt is complete.");

Computer Science and Engineering 40 of 63


BAJAVB407 OOPS with JAVA Lab 41

}
}
}

9.4 Key Exception Keywords Explained

• throw
Used to manually trigger an exception (e.g., throw new Exception()).

• throws
Used in a method signature to warn that this method might cause an excep-
tion.

• try
Contains the code that might "break" or throw an error.

• catch
Contains the logic to fix or report the error if it occurs. finallyCode that
runs no matter what (used for "cleanup" like closing files or databases).

9.5 Results

9>javac -g *.java
9>java Main
Attempting division...
Caught Custom Exception: Error: You cannot divide 10 by zero!
Execution of division attempt is complete.
9>

Computer Science and Engineering 41 of 63


BAJAVB407 OOPS with JAVA Lab 42

10 Expt 10

Write a program to illustrate creation of threads using runnable Interface. (start


method start each of the newly created thread. Inside the run method there is
sleep() for suspend the thread for 500 milliseconds).

10.1 Aim

In Java, creating threads using the Runnable Interface is the preferred approach
because it allows your class to extend another class (like Shape or Employee) while
still gaining threading capabilities.

Here is a program that creates two threads, each printing a message and sleeping
for 500 milliseconds.

10.2 Java Thread Program (Runnable Interface)

class MyThread implements Runnable {


private String threadName;

MyThread(String name) {
[Link] = name;
}

// The run() method contains the code executed by the thread


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {

Computer Science and Engineering 42 of 63


BAJAVB407 OOPS with JAVA Lab 43

[Link](threadName + " - Iteration: " + i);

// Suspend the thread for 500 milliseconds


[Link](500);

} catch (InterruptedException e) {
[Link](threadName + " was interrupted.");
}
}
[Link](threadName + " has finished execution.");
}
}

10.3 How the Thread Lifecycle Works

When you run this program, you will notice that the output from "Thread-A" and
"Thread-B" is interleaved (mixed together). This happens because both threads
are running concurrently.

10.4 Key Components:

• run() method
This is the entry point for the thread. Its the "job" the thread is assigned to
do.

• [Link](500)
This puts the thread into a Timed Waiting state. It pauses the thread,
allowing other threads a chance to use the CPU. It requires a try-catch
block because it can throw an InterruptedException.

• start() method

Computer Science and Engineering 43 of 63


BAJAVB407 OOPS with JAVA Lab 44

This is crucial. You never call run() directly. Calling start() tells the Java
Virtual Machine (JVM) to create a new call stack and then execute run()
inside that new stack.

10.5 Why use Runnable instead of extending Thread?

• Inheritance
Since Java only allows a class to extend one parent class, using Runnable
leaves your class free to extend something else.

• Object Sharing
Multiple threads can share the same Runnable instance to work on the same
data.

10.6 Results

10>javac -g *.java
10>java Main
Thread-B - Iteration: 1
Thread-A - Iteration: 1
Thread-A - Iteration: 2
Thread-B - Iteration: 2
Thread-A - Iteration: 3
Thread-B - Iteration: 3
Thread-A - Iteration: 4
Thread-B - Iteration: 4
Thread-A - Iteration: 5
Thread-B - Iteration: 5
Thread-B has finished execution.
Thread-A has finished execution.

Computer Science and Engineering 44 of 63


BAJAVB407 OOPS with JAVA Lab 45

10>

Computer Science and Engineering 45 of 63


BAJAVB407 OOPS with JAVA Lab 46

PART B: TYPICAL OPEN-ENDED EXPERIMENTS

Computer Science and Engineering 46 of 63


BAJAVB407 OOPS with JAVA Lab 47

11 Expt 1

Write a java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green with radio buttons. On selecting a
button, an appropriate message with stop or ready or go should appear above the
buttons in a selected color. Initially there is no message shown.

11.1 Aim

To create this simulation, we use Java Swing. This allows us to create a graphical
user interface (GUI) with radio buttons and a label that changes dynamically.

We will use a ButtonGroup to ensure that only one radio button can be selected
at a time, and an ActionListener to detect when a user clicks a button.

11.2 Java Traffic Light Program

import [Link].*;
import [Link].*;
import [Link].*;

public class TrafficLight extends JFrame implements ActionListener {


// GUI Components
private JRadioButton redBtn, yellowBtn, greenBtn;
private JLabel messageLabel;
private ButtonGroup group;

public TrafficLight() {
// Setup the Frame

Computer Science and Engineering 47 of 63


BAJAVB407 OOPS with JAVA Lab 48

setTitle("Traffic Light Simulation");


setSize(300, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// 1. Create the Label (Message area)


messageLabel = new JLabel(" ");
[Link](new Font("Arial", [Link], 24));
add(messageLabel);

// 2. Create Radio Buttons


redBtn = new JRadioButton("Red");
yellowBtn = new JRadioButton("Yellow");
greenBtn = new JRadioButton("Green");

// 3. Add buttons to a Group (prevents multiple selections)


group = new ButtonGroup();
[Link](redBtn);
[Link](yellowBtn);
[Link](greenBtn);

// 4. Add Action Listeners


[Link](this);
[Link](this);
[Link](this);

// 5. Add buttons to the frame


add(redBtn);
add(yellowBtn);
add(greenBtn);

setVisible(true);
}

Computer Science and Engineering 48 of 63


BAJAVB407 OOPS with JAVA Lab 49

// Logic for button selection


@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == redBtn) {
[Link]("STOP");
[Link]([Link]);
} else if ([Link]() == yellowBtn) {
[Link]("READY");
[Link]([Link]);
} else if ([Link]() == greenBtn) {
[Link]("GO");
[Link]([Link]);
}
}

public static void main(String[] args) {


// Run the GUI on the Event Dispatch Thread
[Link](() -> new TrafficLight());
}
}

11.3 How it Works

JFrame & FlowLayout: The JFrame is the main window. FlowLayout simply
places the components in a row, wrapping them if the window is too small.

ButtonGroup: This is a non-visual component. Its only job is to ensure that if


you click "Yellow," the "Red" button automatically deselects.

ActionListener: We implement this interface so our class can "listen" for clicks.

Computer Science and Engineering 49 of 63


BAJAVB407 OOPS with JAVA Lab 50

The actionPerformed method is triggered every time a radio button is pressed.

setForeground(Color): This method changes the text color of the JLabel to match
the traffic light logic.

Computer Science and Engineering 50 of 63


BAJAVB407 OOPS with JAVA Lab 51

12 Expt 2

Suppose that a table named [Link] is stored in a text file. The first line in the
file is the header, and the remaining lines correspond to rows in the table. The
elements are separated by commas. Write a java program to display the table
using Labels in Grid Layout.

12.1 Aim

To solve this, we will use Java Swing with a GridLayout. The GridLayout is perfect
for this task because it arranges components in a rectangular grid of equal-sized
cells, mimicking the structure of a spreadsheet or a database table.

The program involves two main steps:

Parsing the File: Reading the text file and counting the rows and columns to set
up the grid.

Building the GUI: Creating JLabel components for each data "cell" and adding
them to the frame.

12.2 Java Program: [Link]

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class TableDisplay extends JFrame {

Computer Science and Engineering 51 of 63


BAJAVB407 OOPS with JAVA Lab 52

public TableDisplay(String filename) {


setTitle("Text File Table Display");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ArrayList<String[]> data = new ArrayList<>();


int columns = 0;

// 1. Read the file into an ArrayList


try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = [Link]()) != null) {
String[] values = [Link](",");
[Link](values);
columns = [Link](columns, [Link]);
}
} catch (IOException e) {
[Link](this, "File not found: " + filename);
return;
}

// 2. Set the Layout (Rows, Columns)


int rows = [Link]();
setLayout(new GridLayout(rows, columns, 5, 5)); // 5px gaps

// 3. Create Labels for each element


for (int i = 0; i < rows; i++) {
String[] rowData = [Link](i);
for (int j = 0; j < columns; j++) {
String cellText = (j < [Link]) ? rowData[j].trim() : "";
JLabel label = new JLabel(cellText, [Link]);

// Style the Header (first row) differently

Computer Science and Engineering 52 of 63


BAJAVB407 OOPS with JAVA Lab 53

if (i == 0) {
[Link](new Font("Arial", [Link], 14));
[Link](true);
[Link](Color.LIGHT_GRAY);
}

[Link]([Link]([Link]));
add(label);
}
}

pack(); // Adjust window size to fit grid


setVisible(true);
}

public static void main(String[] args) {


// Ensure the file exists before running
[Link](() -> new TableDisplay("[Link]"));
}
}

12.3 Key Components Explained

The Grid Layout

The GridLayout(rows, columns, hgap, vgap) constructor ensures that every cell in
your table has the exact same dimensions. If your file has 5 lines and 3 commas
per line, the grid becomes a 5 × 3 matrix.

File Handling

Computer Science and Engineering 53 of 63


BAJAVB407 OOPS with JAVA Lab 54

We use BufferedReader combined with [Link](","). This splits each string into
an array of substrings. Using trim() is important here to remove any accidental
spaces around the commas in your text file.

Conditional Styling

The code checks if (i == 0). This allows the first line (the header) to be bold and
have a background color, making it visually distinct from the data rows.

12.4 How to Prepare your [Link]

Ensure your text file is in the same folder as your .java file. It should look like
this:Plaintext

ID, Name, Department 101, Alice, Engineering 102, Bob, Design 103, Charlie,
Marketing

Computer Science and Engineering 54 of 63


BAJAVB407 OOPS with JAVA Lab 55

13 Expt 3

Write a Java program that reads on file name from the user, then displays infor-
mation about whether the file exists, whether the file is readable, whether the file
is writable, the type of file and the length of the file in bytes?

13.1 Aim

To handle file information in Java, we use the [Link] class. This class provides
built-in methods to probe the file system for metadata like permissions and size.

13.2 Java File Info Program

import [Link];
import [Link];

public class FileInfo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter the file name (with path if necessary): ");


String fileName = [Link]();

// Create a File object


File file = new File(fileName);

[Link]("\n--- File Information ---");

// 1. Check if file exists

Computer Science and Engineering 55 of 63


BAJAVB407 OOPS with JAVA Lab 56

if ([Link]()) {
[Link]("Exists: Yes");

// 2. Check readability
[Link]("Readable: " + ([Link]() ? "Yes" : "No"));

// 3. Check writability
[Link]("Writable: " + ([Link]() ? "Yes" : "No"));

// 4. Determine type (File or Directory)


if ([Link]()) {
[Link]("Type: Directory");
} else if ([Link]()) {
[Link]("Type: Regular File");
} else {
[Link]("Type: Unknown");
}

// 5. Length in bytes
[Link]("Length: " + [Link]() + " bytes");

} else {
[Link]("Exists: No");
[Link]("The specified file does not exist.");
}

[Link]();
}
}

Computer Science and Engineering 56 of 63


BAJAVB407 OOPS with JAVA Lab 57

13.3 Key Methods Used

The File class doesn’t actually open the file’s contents; it just looks at the File
Attributes stored by the Operating System.

exists(): Returns true if the path provided actually points to a physical file or
folder.

canRead() / canWrite(): Checks the OS-level permissions for the user running the
Java program.

isFile() vs isDirectory(): In many operating systems, a "directory" is just a special


type of file. These methods help distinguish between them.

length(): Returns the size of the file as a long value representing total bytes. Note
that for directories, the return value is undefined or 0 on many systems.

Computer Science and Engineering 57 of 63


BAJAVB407 OOPS with JAVA Lab 58

14 Expt 4

Write a Java program that reads a file and displays the file on the screen, with a
line number before each line?

14.1 Aim

To read a file and display it with line numbers, we use the Scanner or Buffere-
dReader class. For this specific task, Scanner is very convenient because it provides
a simple hasNextLine() and nextLine() loop.

We will use a counter variable that increments with every iteration of the loop to
provide the line numbers.

14.2 Java Program: [Link]

import [Link];
import [Link];
import [Link];

public class LineNumberDisplay {


public static void main(String[] args) {
Scanner inputScanner = new Scanner([Link]);

[Link]("Enter the filename to read: ");


String fileName = [Link]();

File file = new File(fileName);

Computer Science and Engineering 58 of 63


BAJAVB407 OOPS with JAVA Lab 59

try {
Scanner fileReader = new Scanner(file);
int lineNumber = 1;

[Link]("\n--- File Content ---");


while ([Link]()) {
String line = [Link]();
// Printing the line number followed by the content
[Link](lineNumber + ": " + line);
lineNumber++;
}
[Link]();

} catch (FileNotFoundException e) {
[Link]("Error: The file '" + fileName + "' was not found.")
} finally {
[Link]();
}
}
}

How the Program Works

File Setup: We create a File object using the path provided by the user. Note that
this doesn’t open the file yet; it just creates a reference to it.

The try-catch Block: File operations are "risky." If the file doesn’t exist or is
locked, Java will throw a FileNotFoundException. We must catch this to prevent
the program from crashing.

Iteration: The while (fi[Link]()) loop is the standard way to pro-


cess a file of unknown length. It keeps going until it reaches the end of the file

Computer Science and Engineering 59 of 63


BAJAVB407 OOPS with JAVA Lab 60

(EOF).

Formatting: Using lineNumber + ": " + line ensures the output looks clean. For
very large files, you might use [Link]("%4d: %s%n", lineNumber, line)
to keep the numbers aligned in a column.

Computer Science and Engineering 60 of 63


BAJAVB407 OOPS with JAVA Lab 61

15 Expt 5

Write a Java program that displays the number of characters, lines and words in
a text?

15.1 Aim

To count characters, lines, and words, we need to process a text string (or file)
and apply different logic for each metric.

In Java, we can use the [Link]() method with Regular Expressions (regex) to
identify words, as words are typically separated by one or more spaces or tabs.

15.2 Java Text Analyzer Program

import [Link];

public class TextAnalyzer {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter your text (Press Enter twice or Ctrl+D to finish)

StringBuilder fullText = new StringBuilder();


int lineCount = 0;

// Reading multi-line input


while ([Link]()) {
String line = [Link]();

Computer Science and Engineering 61 of 63


BAJAVB407 OOPS with JAVA Lab 62

if ([Link]()) break; // Stop if user enters an empty line


[Link](line).append("\n");
lineCount++;
}

String content = [Link]().trim();

if ([Link]()) {
[Link]("No text entered.");
} else {
// 1. Character Count (including spaces)
int charCount = [Link]();

// 2. Word Count
// \\s+ matches one or more whitespace characters
String[] words = [Link]("\\s+");
int wordCount = [Link];

// Display Results
[Link]("\n--- Analysis Results ---");
[Link]("Lines: " + lineCount);
[Link]("Words: " + wordCount);
[Link]("Characters: " + charCount);
}

[Link]();
}
}

Computer Science and Engineering 62 of 63


BAJAVB407 OOPS with JAVA Lab 63

15.3 Logic Breakdown

• Counting Lines
Every time the user presses Enter and the [Link]() loop runs,
we increment our lineCount.

• Counting Words
Counting words is trickier than just looking for spaces. A user might put
three spaces between words by accident. By using the regex \+, we tell
Java to treat any sequence of whitespace (spaces, tabs, newlines) as a single
"separator."

• Counting Characters
The .length() method of the String class returns the total number of char-
acters, including punctuation and spaces.

Computer Science and Engineering 63 of 63

You might also like