OOP JavaLabManual Part-1
OOP JavaLabManual Part-1
For
OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB
(23CS28PC307)
Prepared by
A.Harish, Assistant Professor, CSE Dept.
Laboratory Manual
Course Objectives:
To understand OOP principles.
To understand the Exception Handling mechanism.
To understand Java collection framework.
To understand multithreaded programming.
To understand swing controls in Java.
Course Outcomes:
Able to write the programs for solving real world problems using Java OOP principles.
Able to write programs using Exceptional Handling approach.
Able to write multithreaded applications.
Able to write GUI programs using swing controls in Java.
i
Programming languages:
There are several thousand programming languages that have been documented over the years.
Programming languages can be categorized into several types based on various criteria such as their
purpose, level of abstraction, or historical development.
Low-Level Languages:
Machine Language: Machine language, also known as machine code, is the lowest-level
programming language. It consists of binary digits (0s and 1s) that directly represent
instructions executed by a computer's central processing unit (CPU).
Assembly Language: Assembly language is a human-readable representation of machine
language. It uses mnemonics and symbols to represent machine instructions and data. Assembly
language programs need to be translated into machine code before they can be executed by the
computer.
Ex: An assembly language instruction like MOV AX, 5 might represent moving the value 5
into the AX register of an x86 CPU, which corresponds to a specific sequence of binary
digits in machine language.
High-Level Languages:
Procedural Languages: These languages follow a top-down approach to problem-solving,
where tasks are broken down into procedures that perform specific actions.
Object-Oriented Languages: Object-oriented programming (OOP) languages are based on
the concept of "objects," which are instances of classes that encapsulate data (attributes) and
behaviors (methods).
OOP focuses on organizing code into reusable components, making it easier to manage and
scale large software systems.
Compiler vs Interpreter:
Compiler: A compiler translates the entire source code of a program into machine code or an
intermediate language (like bytecode) all at once, before execution begins. The bytecode that
can be executed directly by the computer's CPU or a virtual machine. (e.g., C, C++).
Interpreter: An interpreter reads and executes each line of source code or script sequentially,
translating it into machine code or executing it directly. (e.g., Python, Ruby).
ii
Installation of Java JDK (Java Development Kit)
For Windows:
1. Download JDK:
o Go to the Oracle JDK download page.
o Choose the JDK version you need and download the installer for Windows.
2. Run the Installer:
o Locate the downloaded .exe file and double-click it to start the installation process.
o Follow the on-screen instructions. You can use the default settings or customize the installation
directory.
3. Set Environment Variables:
o Open the Start Menu and search for Environment Variables, then select Edit the system
environment variables.
o In the System Properties window, click on the Environment Variables button.
o Under System Variables, click New and add a new variable:
Variable name: JAVA_HOME
Variable value: C:\Program Files\Java\jdk-<version> (adjust according to your installation
path).
o Find the Path variable in the System Variables section, select it, and click Edit.
o Add a new entry: %JAVA_HOME%\bin.
4. Verify Installation:
o Open a command prompt and type java -version. You should see the installed Java version.
o Also, type javac -version to check the version of the Java compiler.
iii
INDEX
Week
S.No Name of the Experiment Page.No
No
A basic Java program structure with an example to read the user input
1 1 1
and display it in a desired format
9(A) 5 Program for illustrating the String Operations using String class 13
Reverse a String
9(B) 5 14
Use Eclipse or Net bean platform and acquaint yourself with the
various menus. Create a test project, add a test class, and run it. See
how you can use auto suggestions, auto fill. Try code formatter and
11 6 16
code refactoring like renaming variables, methods, and classes. Try
debug step by step with a small program of about 10 to 15 lines which
contains at least one if else condition and a for loop.
iv
A basic Java program structure consists of the following components-
1. Package Declaration (optional)
2. Import Statements (optional)
3. Class Declaration
4. Main Method
5. Other Methods and Fields
1. Package Declaration (optional)
Packages are used to group related classes. The package statement should be the first line in the file.
package com.example.myapp;
2. Import Statements (optional)
Import statements are used to include external classes and packages. They come after the package
declaration and before the class declaration.
import java.util.Scanner;
3. Class Declaration
Every Java program must have at least one class. The class name should match the filename.
public class MyFirstProgram {
// Fields and methods declaration }
4. Main Method
The main method is the entry point of a Java program. It must be inside a class.
public class MyFirstProgram {
public static void main(String[] args) {
// Program execution starts here
}
}
5. Other Methods and Fields
You can define fields (variables) and methods (functions) inside a class. These can be static or instance
members. Which can be illustrated in below java program.
1. Simple Java program to read the user input and displaying it in a desired format.
//package com.example.src;
//import statement declaration
import java.util.Scanner;
//Class declaration
public class MyFirstProgram{
// Field/Variable/Attribute/Properties declaration
private String message;
//Parameterized Constructor declaration
public MyFirstProgram(String message) {
this.message = message;
}
//Main method declaration
public static void main(String[] args){
// Object declaration
MyFirstProgram program = new MyFirstProgram("Hello, World!");
//calling (invoking) of instance method
program.printMessage();
//Scanner class object for user input
1
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
//read the user entered input
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
//close the scanner object
scanner.close();
}
//method declaration to print message
public void printMessage()
{
//method implementation
System.out.println(message);
}
}
Output:
Hello, World!
Enter your name: RAMA
Hello, RAMA!
Note: Java programming structure consists at least one class having main method or multiple classes
within it, one class is having main method and this respective class can be called as Main class.
Comments Declaration: Comments are used to annotate the code and are ignored by the compiler.
// This is a single-line comment
/*
* This is a multi-line comment
* It spans multiple lines
*/
The JVM (Java Virtual Machine) is responsible for ensuring that Java programs are executed
consistently and reliably across different platforms, adhering to the “Write Once, Run Anywhere”
principle.
Object-Oriented Programming (OOP) is a programming paradigm that promotes the use of objects
(instances of classes) to model and represent real-world entities and their interactions in software. Java
is an object-oriented programming language, and OOP is central to its design.
2
Naming Conventions in Java-
1. Variable Naming Conventions:
- Variable names should be meaningful and describe the purpose of the variable.
- Variable names should start with a lowercase letter and use camelCase for subsequent words.
Examples: int studentAge;
String firstName;
double accountBalance;
2. Class Naming Conventions:
- Class names should be nouns, in mixed case with the first letter of each internal word capitalized
(PascalCase).
- Class names should be meaningful and describe what the class represents.
Examples: public class Student { }
public class BankAccount { }
public class EmployeeRecord { }
3. Method Naming Conventions:
- Method names should be verbs, in mixed case with the first letter lowercase and the first letter of
each internal word capitalized (camelCase).
- Method names should be descriptive of the action they perform.
Examples: public void calculateTotal() { }
public String getFirstName() { }
public boolean isAccountActive() { }
4. Constant Naming Conventions:
- Constant names should be in uppercase with words separated by underscores.
- Constants should be declared `static final`.
Examples: public static final int MAX_USERS = 100;
public static final String DEFAULT_LANGUAGE = "English";
public static final double PI = 3.14159;
5. Package Naming Conventions:
- Package names should be in lowercase to avoid conflicts with class names.
- Typically, they use the reverse domain name of the organization, followed by specific project or
module names.
Examples: package com.example.myapp;
package org.company.project.module;
package edu.university.department;
3
2(a). Calculate the Average of Numbers
import java.util.Scanner;
public class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double sum = 0;
System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
double num = scanner.nextDouble();
sum += num;
}
double average = sum / n;
System.out.println("Average: " + average);
scanner.close();
}
}
Output:
Enter the number of elements: 5
Enter 5 numbers:
2
3
4
5
6
Average: 4.0
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of Circle: ");
double radius = scanner.nextDouble();
double area = Math.PI * radius * radius;
System.out.println("Area of the circle with radius " + radius + " is " + area);
}
}
Output:
Enter the radius of Circle: 7
Area of the circle with radius 7.0 is 153.93804002589985
3(a). Program for find the Factorial of a given Number Using Recursion
import java.util.Scanner;
4
public class FactorialUsingRecursion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
long factorial = calculateFactorial(n);
System.out.println("Factorial of " + n + " is " + factorial);
scanner.close();
}
public static long calculateFactorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * calculateFactorial(n - 1);
}
}
}
Output:
Enter a positive integer: 9
Factorial of 9 is 362880
import java.util.Scanner;
public class PrintPattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer to adjust the size of the triangle: ");
int n = scanner.nextInt();
for (int i =1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
Enter a positive integer to adjust the size of the triangle: 6
*
**
***
****
*****
******
5
4(a). Program for using Single Dimensional Arrays
import java.util.Scanner;
public class ArrayInputOutput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Create the array with the specified size
int[] array = new int[size];
// Input: Elements of the array
System.out.println("Enter " + size + " elements for the array:");
for (int i = 0; i < size; i++) {
System.out.print("Element " + (i + 1) + ": ");
array[i] = scanner.nextInt();
}
// Display the elements of the array
System.out.println("The elements of the array are:");
for (int i = 0; i < size; i++) {
System.out.println("Element " + (i + 1) + ": " + array[i]);
}
scanner.close();
}
}
Output:
Enter the size of the array: 6
Enter 6 elements for the array:
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Element 6: 7
The elements of the array are:
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Element 6: 7
import java.util.Scanner;
public class TwoDimensionalArray {
6
// Method to create and initialize a 2D array
public static int[][] create2DArray(int rows, int cols) {
return new int[rows][cols];
}
// Method to fill the 2D array with user input
public static void fill2DArray(int[][] array, Scanner scanner) {
System.out.println("Enter the values for the 2D array:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print("Enter value for position (" + i + "," + j + "): ");
array[i][j] = scanner.nextInt();
}
}
}
// Method to display the 2D array
public static void display2DArray(int[][] array) {
System.out.println("The 2D array is:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input number of rows and columns
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter number of columns: ");
int cols = scanner.nextInt();
// Create the 2D array
int[][] array = create2DArray(rows, cols);
// Fill the 2D array with user input
fill2DArray(array, scanner);
// Display the 2D array
display2DArray(array);
// Close the scanner
scanner.close();
}
}
Output:
Enter number of rows: 3
Enter number of columns: 2
Enter the values for the 2D array:
Enter value for position (0,0): 2
Enter value for position (0,1): 3
7
Enter value for position (1,0): 4
Enter value for position (1,1): 5
Enter value for position (2,0): 6
Enter value for position (2,1): 7
The 2D array is:
23
45
67
8
c *= 2;
System.out.println("c *= 2: " + c);
c /= 4;
System.out.println("c /= 4: " + c);
c %= 3;
System.out.println("c %= 3: " + c);
}
}
Output:
a + b = 15
a-b=5
a * b = 50
a/b=2
a%b=0
a == b: false
a != b: true
a > b: true
a < b: false
a >= b: true
a <= b: false
x && y: false
x || y: true
!x: false
c = 15
c += 5: 20
c -= 3: 17
c *= 2: 34
c /= 4: 8
c %= 3: 2
9
System.out.println("Excellent!");
break;
case 'B':
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
// While Loop
int count = 1;
while (count <= 3) {
System.out.println("Count is: " + count);
count++;
}
// Do-While Loop
int counter = 1;
do {
System.out.println("Counter is: " + counter);
counter++;
} while (counter <= 3);
// For Loop
for (int i = 1; i <= 3; i++) {
System.out.println("i is: " + i);
}
// Break Statement
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // exit the loop when i is 3
}
System.out.println("i (with break) is: " + i);
}
// Continue Statement
for (int i = 1; i <= 3; i++) {
if (i == 2) {
continue; // skip the iteration when i is 2
}
System.out.println("i (with continue) is: " + i);
}
}
}
10
Output:
10 is a positive number.
Well done
Count is: 1
Count is: 2
Count is: 3
Counter is: 1
Counter is: 2
Counter is: 3
i is: 1
i is: 2
i is: 3
i (with break) is: 1
i (with break) is: 2
i (with continue) is: 1
i (with continue) is: 3
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.println("Choose an operation (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
} else {
System.out.println("Cannot divide by zero.");
return;
11
}
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println("Result: " + result);
scanner.close();
}
}
Output:
Enter the first number: 7
Enter the second number: 9
Choose an operation (+, -, *, /):
+
Result: 16.0
Constructor: Used to initialize the objects with initial values. It's called when an instance of a class is
created.
Getters and Setters: Methods used to retrieve and update the value of a private field of a class,
providing controlled access.
8. Program for how to use a constructor to initialize an object and how to use getters and setters
to access and modify private fields.
12
public void setAge(int age) {
// You can add validation logic here
if(age > 0) {
this.age = age;
} else {
System.out.println("Age must be positive.");
}
}
// Main method to test the Person class
public static void main(String[] args) {
// Create a Person object using the constructor
Person person = new Person("Rama", 25);
// Access fields using getters
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Modify fields using setters
person.setName("Sitha");
person.setAge(30);
// Access modified fields using getters
System.out.println("Updated Name: " + person.getName());
System.out.println("Updated Age: " + person.getAge());
// Try setting an invalid age
person.setAge(-5);
}
}
Output:
Name: Rama
Age: 25
Updated Name: Sitha
Updated Age: 30
Age must be positive.
9(a). Program for illustrating the String Operations using String class
13
char charAt2 = str4.charAt(2);
System.out.println("Character at index 2 in str4: " + charAt2);
// Substring
String substring = str4.substring(6);
System.out.println("Substring of str4 starting from index 6: " + substring);
// String comparison
boolean isEqual = str1.equals(str2);
System.out.println("str1 equals str2: " + isEqual);
boolean isEqualIgnoreCase = str1.equalsIgnoreCase("hello");
System.out.println("str1 equals 'hello' (ignore case): " + isEqualIgnoreCase);
int comparisonResult = str1.compareTo(str2);
System.out.println("Comparison of str1 and str2: " + comparisonResult);
// Checking if a string contains a substring
boolean contains = str4.contains("World");
System.out.println("str4 contains 'World': " + contains);
// Replacing characters in a string
String replacedString = str4.replace('o', 'a');
System.out.println("String after replacing 'o' with 'a': " + replacedString);
// Converting string to uppercase and lowercase
String upperCaseString = str4.toUpperCase();
String lowerCaseString = str4.toLowerCase();
System.out.println("Uppercase str4: " + upperCaseString);
System.out.println("Lowercase str4: " + lowerCaseString);
// Trimming whitespace from a string
String str5 = " Hello World ";
String trimmedString = str5.trim();
System.out.println("Trimmed str5: '" + trimmedString + "'");
}
}
Output:
Concatenated String: Hello World
Length of str4: 11
Character at index 2 in str4: l
Substring of str4 starting from index 6: World
str1 equals str2: false
str1 equals 'hello' (ignore case): true
Comparison of str1 and str2: -15
str4 contains 'World': true
String after replacing 'o' with 'a': Hella Warld
Uppercase str4: HELLO WORLD
Lowercase str4: hello world
Trimmed str5: 'Hello World'
import java.util.Scanner;
public class ReverseString {
14
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
String reversed = "";
for (int i = input.length() - 1; i>= 0; i--) {
reversed += input.charAt(i);
}
System.out.println("Reversed string: " + reversed);
scanner.close();
}
}
Output:
Enter a string: Hello World!
Reversed string: !dlroW olleH
10. A program to check some constraints (final, static, access modifiers) using inheritance in java.
class Sample
{
public int a=20; //instance variable of public type
private static int b=50; //static variable of private type
public static final int CONST=60; //constant variable of public type
public static void method1() //static method
{
System.out.println("this is from class Sample as a static method ");
}
public void method2() //instance method
{
System.out.println("this is from class Sample as a instance method ");
}
private void method3() //instance method as private type
{
System.out.println("this is from class Sample as instance method ");
}
}
class SampleTest extends Sample //inheriting Sample class to SampleTest
{
public int d=100; //instance variable
private static int b=40; //static variable
/*public void method1() //static method can't be override
{
System.out.println("this is from class B as instance method");
}*/
public void method2() //instance method overriding
{
System.out.println("this is overridden method from class SampleTest");
15
}
public static void main(String args[])
{
SampleTest st=new SampleTest (); //object of SampleTest
System.out.println("the value of a is :"+st.a);
//System.out.println("the value of b from class Sample is :"+Sample.b); //not accessing a private
variable
System.out.println("the value of c is :"+Sample.CONST); //static variable accessing by class name
//Sample.CONST=90; // final variable can't be modified
System.out.println("the value of b from class SampleTest is :"+SampleTest.b);
System.out.println("the value of d is :"+st.d);
Sample.method1(); //accessing static method in class Sample
st.method2(); //accessing overriden method
//st.method3(); //can't accessing private method of class Sample
}
}
Output:
the value of a is :20
the value of c is :60
the value of b from class SampleTest is :40
the value of d is :100
this is from class Sample as a static method
this is overridden method from class SampleTest
I. Use Eclipse or Net bean platform and acquaint yourself with the various menus. Create a test
project, add a test class, and run it. See how you can use auto suggestions, auto fill. Try code
formatter and code refactoring like renaming variables, methods, and classes. Try debug step
by step with a small program of about 10 to 15 lines which contains at least one if else
condition and a for loop.
Using Eclipse:
1. Download and Install Eclipse:
Go to the Eclipse downloads page and download the Eclipse IDE for Java Developers.
Install Eclipse by following the on-screen instructions.
2. Create a Test Project:
Open Eclipse.
Go to File > New > Java Project.
Enter a project name (e.g., TestProject) and click Finish.
3. Add a Test Class:
Right-click on the src folder in your project.
Select New > Class.
Enter a package name (e.g., com.example) and a class name (e.g., TestClass).
Check the box to include the public static void main(String[] args) method.
Click Finish.
4. Write and Run a Test Program:
Open the TestClass.java file and add below code:
16
package com.example;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is 5 or less");
}
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
scanner.close();
}
}
Save the file and run it by right-clicking on the file and selecting Run As > Java Application.
5. Use Autosuggestions and Autofill:
Start typing code, and you will see Eclipse providing suggestions and autofill options. For
example, type Sys and press Ctrl+Space to see suggestions for System.
6. Code Formatting:
Right-click on your Java file and select Source > Format to automatically format your code
according to the default style settings.
7. Code Refactoring:
Right-click on a variable, method, or class name and select Refactor > Rename to rename it
across the entire project.
8. Debug Step-by-Step:
Set a breakpoint by double-clicking on the left margin next to a line of code.
Right-click on the file and select Debug As > Java Application.
Use the debug perspective to step through the code, inspect variables, and control the execution
flow.
9. Run:
To run the project Select run menu, click on the run (ctrl+F11).
Output:
Enter a number: 7
Number is greater than 5
Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
17
Characteristics of Object-Oriented Languages:
1. Objects: Objects are instances of classes that combine data (attributes or properties) and behaviors
(methods or functions).
2. Classes: Classes are blueprints or templates that define the properties and behaviors common to all
objects of that class.
3. Encapsulation: Encapsulation refers to bundling data and methods together within a class, hiding
the internal workings of an object and exposing only the necessary interfaces.
4. Inheritance: Inheritance allows a class (subclass or derived class) to inherit properties and behaviors
from another class (super class or base class), facilitating code reuse and promoting the DRY (Don't
Repeat Yourself) principle.
5. Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a
common super class. It enables the same method to be used for different types of objects, providing
flexibility and extensibility.
6. Abstraction: Abstraction is the concept of hiding the complex implementation details and showing
only the necessary features. We'll use abstract classes to demonstrate abstraction.
18