Oops Java Manual (1)
Oops Java Manual (1)
LABORATORY MANUAL
IV Semester
DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024
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
3*1=3
3*2=6
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).
Develop the code for the class MyPoint. Also develop a JAVA
program (called TestMyPoint) to test all the methods defined in the
class.
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.
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?
DEPARTMENT OF CSE
Atria Institute of Technology
Bengaluru – 560 024
BAJAVB407 OOPS with JAVA Lab 1
1 Expt 1
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
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.
import [Link];
[Link]();
}
}
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:
2. float
3. long
Since double is higher than int, the integer 90 is temporarily treated as a double.
1.5 Results
1>javac -g *.java
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.
import [Link];
if ([Link]()) {
int num = [Link]();
[Link]("Multiplication Table for " + num + ":");
// 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]();
}
}
• The for loop is the engine of this program. It follows a specific three-step
logic to ensure it runs exactly 10 times.
• Condition (i <= 10): The loop keeps running as long as i is less than or
equal to 10.
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
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.
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.
if (isEmpty()) {
[Link]("Stack Underflow! No elements to pop.");
return -1;
} else {
return stackArray[top--];
}
}
// Check if empty
[Link]("Is stack empty? " + [Link]());
• LIFO Principle: The last element added (e.g., 30) is the first one removed.
• 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.
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>
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.
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.
// Constructor
public Employee(int id, String name, double salary) {
[Link] = id;
[Link] = name;
[Link] = salary;
}
salary += increase;
[Link]("Salary raised by " + percent + "%. New Salary: " +
} else {
[Link]("Invalid percentage.");
}
}
The Main class tests the logic by creating an object and applying the raiseSalary
method.
1. The Constructor
When we call new Employee(. . . ), it sets the initial values for that specific
"instance."
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.
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>
4 Expt 4
• A method called distance(int x, int y) that returns the distance from this
point to another point at the given (x, y) coordinates.
• 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.
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.
The formula used for distance between (x1 , y1 ) and (x2 , y2 ) is:
√
d= (x2 − x1 )2 + (y2 − y1 )2
// Default Constructor
public MyPoint() {
}
// Overloaded Constructor
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
this.y = y;
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
This program initializes points and triggers every method to ensure the logic is
sound.
// Test toString()
[Link]("Point 1: " + p1);
[Link]("Point 2: " + p2);
This program initializes points and triggers every method to ensure the logic is
sound.
// Test toString()
[Link]("Point 1: " + p1);
[Link]("Point 2: " + p2);
• 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
maintenance easier.
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
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
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");
}
void erase() {
[Link]("Erasing a generic shape");
}
}
@Override
void draw() {
[Link]("Drawing a " + color + " Circle.");
}
@Override
void erase() {
[Link]("Erasing the Circle.");
}
}
@Override
void draw() {
[Link]("Drawing a " + color + " Triangle.");
}
@Override
void erase() {
[Link]("Erasing the Triangle.");
}
}
@Override
void draw() {
[Link]("Drawing a " + color + " Square.");
}
@Override
void erase() {
[Link]("Erasing the Square.");
}
}
• 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.
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>
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."
• Triangle Perimeter: a + b + c
@Override
double calculateArea() {
return [Link] * [Link](radius, 2);
}
@Override
double calculatePerimeter() {
return 2 * [Link] * radius;
}
}
@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;
}
}
// Circle Calculations
[Link]("Circle");
[Link]("Area: %.2f%n", [Link]());
[Link]("Perimeter: %.2f%n", [Link]());
// Triangle Calculations
[Link]("Triangle");
[Link]("Area: %.2f%n", [Link]());
• 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
7 Expt 7
7.1 Aim
By implementing Resizable, our Rectangle class gains the ability to change its
dimensions dynamically.
// Constructor
public Rectangle(int width, int height) {
[Link] = width;
[Link] = height;
}
• 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
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>
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.
This file must have the package keyword at the very top. We will save this in a
folder named mypack.
This file will be located outside the mypack folder. We use the import keyword to
gain access to MyClass.
Because packages rely on the folder structure, you must follow these specific steps
in your terminal/command prompt:
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/.
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>
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
We use a method that "throws" our custom exception if the divisor is zero. We
then handle it using the try-catch-finally block.
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.");
}
}
}
• 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>
10 Expt 10
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.
MyThread(String name) {
[Link] = name;
}
} catch (InterruptedException e) {
[Link](threadName + " was interrupted.");
}
}
[Link](threadName + " has finished execution.");
}
}
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.
• 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
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.
• 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.
10>
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.
import [Link].*;
import [Link].*;
import [Link].*;
public TrafficLight() {
// Setup the Frame
setVisible(true);
}
JFrame & FlowLayout: The JFrame is the main window. FlowLayout simply
places the components in a row, wrapping them if the window is too small.
ActionListener: We implement this interface so our class can "listen" for clicks.
setForeground(Color): This method changes the text color of the JLabel to match
the traffic light logic.
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.
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.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
if (i == 0) {
[Link](new Font("Arial", [Link], 14));
[Link](true);
[Link](Color.LIGHT_GRAY);
}
[Link]([Link]([Link]));
add(label);
}
}
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
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.
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
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.
import [Link];
import [Link];
if ([Link]()) {
[Link]("Exists: Yes");
// 2. Check readability
[Link]("Readable: " + ([Link]() ? "Yes" : "No"));
// 3. Check writability
[Link]("Writable: " + ([Link]() ? "Yes" : "No"));
// 5. Length in bytes
[Link]("Length: " + [Link]() + " bytes");
} else {
[Link]("Exists: No");
[Link]("The specified file does not exist.");
}
[Link]();
}
}
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.
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.
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.
import [Link];
import [Link];
import [Link];
try {
Scanner fileReader = new Scanner(file);
int lineNumber = 1;
} catch (FileNotFoundException e) {
[Link]("Error: The file '" + fileName + "' was not found.")
} finally {
[Link]();
}
}
}
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.
(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.
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.
import [Link];
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]();
}
}
• 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.