SlideShare a Scribd company logo
1 of 83
Download to read offline
OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY MANUAL
[21CSL35] (III SEMESTER)
By:
Dr. G T Raju
Principal
SJCIT, Chickballapur
SJC INSTITUTE OF TECHNOLOGY, CHICKBALLAPUR- 562101
DEPARTMENT OF COMPUTER SCIENCE & INFORMATION SCIENCE ENGINEERING
(NEP) For the Year: 2022-23
|| Jai Sri Gurudev ||
Adichunchanagiri Shikshana Trust(R.)
SJC INSTITUTE OF TECHNOLOGY
VTU Affiliated, AICTE Approved, Accredited by NAAC & NBA
(CSE, ISE, ECE, ME, CV, AE) Gold rated by QS I-Gauge
INSTITUTION VISION AND MISSION
VISION
Preparing Competent Engineering and Management Professionals to Serve the
Society.
MISSION
M1: Providing Students with a Sound Knowledge in Fundamentals of their
branch of Study.
M2: Promoting Excellence in Teaching, Training, Research and Consultancy.
M3: Exposing Students to Emerging Frontiers in various domains enabling
Continuous Learning.
M4: Developing Entrepreneurial acumen to venture into Innovative areas.
M5: Imparting Value based Professional Education with a sense of Social
Responsibility.
DEPARTMENT OF COMPUTER SCIENCE ENGINEERING
VISION
Building Proficient Computer Science Engineers having Core Values to
Solve Real Life Problems.
MISSION
M1: Strengthening Students with Fundamental and Applied aspects in Design and
Implementation of Computational Systems.
M2: Empowering the Students with Sound Knowledge in AI & ML, Data
Analytics, Block Chain, AR and VR systems to Solve Multidisciplinary Problem.
M3: Developing Analytical Skills to meet the Complex, Societal and Industrial
needs.
M4: Promoting Research blend of mind among Students enabling Continuous
Learning.
M5: Encouraging Entrepreneurship including Ethical Values and Team building
abilities.
DEPARTMENT OF INFORMATION SCIENCE ENGINEERING
VISION
Educating Students to Engineer Information Science and Technology for
Advancing the Knowledge as to Best Serve the Real World.
MISSION
M1: Focusing on Fundamentals and Applied aspects in both Information Science
Theory and Programming practices.
M2: Training comprehensively and encouraging R&D culture in trending areas of
Information Technology.
M3: Collaborating with premier Institutes and Industries to nurture Innovation and
learning, in cutting edge Information Technology.
M4: Preparing the students who are much Sought-after, Productive and Well-
respected for their work culture having Lifelong Learning practice.
M5: Promoting ethical and moral values among the students so as to enable them
emerge as responsible professionals.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 1 2022-23
OBJECT ORIENTED PROGRAMMING
WITH JAVA LABORATORY
Course Code 21CSL35 CIE Marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 1 Exam Hours 03
Course Objectives:
CLO 1. Demonstrate the use of Eclipse/NetBeans IDE to create Java Applications.
CLO 2. Using java programming to develop programs for solving real-world problems.
CLO 3. Reinforce the understanding of basic object-oriented programming concepts.
CLO 4. Understand and apply the concepts of classes, packages, interfaces, array list,
exception handling and file processing
CLO 5. Develop applications using generic programming and event handling
Course Outcomes:
At the end of the course the student will be able to:
CO 1. Use Eclipse/NetBeans IDE to design, develop, debug Java Projects.
CO 2. Analyze the necessity for Object Oriented Programming paradigm over structured
programming
CO 3. Develop and implement Java programs for simple applications that make use of classes,
packages and interfaces.
CO 3. Develop and implement Java programs with array list, exception handling and multithreading.
CO 4. Apply the concepts of multiprogramming, event handling, abstraction to develop robust
programs.
CO 6. Develop user friendly applications using File I/O and GUI concepts.
Recommended System/Software Requirements:
 Intel based desktop PC with minimum of 2.6GHZ or faster processor with at
least 256 MB RAM and 40GB free disk space.
 Operating system: Windows or Linux
 Software: As of September 2022, Java 19 is the latest released Java version. In
March 2023, Java 20 will follow. The last long-term support version (LTS) of
Java is Java 17, released in September 2021. Install JDK 17 or above
 IDE: Eclipse or Net beam.
Download and Install Java Development Kit (JDK) on Windows
Setting up a Suitable Development Environment is necessary before one can begin creating any
Applications. It makes it easier for developers to use the tools required to create any Application
and ensures that all Operations or Processes run smoothly. JDK must be installed in order to
create Application Source Files using the Java Programming Language. The system will execute
the code using a set of Libraries and Compilers.
The JDK can be installed on the following Platforms:
 Microsoft Windows
 Linux
 macOS
Installation of JDK on Microsoft Windows:
Step 1: Download and Install Oracle Java Development Kit (JDK)
The very first step is to download the Oracle Java Development Kit (JDK) from the Official Oracle
Website. https://www.oracle.com/java/technologies/downloads/#jdk18-windows
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 2 2022-23
You need to identify your system specifications to choose the Product/file description. The website will
contain the latest version for your corresponding system. For Windows, we’ll be downloading the
latest x64 Installer of Java SE Development Kit 18. After the download is complete, proceed to install
the JDK by following the bootstrapped steps.
Step 2: Configure Environment Variables
After the installation is complete, we have to configure environment variables to notify the system
about the directory in which JDK files are located. Proceed to C:Program FilesJavajdk-
{YOUR_JDK_VERSION}bin (replace {-} with your JDK version)
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 3 2022-23
To set the Environment Variables, you need to search Environment Variables in the Task Bar and click
on “Edit the system environment variables”.
Under the Advanced section, Click on “Environment Variables”.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 4 2022-23
Under System variables, select the “Path” variable and click on “Edit”. Click on “New” then paste the
Path Address i.e. C:Program FilesJavajdk-{YOUR_JDK_VERSION}bin. Click on “OK”.
Now, in the Environment Variables dialogue, under System variables, click on “New” and then
under Variable name: JAVA_HOME and Variable value: paste address i.e. C:Program Files Java
jdk-{YOUR_JDK_VERSION}. Click on OK => OK => OK.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 5 2022-23
Step 3: Check the Java Version
Open Command Prompt and enter the following commands
java -version
javac -version
Introduction to OOP:
Object-oriented programming (OOP) is a computer science term was originally coined by Xerox PARC in
1960’s to designate a computer application that describes the methodology of using objects as the
foundation for computation. By the 1980’s, OOP rose to prominence as the programming language of
choice, exemplified by the success of C++. Currently, OOP such as Java, J2EE, C++,C#, Visual Basic.NET,
Python and java Script are popular OOP programming languages that any career-oriented Software
Engineer or developer should be familiar with. OOP is widely accepted as being far more flexible than
other computer programming languages. OOP use three basic concepts as the fundamentals for the
Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within
objectoriented programming languages that are explained in online tutorial describing the functionality
of each concept in detail. The java platform is undoubtedly fast moving and comprehensive. Its many
application programming interfaces (APIs) provide a wealth of functionality for all aspects of application
and system-level programming. Real-world developers never use one or two APIs to solve a problem, but
bring together key functionality spanning a number of APIs, Knowing which APIs you need, and how the
APIs work together to create the best solution can be a daunting task.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 6 2022-23
1. Aim: Introduce the java fundamentals, data types, operators in java
Program: Write a java program that prints all real solutions to the quadratic equationax2+bx+c=0. Read in
a, b, c and use the quadratic formula.
The standard form of a quadratic equation is ax2+bx+c=0. It is also known as the second-degree equation.
In the equation ax2+bx+c=0, a, b, and c are unknown values and a cannot be 0. x is an unknown variable.
The formula to find the roots of the quadratic equation is given by:
A quadratic equation has two roots and the roots depend on the discriminant. In the above formula,
(√b2-4ac) is called discriminant (d). The value of d may be positive, negative, or zero.
If d is positive (d>0), the root will be:
If the value of d is positive, both roots are real and different. It means there are two real solutions.
If d is zero (d=0), the root will be:
If the value of d is zero, both roots are real and the same. It means we get one real solution.
If d is negative (d<0), the root will be:
If the value of d is negative, both roots are distinct and imaginary or complex. It means that there are two
complex solutions.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 7 2022-23
Algorithm to Find the Roots of the Quadratic Equation
Step 1: Start
Step 2: Read a, b, c
Step 3: Compute d<-(b*b)-(4*a*c)
Step 4: Compute r<- b/2*a
Step 5: if d>0 go to Step 6, else go to Step 8
Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a)
Step 7: prints roots are real and distinct, first root r1 second root r2
Step 8: if d=0 go to Step 9, else go to Step 10
Step 9: print roots are real and equal, -r
Step 10: d=-d
Step 11: im=sqrt(d)/2*a
Step 12: print roots are imaginary, first root is r+i im, and the second root is r-i im
Step 13: Stop
Pseudocode:
Start
Read the values of a, b, c
Compute d = b2 – 4ac
If d > 0
calculate root1 = {-b + √(b2 – 4ac)}/2a
calculate root2 = {-b – √(b2 – 4ac)}/2a
else If d = 0
calculate root1 = root2 = (-b/2a)
else
calculate root1 = {-b + i√-(b2 – 4ac)}/2a
calculate root2 = {-b + i√-(b2 – 4ac)}/2a
print root1 and root2
End
Let's create a Java program and implement the above steps.
// Java program to find roots of a quadratic equation
import static java.lang.Math.*;
import java.io.*;
class Quadratic {
// Prints roots of quadratic equation ax * 2 + bx + x
static void findRoots(int a, int b, int c)
{
// If a is 0, then equation is not quadratic, but linear
if (a == 0) {
System.out.println("Invalid");
return;
}
int d = b * b - 4 * a * c;
double sqrt_val = sqrt(abs(d));
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 8 2022-23
if (d > 0) {
System.out.println(
"Roots are real and different n");
System.out.println(
(double)(-b + sqrt_val) / (2 * a) + "n"
+ (double)(-b - sqrt_val) / (2 * a));
}
else if (d == 0) {
System.out.println(
"Roots are real and same n");
System.out.println(-(double)b / (2 * a) + "n"
+ -(double)b / (2 * a));
}
else // d < 0
{
System.out.println("Roots are complex n");
System.out.println(-(double)b / (2 * a) + " + i"
+ sqrt_val / (2 * a) + "n"
+ -(double)b / (2 * a) + " - i"
+ sqrt_val / (2 * a));
}
}
// Driver code
public static void main(String args[])
{
int a = 1, b = -7, c = 12;
// Function call
findRoots(a, b, c);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 9 2022-23
QuadraticEquationExample1.java
import java.util.Scanner;
public class QuadraticEquationExample1
{
public static void main(String[] Strings)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();
double d = b * b - 4.0 * a * c;
if (d > 0.0)
{
System.out.println("The roots of the equation are real and different. n");
double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
System.out.println("The roots are " + r1 + " and " + r2);
}
else if (d == 0.0)
{
System.out.println("The roots of the equation are real and same. n");
double r1 = -b / (2.0 * a);
System.out.println("The root is " + r1);
}
else
{
System.out.println("Roots are not real.");
System.out.println(-(double)b / (2 * a) + " + i"
+ sqrt_val / (2 * a) + "n" + -(double)b / (2 * a) + " - i"
+ sqrt_val / (2 * a));
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 10 2022-23
Using Function
QuadraticEquationExample2.java
import static java.lang.Math.*;
public class QuadraticEquationExample2
{
//defining a static method that finds the roots of the quadratic equation
static void calculateRoots(int a, int b, int c)
{
//comparing the value of a with 0, if a is 0 then the equation is not quadratic
if (a == 0)
{
System.out.println("The value of a cannot be 0."); return;
}
//calculating discriminant (d)
int d = b * b - 4 * a * c;
double sqrtval = sqrt(abs(d));
if (d > 0)
{
System.out.println("The roots of the equation are real and different. n");
System.out.println((double)(-b + sqrtval) / (2 * a) + "n"+ (double)(-b - sqrtval) / (2 *
a));
}
else if (d == 0)
{
System.out.println("The roots of the equation are real and same. n");
System.out.println(-(double)b / (2 * a) + "n"+ -(double)b / (2 * a));
}
// executes if d < 0
else
{
System.out.println("The roots of the equation are complex and different. n");
System.out.println(-(double)b / (2 * a) + " + i"+ sqrtval + "n"+ -(double)b / (2 * a)+ " - i"
+ sqrtval);
}
}
//main method
public static void main(String args[])
{
//Output 1: int a = 1, b = 5, c = 2;
//calling function
calculateRoots(a, b, c);
//Output 2: int a=1, b=1, c=1
//Output 3: int a=1, b=-2, c=1 } }
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 11 2022-23
Alternative Solution 2: Main.java
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) {
// value a, b, and c
double a = 2.3, b = 4, c = 5.6;
double root1, root2;
// calculate the determinant (b2 - 4ac)
double determinant = b * b - 4 * a * c;
// check if determinant is greater than 0
if (determinant > 0) {
// two real and distinct roots
root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);
System.out.println ("root1 = %.2f and root2 = %.2f", root1, root2);
}
// check if determinant is equal to 0
else if (determinant == 0) {
// two real and equal roots
// determinant is equal to 0
// so -b + 0 == -b
root1 = root2 = -b / (2 * a);
System.out.println ("root1 = root2 = %.2f;", root1);
}
// if determinant is less than zero
else {
// roots are complex number and distinct
double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.println ("root1 = %.2f+%.2fi", real, imaginary);
System.out.println ("nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 12 2022-23
2. Aim: Demonstrating creation of java classes, objects, constructors, declaration and initialization of
variables.
Create a Java class called Student with the following details as variables within it.
(i) USN
(ii) Name
(iii) Branch
(iv) Phone
Write a Java program to create n Student objects and print the USN, Name, Branch, and
Phone of these objects with suitable headings.
Solution:
The aim of this program is to create a class and make objects of that class to print the details of a student.
Implementation:
• Create a class named “student”.
• Declare variables within it containing the details like name, USN, Branch, Phone no
• Create a constructor to initialize these variables.
• Create a function that prints these details like usn, name, branch and phone no.
• Create multiple objects of “student” class that calls the function to print the details.
Algorithm:
//Input: Values for USN, name, branch and phone no
//Output: Displaying the details of n student objects
//Steps:
1) class “student” is created
2) Declare variables USN, Name, Branch, and Phone no.
3) a constructor of Student class is created to initialize these variables.
4) multiple objects of “student” class is created and print the details contained student class
Program:
Main.java
import java.util.Scanner;
class Student {
private String usn, name, branch, ph;
public void accept() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Usnn");
usn = sc.next();
System.out.println("Enter Namen");
name = sc.next();
System.out.println("Enter Branchn");
branch = sc.next();
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 13 2022-23
System.out.println("Enter Phonen");
ph = sc.next();
}
public void display() {
System.out.println("Student details");
System.out.println("Usn: " + usn);
System.out.println("Name: " + name);
System.out.println("Branch: " + branch);
System.out.println("Phone: " + ph);
System.out.println();
}
}
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for n");
int n = sc.nextInt();
Student[] ob1 = new Student[n];
for (int i = 0; i < n; i++) {
ob1[i] = new Student();
ob1[i].accept();
}
for (int i = 0; i < n; i++) {
ob1[i].display();
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 14 2022-23
Alternative Solution1:
import java.util.Scanner;
public class student
{
String USN;
String Name;
String branch;
int phone;
void insertRecord(String reg, String name, String brnch, int ph)
{
USN=reg;
Name=name;
branch=brnch;
phone=ph;
}
void displayRecord()
{
System.out.println(USN+" "+Name+" "+branch+" "+phone);
}
public static void main(String args[])
{
student s[]=new student [100];
Scanner sc=new Scanner(System.in);
System.out.println("enter the number of students");
int n=sc.nextInt();
for(int i=0;i<n;i++)
s[i]=new student();
for(int j=0;j<n;j++)
{ System.out.println("enter the usn,name,branch,phone")
String USN=sc.next();
String Name=sc.next();
String branch=sc.next();
int phone=sc.nextInt();
s[j].insertRecord(USN,Name,branch,phone);
}
for( int m=0;m<n;m++)
{
s[m].displayRecord();
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 15 2022-23
OUTPUT
enter the number of students
2
enter the usn,name,branch,phone
1
monika
cse
9341155665
enter the usn,name,branch,phone
2
gowda
cse
9785443355
students details are
1 monika cse 9341155665
2 gowda cse 9785443355
Alternative Solution2:
import java.io.*;
class Student
{
String usn, name, programme;
long ph;
Student()
{
usn = name = programme = "No value";
ph = 0;
}
void read_data(String u, String n, String p, long m)
{
usn = u;
name = n;
programme = p;
ph =m;
}
void display()
{
System.out.println(usn + "t" + name + "t" + programme + "tt" + ph);
}
}
class Record
{
public static void main(String args[]) throws Exception
{
String u, n, p;
long m;
int no;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter number of records:");
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 16 2022-23
no = Integer.parseInt(br.readLine());
Student[] s = new Student[no];
for(int i=0; i<s.length;i++)
{
System.out.println("nEnter Student " + (i + 1) + " record");
s[i] = new Student();
System.out.print("Enter student USN: ");
u = br.readLine();
System.out.print("Enter student Name: ");
n = br.readLine();
System.out.print("Enter student Programme: ");
p = br.readLine();
System.out.print("Enter student Phone number: ");
m = Long.parseLong(br.readLine());
s[i].read_data(u, n, p, m);
}
System.out.println("USN t NAME t PROGRAMME t PHONE NO");
for(int i=0; i<s.length;i++)
{
s[i].display();
}
}
}
Alternative Solution3:
import java.util.Scanner;
public class Room {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n,i;
Student[] s=new Student[100];
System.out.println("Enter the Number of Objects");
n=scan.nextInt();
for(i=0;i<n;i++)
{
s[i]=new Student();
}
for(i=0;i<n;i++)
{
System.out.println("Enter the Details in Order - Name , Usn , Branch , Phone
No");
String name = scan.next();
String usn = scan.next();
String branch = scan.next();
String phno = scan.next();
s[i].assignvalue(name, usn, branch, phno);
}
System.out.println("Students Details are as Follow:");
for(i=0;i<n;i++)
{
s[i].display();
}
scan.close();
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 17 2022-23
class Student
{
String name,usn,branch,phno;
void assignvalue(String n,String u,String b,String p)
{
name=n;
usn=u;
branch=b;
phno=p;
}
void display()
{
System.out.println("Name :"+name+" USN :"+usn+" Branch :"+branch+" Phone Number :"+phno);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 18 2022-23
3. Aim: Discuss the various Decision-making statements, loop constructs in java
A. Write a program to check prime number
B. Write a program for Arithmetic calculator using switch case menu
Solution:
Any natural number greater than 1, is only divisible by 1, and the number itself is called a prime number.
In other words, prime numbers have just two factors i.e. 1 and number itself.
Example : 2,3,5,7,11,13...... All the natural numbers other than 1 and prime numbers are called composite
numbers.
Solution A:
import java.util.Scanner;
import static java.lang.Math.*;
public class PrimeCheck
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = s.nextInt();
if (isPrime(n))
{
System.out.println(n + " is a prime number.");
}
else
{
System.out.println(n + " is not a prime number.");
}
}
public static boolean isPrime(int n)
{
if (n <= 1)
{
return false;
}
for (int i = 2; i < Math.sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
return true;
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 19 2022-23
Solution B:
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
char operator;
Double number1, number2, result;
// create an object of Scanner class
Scanner input = new Scanner(System.in);
// ask users to enter operator
System.out.println("Choose an operator: +, -, *, or /");
operator = input.next().charAt(0);
// ask users to enter numbers
System.out.println("Enter first number");
number1 = input.nextDouble();
System.out.println("Enter second number");
number2 = input.nextDouble();
switch (operator)
{
// performs addition between numbers
case '+':
result = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + result);
break;
// performs subtraction between numbers
case '-':
result = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + result);
break;
// performs multiplication between numbers
case '*':
result = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + result);
break;
// performs division between numbers
case '/':
result = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + result);
break;
default:
System.out.println("Invalid operator!");
break;
}
input.close();
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 20 2022-23
Solution B: Alternate-1
import java.util.Scanner;
public class OperatorSwitch {
public static void main(String[] args) {
char operator;
Double my_input_1, my_input_2, my_result;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.println("Enter the first number");
my_input_1 = my_scanner.nextDouble();
System.out.println("Enter the second number");
my_input_2 = my_scanner.nextDouble();
System.out.println("Enter any of the following operator: +, -, *, /, %");
operator = my_scanner.next().charAt(0);
switch (operator) {
case '+':
my_result = my_input_1 + my_input_2;
System.out.println(my_input_1 + " + " + my_input_2 + " = " + my_result);
break;
case '-':
my_result = my_input_1 - my_input_2;
System.out.println(my_input_1 + " - " + my_input_2 + " = " + my_result);
break;
case '*':
my_result = my_input_1 * my_input_2;
System.out.println(my_input_1 + " * " + my_input_2 + " = " + my_result);
break;
case '/':
my_result = my_input_1 / my_input_2;
System.out.println(my_input_1 + " / " + my_input_2 + " = " + my_result);
break;
case '%':
my_result = my_input_1 % my_input_2;
System.out.println(my_input_1 + " % " + my_input_2 + " = " + my_result);
break;
default:
System.out.println("The operator you have selected is invalid");
break;
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 21 2022-23
Solution B: Alternate-2
import java.util.Scanner;
public class Calculator {
public static void main(String[] args)
{
double a,b,result; // Declaring a variables
Scanner s = new Scanner(System.in);
System.out.print("Enter first number value:");
a = s.nextDouble(); // getting values from user...
System.out.print("Enter second number value:");
b = s.nextDouble();
System.out.print("Enter any operator (+, -, *, /): ");
char opt = s.next().charAt(0); // taking operator
switch(opt) // using switch case to create Caluclator
{
case '+':
result = a + b;
break; // condition for addition
case '-':
result =a - b;
break; // condition for subtraction
case '*':
result = a * b;
break; // condition for Multiplicatin
case '/':
result = a / b;
break; // condition for Divison
default:
System.out.printf("You have entered wrong operator or value");
return;
}
System.out.println(a+" "+opt+" "+b+": "+result);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 22 2022-23
4. Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism
Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by
writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract
(period). Write a Java program to read and display at least 3 staff objects of all three categories.
Solution:
import java.util.Scanner;
class Staff {
private String staffId;
private String name;
private int phone;
private float salary;
public void accept() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Staff Id");
staffId = scanner.next();
System.out.println("Enter Name");
name = scanner.next();
System.out.println("Enter Phone");
phone = scanner.nextInt();
System.out.println("Enter Salary");
salary = scanner.nextFloat();
}
public void display() {
System.out.println("Staff Id: " + staffId);
System.out.println("Name: " + name);
System.out.println("Phone: " + phone);
System.out.println("Salary: " + salary);
}
}
class Teaching extends Staff {
private String domain;
private String[] publications;
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Domain");
domain = scanner.next();
System.out.println("Enter Number of Publications");
int n = scanner.nextInt();
publications = new String[n];
System.out.println("Enter Publications");
for (int i = 0; i < n; i++) {
publications[i] = scanner.next();
}
}
public void display() {
super.display();
System.out.println("Domain: " + domain);
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 23 2022-23
System.out.println("Publications:");
for (int i = 0; i < publications.length; i++) {
System.out.println(publications[i]);
}
}
}
class Technical extends Staff {
private String[] skills;
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number of Skills");
int n = scanner.nextInt();
skills = new String[n];
System.out.println("Enter Skills");
for (int i = 0; i < n; i++) {
skills[i] = scanner.next();
}
}
public void display() {
super.display();
System.out.println("Skills:");
for (int i = 0; i < skills.length; i++) {
System.out.println(skills[i]);
}
}
}
class Contract extends Staff {
private int period;
public void accept() {
super.accept();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Period");
period = scanner.nextInt();
}
public void display() {
super.display();
System.out.println("Period: " + period);
}
}
class Main {
public static void main(String[] args) {
Teaching teaching = new Teaching();
Technical technical = new Technical();
Contract contract = new Contract();
System.out.println("Enter Details for Teaching Staff Member");
teaching.accept();
System.out.println("Enter Details for Technical Staff Member");
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 24 2022-23
technical.accept();
System.out.println("Enter Details for Contract Staff Member");
contract.accept();
System.out.println("Details for Teaching Staff Member are");
teaching.display();
System.out.println("Details for Technical Staff Member are");
technical.display();
System.out.println("Details for Contract Staff Member are");
contract.display();
}
}
Solution: Alternate-1
class Staff
{
private int StaffId;
private String Name;
private String Phone;
private long Salary;
public Staff(int staffId,String name,String phone,long salary)
{
StaffId = staffId;
Name = name;
Phone = phone;
Salary = salary;
}
public void Display()
{
System.out.print("t"+StaffId+"t"+Name+"tt"+Phone+"tt"+Salary);
}
}
class Teaching extends Staff
{
private String Domain;
private int Publications;
public Teaching(int staffId, String name, String phone,long salary, String domain, int
publications)
{
super(staffId, name, phone, salary);
Domain = domain;
Publications = publications;
}
public void Display()
{
super.Display();
System.out.print("tt"+Domain+"tt"+Publications+"tt"+"--"+"t"+"--");
}
}
class Technical extends Staff
{
private String Skills;
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 25 2022-23
public Technical(int staffId, String name, String phone,long salary, String skills)
{
super(staffId, name, phone, salary);
Skills = skills;
}
public void Display()
{
super.Display();
System.out.print("tt--"+"tt"+"--"+"t"+Skills+"t"+"--");
}
}
class Contract extends Staff
{
private int Period;
public Contract(int staffId, String name, String phone, long salary, int period)
{
super(staffId, name, phone, salary);
this.Period = period;
}
public void Display()
{
super.Display();
System.out.print("tt--"+"tt"+"--"+"tt"+"--"+"t"+Period);
}
}
public class Polyinherit4
{
public static void main(String[] args)
{
Staff staff[]=new Staff[3];
staff[0]=new Teaching(0001,"Raju","271173",90000,"CSE",3);
staff[1]=new Technical(0002,"Anu","271172",20000,"Server Admin");
staff[2]=new Contract(0003,"Ganavi","271174",9000,3);
System.out.println("StaffIDtNamettPhonettSalaryttDomaintPublicationtSkills
ttPeriod");
for(int i=0;i<3;i++)
{
staff[i].Display();
System.out.println();
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 26 2022-23
5. Aim: Introduce concepts of method overloading, constructor overloading, overriding.
Program: Write a java program demonstrating Method overloading and Constructor overloading.
The constructor overloading can be defined as the concept of having more than one constructor
with different parameters so that every constructor can perform a different task. If a class has
multiple methods having same name but different in parameters, it is known as Method
Overloading. Method overloading increases the readability of the program. There are two ways to
overload the method in java
1. By changing number of arguments
2. By changing the data type
// Constructor overloading
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("nDefault Constructor values: n");
System.out.println("Student Id : "+s.id + "nStudent Name : "+s.name);
System.out.println("nParameterized Constructor values: n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "nStudent Name :
"+student.name);
}
}
// Method Overloading: changing no. of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 27 2022-23
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}
//Method Overloading: changing data type of arguments
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
class MethodOverloading {
// this method accepts int
private static void display(int a){
System.out.println("Got Integer data.");
}
// this method accepts String object
private static void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 28 2022-23
6. Aim: Introduce the concept of Abstraction, packages.
Program: Develop a java application to implement currency converter (Dollar to INR, EURO
to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and viceversa), time
converter (hours to minutes, seconds and vice versa) using packages.
Procedure:
1. Create a Package currencyconversion and place the class currency under the package
2. Create the methods to perform currency conversion from dollar to rupee, rupee to dollar, euro to
rupee, rupee to euro, yen to rupee and rupee to yen.
3. Create the package distanceconverion and create the class distance within the package
4. Create the methods to convert from meter to km, km to meter, miles to km,km to miles
5. Create the package timeconversion and create the class timer. Create the methods to convert from
hours to minutes ,hours to seconds , minutes to hours and seconds to hours
6. Create a class and import the packages currencyconversion, distanceconversion and time
conversion. Create the objects for the class currency,distance and timer.
7. Get the choice from the user and invoke the methods to perform the corresponding conversion and
display the value.
currencyconversion.java
package currencyconversion;
import java.util.*;
public class currency
{
double inr,usd;
double euro,yen;
Scanner in=new Scanner(System.in);
public void dollartorupee()
{
System.out.println("Enter dollars to convert into Rupees:");
usd=in.nextInt();
inr=usd*67;
System.out.println("Dollar ="+usd+"equal to INR="+inr);
}
public void rupeetodollar()
{
System.out.println("Enter Rupee to convert into Dollars:");
inr=in.nextInt();
usd=inr/67;
System.out.println("Rupee ="+inr+"equal to Dollars="+usd);
}
public void eurotorupee()
{
System.out.println("Enter euro to convert into Rupees:");
euro=in.nextInt();
inr=euro*79.50;
System.out.println("Euro ="+euro +"equal to INR="+inr);
}
public void rupeetoeuro()
{
System.out.println("Enter Rupees to convert into Euro:");
inr=in.nextInt();
euro=(inr/79.50);
System.out.println("Rupee ="+inr +"equal to Euro="+euro);
}
public void yentorupee()
{
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 29 2022-23
System.out.println("Enter yen to convert into Rupees:");
yen=in.nextInt();
inr=yen*0.61;
System.out.println("YEN="+yen +"equal to INR="+inr);
}
public void rupeetoyen()
{
System.out.println("Enter Rupees to convert into Yen:");
inr=in.nextInt();
yen=(inr/0.61);
System.out.println("INR="+inr +"equal to YEN"+yen);
}
}
distance.java
package distanceconversion;
import java.util.*;
public class distance
{
double km,m,miles;
Scanner sc = new Scanner(System.in);
public void kmtom()
{
System.out.print("Enter in km ");
km=sc.nextDouble();
m=(km*1000);
System.out.println(km+"km" +"equal to"+m+"metres");
}
public void mtokm()
{
System.out.print("Enter in meter ");
m=sc.nextDouble();
km=(m/1000);
System.out.println(m+"m" +"equal to"+km+"kilometres");
}
public void milestokm()
{
System.out.print("Enter in miles");
miles=sc.nextDouble();
km=(miles*1.60934);
System.out.println(miles+"miles" +"equal to"+km+"kilometres");
}
public void kmtomiles()
{
System.out.print("Enter in km");
km=sc.nextDouble();
miles=(km*0.621371);
System.out.println(km+"km" +"equal to"+miles+"miles");
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 30 2022-23
timer.java
package timeconversion;
import java.util.*;
public class timer
{
int hours,seconds,minutes;
int input;
Scanner sc = new Scanner(System.in);
public void secondstohours()
{
System.out.print("Enter the number of seconds: ");
input = sc.nextInt();
hours = input / 3600;
minutes = (input % 3600) / 60;
seconds = (input % 3600) % 60;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
System.out.println("Seconds: " + seconds);
}
public void minutestohours()
{
System.out.print("Enter the number of minutes: ");
minutes=sc.nextInt();
hours=minutes/60;
minutes=minutes%60;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
}
public void hourstominutes()
{
System.out.println("enter the no of hours");
hours=sc.nextInt();
minutes=(hours*60);
System.out.println("Minutes: " + minutes);
}
public void hourstoseconds()
{
System.out.println("enter the no of hours");
hours=sc.nextInt();
seconds=(hours*3600);
System.out.println("Minutes: " + seconds);
}
}
converter.java
import java.util.*;
import java.io.*;
import currencyconversion.*;
import distanceconversion.*;
import timeconversion.*;
class converter
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int choice,ch;
currency c=new currency();
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 31 2022-23
distance d=new distance();
timer t=new timer();
do
{
System.out.println("1.dollar to rupee ");
System.out.println("2.rupee to dollar ");
System.out.println("3.Euro to rupee ");
System.out.println("4..rupee to Euro ");
System.out.println("5.Yen to rupee ");
System.out.println("6.Rupee to Yen ");
System.out.println("7.Meter to kilometer ");
System.out.println("8.kilometer to meter ");
System.out.println("9.Miles to kilometer ");
System.out.println("10.kilometer to miles");
System.out.println("11.Hours to Minutes");
System.out.println("12.Hours to Seconds");
System.out.println("13.Seconds to Hours");
System.out.println("14.Minutes to Hours");
System.out.println("Enter ur choice");
choice=s.nextInt();
switch(choice)
{
case 1:
{
c.dollartorupee();
break;
}
case 2:
{
c.rupeetodollar();
break;
}
case 3:
{
c.eurotorupee();
break;
}
case 4:
{
c.rupeetoeuro();
break;
}
case 5:
{c.yentorupee();
break;}
case 6 :
{
c.rupeetoyen();
break;
}
case 7 :
{
d.mtokm();
break;
}
case 8 :
{
d.kmtom();
break;
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 32 2022-23
}
case 9 :
{
d.milestokm();
break;
}
case 10 :
{
d.kmtomiles();
break;
}
case 11 :
{
t.hourstominutes();
break;
}
case 12 :
{
t.hourstoseconds();
break;
}
case 13 :
{
t.secondstohours();
break;
}
case 14 :
{
t.minutestohours();
break;
}}
System.out.println("Enter 0 to quit and 1 to continue ");
ch=s.nextInt();
}while(ch==1);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 33 2022-23
7. Aim: Introduction to abstract classes, abstract methods, and Interface in java
Program: Write a program to generate the resume. Create 2 Java classes Teacher (data: personal
information, qualification, experience, achievements) and Student (data: personal information,
result, discipline) which implements the java interface Resume with the method biodata().
// Java program to demonstrate Interfaces
import java.io.*;
interface Resume {
// abstract method
void biodata(String N, String Q, double E, String A);
}
class Teacher implements Resume{
String Name;
String Qual;
double Exp;
String Ach;
// to build resume
public void biodata(String N, String Q, double E, String A)
{
Name = N;
Qual = Q;
Exp = E;
Ach = A;
}
public void printResume() {
System.out.println("Name: " + Name + " Qualification: "+ Qual + " Experience: " + Exp + "
Achievements " + Ach);
}
}
class Student implements Resume{
String Name;
String Std;
double Result;
String Branch;
// to build resume
public void biodata(String N, String C, double R, String B)
{
Name = N;
Std = C;
Result = R;
Branch = B;
}
public void printResume() {
System.out.println("Name: " + Name + " Class:" + Std + "Result " + Result + " Discipline " +
Branch);
}
}
class GTR7 {
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 34 2022-23
public static void main (String[] args) {
// creating an instance of Teacher
Teacher T = new Teacher();
T.biodata("Raju", "PhD",28.6,"Best Teacher");
System.out.println("Teacher Biodata :");
T.printResume();
// creating instance of the Student.
Student S = new Student();
S.biodata("Anu","First Year", 96.6,"CSE");
System.out.println("Student Biodata :");
S.printResume();
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 35 2022-23
8. Aim: Demonstrate creation of threads using Thread class and Runnable interface, multi-
threaded programming.
Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer for every 1 second; second thread computes the square of the
number and prints; third thread will print the value of cube of the number.
import java.util.Random;
class SquareThread implements Runnable {
int x;
SquareThread(int x) {
this.x = x;
}
public void run() {
System.out.println("Thread Name:Square Thread and Square of " + x + " is: "
+ x * x);
}
}
class CubeThread implements Runnable {
int x;
CubeThread(int x) {
this.x = x;
}
public void run() {
System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: "
+ x * x * x);
}
}
class RandomThread implements Runnable {
Random r;
Thread t2, t3;
public void run() {
int num;
r = new Random();
try {
while (true) {
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
t2 = new Thread(new SquareThread(num));
t2.start();
t3 = new Thread(new CubeThread(num));
t3.start();
Thread.sleep(1000);
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 36 2022-23
System.out.println("---------------------");
}
} catch (Exception ex) {
System.out.println("Interrupted Exception");
}
}
}
public class MainThread {
public static void main(String[] args) {
RandomThread thread_obj = new RandomThread();
Thread t1 = new Thread(thread_obj);
t1.start();
}
}
Alternate Solution:
import java.util.Random;
class RandomNumberThread extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
class SquareThread extends Thread {
int number;
SquareThread(int randomNumbern) {
number = randomNumbern;
}
public void run() {
System.out.println("Square of " + number + " = " + (number * number));
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 37 2022-23
class CubeThread extends Thread {
int number;
CubeThread(int randomNumber) {
number = randomNumber;
}
public void run() {
System.out.println("Cube of " + number + " = " + number * number * number);
}
}
public class MultiThreadingTest {
public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}
MultiThreadRandOddEven.java
import java.util.*;
// class for Even Number
class EvenNum implements Runnable {
public int a;
public EvenNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable {
public int a;
public OddNum(int a) {
this.a = a;
}
public void run() {
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread {
public void run() {
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++) {
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0) {
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 38 2022-23
}
else {
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
// thread wait for 1 second
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
// Driver class
public class MultiThreadRandOddEven {
public static void main(String[] args) {
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 39 2022-23
9. Aim: Introduce java Collections.
write a java program to perform string operations using ArrayList for the following functions
a. Append – add at end
b. Insert – add at particular index
c. Search
d. List all string starts with a given letter
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It
is found in the java.util package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can
use all the methods of the List interface here. The ArrayList maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about the Java ArrayList class are:
 Java ArrayList class can contain duplicate elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because the array works on an index basis.
 In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of
shifting needs to occur if any element is removed from the array list.
 We can not create an array list of the primitive types, such as int, float, char, etc. It is required
to use the required wrapper class in such cases.
 For example:
a. ArrayList<int> al = ArrayList<int>(); // does not work
b. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
c. Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies
according to the elements getting added or removed from the list.
Hierarchy of ArrayList class
As shown in the above diagram, the Java ArrayList class extends AbstractList class which implements
the List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Clone
able, Serializable
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 40 2022-23
Constructors of ArrayList
Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection<? extends E>
c)
It is used to build an array list that is initialized with the
elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified
position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified
collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
boolean addAll(int index, Collection<?
extends E> c)
It is used to append all the elements in the specified
collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int
requiredCapacity)
It is used to enhance the capacity of an ArrayList instance.
E get(int index) It is used to fetch the element from the particular position of
the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.
Object[] toArray() It is used to return an array containing all of the elements in
this list in the correct order.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in
this list in the correct order.
Object clone() It is used to return a shallow copy of an ArrayList.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 41 2022-23
boolean contains(Object o) It returns true if the list contains the specified element.
int indexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain this
element.
E remove(int index) It is used to remove the element present at the specified
position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified
element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E>
filter)
It is used to remove all the elements from the list that satisfies
the given predicate.
protected void removeRange(int
fromIndex, int toIndex)
It is used to remove all the elements lies within the given
range.
void replaceAll(UnaryOperator<E>
operator)
It is used to replace all the elements from the list with the
specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present
in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present
at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the
specified comparator.
Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.
List<E> subList(int fromIndex, int
toIndex)
It is used to fetch all the elements that lies within the given
range.
int size() It is used to return the number of elements present in the list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be
the list's current size.
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 42 2022-23
import java.util.*;
import java.io.*;
public class arraylistexample
{
public static void main(String args[])throws IOException
{
ArrayList<String> obj = new ArrayList<String>();
DataInputStream in=new DataInputStream(System.in);
int c,ch;
int i,j;
String str,str1;
do
{
System.out.println("STRING MANIPULATION");
System.out.println("******************************");
System.out.println(" 1. Append at end t 2.Insert at particular index t 3.Search t");
System.out.println( "4.List string that starting with letter t");
System.out.println("5. Size t 6.Remove t 7.Sortt 8.Displayt" );
System.out.println("Enter the choice ");
c=Integer.parseInt(in.readLine());
switch(c)
{
case 1:
{
System.out.println("Enter the string ");
str=in.readLine();
obj.add(str);
break;
}
case 2:
{
System.out.println("Enter the string ");
str=in.readLine();
System.out.println("Specify the index/position to insert");
i=Integer.parseInt(in.readLine());
obj.add(i-1,str);
System.out.println("The array list has following elements:"+obj);
break;
}
case 3:
{
System.out.println("Enter the string to search ");
str=in.readLine();
j=obj.indexOf(str);
if(j==-1)
System.out.println("Element not found");
else
System.out.println("Index of:"+str+"is"+j);
break;
}
case 4:
{
System.out.println("Enter the character to List string that starts with
specified character");
str=in.readLine();
for(i=0;i<(obj.size()-1);i++)
{
str1=obj.get(i);
if(str1.startsWith(str))
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 43 2022-23
{
System.out.println(str1);
}
}
break;
}
case 5:
{
System.out.println("Size of the list "+obj.size());
break;
}
case 6:
{
System.out.println("Enter the element to remove");
str=in.readLine();
if(obj.remove(str))
{
System.out.println("Element Removed"+str);
}
else
{
System.out.println("Element not present");
}
break;
}
case 7:
{
Collections.sort(obj);
System.out.println("The array list has following elements:"+obj);
break;
}
case 8:
{
System.out.println("The array list has following elements:"+obj);
break;
}
}
System.out.println("enter 0 to break and 1 to continue");
ch=Integer.parseInt(in.readLine());
}while(ch==1);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 44 2022-23
10. Aim: Exception handling in java, introduction to throwable class, throw, throws, finally.
Program: Write a Java program to read two integers a and b. Compute a/b and print, when b is not
zero. Raise an exception when b is equal to zero.
Exceptions These are the events that occur due to the programmer error or machine error which
causes a disturbance in the normal flow of execution of the program.
Handling Multiple exceptions: There are two methods to handle multiple exceptions in java.
1. Using a Single try-catch block try statement allows you to define a block of code to be tested for
errors, and we can give exception objects to the catch blow because this all the exceptions inherited
by the Exception class.
2. The second method is to create individual catch blocks for the different exception handler.
Hierarchy of the exceptions:
import java.util.Scanner;
class division
{
public static void main(String[] args)
{
int a,b,result;
Scanner input =new Scanner(System.in);
System.out.println("Input two integers");
a=input.nextInt();
b=input.nextInt();
try
{
result=a/b;
System.out.println("Result="+result);
}
catch(ArithmeticException e)
{
System.out.println("exception caught: Divide by zero error"+e);
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 45 2022-23
Alternate Solution:
import java.util.Scanner;
public class Exception {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a,b,c;
System.out.print("Enter the Two Interger ValuesnA :");
a=scan.nextInt();
System.out.print("B :");
b=scan.nextInt();
scan.close();
try {
if(b==0)
throw new ArithmeticException("Divide By Zero");
c=a/b;
System.out.println("nThe Value of "+a+" / "+b+" is "+c);
}catch(ArithmeticException e)
{
e.printStackTrace();
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 46 2022-23
11. Aim: Introduce File operations in java.
Program:
Write a java program that reads a file name from the user, displays information about whether the
file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 47 2022-23
Alternate Solution:
import java.io.*;
import java.util.*;
class AboutFile{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file:");
String file_name = input.nextLine();
File f = new File(file_name);
if(f.exists())
System.out.println("The file " +file_name+ " exists");
else
System.out.println("The file " +file_name+ " does not exist");
if(f.exists()){
if(f.canRead())
System.out.println("The file " +file_name+ " is readable");
else
System.out.println("The file " +file_name+ " is not readable");
if(f.canWrite())
System.out.println("The file " +file_name+ " is writeable");
else
System.out.println("The file " +file_name+ " is not writeable");
System.out.println("The file type is: " +file_name.substring(file_name.indexOf('.')+1));
System.out.println("The Length of the file:" +f.length());
}
}
}
Alternate Solution-2:
import java.io.*;
import java.util.*;
class Fileattr
{
public static void main(String args[])
{
File f1=new File(args[0]);
System.out.println(f1.exists()?”file exists”:”does not exist”);
System.out.println(“Filename:”+f1.getName());
System.out.println(“Filepath:”+f1.getAbsolutePath());
System.out.println(f1.isDirectory()?”is a directory”:”is a simple file”);
System.out.println(f1.canRead()?”can be read”:”can not be read”);
System.out.println(f1.canWrite()?”can be write”:”can not be write”);
System.out.println(“length of file in bytes:”+f1.length());
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 48 2022-23
12. Aim: Introduce java Applet, awt, swings.
Programs:
Develop an applet that displays a simple message in center of the screen.Develop a simple calculator
using Swings.
Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s
Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java
Programs.Swing was created to provide more powerful and flexible components than Java AWT
(Abstract Window Toolkit).
In this article we will use Java Swing components to create a simple calculator with only +, -, /, *
operations.
methods used:
1. add(Component c) : adds component to container.
2. addActionListenerListener(ActionListener d) : add actionListener for specified
component
3. setBackground(Color c) : sets the background color of the specified container
4. setSize(int a, int b) : sets the size of container to specified dimensions.
5. setText(String s) : sets the text of the label to s.
6. getText() : returns the text of the label.
// Java program to create a simple calculator with basic +, -, /, * using // java swing elements
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// store operator and operands
String s0, s1, s2;
// default constructor
calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");
try {
// set look and feel
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 49 2022-23
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
// create a object of class
calculator c = new calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
// add action listeners
bm.addActionListener(c);
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 50 2022-23
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
// add elements to panel
p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
// set Background of panel
p.setBackground(Color.blue);
// add panel to frame
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 51 2022-23
String s = e.getActionCommand();
// if the value is a number
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// set the value of text
l.setText(s0 + s1 + s2 + "=" + te);
// convert it to string
s0 = Double.toString(te);
s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 52 2022-23
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
}
// set the value of text
l.setText(s0 + s1 + s2);
}
}
}
Output :
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 53 2022-23
Alternate Solution:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Calculator implements ActionListener {
private static JTextField inputBox;
Calculator(){}
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createUI(frame);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame) {
JPanel panel = new JPanel();
Calculator calculator = new Calculator();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(layout);
inputBox = new JTextField(10);
inputBox.setEditable(false);
JButton button0 = new JButton("0");JButton button1 = new JButton("1");
JButton button2 = new JButton("2");JButton button3 = new JButton("3");
JButton button4 = new JButton("4");JButton button5 = new JButton("5");
JButton button6 = new JButton("6");JButton button7 = new JButton("7");
JButton button8 = new JButton("8");JButton button9 = new JButton("9");
JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-");
JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x");
JButton buttonClear = new JButton("C");JButton buttonDot = new JButton(".");
JButton buttonEquals = new JButton("=");
button1.addActionListener(calculator);button2.addActionListener(calculator);
button3.addActionListener(calculator);button4.addActionListener(calculator);
button5.addActionListener(calculator);button6.addActionListener(calculator);
button7.addActionListener(calculator);button8.addActionListener(calculator);
button9.addActionListener(calculator);button0.addActionListener(calculator);
buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator);
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 54 2022-23
buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator);
buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator);
buttonEquals.addActionListener(calculator);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc);
gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc);
gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc);
gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc);
gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc);
gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc);
gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc);
gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc);
gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc);
gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc);
gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc);
gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc);
gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc);
gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc);
gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc);
gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc);
gbc.gridwidth = 3;
gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc);
gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc);
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.charAt(0) == 'C') {
inputBox.setText("");
}else if (command.charAt(0) == '=') {
inputBox.setText(evaluate(inputBox.getText()));
}else {
inputBox.setText(inputBox.getText() + command);
}
}
public static String evaluate(String expression) {
char[] arr = expression.toCharArray();
String operand1 = "";String operand2 = "";String operator = "";
double result = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') {
if(operator.isEmpty()){
operand1 += arr[i];
}else{
operand2 += arr[i];
}
}
if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') {
operator += arr[i];
}
}
if (operator.equals("+"))
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 55 2022-23
result = (Double.parseDouble(operand1) + Double.parseDouble(operand2));
else if (operator.equals("-"))
result = (Double.parseDouble(operand1) - Double.parseDouble(operand2));
else if (operator.equals("/"))
result = (Double.parseDouble(operand1) / Double.parseDouble(operand2));
else
result = (Double.parseDouble(operand1) * Double.parseDouble(operand2));
return operand1 + operator + operand2 + "=" +result;
}
}
Output
// This java program uses an applet that displays a simple message in center of the screen.
package Applet;
import java.applet.*;
import java.awt.*;
public class WelcomeToApplet extends Applet
{
// create paint class to print on the screen.
public void paint (Graphics g)
{
// Enter message with co-ordinates to make it in centre.
g.drawString ("Welcome To JAVA Programming", 25, 50);
}
}
Alternate Solution:
/* Develop an applet that displays a simple message */
import java.awt.*;
import java.applet.*;
class weeka extends Applet
{
public static void init() {
setForeground(Color.yellow); }
public static void paint(Graphics g) {
g.drawString(" Hello World ",80,40); }
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 56 2022-23
Additional Problems:
1. Write a Java program to accept a number and check the number is even or not
2. Write a Java program which takes three numbers from the user and print the greatest number
3. Write a Java program to print numbers between 1 to 100 which are divisible by 3, 5 and by both
4. Write a program in Java to display the multiplication table of a given integer.
5. Write a Java Program to Convert Celsius to Fahrenheit
6. Write a Java program to convert seconds to hour, minute and seconds
7. Write a Java program that takes a year from user and print whether that year is a leap year or
not
8. Write a Java program to check whether a given integer is a power of 5 or not
9. Write a Java Program to display Fibonacci Series using While Loop
10. Write a Java Program to Find GCD(HCF) and LCM of Two Numbers
11. Write a program that accepts three numbers from the user and prints "increasing" if the
numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and
"Neither increasing or decreasing order" otherwise
12. Write a Java program to compute the sum of the first 100 prime numbers
13. Write a Java program to convert a decimal number to binary number
14. Write a Java program to display Pascal's triangle
15. Write a Java program to convert a binary number to decimal number
16. Write a Java program to compute the sum of the digits of an integer
17. Write a Java program to check if a positive number is a palindrome or not
18. Write a Java program to compute the area of a polygon
19. Write Java methods to calculate the area of a triangle
20. Write a Java program to reverse a string / number
21. Java Program to display n Prime Numbers using Exception Handling
22. Java Program to print Armstrong numbers between desired Range
23. Write a Java method to count all vowels in a string
24. Write a Java program to count the letters, spaces, numbers and other characters of an input
string
25. Write a Java program that searches a value in an m x n matrix
26. Write a Java program to calculate the median of a given unsorted array of integers
27. Write a Java program to search an element in a array list
28. Write a Java Program for Binary Search on Unsorted Array
29. Write a Java program to sort a given array list
30. Java Program to perform Insertion Sort using function
31. Write a Java program to remove duplicates from a sorted linked list
32. Write a Java program to merge two given sorted lists.
33. Write a Java program to check if a file or directory specified by pathname exists or not and to
check if a file or directory has read and write permission
34. Write a Java program to find the longest word in a text file
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 57 2022-23
Sample Solutions to Additional Problems:
1. Java program to check whether the given number is even or odd
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter a number: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
int x = number%2;
if(x==0){
System.out.println("The number is Even");
}
else{
System.out.println("The number is Odd");
}
}
}
2. Java program to convert the temperature in Degree Centigrade to Fahrenheit
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter temperature in Centigrade: ");
Scanner sc = new Scanner(System.in);
int c =Integer.parseInt(sc.nextLine());
float f = ((9*c)/5)+32;
System.out.println("Temperature in Fahrenheit is: "+f);
}
}
3. Java program to find the area of a triangle whose three sides are given
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the 1st side:");
int a= sc.nextInt();
System.out.println("Enter the 2nd side:");
int b= sc.nextInt();
System.out.println("Enter the 3rd side:");
int c= sc.nextInt();
if((a+b)>c && (a+c)>b && (b+c)>a)
{
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 58 2022-23
double s=(a+b+c)/2.0;
double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("Area of Triangle is: " + area);
}
else
System.out.println("Area of the triangle does not exist");
}
}
4. Java program to find out the average of a set of integers
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the count of numbers: ");
int count = Integer.parseInt(sc.nextLine());
int i = 0;
float sum = 0;
for(i=0;i<count;i++){
System.out.println("Enter an integer: ");
int x = Integer.parseInt(sc.nextLine());
sum = sum + x;
}
float avg = sum/count;
System.out.println("The average is: "+avg);
}
}
5. Java program to find the product of a set of real numbers
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of real numbers: ");
int count = Integer.parseInt(sc.nextLine());
int i = 0;
float product = 1.0f;
for(i=0;i<count;i++){
System.out.println("Enter a real number: ");
float x = Float.parseFloat(sc.nextLine());
product = product * x;
}
System.out.println("The product of the numbers is: "+product);
}
}
6. Java program to find the circumference and area of a circle with a given radius
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input the radius of the circle: ");
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 59 2022-23
double radius = Float.parseFloat(sc.nextLine());
double c = 2 * Math.PI * radius;
double area = Math.PI * radius * radius;
System.out.println("The circumference of the circle is: "+c);
System.out.println("The area of the circle is: "+area);
}
}
7. Java program to check whether the given integer is a multiple of 5
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
if(number%5==0){
System.out.println(number+" is a multiple of 5");
}
else{
System.out.println(number+" is not a multiple of 5");
}
}
}
8. Java program to check whether the given integer is a multiple of both 5 and 7
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
if((number%5==0)&&(number%7==0)){
System.out.println(number+" is a multiple of both 5 and 7");
}
else{
System.out.println(number+" is not a multiple of both 5 and 7");
}
}
}
9. Java program to find the average of 5 numbers using while loop
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int count = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 60 2022-23
while(count<5){
System.out.println("Enter an integer: ");
int number =Integer.parseInt(sc.nextLine());
sum = sum+number;
count++;
}
double avg = ((double) sum) / 5.0;
System.out.println("Average is :"+avg);
}
}
10. Java program to display the given integer in reverse manner
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number =Integer.parseInt(sc.nextLine());
int rev = 0;
while(number!=0){
int digit = number%10;
rev = (rev*10)+digit;
number = number/10;
}
System.out.println(rev);
}
}
11. Java program to find the geometric mean of n numbers
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int c = 0;
double p = 1.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of values: ");
int count =Integer.parseInt(sc.nextLine());
while((c<count)){
System.out.println("Enter a real number: ");
double x =Double.parseDouble(sc.nextLine());
c = c+1;
p = p * x;
}
double gm = Math.pow(p,1.0/count);
System.out.println("The geometric mean is: "+gm);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 61 2022-23
12. Java program to find the sum of the digits of an integer using while loop
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number =Integer.parseInt(sc.nextLine());
while(number!=0){
int digit = number%10;
sum = sum+digit;
number = number/10;
}
System.out.println(("Sum of digits is: "+ sum));
}
}
13. Java program to display all the multiples of 3 within the range 10 to 50
import java.util.Scanner;
class Main {
public static void main(String[] args) {
for(int i=10;i<50;i++){
if(i%3==0)
System.out.println(i);
}
}
}
14. Java program to display all integers within the range 100-150 whose sum of digits is an even
number
import java.util.Scanner;
class Main {
public static void main(String[] args) {
for(int i=100;i<150;i++){
int num = i;
int sum = 0;
while(num!=0){
int digit = num%10;
sum = sum + digit;
num = num/10;
}
if(sum%2==0){
System.out.println(i);
}
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 62 2022-23
15. Java program to check whether the given integer is a prime number or not
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter an integer greater than 1: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
int isprime = 1;
for(int i=2;i<(number/2);i++){
if(number%i==0){
isprime = 0;
break;
}
}
if(isprime==1){
System.out.println(number+" is a prime number");
}
else{
System.out.println(number+" is not a prime number");
}
}
}
16. Java program to generate the prime numbers from 1 to N
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter the range: ");
Scanner sc = new Scanner(System.in);
int number =Integer.parseInt(sc.nextLine());
for (int num = 2; num <= number; num++)
{
boolean isPrime = true;
for (int i=2; i <= num/2; i++)
{
if ( num % i == 0)
{
isPrime = false;
break;
}
}
if ( isPrime == true )
System.out.println(num);
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 63 2022-23
17. Java program to find the roots of a quadratic equation
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter the first coefficient: ");
Scanner sc = new Scanner(System.in);
double a = Integer.parseInt(sc.nextLine());
System.out.println("Enter the second coefficient: ");
double b = Integer.parseInt(sc.nextLine());
System.out.println("Enter the third coefficient: ");
double c = Integer.parseInt(sc.nextLine());
if(a!=0.0){
double d = (b*b)-(4*a*c);
if (d==0.0){
System.out.println("The roots are real and equal.");
double r = -b/(2*a);
System.out.println("The roots are "+ r+"and"+ r);
}else if(d>0.0){
System.out.println("The roots are real and distinct.");
double r1 = (-b+(Math.sqrt(d)))/(2*a);
double r2 = (-b-(Math.sqrt(d)))/(2*a);
System.out.println("The root1 is: "+ r1);
System.out.println("The root2 is: "+ r2);
}else{
System.out.println("The roots are imaginary.");
double rp = -b/(2*a);
double ip = Math.sqrt(-d)/(2*a);
System.out.println("The root1 is: "+ rp+ "+ i"+ip);
System.out.println("The root2 is: "+ rp+ "- i"+ip);
}
}else{
System.out.println("Not a quadratic equation.");
}
}
}
18. Java program to print the numbers from a given number n till 0 using recursion
class Main {
public static void main(String[] args) {
print_till_zero(8);
}
public static void print_till_zero(int n){
if(n==0)
return;
System.out.println(n);
n=n-1;
print_till_zero(n);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 64 2022-23
19. Java program to find the factorial of a number using recursion
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int a = Integer.parseInt(sc.nextLine());
int result = fact(a);
System.out.println("The factorial of"+ a + " is: "+ result);
}
public static int fact(int n){
int f;
if(n==1)
f=1;
else
f = n * fact(n-1);
return f;
}
}
20. Java program to display the sum of n numbers using an array
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("How many numbers: ");
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
int[] numbers = new int[num];
int sum=0;
for(int n=0;n<num;n++){
System.out.println("Enter number: ");
int x = Integer.parseInt(sc.nextLine());
numbers[n] = x;
}
for(int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum of all the elements of the array: " + sum);
}
}
21. Java program to implement linear search
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int[] numbers = {4,2,7,1,8,3,6};
int flag = 0;
System.out.println("Enter the number to be found out: ");
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 65 2022-23
Scanner sc = new Scanner(System.in);
int x = Integer.parseInt(sc.nextLine());
for(int i=0;i<numbers.length;i++){
if (x==numbers[i]){
System.out.println("Successful search, the element is found at position "+ i);
flag = 1;
break;
}
}
if(flag==0){
System.out.println("Oops! Search unsuccessful");
}
}
}
22. Java program to implement binary search
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers
System.out.println("Enter the number to be found out: ");
Scanner sc = new Scanner(System.in);
int x = Integer.parseInt(sc.nextLine());
int result = binarySearch(numbers, 0, numbers.length-1, x);
if (result != -1)
System.out.println("Search successful, element found at position "+result);
else
System.out.println("The given element is not present in the array");
}
public static int binarySearch(int[] numbers,int low,int high,int x){
if (high >= low){
int mid = low + (high - low)/2;
if (numbers[mid] == x)
return mid;
else if (numbers[mid] > x)
return binarySearch(numbers, low, mid-1, x);
else
return binarySearch(numbers, mid+1, high, x);
}else{
return -1;
}
}
}
23. Java program to find the number of odd numbers in an array
class Main {
public static void main(String[] args) {
int[] numbers = {8,3,1,6,2,4,5,9};
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 66 2022-23
int count = 0;
for(int i=0;i<numbers.length;i++){
if(numbers[i]%2!=0)
count++;
}
System.out.println("The number of odd numbers in the list are: "+count);
}
}
24. Java program to find the largest number in an array without using built-in functions
class Main {
public static void main(String[] args) {
int[] numbers = {3,8,1,7,2,9,5,4};
int largest = numbers[0];
int position = 0;
for(int i=0;i<numbers.length;i++){
if(numbers[i]>largest){
largest = numbers[i];
position = i;
}
}
System.out.println("The largest element is "+largest+" which is found at position
"+position);
}
}
25. Java program to insert a number to any position in an array
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] numbers = {3,4,1,9,6,2,8};
System.out.println(Arrays.toString(numbers));
System.out.println("Enter the number to be inserted: ");
Scanner sc = new Scanner(System.in);
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter the position: ");
int y = Integer.parseInt(sc.nextLine());
for(int i=numbers.length-1;i>y;i--){
numbers[i] = numbers[i-1];
}
numbers[y] = x;
System.out.println(Arrays.toString(numbers));
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 67 2022-23
26. Java program to delete an element from an array by index
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>(5);
numbers.add(3);
numbers.add(7);
numbers.add(1);
numbers.add(4);
System.out.println(numbers);
System.out.println("Enter the position of the element to be deleted: ");
Scanner sc = new Scanner(System.in);
int x = Integer.parseInt(sc.nextLine());
numbers.remove(x);
System.out.println(numbers);
}
}
27. Java program to check whether a string is palindrome or not
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String a, b = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter the string you want to check: ");
a = s.nextLine();
int n = a.length();
for(int i = n - 1; i >= 0; i--){
b = b + a.charAt(i);
}
if(a.equalsIgnoreCase(b)){
System.out.println("The string is palindrome.");
}else{
System.out.println("The string is not palindrome.");
}
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 68 2022-23
28. Java program to implement matrix addition
class Main {
public static void main(String[] args) {
//creating two matrices
int a[][]={{8,5,1},{9,3,2},{4,6,3}};
int b[][]={{8,5,3},{9,5,7},{9,4,1}};
//matrix to store the sum of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//adding 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.print("n");
}
}
}
29. Java program to implement matrix multiplication
class Main {
public static void main(String[] args) {
//creating two matrices
int a[][]={{8,5,1},{9,3,2},{4,6,3}};
int b[][]={{8,5,3},{9,5,7},{9,4,1}};
//matrix to store the product of two matrices
int c[][]=new int[3][3];
//multiplying 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++){
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.print("n");
}
}
}
30. Java program to check leap year
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the year you want to check: ");
int year = Integer.parseInt(sc.nextLine());
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 69 2022-23
boolean leap = false;
// if the year is divided by 4
if (year % 4 == 0) {
// if the year is century
if (year % 100 == 0) {
// if year is divided by 400, then it is a leap year
if (year % 400 == 0)
leap = true;
else
leap = false;
}
// if the year is not century
else
leap = true;
}
else
leap = false;
if (leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");
}
}
31. Java program to find the Nth term in a Fibonacci series using recursion
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
int n;
System.out.print("Enter the position(N): ");
n=cs.nextInt();
System.out.print("Nth Fibonacci Number is:
"+NthFibonacciNumber(n));
}
static int NthFibonacciNumber(int n){
if(n==1)
return 0;
else if(n==2)
return 1;
else
return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2);
}
}
32. Java program to print Fibonacci series using iteration
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int n1=0,n2=1;
Scanner cs=new Scanner(System.in);
System.out.print("Enter the number of terms in the sequence: ");
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 70 2022-23
int count = cs.nextInt();
int n3,i;
System.out.print(n1+" "+n2);//printing 0 and 1
//printing from 2 because 0 and 1 are already printed
for(i=2;i<count;++i){
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
33. Java program to implement a calculator to do basic operations
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int firstNumber, secondNumber, opt, add, sub, mul;
double div;
Scanner s = new Scanner(System.in);
System.out.print("Enter first number: ");
firstNumber = s.nextInt();
System.out.print("Enter second number: ");
secondNumber = s.nextInt();
while(true){
System.out.println("Enter 1 for addition");
System.out.println("Enter 2 for subtraction");
System.out.println("Enter 3 for multiplication");
System.out.println("Enter 4 for division");
System.out.println("Enter 5 to Exit");
int option = s.nextInt();
switch(option){
case 1:
add = firstNumber + secondNumber;
System.out.println("Result:"+add);
break;
case 2:
sub = firstNumber - secondNumber;
System.out.println("Result:"+sub);
break;
case 3:
mul = firstNumber * secondNumber;
System.out.println("Result:"+mul);
break;
case 4:
div = (double)firstNumber / secondNumber;
System.out.println("Result:"+div);
break;
case 5:
System.exit(0);
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 71 2022-23
}
}
}
34. Java Program to Find Your Weight on Mars
Mars’ gravity is about 38% of Earth’s. Write a program that will calculate your weight on
Mars.
Declare all variables at the top of the class.
Initial variables are to be of float type.
After making the calculations, assign the result to a new variable, this time of the double
type.
After assigning the assignment, write the variable double to the console, limiting its
length to 4 decimal places.
Cast the above variable of double type to a new variable of int type.
Cast the above variable of type int to a new variable of type char.
Do any math operation on this variable char type and assign the value of this activity to
the new variable int type.
Each of the above actions should be written to the console, adding some text explaining
what has been done.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many pounds (lbs) do you weigh? ") ;
float weight = input.nextFloat();
// computing the weight on mars
double weightOnMars = (weight * .38);
// displaying results with 4 decimal places
System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on
Mars");
System.out.println("Converting the variable into integer");
int weightOnMarsInt = (int)weightOnMars;
System.out.println(weightOnMarsInt);
System.out.println("Converting the variable into char");
char weightOnMarsChar = (char)weightOnMars;
System.out.println(weightOnMarsChar);
System.out.println("Converting the variable into Int and doing an operation on it");
int newIntVariable = weightOnMarsChar * 2;
System.out.println(newIntVariable);
}
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 72 2022-23
35. Java Program to Check Whether the Generated Random Number Is Even or Odd
Write a program that generates a random number between 1 and 100 (you can use the Random ()
method from the Math class.
In the next step check whether it is an even or an odd number. Each of the above actions should be
written to the console.
import java.util.Random;
class Main {
public static void main(String[] args) {
int min = 1;
int max = 100;
//Generating a random number
Random r = new Random();
int randomNumber = min + r.nextInt(max);
System.out.println("Generated random number is: "+randomNumber);
//Checking whether the number is odd or even
if(randomNumber%2==0){
System.out.println("The generated random number is even.");
}else{
System.out.println("The generated random number is odd.");
}
}
}
36. Java Program to Find the Number of Containers You Need
Choose an odd number between 50 and 100 and save it as an int variable telling us how many Lego
bricks we have (e.g. amountOfBricks ), then select an even number between 5 and 10 stating how
many Lego blocks fit in one container (e.g.: containerCapacity ) and save it as an int variable as well.
Write a program that will calculate how many full containers we have, how many containers, in
general, are full and not full, and how many blocks are in the container that is not completely full
(use the modulo operator for this).
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many Lego bricks do we have? Choose an odd number
between 50 and 100: ");
int amountOfBricks = Integer.parseInt(sc.nextLine());
System.out.println("How many Lego blocks fit in one container? Choose an even
number between 5 and 10: ");
int containerCapacity = Integer.parseInt(sc.nextLine());
int noOfFullContainers = amountOfBricks/containerCapacity;
int noOfTotalContainers;
int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf
_OOP with JAVA Solution Manual (1).pdf

More Related Content

Similar to _OOP with JAVA Solution Manual (1).pdf

Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Pratima Parida
 
Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Pratima Parida
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Robin O'Brien
 
Webface - Passion is Innovation
Webface - Passion is InnovationWebface - Passion is Innovation
Webface - Passion is InnovationAbhishek kumar
 
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...DicodingEvent
 
Daa final 2019 20
Daa final 2019 20Daa final 2019 20
Daa final 2019 20Snk Nks
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfLPSChandana
 
Java report by ravi raja
Java report by ravi rajaJava report by ravi raja
Java report by ravi rajaRaviRaja55
 
Bca 4020 java programming
Bca 4020   java programmingBca 4020   java programming
Bca 4020 java programmingsmumbahelp
 
Pg certificate
Pg certificatePg certificate
Pg certificatedkhari
 
Supporting Coding and Testing
Supporting Coding and TestingSupporting Coding and Testing
Supporting Coding and TestingSuelen Carvalho
 
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdfcNguyn506241
 
Industrial Summer Training for MCA/BCA/BE/B-Tech Students
Industrial Summer Training for MCA/BCA/BE/B-Tech StudentsIndustrial Summer Training for MCA/BCA/BE/B-Tech Students
Industrial Summer Training for MCA/BCA/BE/B-Tech StudentsTech Mentro
 

Similar to _OOP with JAVA Solution Manual (1).pdf (20)

DebarghyaNag_Resume
DebarghyaNag_ResumeDebarghyaNag_Resume
DebarghyaNag_Resume
 
Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)
 
Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)Java Semimar Slide (Cetpa)
Java Semimar Slide (Cetpa)
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development
 
Stacker's
Stacker'sStacker's
Stacker's
 
Webface - Passion is Innovation
Webface - Passion is InnovationWebface - Passion is Innovation
Webface - Passion is Innovation
 
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...
Memulai Karir menjadi iOS Developer - Gilang ramadhan (Academy Content Writer...
 
Daa final 2019 20
Daa final 2019 20Daa final 2019 20
Daa final 2019 20
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
 
Resume (5)
Resume (5)Resume (5)
Resume (5)
 
Java report by ravi raja
Java report by ravi rajaJava report by ravi raja
Java report by ravi raja
 
Resume_Avik
Resume_AvikResume_Avik
Resume_Avik
 
Bca 4020 java programming
Bca 4020   java programmingBca 4020   java programming
Bca 4020 java programming
 
Pg certificate
Pg certificatePg certificate
Pg certificate
 
Supporting Coding and Testing
Supporting Coding and TestingSupporting Coding and Testing
Supporting Coding and Testing
 
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
49.INS2065.Computer Based Technologies.TA.NguyenDucAnh.pdf
 
Industrial Summer Training for MCA/BCA/BE/B-Tech Students
Industrial Summer Training for MCA/BCA/BE/B-Tech StudentsIndustrial Summer Training for MCA/BCA/BE/B-Tech Students
Industrial Summer Training for MCA/BCA/BE/B-Tech Students
 
Nagacv
NagacvNagacv
Nagacv
 
Gaurav agarwal
Gaurav agarwalGaurav agarwal
Gaurav agarwal
 
Abhishek Mittal Resume
Abhishek Mittal ResumeAbhishek Mittal Resume
Abhishek Mittal Resume
 

Recently uploaded

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 

Recently uploaded (20)

(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 

_OOP with JAVA Solution Manual (1).pdf

  • 1. OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY MANUAL [21CSL35] (III SEMESTER) By: Dr. G T Raju Principal SJCIT, Chickballapur SJC INSTITUTE OF TECHNOLOGY, CHICKBALLAPUR- 562101 DEPARTMENT OF COMPUTER SCIENCE & INFORMATION SCIENCE ENGINEERING (NEP) For the Year: 2022-23 || Jai Sri Gurudev || Adichunchanagiri Shikshana Trust(R.) SJC INSTITUTE OF TECHNOLOGY VTU Affiliated, AICTE Approved, Accredited by NAAC & NBA (CSE, ISE, ECE, ME, CV, AE) Gold rated by QS I-Gauge
  • 2. INSTITUTION VISION AND MISSION VISION Preparing Competent Engineering and Management Professionals to Serve the Society. MISSION M1: Providing Students with a Sound Knowledge in Fundamentals of their branch of Study. M2: Promoting Excellence in Teaching, Training, Research and Consultancy. M3: Exposing Students to Emerging Frontiers in various domains enabling Continuous Learning. M4: Developing Entrepreneurial acumen to venture into Innovative areas. M5: Imparting Value based Professional Education with a sense of Social Responsibility.
  • 3. DEPARTMENT OF COMPUTER SCIENCE ENGINEERING VISION Building Proficient Computer Science Engineers having Core Values to Solve Real Life Problems. MISSION M1: Strengthening Students with Fundamental and Applied aspects in Design and Implementation of Computational Systems. M2: Empowering the Students with Sound Knowledge in AI & ML, Data Analytics, Block Chain, AR and VR systems to Solve Multidisciplinary Problem. M3: Developing Analytical Skills to meet the Complex, Societal and Industrial needs. M4: Promoting Research blend of mind among Students enabling Continuous Learning. M5: Encouraging Entrepreneurship including Ethical Values and Team building abilities. DEPARTMENT OF INFORMATION SCIENCE ENGINEERING VISION Educating Students to Engineer Information Science and Technology for Advancing the Knowledge as to Best Serve the Real World. MISSION M1: Focusing on Fundamentals and Applied aspects in both Information Science Theory and Programming practices. M2: Training comprehensively and encouraging R&D culture in trending areas of Information Technology. M3: Collaborating with premier Institutes and Industries to nurture Innovation and learning, in cutting edge Information Technology. M4: Preparing the students who are much Sought-after, Productive and Well- respected for their work culture having Lifelong Learning practice. M5: Promoting ethical and moral values among the students so as to enable them emerge as responsible professionals.
  • 4. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 1 2022-23 OBJECT ORIENTED PROGRAMMING WITH JAVA LABORATORY Course Code 21CSL35 CIE Marks 50 Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50 Total Hours of Pedagogy 24 Total Marks 100 Credits 1 Exam Hours 03 Course Objectives: CLO 1. Demonstrate the use of Eclipse/NetBeans IDE to create Java Applications. CLO 2. Using java programming to develop programs for solving real-world problems. CLO 3. Reinforce the understanding of basic object-oriented programming concepts. CLO 4. Understand and apply the concepts of classes, packages, interfaces, array list, exception handling and file processing CLO 5. Develop applications using generic programming and event handling Course Outcomes: At the end of the course the student will be able to: CO 1. Use Eclipse/NetBeans IDE to design, develop, debug Java Projects. CO 2. Analyze the necessity for Object Oriented Programming paradigm over structured programming CO 3. Develop and implement Java programs for simple applications that make use of classes, packages and interfaces. CO 3. Develop and implement Java programs with array list, exception handling and multithreading. CO 4. Apply the concepts of multiprogramming, event handling, abstraction to develop robust programs. CO 6. Develop user friendly applications using File I/O and GUI concepts. Recommended System/Software Requirements:  Intel based desktop PC with minimum of 2.6GHZ or faster processor with at least 256 MB RAM and 40GB free disk space.  Operating system: Windows or Linux  Software: As of September 2022, Java 19 is the latest released Java version. In March 2023, Java 20 will follow. The last long-term support version (LTS) of Java is Java 17, released in September 2021. Install JDK 17 or above  IDE: Eclipse or Net beam. Download and Install Java Development Kit (JDK) on Windows Setting up a Suitable Development Environment is necessary before one can begin creating any Applications. It makes it easier for developers to use the tools required to create any Application and ensures that all Operations or Processes run smoothly. JDK must be installed in order to create Application Source Files using the Java Programming Language. The system will execute the code using a set of Libraries and Compilers. The JDK can be installed on the following Platforms:  Microsoft Windows  Linux  macOS Installation of JDK on Microsoft Windows: Step 1: Download and Install Oracle Java Development Kit (JDK) The very first step is to download the Oracle Java Development Kit (JDK) from the Official Oracle Website. https://www.oracle.com/java/technologies/downloads/#jdk18-windows
  • 5. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 2 2022-23 You need to identify your system specifications to choose the Product/file description. The website will contain the latest version for your corresponding system. For Windows, we’ll be downloading the latest x64 Installer of Java SE Development Kit 18. After the download is complete, proceed to install the JDK by following the bootstrapped steps. Step 2: Configure Environment Variables After the installation is complete, we have to configure environment variables to notify the system about the directory in which JDK files are located. Proceed to C:Program FilesJavajdk- {YOUR_JDK_VERSION}bin (replace {-} with your JDK version)
  • 6. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 3 2022-23 To set the Environment Variables, you need to search Environment Variables in the Task Bar and click on “Edit the system environment variables”. Under the Advanced section, Click on “Environment Variables”.
  • 7. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 4 2022-23 Under System variables, select the “Path” variable and click on “Edit”. Click on “New” then paste the Path Address i.e. C:Program FilesJavajdk-{YOUR_JDK_VERSION}bin. Click on “OK”. Now, in the Environment Variables dialogue, under System variables, click on “New” and then under Variable name: JAVA_HOME and Variable value: paste address i.e. C:Program Files Java jdk-{YOUR_JDK_VERSION}. Click on OK => OK => OK.
  • 8. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 5 2022-23 Step 3: Check the Java Version Open Command Prompt and enter the following commands java -version javac -version Introduction to OOP: Object-oriented programming (OOP) is a computer science term was originally coined by Xerox PARC in 1960’s to designate a computer application that describes the methodology of using objects as the foundation for computation. By the 1980’s, OOP rose to prominence as the programming language of choice, exemplified by the success of C++. Currently, OOP such as Java, J2EE, C++,C#, Visual Basic.NET, Python and java Script are popular OOP programming languages that any career-oriented Software Engineer or developer should be familiar with. OOP is widely accepted as being far more flexible than other computer programming languages. OOP use three basic concepts as the fundamentals for the Abstraction, Polymorphism, Event Handling and Encapsulation are also significant concepts within objectoriented programming languages that are explained in online tutorial describing the functionality of each concept in detail. The java platform is undoubtedly fast moving and comprehensive. Its many application programming interfaces (APIs) provide a wealth of functionality for all aspects of application and system-level programming. Real-world developers never use one or two APIs to solve a problem, but bring together key functionality spanning a number of APIs, Knowing which APIs you need, and how the APIs work together to create the best solution can be a daunting task.
  • 9. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 6 2022-23 1. Aim: Introduce the java fundamentals, data types, operators in java Program: Write a java program that prints all real solutions to the quadratic equationax2+bx+c=0. Read in a, b, c and use the quadratic formula. The standard form of a quadratic equation is ax2+bx+c=0. It is also known as the second-degree equation. In the equation ax2+bx+c=0, a, b, and c are unknown values and a cannot be 0. x is an unknown variable. The formula to find the roots of the quadratic equation is given by: A quadratic equation has two roots and the roots depend on the discriminant. In the above formula, (√b2-4ac) is called discriminant (d). The value of d may be positive, negative, or zero. If d is positive (d>0), the root will be: If the value of d is positive, both roots are real and different. It means there are two real solutions. If d is zero (d=0), the root will be: If the value of d is zero, both roots are real and the same. It means we get one real solution. If d is negative (d<0), the root will be: If the value of d is negative, both roots are distinct and imaginary or complex. It means that there are two complex solutions.
  • 10. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 7 2022-23 Algorithm to Find the Roots of the Quadratic Equation Step 1: Start Step 2: Read a, b, c Step 3: Compute d<-(b*b)-(4*a*c) Step 4: Compute r<- b/2*a Step 5: if d>0 go to Step 6, else go to Step 8 Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a) Step 7: prints roots are real and distinct, first root r1 second root r2 Step 8: if d=0 go to Step 9, else go to Step 10 Step 9: print roots are real and equal, -r Step 10: d=-d Step 11: im=sqrt(d)/2*a Step 12: print roots are imaginary, first root is r+i im, and the second root is r-i im Step 13: Stop Pseudocode: Start Read the values of a, b, c Compute d = b2 – 4ac If d > 0 calculate root1 = {-b + √(b2 – 4ac)}/2a calculate root2 = {-b – √(b2 – 4ac)}/2a else If d = 0 calculate root1 = root2 = (-b/2a) else calculate root1 = {-b + i√-(b2 – 4ac)}/2a calculate root2 = {-b + i√-(b2 – 4ac)}/2a print root1 and root2 End Let's create a Java program and implement the above steps. // Java program to find roots of a quadratic equation import static java.lang.Math.*; import java.io.*; class Quadratic { // Prints roots of quadratic equation ax * 2 + bx + x static void findRoots(int a, int b, int c) { // If a is 0, then equation is not quadratic, but linear if (a == 0) { System.out.println("Invalid"); return; } int d = b * b - 4 * a * c; double sqrt_val = sqrt(abs(d));
  • 11. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 8 2022-23 if (d > 0) { System.out.println( "Roots are real and different n"); System.out.println( (double)(-b + sqrt_val) / (2 * a) + "n" + (double)(-b - sqrt_val) / (2 * a)); } else if (d == 0) { System.out.println( "Roots are real and same n"); System.out.println(-(double)b / (2 * a) + "n" + -(double)b / (2 * a)); } else // d < 0 { System.out.println("Roots are complex n"); System.out.println(-(double)b / (2 * a) + " + i" + sqrt_val / (2 * a) + "n" + -(double)b / (2 * a) + " - i" + sqrt_val / (2 * a)); } } // Driver code public static void main(String args[]) { int a = 1, b = -7, c = 12; // Function call findRoots(a, b, c); } }
  • 12. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 9 2022-23 QuadraticEquationExample1.java import java.util.Scanner; public class QuadraticEquationExample1 { public static void main(String[] Strings) { Scanner input = new Scanner(System.in); System.out.print("Enter the value of a: "); double a = input.nextDouble(); System.out.print("Enter the value of b: "); double b = input.nextDouble(); System.out.print("Enter the value of c: "); double c = input.nextDouble(); double d = b * b - 4.0 * a * c; if (d > 0.0) { System.out.println("The roots of the equation are real and different. n"); double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a); double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a); System.out.println("The roots are " + r1 + " and " + r2); } else if (d == 0.0) { System.out.println("The roots of the equation are real and same. n"); double r1 = -b / (2.0 * a); System.out.println("The root is " + r1); } else { System.out.println("Roots are not real."); System.out.println(-(double)b / (2 * a) + " + i" + sqrt_val / (2 * a) + "n" + -(double)b / (2 * a) + " - i" + sqrt_val / (2 * a)); } } }
  • 13. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 10 2022-23 Using Function QuadraticEquationExample2.java import static java.lang.Math.*; public class QuadraticEquationExample2 { //defining a static method that finds the roots of the quadratic equation static void calculateRoots(int a, int b, int c) { //comparing the value of a with 0, if a is 0 then the equation is not quadratic if (a == 0) { System.out.println("The value of a cannot be 0."); return; } //calculating discriminant (d) int d = b * b - 4 * a * c; double sqrtval = sqrt(abs(d)); if (d > 0) { System.out.println("The roots of the equation are real and different. n"); System.out.println((double)(-b + sqrtval) / (2 * a) + "n"+ (double)(-b - sqrtval) / (2 * a)); } else if (d == 0) { System.out.println("The roots of the equation are real and same. n"); System.out.println(-(double)b / (2 * a) + "n"+ -(double)b / (2 * a)); } // executes if d < 0 else { System.out.println("The roots of the equation are complex and different. n"); System.out.println(-(double)b / (2 * a) + " + i"+ sqrtval + "n"+ -(double)b / (2 * a)+ " - i" + sqrtval); } } //main method public static void main(String args[]) { //Output 1: int a = 1, b = 5, c = 2; //calling function calculateRoots(a, b, c); //Output 2: int a=1, b=1, c=1 //Output 3: int a=1, b=-2, c=1 } }
  • 14. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 11 2022-23 Alternative Solution 2: Main.java import static java.lang.Math.*; public class Main { public static void main(String[] args) { // value a, b, and c double a = 2.3, b = 4, c = 5.6; double root1, root2; // calculate the determinant (b2 - 4ac) double determinant = b * b - 4 * a * c; // check if determinant is greater than 0 if (determinant > 0) { // two real and distinct roots root1 = (-b + Math.sqrt(determinant)) / (2 * a); root2 = (-b - Math.sqrt(determinant)) / (2 * a); System.out.println ("root1 = %.2f and root2 = %.2f", root1, root2); } // check if determinant is equal to 0 else if (determinant == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b root1 = root2 = -b / (2 * a); System.out.println ("root1 = root2 = %.2f;", root1); } // if determinant is less than zero else { // roots are complex number and distinct double real = -b / (2 * a); double imaginary = Math.sqrt(-determinant) / (2 * a); System.out.println ("root1 = %.2f+%.2fi", real, imaginary); System.out.println ("nroot2 = %.2f-%.2fi", real, imaginary); } } }
  • 15. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 12 2022-23 2. Aim: Demonstrating creation of java classes, objects, constructors, declaration and initialization of variables. Create a Java class called Student with the following details as variables within it. (i) USN (ii) Name (iii) Branch (iv) Phone Write a Java program to create n Student objects and print the USN, Name, Branch, and Phone of these objects with suitable headings. Solution: The aim of this program is to create a class and make objects of that class to print the details of a student. Implementation: • Create a class named “student”. • Declare variables within it containing the details like name, USN, Branch, Phone no • Create a constructor to initialize these variables. • Create a function that prints these details like usn, name, branch and phone no. • Create multiple objects of “student” class that calls the function to print the details. Algorithm: //Input: Values for USN, name, branch and phone no //Output: Displaying the details of n student objects //Steps: 1) class “student” is created 2) Declare variables USN, Name, Branch, and Phone no. 3) a constructor of Student class is created to initialize these variables. 4) multiple objects of “student” class is created and print the details contained student class Program: Main.java import java.util.Scanner; class Student { private String usn, name, branch, ph; public void accept() { Scanner sc = new Scanner(System.in); System.out.println("Enter Usnn"); usn = sc.next(); System.out.println("Enter Namen"); name = sc.next(); System.out.println("Enter Branchn"); branch = sc.next();
  • 16. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 13 2022-23 System.out.println("Enter Phonen"); ph = sc.next(); } public void display() { System.out.println("Student details"); System.out.println("Usn: " + usn); System.out.println("Name: " + name); System.out.println("Branch: " + branch); System.out.println("Phone: " + ph); System.out.println(); } } class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter value for n"); int n = sc.nextInt(); Student[] ob1 = new Student[n]; for (int i = 0; i < n; i++) { ob1[i] = new Student(); ob1[i].accept(); } for (int i = 0; i < n; i++) { ob1[i].display(); } } }
  • 17. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 14 2022-23 Alternative Solution1: import java.util.Scanner; public class student { String USN; String Name; String branch; int phone; void insertRecord(String reg, String name, String brnch, int ph) { USN=reg; Name=name; branch=brnch; phone=ph; } void displayRecord() { System.out.println(USN+" "+Name+" "+branch+" "+phone); } public static void main(String args[]) { student s[]=new student [100]; Scanner sc=new Scanner(System.in); System.out.println("enter the number of students"); int n=sc.nextInt(); for(int i=0;i<n;i++) s[i]=new student(); for(int j=0;j<n;j++) { System.out.println("enter the usn,name,branch,phone") String USN=sc.next(); String Name=sc.next(); String branch=sc.next(); int phone=sc.nextInt(); s[j].insertRecord(USN,Name,branch,phone); } for( int m=0;m<n;m++) { s[m].displayRecord(); } } }
  • 18. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 15 2022-23 OUTPUT enter the number of students 2 enter the usn,name,branch,phone 1 monika cse 9341155665 enter the usn,name,branch,phone 2 gowda cse 9785443355 students details are 1 monika cse 9341155665 2 gowda cse 9785443355 Alternative Solution2: import java.io.*; class Student { String usn, name, programme; long ph; Student() { usn = name = programme = "No value"; ph = 0; } void read_data(String u, String n, String p, long m) { usn = u; name = n; programme = p; ph =m; } void display() { System.out.println(usn + "t" + name + "t" + programme + "tt" + ph); } } class Record { public static void main(String args[]) throws Exception { String u, n, p; long m; int no; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter number of records:");
  • 19. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 16 2022-23 no = Integer.parseInt(br.readLine()); Student[] s = new Student[no]; for(int i=0; i<s.length;i++) { System.out.println("nEnter Student " + (i + 1) + " record"); s[i] = new Student(); System.out.print("Enter student USN: "); u = br.readLine(); System.out.print("Enter student Name: "); n = br.readLine(); System.out.print("Enter student Programme: "); p = br.readLine(); System.out.print("Enter student Phone number: "); m = Long.parseLong(br.readLine()); s[i].read_data(u, n, p, m); } System.out.println("USN t NAME t PROGRAMME t PHONE NO"); for(int i=0; i<s.length;i++) { s[i].display(); } } } Alternative Solution3: import java.util.Scanner; public class Room { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n,i; Student[] s=new Student[100]; System.out.println("Enter the Number of Objects"); n=scan.nextInt(); for(i=0;i<n;i++) { s[i]=new Student(); } for(i=0;i<n;i++) { System.out.println("Enter the Details in Order - Name , Usn , Branch , Phone No"); String name = scan.next(); String usn = scan.next(); String branch = scan.next(); String phno = scan.next(); s[i].assignvalue(name, usn, branch, phno); } System.out.println("Students Details are as Follow:"); for(i=0;i<n;i++) { s[i].display(); } scan.close(); } }
  • 20. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 17 2022-23 class Student { String name,usn,branch,phno; void assignvalue(String n,String u,String b,String p) { name=n; usn=u; branch=b; phno=p; } void display() { System.out.println("Name :"+name+" USN :"+usn+" Branch :"+branch+" Phone Number :"+phno); } }
  • 21. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 18 2022-23 3. Aim: Discuss the various Decision-making statements, loop constructs in java A. Write a program to check prime number B. Write a program for Arithmetic calculator using switch case menu Solution: Any natural number greater than 1, is only divisible by 1, and the number itself is called a prime number. In other words, prime numbers have just two factors i.e. 1 and number itself. Example : 2,3,5,7,11,13...... All the natural numbers other than 1 and prime numbers are called composite numbers. Solution A: import java.util.Scanner; import static java.lang.Math.*; public class PrimeCheck { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter a number: "); int n = s.nextInt(); if (isPrime(n)) { System.out.println(n + " is a prime number."); } else { System.out.println(n + " is not a prime number."); } } public static boolean isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i < Math.sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } }
  • 22. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 19 2022-23 Solution B: import java.util.Scanner; class Main { public static void main(String[] args) { char operator; Double number1, number2, result; // create an object of Scanner class Scanner input = new Scanner(System.in); // ask users to enter operator System.out.println("Choose an operator: +, -, *, or /"); operator = input.next().charAt(0); // ask users to enter numbers System.out.println("Enter first number"); number1 = input.nextDouble(); System.out.println("Enter second number"); number2 = input.nextDouble(); switch (operator) { // performs addition between numbers case '+': result = number1 + number2; System.out.println(number1 + " + " + number2 + " = " + result); break; // performs subtraction between numbers case '-': result = number1 - number2; System.out.println(number1 + " - " + number2 + " = " + result); break; // performs multiplication between numbers case '*': result = number1 * number2; System.out.println(number1 + " * " + number2 + " = " + result); break; // performs division between numbers case '/': result = number1 / number2; System.out.println(number1 + " / " + number2 + " = " + result); break; default: System.out.println("Invalid operator!"); break; } input.close(); } }
  • 23. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 20 2022-23 Solution B: Alternate-1 import java.util.Scanner; public class OperatorSwitch { public static void main(String[] args) { char operator; Double my_input_1, my_input_2, my_result; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.println("Enter the first number"); my_input_1 = my_scanner.nextDouble(); System.out.println("Enter the second number"); my_input_2 = my_scanner.nextDouble(); System.out.println("Enter any of the following operator: +, -, *, /, %"); operator = my_scanner.next().charAt(0); switch (operator) { case '+': my_result = my_input_1 + my_input_2; System.out.println(my_input_1 + " + " + my_input_2 + " = " + my_result); break; case '-': my_result = my_input_1 - my_input_2; System.out.println(my_input_1 + " - " + my_input_2 + " = " + my_result); break; case '*': my_result = my_input_1 * my_input_2; System.out.println(my_input_1 + " * " + my_input_2 + " = " + my_result); break; case '/': my_result = my_input_1 / my_input_2; System.out.println(my_input_1 + " / " + my_input_2 + " = " + my_result); break; case '%': my_result = my_input_1 % my_input_2; System.out.println(my_input_1 + " % " + my_input_2 + " = " + my_result); break; default: System.out.println("The operator you have selected is invalid"); break; } } }
  • 24. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 21 2022-23 Solution B: Alternate-2 import java.util.Scanner; public class Calculator { public static void main(String[] args) { double a,b,result; // Declaring a variables Scanner s = new Scanner(System.in); System.out.print("Enter first number value:"); a = s.nextDouble(); // getting values from user... System.out.print("Enter second number value:"); b = s.nextDouble(); System.out.print("Enter any operator (+, -, *, /): "); char opt = s.next().charAt(0); // taking operator switch(opt) // using switch case to create Caluclator { case '+': result = a + b; break; // condition for addition case '-': result =a - b; break; // condition for subtraction case '*': result = a * b; break; // condition for Multiplicatin case '/': result = a / b; break; // condition for Divison default: System.out.printf("You have entered wrong operator or value"); return; } System.out.println(a+" "+opt+" "+b+": "+result); } }
  • 25. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 22 2022-23 4. Aim: Demonstrate the core object-oriented concept of Inheritance, polymorphism Design a super class called Staff with details as StaffId, Name, Phone, Salary. Extend this class by writing three subclasses namely Teaching (domain, publications), Technical (skills), and Contract (period). Write a Java program to read and display at least 3 staff objects of all three categories. Solution: import java.util.Scanner; class Staff { private String staffId; private String name; private int phone; private float salary; public void accept() { Scanner scanner = new Scanner(System.in); System.out.println("Enter Staff Id"); staffId = scanner.next(); System.out.println("Enter Name"); name = scanner.next(); System.out.println("Enter Phone"); phone = scanner.nextInt(); System.out.println("Enter Salary"); salary = scanner.nextFloat(); } public void display() { System.out.println("Staff Id: " + staffId); System.out.println("Name: " + name); System.out.println("Phone: " + phone); System.out.println("Salary: " + salary); } } class Teaching extends Staff { private String domain; private String[] publications; public void accept() { super.accept(); Scanner scanner = new Scanner(System.in); System.out.println("Enter Domain"); domain = scanner.next(); System.out.println("Enter Number of Publications"); int n = scanner.nextInt(); publications = new String[n]; System.out.println("Enter Publications"); for (int i = 0; i < n; i++) { publications[i] = scanner.next(); } } public void display() { super.display(); System.out.println("Domain: " + domain);
  • 26. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 23 2022-23 System.out.println("Publications:"); for (int i = 0; i < publications.length; i++) { System.out.println(publications[i]); } } } class Technical extends Staff { private String[] skills; public void accept() { super.accept(); Scanner scanner = new Scanner(System.in); System.out.println("Enter Number of Skills"); int n = scanner.nextInt(); skills = new String[n]; System.out.println("Enter Skills"); for (int i = 0; i < n; i++) { skills[i] = scanner.next(); } } public void display() { super.display(); System.out.println("Skills:"); for (int i = 0; i < skills.length; i++) { System.out.println(skills[i]); } } } class Contract extends Staff { private int period; public void accept() { super.accept(); Scanner scanner = new Scanner(System.in); System.out.println("Enter Period"); period = scanner.nextInt(); } public void display() { super.display(); System.out.println("Period: " + period); } } class Main { public static void main(String[] args) { Teaching teaching = new Teaching(); Technical technical = new Technical(); Contract contract = new Contract(); System.out.println("Enter Details for Teaching Staff Member"); teaching.accept(); System.out.println("Enter Details for Technical Staff Member");
  • 27. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 24 2022-23 technical.accept(); System.out.println("Enter Details for Contract Staff Member"); contract.accept(); System.out.println("Details for Teaching Staff Member are"); teaching.display(); System.out.println("Details for Technical Staff Member are"); technical.display(); System.out.println("Details for Contract Staff Member are"); contract.display(); } } Solution: Alternate-1 class Staff { private int StaffId; private String Name; private String Phone; private long Salary; public Staff(int staffId,String name,String phone,long salary) { StaffId = staffId; Name = name; Phone = phone; Salary = salary; } public void Display() { System.out.print("t"+StaffId+"t"+Name+"tt"+Phone+"tt"+Salary); } } class Teaching extends Staff { private String Domain; private int Publications; public Teaching(int staffId, String name, String phone,long salary, String domain, int publications) { super(staffId, name, phone, salary); Domain = domain; Publications = publications; } public void Display() { super.Display(); System.out.print("tt"+Domain+"tt"+Publications+"tt"+"--"+"t"+"--"); } } class Technical extends Staff { private String Skills;
  • 28. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 25 2022-23 public Technical(int staffId, String name, String phone,long salary, String skills) { super(staffId, name, phone, salary); Skills = skills; } public void Display() { super.Display(); System.out.print("tt--"+"tt"+"--"+"t"+Skills+"t"+"--"); } } class Contract extends Staff { private int Period; public Contract(int staffId, String name, String phone, long salary, int period) { super(staffId, name, phone, salary); this.Period = period; } public void Display() { super.Display(); System.out.print("tt--"+"tt"+"--"+"tt"+"--"+"t"+Period); } } public class Polyinherit4 { public static void main(String[] args) { Staff staff[]=new Staff[3]; staff[0]=new Teaching(0001,"Raju","271173",90000,"CSE",3); staff[1]=new Technical(0002,"Anu","271172",20000,"Server Admin"); staff[2]=new Contract(0003,"Ganavi","271174",9000,3); System.out.println("StaffIDtNamettPhonettSalaryttDomaintPublicationtSkills ttPeriod"); for(int i=0;i<3;i++) { staff[i].Display(); System.out.println(); } } }
  • 29. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 26 2022-23 5. Aim: Introduce concepts of method overloading, constructor overloading, overriding. Program: Write a java program demonstrating Method overloading and Constructor overloading. The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task. If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. Method overloading increases the readability of the program. There are two ways to overload the method in java 1. By changing number of arguments 2. By changing the data type // Constructor overloading public class Student { //instance variables of the class int id; String name; Student(){ System.out.println("this a default constructor"); } Student(int i, String n){ id = i; name = n; } public static void main(String[] args) { //object creation Student s = new Student(); System.out.println("nDefault Constructor values: n"); System.out.println("Student Id : "+s.id + "nStudent Name : "+s.name); System.out.println("nParameterized Constructor values: n"); Student student = new Student(10, "David"); System.out.println("Student Id : "+student.id + "nStudent Name : "+student.name); } } // Method Overloading: changing no. of arguments class Adder{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} class MethodOverloading { private static void display(int a){ System.out.println("Arguments: " + a); }
  • 30. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 27 2022-23 private static void display(int a, int b){ System.out.println("Arguments: " + a + " and " + b); } public static void main(String[] args) { display(1); display(1, 4); } } //Method Overloading: changing data type of arguments class Adder{ static int add(int a, int b){return a+b;} static double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} class MethodOverloading { // this method accepts int private static void display(int a){ System.out.println("Got Integer data."); } // this method accepts String object private static void display(String a){ System.out.println("Got String object."); } public static void main(String[] args) { display(1); display("Hello"); } }
  • 31. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 28 2022-23 6. Aim: Introduce the concept of Abstraction, packages. Program: Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM, miles to KM and viceversa), time converter (hours to minutes, seconds and vice versa) using packages. Procedure: 1. Create a Package currencyconversion and place the class currency under the package 2. Create the methods to perform currency conversion from dollar to rupee, rupee to dollar, euro to rupee, rupee to euro, yen to rupee and rupee to yen. 3. Create the package distanceconverion and create the class distance within the package 4. Create the methods to convert from meter to km, km to meter, miles to km,km to miles 5. Create the package timeconversion and create the class timer. Create the methods to convert from hours to minutes ,hours to seconds , minutes to hours and seconds to hours 6. Create a class and import the packages currencyconversion, distanceconversion and time conversion. Create the objects for the class currency,distance and timer. 7. Get the choice from the user and invoke the methods to perform the corresponding conversion and display the value. currencyconversion.java package currencyconversion; import java.util.*; public class currency { double inr,usd; double euro,yen; Scanner in=new Scanner(System.in); public void dollartorupee() { System.out.println("Enter dollars to convert into Rupees:"); usd=in.nextInt(); inr=usd*67; System.out.println("Dollar ="+usd+"equal to INR="+inr); } public void rupeetodollar() { System.out.println("Enter Rupee to convert into Dollars:"); inr=in.nextInt(); usd=inr/67; System.out.println("Rupee ="+inr+"equal to Dollars="+usd); } public void eurotorupee() { System.out.println("Enter euro to convert into Rupees:"); euro=in.nextInt(); inr=euro*79.50; System.out.println("Euro ="+euro +"equal to INR="+inr); } public void rupeetoeuro() { System.out.println("Enter Rupees to convert into Euro:"); inr=in.nextInt(); euro=(inr/79.50); System.out.println("Rupee ="+inr +"equal to Euro="+euro); } public void yentorupee() {
  • 32. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 29 2022-23 System.out.println("Enter yen to convert into Rupees:"); yen=in.nextInt(); inr=yen*0.61; System.out.println("YEN="+yen +"equal to INR="+inr); } public void rupeetoyen() { System.out.println("Enter Rupees to convert into Yen:"); inr=in.nextInt(); yen=(inr/0.61); System.out.println("INR="+inr +"equal to YEN"+yen); } } distance.java package distanceconversion; import java.util.*; public class distance { double km,m,miles; Scanner sc = new Scanner(System.in); public void kmtom() { System.out.print("Enter in km "); km=sc.nextDouble(); m=(km*1000); System.out.println(km+"km" +"equal to"+m+"metres"); } public void mtokm() { System.out.print("Enter in meter "); m=sc.nextDouble(); km=(m/1000); System.out.println(m+"m" +"equal to"+km+"kilometres"); } public void milestokm() { System.out.print("Enter in miles"); miles=sc.nextDouble(); km=(miles*1.60934); System.out.println(miles+"miles" +"equal to"+km+"kilometres"); } public void kmtomiles() { System.out.print("Enter in km"); km=sc.nextDouble(); miles=(km*0.621371); System.out.println(km+"km" +"equal to"+miles+"miles"); } }
  • 33. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 30 2022-23 timer.java package timeconversion; import java.util.*; public class timer { int hours,seconds,minutes; int input; Scanner sc = new Scanner(System.in); public void secondstohours() { System.out.print("Enter the number of seconds: "); input = sc.nextInt(); hours = input / 3600; minutes = (input % 3600) / 60; seconds = (input % 3600) % 60; System.out.println("Hours: " + hours); System.out.println("Minutes: " + minutes); System.out.println("Seconds: " + seconds); } public void minutestohours() { System.out.print("Enter the number of minutes: "); minutes=sc.nextInt(); hours=minutes/60; minutes=minutes%60; System.out.println("Hours: " + hours); System.out.println("Minutes: " + minutes); } public void hourstominutes() { System.out.println("enter the no of hours"); hours=sc.nextInt(); minutes=(hours*60); System.out.println("Minutes: " + minutes); } public void hourstoseconds() { System.out.println("enter the no of hours"); hours=sc.nextInt(); seconds=(hours*3600); System.out.println("Minutes: " + seconds); } } converter.java import java.util.*; import java.io.*; import currencyconversion.*; import distanceconversion.*; import timeconversion.*; class converter { public static void main(String args[]) { Scanner s=new Scanner(System.in); int choice,ch; currency c=new currency();
  • 34. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 31 2022-23 distance d=new distance(); timer t=new timer(); do { System.out.println("1.dollar to rupee "); System.out.println("2.rupee to dollar "); System.out.println("3.Euro to rupee "); System.out.println("4..rupee to Euro "); System.out.println("5.Yen to rupee "); System.out.println("6.Rupee to Yen "); System.out.println("7.Meter to kilometer "); System.out.println("8.kilometer to meter "); System.out.println("9.Miles to kilometer "); System.out.println("10.kilometer to miles"); System.out.println("11.Hours to Minutes"); System.out.println("12.Hours to Seconds"); System.out.println("13.Seconds to Hours"); System.out.println("14.Minutes to Hours"); System.out.println("Enter ur choice"); choice=s.nextInt(); switch(choice) { case 1: { c.dollartorupee(); break; } case 2: { c.rupeetodollar(); break; } case 3: { c.eurotorupee(); break; } case 4: { c.rupeetoeuro(); break; } case 5: {c.yentorupee(); break;} case 6 : { c.rupeetoyen(); break; } case 7 : { d.mtokm(); break; } case 8 : { d.kmtom(); break;
  • 35. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 32 2022-23 } case 9 : { d.milestokm(); break; } case 10 : { d.kmtomiles(); break; } case 11 : { t.hourstominutes(); break; } case 12 : { t.hourstoseconds(); break; } case 13 : { t.secondstohours(); break; } case 14 : { t.minutestohours(); break; }} System.out.println("Enter 0 to quit and 1 to continue "); ch=s.nextInt(); }while(ch==1); } }
  • 36. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 33 2022-23 7. Aim: Introduction to abstract classes, abstract methods, and Interface in java Program: Write a program to generate the resume. Create 2 Java classes Teacher (data: personal information, qualification, experience, achievements) and Student (data: personal information, result, discipline) which implements the java interface Resume with the method biodata(). // Java program to demonstrate Interfaces import java.io.*; interface Resume { // abstract method void biodata(String N, String Q, double E, String A); } class Teacher implements Resume{ String Name; String Qual; double Exp; String Ach; // to build resume public void biodata(String N, String Q, double E, String A) { Name = N; Qual = Q; Exp = E; Ach = A; } public void printResume() { System.out.println("Name: " + Name + " Qualification: "+ Qual + " Experience: " + Exp + " Achievements " + Ach); } } class Student implements Resume{ String Name; String Std; double Result; String Branch; // to build resume public void biodata(String N, String C, double R, String B) { Name = N; Std = C; Result = R; Branch = B; } public void printResume() { System.out.println("Name: " + Name + " Class:" + Std + "Result " + Result + " Discipline " + Branch); } } class GTR7 {
  • 37. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 34 2022-23 public static void main (String[] args) { // creating an instance of Teacher Teacher T = new Teacher(); T.biodata("Raju", "PhD",28.6,"Best Teacher"); System.out.println("Teacher Biodata :"); T.printResume(); // creating instance of the Student. Student S = new Student(); S.biodata("Anu","First Year", 96.6,"CSE"); System.out.println("Student Biodata :"); S.printResume(); } }
  • 38. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 35 2022-23 8. Aim: Demonstrate creation of threads using Thread class and Runnable interface, multi- threaded programming. Write a Java program that implements a multi-thread application that has three threads. First thread generates a random integer for every 1 second; second thread computes the square of the number and prints; third thread will print the value of cube of the number. import java.util.Random; class SquareThread implements Runnable { int x; SquareThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Square Thread and Square of " + x + " is: " + x * x); } } class CubeThread implements Runnable { int x; CubeThread(int x) { this.x = x; } public void run() { System.out.println("Thread Name:Cube Thread and Cube of " + x + " is: " + x * x * x); } } class RandomThread implements Runnable { Random r; Thread t2, t3; public void run() { int num; r = new Random(); try { while (true) { num = r.nextInt(100); System.out.println("Main Thread and Generated Number is " + num); t2 = new Thread(new SquareThread(num)); t2.start(); t3 = new Thread(new CubeThread(num)); t3.start(); Thread.sleep(1000);
  • 39. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 36 2022-23 System.out.println("---------------------"); } } catch (Exception ex) { System.out.println("Interrupted Exception"); } } } public class MainThread { public static void main(String[] args) { RandomThread thread_obj = new RandomThread(); Thread t1 = new Thread(thread_obj); t1.start(); } } Alternate Solution: import java.util.Random; class RandomNumberThread extends Thread { public void run() { Random random = new Random(); for (int i = 0; i < 10; i++) { int randomInteger = random.nextInt(100); System.out.println("Random Integer generated : " + randomInteger); if((randomInteger%2) == 0) { SquareThread sThread = new SquareThread(randomInteger); sThread.start(); } else { CubeThread cThread = new CubeThread(randomInteger); cThread.start(); } try { Thread.sleep(1000); } catch (InterruptedException ex) { System.out.println(ex); } } } } class SquareThread extends Thread { int number; SquareThread(int randomNumbern) { number = randomNumbern; } public void run() { System.out.println("Square of " + number + " = " + (number * number)); } }
  • 40. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 37 2022-23 class CubeThread extends Thread { int number; CubeThread(int randomNumber) { number = randomNumber; } public void run() { System.out.println("Cube of " + number + " = " + number * number * number); } } public class MultiThreadingTest { public static void main(String args[]) { RandomNumberThread rnThread = new RandomNumberThread(); rnThread.start(); } } MultiThreadRandOddEven.java import java.util.*; // class for Even Number class EvenNum implements Runnable { public int a; public EvenNum(int a) { this.a = a; } public void run() { System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a); } } // class for Odd Number class OddNum implements Runnable { public int a; public OddNum(int a) { this.a = a; } public void run() { System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a * a); } } // class to generate random number class RandomNumGenerator extends Thread { public void run() { int n = 0; Random rand = new Random(); try { for (int i = 0; i < 10; i++) { n = rand.nextInt(20); System.out.println("Generated Number is " + n); // check if random number is even or odd if (n % 2 == 0) { Thread thread1 = new Thread(new EvenNum(n)); thread1.start();
  • 41. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 38 2022-23 } else { Thread thread2 = new Thread(new OddNum(n)); thread2.start(); } // thread wait for 1 second Thread.sleep(1000); System.out.println("------------------------------------"); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } } // Driver class public class MultiThreadRandOddEven { public static void main(String[] args) { RandomNumGenerator rand_num = new RandomNumGenerator(); rand_num.start(); } }
  • 42. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 39 2022-23 9. Aim: Introduce java Collections. write a java program to perform string operations using ArrayList for the following functions a. Append – add at end b. Insert – add at particular index c. Search d. List all string starts with a given letter Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size limit. We can add or remove elements anytime. So, it is much more flexible than the traditional array. It is found in the java.util package. It is like the Vector in C++. The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally. It inherits the AbstractList class and implements List interface. The important points about the Java ArrayList class are:  Java ArrayList class can contain duplicate elements.  Java ArrayList class maintains insertion order.  Java ArrayList class is non synchronized.  Java ArrayList allows random access because the array works on an index basis.  In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting needs to occur if any element is removed from the array list.  We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use the required wrapper class in such cases.  For example: a. ArrayList<int> al = ArrayList<int>(); // does not work b. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine c. Java ArrayList gets initialized by the size. The size is dynamic in the array list, which varies according to the elements getting added or removed from the list. Hierarchy of ArrayList class As shown in the above diagram, the Java ArrayList class extends AbstractList class which implements the List interface. The List interface extends the Collection and Iterable interfaces in hierarchical order. ArrayList class declaration Let's see the declaration for java.util.ArrayList class. 1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Clone able, Serializable
  • 43. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 40 2022-23 Constructors of ArrayList Constructor Description ArrayList() It is used to build an empty array list. ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the collection c. ArrayList(int capacity) It is used to build an array list that has the specified initial capacity. Methods of ArrayList Method Description void add(int index, E element) It is used to insert the specified element at the specified position in a list. boolean add(E e) It is used to append the specified element at the end of a list. boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. boolean addAll(int index, Collection<? extends E> c) It is used to append all the elements in the specified collection, starting at the specified position of the list. void clear() It is used to remove all of the elements from this list. void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an ArrayList instance. E get(int index) It is used to fetch the element from the particular position of the list. boolean isEmpty() It returns true if the list is empty, otherwise false. Iterator() listIterator() int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. Object[] toArray() It is used to return an array containing all of the elements in this list in the correct order. <T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the correct order. Object clone() It is used to return a shallow copy of an ArrayList.
  • 44. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 41 2022-23 boolean contains(Object o) It returns true if the list contains the specified element. int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. E remove(int index) It is used to remove the element present at the specified position in the list. boolean remove(Object o) It is used to remove the first occurrence of the specified element. boolean removeAll(Collection<?> c) It is used to remove all the elements from the list. boolean removeIf(Predicate<? super E> filter) It is used to remove all the elements from the list that satisfies the given predicate. protected void removeRange(int fromIndex, int toIndex) It is used to remove all the elements lies within the given range. void replaceAll(UnaryOperator<E> operator) It is used to replace all the elements from the list with the specified element. void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the specified collection. E set(int index, E element) It is used to replace the specified element in the list, present at the specified position. void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the specified comparator. Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list. List<E> subList(int fromIndex, int toIndex) It is used to fetch all the elements that lies within the given range. int size() It is used to return the number of elements present in the list. void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's current size.
  • 45. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 42 2022-23 import java.util.*; import java.io.*; public class arraylistexample { public static void main(String args[])throws IOException { ArrayList<String> obj = new ArrayList<String>(); DataInputStream in=new DataInputStream(System.in); int c,ch; int i,j; String str,str1; do { System.out.println("STRING MANIPULATION"); System.out.println("******************************"); System.out.println(" 1. Append at end t 2.Insert at particular index t 3.Search t"); System.out.println( "4.List string that starting with letter t"); System.out.println("5. Size t 6.Remove t 7.Sortt 8.Displayt" ); System.out.println("Enter the choice "); c=Integer.parseInt(in.readLine()); switch(c) { case 1: { System.out.println("Enter the string "); str=in.readLine(); obj.add(str); break; } case 2: { System.out.println("Enter the string "); str=in.readLine(); System.out.println("Specify the index/position to insert"); i=Integer.parseInt(in.readLine()); obj.add(i-1,str); System.out.println("The array list has following elements:"+obj); break; } case 3: { System.out.println("Enter the string to search "); str=in.readLine(); j=obj.indexOf(str); if(j==-1) System.out.println("Element not found"); else System.out.println("Index of:"+str+"is"+j); break; } case 4: { System.out.println("Enter the character to List string that starts with specified character"); str=in.readLine(); for(i=0;i<(obj.size()-1);i++) { str1=obj.get(i); if(str1.startsWith(str))
  • 46. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 43 2022-23 { System.out.println(str1); } } break; } case 5: { System.out.println("Size of the list "+obj.size()); break; } case 6: { System.out.println("Enter the element to remove"); str=in.readLine(); if(obj.remove(str)) { System.out.println("Element Removed"+str); } else { System.out.println("Element not present"); } break; } case 7: { Collections.sort(obj); System.out.println("The array list has following elements:"+obj); break; } case 8: { System.out.println("The array list has following elements:"+obj); break; } } System.out.println("enter 0 to break and 1 to continue"); ch=Integer.parseInt(in.readLine()); }while(ch==1); } }
  • 47. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 44 2022-23 10. Aim: Exception handling in java, introduction to throwable class, throw, throws, finally. Program: Write a Java program to read two integers a and b. Compute a/b and print, when b is not zero. Raise an exception when b is equal to zero. Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. Handling Multiple exceptions: There are two methods to handle multiple exceptions in java. 1. Using a Single try-catch block try statement allows you to define a block of code to be tested for errors, and we can give exception objects to the catch blow because this all the exceptions inherited by the Exception class. 2. The second method is to create individual catch blocks for the different exception handler. Hierarchy of the exceptions: import java.util.Scanner; class division { public static void main(String[] args) { int a,b,result; Scanner input =new Scanner(System.in); System.out.println("Input two integers"); a=input.nextInt(); b=input.nextInt(); try { result=a/b; System.out.println("Result="+result); } catch(ArithmeticException e) { System.out.println("exception caught: Divide by zero error"+e); } } }
  • 48. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 45 2022-23 Alternate Solution: import java.util.Scanner; public class Exception { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a,b,c; System.out.print("Enter the Two Interger ValuesnA :"); a=scan.nextInt(); System.out.print("B :"); b=scan.nextInt(); scan.close(); try { if(b==0) throw new ArithmeticException("Divide By Zero"); c=a/b; System.out.println("nThe Value of "+a+" / "+b+" is "+c); }catch(ArithmeticException e) { e.printStackTrace(); } } }
  • 49. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 46 2022-23 11. Aim: Introduce File operations in java. Program: Write a java program that reads a file name from the user, displays information about whether the file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes import java.io.*; import javax.swing.*; class FileDemo { public static void main(String args[]) { String filename = JOptionPane.showInputDialog("Enter filename: "); File f = new File(filename); System.out.println("File exists: "+f.exists()); System.out.println("File is readable: "+f.canRead()); System.out.println("File is writable: "+f.canWrite()); System.out.println("Is a directory: "+f.isDirectory()); System.out.println("length of the file: "+f.length()+" bytes"); try { char ch; StringBuffer buff = new StringBuffer(""); FileInputStream fis = new FileInputStream(filename); while(fis.available()!=0) { ch = (char)fis.read(); buff.append(ch); } System.out.println("nContents of the file are: "); System.out.println(buff); fis.close(); } catch(FileNotFoundException e) { System.out.println("Cannot find the specified file..."); } catch(IOException i) { System.out.println("Cannot read file..."); } } }
  • 50. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 47 2022-23 Alternate Solution: import java.io.*; import java.util.*; class AboutFile{ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the name of the file:"); String file_name = input.nextLine(); File f = new File(file_name); if(f.exists()) System.out.println("The file " +file_name+ " exists"); else System.out.println("The file " +file_name+ " does not exist"); if(f.exists()){ if(f.canRead()) System.out.println("The file " +file_name+ " is readable"); else System.out.println("The file " +file_name+ " is not readable"); if(f.canWrite()) System.out.println("The file " +file_name+ " is writeable"); else System.out.println("The file " +file_name+ " is not writeable"); System.out.println("The file type is: " +file_name.substring(file_name.indexOf('.')+1)); System.out.println("The Length of the file:" +f.length()); } } } Alternate Solution-2: import java.io.*; import java.util.*; class Fileattr { public static void main(String args[]) { File f1=new File(args[0]); System.out.println(f1.exists()?”file exists”:”does not exist”); System.out.println(“Filename:”+f1.getName()); System.out.println(“Filepath:”+f1.getAbsolutePath()); System.out.println(f1.isDirectory()?”is a directory”:”is a simple file”); System.out.println(f1.canRead()?”can be read”:”can not be read”); System.out.println(f1.canWrite()?”can be write”:”can not be write”); System.out.println(“length of file in bytes:”+f1.length()); } }
  • 51. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 48 2022-23 12. Aim: Introduce java Applet, awt, swings. Programs: Develop an applet that displays a simple message in center of the screen.Develop a simple calculator using Swings. Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful and flexible components than Java AWT (Abstract Window Toolkit). In this article we will use Java Swing components to create a simple calculator with only +, -, /, * operations. methods used: 1. add(Component c) : adds component to container. 2. addActionListenerListener(ActionListener d) : add actionListener for specified component 3. setBackground(Color c) : sets the background color of the specified container 4. setSize(int a, int b) : sets the size of container to specified dimensions. 5. setText(String s) : sets the text of the label to s. 6. getText() : returns the text of the label. // Java program to create a simple calculator with basic +, -, /, * using // java swing elements import java.awt.event.*; import javax.swing.*; import java.awt.*; class calculator extends JFrame implements ActionListener { // create a frame static JFrame f; // create a textfield static JTextField l; // store operator and operands String s0, s1, s2; // default constructor calculator() { s0 = s1 = s2 = ""; } // main function public static void main(String args[]) { // create a frame f = new JFrame("calculator"); try { // set look and feel
  • 52. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 49 2022-23 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println(e.getMessage()); } // create a object of class calculator c = new calculator(); // create a textfield l = new JTextField(16); // set the textfield to non editable l.setEditable(false); // create number buttons and some operators JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1; // create number buttons b0 = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); // equals button beq1 = new JButton("="); // create operator buttons ba = new JButton("+"); bs = new JButton("-"); bd = new JButton("/"); bm = new JButton("*"); beq = new JButton("C"); // create . button be = new JButton("."); // create a panel JPanel p = new JPanel(); // add action listeners bm.addActionListener(c);
  • 53. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 50 2022-23 bd.addActionListener(c); bs.addActionListener(c); ba.addActionListener(c); b9.addActionListener(c); b8.addActionListener(c); b7.addActionListener(c); b6.addActionListener(c); b5.addActionListener(c); b4.addActionListener(c); b3.addActionListener(c); b2.addActionListener(c); b1.addActionListener(c); b0.addActionListener(c); be.addActionListener(c); beq.addActionListener(c); beq1.addActionListener(c); // add elements to panel p.add(l); p.add(ba); p.add(b1); p.add(b2); p.add(b3); p.add(bs); p.add(b4); p.add(b5); p.add(b6); p.add(bm); p.add(b7); p.add(b8); p.add(b9); p.add(bd); p.add(be); p.add(b0); p.add(beq); p.add(beq1); // set Background of panel p.setBackground(Color.blue); // add panel to frame f.add(p); f.setSize(200, 220); f.show(); } public void actionPerformed(ActionEvent e) {
  • 54. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 51 2022-23 String s = e.getActionCommand(); // if the value is a number if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') { // if operand is present then add to second no if (!s1.equals("")) s2 = s2 + s; else s0 = s0 + s; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == 'C') { // clear the one letter s0 = s1 = s2 = ""; // set the value of text l.setText(s0 + s1 + s2); } else if (s.charAt(0) == '=') { double te; // store the value in 1st if (s1.equals("+")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals("-")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals("/")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // set the value of text l.setText(s0 + s1 + s2 + "=" + te); // convert it to string s0 = Double.toString(te); s1 = s2 = ""; } else { // if there was no operand if (s1.equals("") || s2.equals("")) s1 = s; // else evaluate else {
  • 55. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 52 2022-23 double te; // store the value in 1st if (s1.equals("+")) te = (Double.parseDouble(s0) + Double.parseDouble(s2)); else if (s1.equals("-")) te = (Double.parseDouble(s0) - Double.parseDouble(s2)); else if (s1.equals("/")) te = (Double.parseDouble(s0) / Double.parseDouble(s2)); else te = (Double.parseDouble(s0) * Double.parseDouble(s2)); // convert it to string s0 = Double.toString(te); // place the operator s1 = s; // make the operand blank s2 = ""; } // set the value of text l.setText(s0 + s1 + s2); } } } Output :
  • 56. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 53 2022-23 Alternate Solution: import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Calculator implements ActionListener { private static JTextField inputBox; Calculator(){} public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(JFrame frame) { JPanel panel = new JPanel(); Calculator calculator = new Calculator(); GridBagLayout layout = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); panel.setLayout(layout); inputBox = new JTextField(10); inputBox.setEditable(false); JButton button0 = new JButton("0");JButton button1 = new JButton("1"); JButton button2 = new JButton("2");JButton button3 = new JButton("3"); JButton button4 = new JButton("4");JButton button5 = new JButton("5"); JButton button6 = new JButton("6");JButton button7 = new JButton("7"); JButton button8 = new JButton("8");JButton button9 = new JButton("9"); JButton buttonPlus = new JButton("+");JButton buttonMinus = new JButton("-"); JButton buttonDivide = new JButton("/");JButton buttonMultiply = new JButton("x"); JButton buttonClear = new JButton("C");JButton buttonDot = new JButton("."); JButton buttonEquals = new JButton("="); button1.addActionListener(calculator);button2.addActionListener(calculator); button3.addActionListener(calculator);button4.addActionListener(calculator); button5.addActionListener(calculator);button6.addActionListener(calculator); button7.addActionListener(calculator);button8.addActionListener(calculator); button9.addActionListener(calculator);button0.addActionListener(calculator); buttonPlus.addActionListener(calculator);buttonMinus.addActionListener(calculator);
  • 57. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 54 2022-23 buttonDivide.addActionListener(calculator);buttonMultiply.addActionListener(calculator); buttonClear.addActionListener(calculator);buttonDot.addActionListener(calculator); buttonEquals.addActionListener(calculator); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(button1, gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(button2, gbc); gbc.gridx = 2; gbc.gridy = 0; panel.add(button3, gbc); gbc.gridx = 3; gbc.gridy = 0; panel.add(buttonPlus, gbc); gbc.gridx = 0; gbc.gridy = 1; panel.add(button4, gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(button5, gbc); gbc.gridx = 2; gbc.gridy = 1; panel.add(button6, gbc); gbc.gridx = 3; gbc.gridy = 1; panel.add(buttonMinus, gbc); gbc.gridx = 0; gbc.gridy = 2; panel.add(button7, gbc); gbc.gridx = 1; gbc.gridy = 2; panel.add(button8, gbc); gbc.gridx = 2; gbc.gridy = 2; panel.add(button9, gbc); gbc.gridx = 3; gbc.gridy = 2; panel.add(buttonDivide, gbc); gbc.gridx = 0; gbc.gridy = 3; panel.add(buttonDot, gbc); gbc.gridx = 1; gbc.gridy = 3; panel.add(button0, gbc); gbc.gridx = 2; gbc.gridy = 3; panel.add(buttonClear, gbc); gbc.gridx = 3; gbc.gridy = 3; panel.add(buttonMultiply, gbc); gbc.gridwidth = 3; gbc.gridx = 0; gbc.gridy = 4; panel.add(inputBox, gbc); gbc.gridx = 3; gbc.gridy = 4; panel.add(buttonEquals, gbc); frame.getContentPane().add(panel, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.charAt(0) == 'C') { inputBox.setText(""); }else if (command.charAt(0) == '=') { inputBox.setText(evaluate(inputBox.getText())); }else { inputBox.setText(inputBox.getText() + command); } } public static String evaluate(String expression) { char[] arr = expression.toCharArray(); String operand1 = "";String operand2 = "";String operator = ""; double result = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] >= '0' && arr[i] <= '9' || arr[i] == '.') { if(operator.isEmpty()){ operand1 += arr[i]; }else{ operand2 += arr[i]; } } if(arr[i] == '+' || arr[i] == '-' || arr[i] == '/' || arr[i] == '*') { operator += arr[i]; } } if (operator.equals("+"))
  • 58. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 55 2022-23 result = (Double.parseDouble(operand1) + Double.parseDouble(operand2)); else if (operator.equals("-")) result = (Double.parseDouble(operand1) - Double.parseDouble(operand2)); else if (operator.equals("/")) result = (Double.parseDouble(operand1) / Double.parseDouble(operand2)); else result = (Double.parseDouble(operand1) * Double.parseDouble(operand2)); return operand1 + operator + operand2 + "=" +result; } } Output // This java program uses an applet that displays a simple message in center of the screen. package Applet; import java.applet.*; import java.awt.*; public class WelcomeToApplet extends Applet { // create paint class to print on the screen. public void paint (Graphics g) { // Enter message with co-ordinates to make it in centre. g.drawString ("Welcome To JAVA Programming", 25, 50); } } Alternate Solution: /* Develop an applet that displays a simple message */ import java.awt.*; import java.applet.*; class weeka extends Applet { public static void init() { setForeground(Color.yellow); } public static void paint(Graphics g) { g.drawString(" Hello World ",80,40); } }
  • 59. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 56 2022-23 Additional Problems: 1. Write a Java program to accept a number and check the number is even or not 2. Write a Java program which takes three numbers from the user and print the greatest number 3. Write a Java program to print numbers between 1 to 100 which are divisible by 3, 5 and by both 4. Write a program in Java to display the multiplication table of a given integer. 5. Write a Java Program to Convert Celsius to Fahrenheit 6. Write a Java program to convert seconds to hour, minute and seconds 7. Write a Java program that takes a year from user and print whether that year is a leap year or not 8. Write a Java program to check whether a given integer is a power of 5 or not 9. Write a Java Program to display Fibonacci Series using While Loop 10. Write a Java Program to Find GCD(HCF) and LCM of Two Numbers 11. Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise 12. Write a Java program to compute the sum of the first 100 prime numbers 13. Write a Java program to convert a decimal number to binary number 14. Write a Java program to display Pascal's triangle 15. Write a Java program to convert a binary number to decimal number 16. Write a Java program to compute the sum of the digits of an integer 17. Write a Java program to check if a positive number is a palindrome or not 18. Write a Java program to compute the area of a polygon 19. Write Java methods to calculate the area of a triangle 20. Write a Java program to reverse a string / number 21. Java Program to display n Prime Numbers using Exception Handling 22. Java Program to print Armstrong numbers between desired Range 23. Write a Java method to count all vowels in a string 24. Write a Java program to count the letters, spaces, numbers and other characters of an input string 25. Write a Java program that searches a value in an m x n matrix 26. Write a Java program to calculate the median of a given unsorted array of integers 27. Write a Java program to search an element in a array list 28. Write a Java Program for Binary Search on Unsorted Array 29. Write a Java program to sort a given array list 30. Java Program to perform Insertion Sort using function 31. Write a Java program to remove duplicates from a sorted linked list 32. Write a Java program to merge two given sorted lists. 33. Write a Java program to check if a file or directory specified by pathname exists or not and to check if a file or directory has read and write permission 34. Write a Java program to find the longest word in a text file
  • 60. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 57 2022-23 Sample Solutions to Additional Problems: 1. Java program to check whether the given number is even or odd import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter a number: "); Scanner sc = new Scanner(System.in); int number =Integer.parseInt(sc.nextLine()); int x = number%2; if(x==0){ System.out.println("The number is Even"); } else{ System.out.println("The number is Odd"); } } } 2. Java program to convert the temperature in Degree Centigrade to Fahrenheit import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter temperature in Centigrade: "); Scanner sc = new Scanner(System.in); int c =Integer.parseInt(sc.nextLine()); float f = ((9*c)/5)+32; System.out.println("Temperature in Fahrenheit is: "+f); } } 3. Java program to find the area of a triangle whose three sides are given import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.println("Enter the 1st side:"); int a= sc.nextInt(); System.out.println("Enter the 2nd side:"); int b= sc.nextInt(); System.out.println("Enter the 3rd side:"); int c= sc.nextInt(); if((a+b)>c && (a+c)>b && (b+c)>a) {
  • 61. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 58 2022-23 double s=(a+b+c)/2.0; double area=Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println("Area of Triangle is: " + area); } else System.out.println("Area of the triangle does not exist"); } } 4. Java program to find out the average of a set of integers import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the count of numbers: "); int count = Integer.parseInt(sc.nextLine()); int i = 0; float sum = 0; for(i=0;i<count;i++){ System.out.println("Enter an integer: "); int x = Integer.parseInt(sc.nextLine()); sum = sum + x; } float avg = sum/count; System.out.println("The average is: "+avg); } } 5. Java program to find the product of a set of real numbers import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number of real numbers: "); int count = Integer.parseInt(sc.nextLine()); int i = 0; float product = 1.0f; for(i=0;i<count;i++){ System.out.println("Enter a real number: "); float x = Float.parseFloat(sc.nextLine()); product = product * x; } System.out.println("The product of the numbers is: "+product); } } 6. Java program to find the circumference and area of a circle with a given radius import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Input the radius of the circle: ");
  • 62. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 59 2022-23 double radius = Float.parseFloat(sc.nextLine()); double c = 2 * Math.PI * radius; double area = Math.PI * radius * radius; System.out.println("The circumference of the circle is: "+c); System.out.println("The area of the circle is: "+area); } } 7. Java program to check whether the given integer is a multiple of 5 import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter an integer: "); Scanner sc = new Scanner(System.in); int number =Integer.parseInt(sc.nextLine()); if(number%5==0){ System.out.println(number+" is a multiple of 5"); } else{ System.out.println(number+" is not a multiple of 5"); } } } 8. Java program to check whether the given integer is a multiple of both 5 and 7 import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter an integer: "); Scanner sc = new Scanner(System.in); int number =Integer.parseInt(sc.nextLine()); if((number%5==0)&&(number%7==0)){ System.out.println(number+" is a multiple of both 5 and 7"); } else{ System.out.println(number+" is not a multiple of both 5 and 7"); } } } 9. Java program to find the average of 5 numbers using while loop import java.util.Scanner; class Main { public static void main(String[] args) { int count = 0; int sum = 0; Scanner sc = new Scanner(System.in);
  • 63. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 60 2022-23 while(count<5){ System.out.println("Enter an integer: "); int number =Integer.parseInt(sc.nextLine()); sum = sum+number; count++; } double avg = ((double) sum) / 5.0; System.out.println("Average is :"+avg); } } 10. Java program to display the given integer in reverse manner import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter an integer: "); int number =Integer.parseInt(sc.nextLine()); int rev = 0; while(number!=0){ int digit = number%10; rev = (rev*10)+digit; number = number/10; } System.out.println(rev); } } 11. Java program to find the geometric mean of n numbers import java.util.Scanner; class Main { public static void main(String[] args) { int c = 0; double p = 1.0; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of values: "); int count =Integer.parseInt(sc.nextLine()); while((c<count)){ System.out.println("Enter a real number: "); double x =Double.parseDouble(sc.nextLine()); c = c+1; p = p * x; } double gm = Math.pow(p,1.0/count); System.out.println("The geometric mean is: "+gm); } }
  • 64. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 61 2022-23 12. Java program to find the sum of the digits of an integer using while loop import java.util.Scanner; class Main { public static void main(String[] args) { int sum = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter an integer: "); int number =Integer.parseInt(sc.nextLine()); while(number!=0){ int digit = number%10; sum = sum+digit; number = number/10; } System.out.println(("Sum of digits is: "+ sum)); } } 13. Java program to display all the multiples of 3 within the range 10 to 50 import java.util.Scanner; class Main { public static void main(String[] args) { for(int i=10;i<50;i++){ if(i%3==0) System.out.println(i); } } } 14. Java program to display all integers within the range 100-150 whose sum of digits is an even number import java.util.Scanner; class Main { public static void main(String[] args) { for(int i=100;i<150;i++){ int num = i; int sum = 0; while(num!=0){ int digit = num%10; sum = sum + digit; num = num/10; } if(sum%2==0){ System.out.println(i); } } } }
  • 65. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 62 2022-23 15. Java program to check whether the given integer is a prime number or not import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter an integer greater than 1: "); Scanner sc = new Scanner(System.in); int number =Integer.parseInt(sc.nextLine()); int isprime = 1; for(int i=2;i<(number/2);i++){ if(number%i==0){ isprime = 0; break; } } if(isprime==1){ System.out.println(number+" is a prime number"); } else{ System.out.println(number+" is not a prime number"); } } } 16. Java program to generate the prime numbers from 1 to N import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter the range: "); Scanner sc = new Scanner(System.in); int number =Integer.parseInt(sc.nextLine()); for (int num = 2; num <= number; num++) { boolean isPrime = true; for (int i=2; i <= num/2; i++) { if ( num % i == 0) { isPrime = false; break; } } if ( isPrime == true ) System.out.println(num); } } }
  • 66. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 63 2022-23 17. Java program to find the roots of a quadratic equation import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter the first coefficient: "); Scanner sc = new Scanner(System.in); double a = Integer.parseInt(sc.nextLine()); System.out.println("Enter the second coefficient: "); double b = Integer.parseInt(sc.nextLine()); System.out.println("Enter the third coefficient: "); double c = Integer.parseInt(sc.nextLine()); if(a!=0.0){ double d = (b*b)-(4*a*c); if (d==0.0){ System.out.println("The roots are real and equal."); double r = -b/(2*a); System.out.println("The roots are "+ r+"and"+ r); }else if(d>0.0){ System.out.println("The roots are real and distinct."); double r1 = (-b+(Math.sqrt(d)))/(2*a); double r2 = (-b-(Math.sqrt(d)))/(2*a); System.out.println("The root1 is: "+ r1); System.out.println("The root2 is: "+ r2); }else{ System.out.println("The roots are imaginary."); double rp = -b/(2*a); double ip = Math.sqrt(-d)/(2*a); System.out.println("The root1 is: "+ rp+ "+ i"+ip); System.out.println("The root2 is: "+ rp+ "- i"+ip); } }else{ System.out.println("Not a quadratic equation."); } } } 18. Java program to print the numbers from a given number n till 0 using recursion class Main { public static void main(String[] args) { print_till_zero(8); } public static void print_till_zero(int n){ if(n==0) return; System.out.println(n); n=n-1; print_till_zero(n); } }
  • 67. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 64 2022-23 19. Java program to find the factorial of a number using recursion import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("Enter an integer: "); Scanner sc = new Scanner(System.in); int a = Integer.parseInt(sc.nextLine()); int result = fact(a); System.out.println("The factorial of"+ a + " is: "+ result); } public static int fact(int n){ int f; if(n==1) f=1; else f = n * fact(n-1); return f; } } 20. Java program to display the sum of n numbers using an array import java.util.Scanner; class Main { public static void main(String[] args) { System.out.println("How many numbers: "); Scanner sc = new Scanner(System.in); int num = Integer.parseInt(sc.nextLine()); int[] numbers = new int[num]; int sum=0; for(int n=0;n<num;n++){ System.out.println("Enter number: "); int x = Integer.parseInt(sc.nextLine()); numbers[n] = x; } for(int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } System.out.println("Sum of all the elements of the array: " + sum); } } 21. Java program to implement linear search import java.util.Scanner; class Main { public static void main(String[] args) { int[] numbers = {4,2,7,1,8,3,6}; int flag = 0; System.out.println("Enter the number to be found out: ");
  • 68. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 65 2022-23 Scanner sc = new Scanner(System.in); int x = Integer.parseInt(sc.nextLine()); for(int i=0;i<numbers.length;i++){ if (x==numbers[i]){ System.out.println("Successful search, the element is found at position "+ i); flag = 1; break; } } if(flag==0){ System.out.println("Oops! Search unsuccessful"); } } } 22. Java program to implement binary search import java.util.Scanner; class Main { public static void main(String[] args) { int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers System.out.println("Enter the number to be found out: "); Scanner sc = new Scanner(System.in); int x = Integer.parseInt(sc.nextLine()); int result = binarySearch(numbers, 0, numbers.length-1, x); if (result != -1) System.out.println("Search successful, element found at position "+result); else System.out.println("The given element is not present in the array"); } public static int binarySearch(int[] numbers,int low,int high,int x){ if (high >= low){ int mid = low + (high - low)/2; if (numbers[mid] == x) return mid; else if (numbers[mid] > x) return binarySearch(numbers, low, mid-1, x); else return binarySearch(numbers, mid+1, high, x); }else{ return -1; } } } 23. Java program to find the number of odd numbers in an array class Main { public static void main(String[] args) { int[] numbers = {8,3,1,6,2,4,5,9};
  • 69. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 66 2022-23 int count = 0; for(int i=0;i<numbers.length;i++){ if(numbers[i]%2!=0) count++; } System.out.println("The number of odd numbers in the list are: "+count); } } 24. Java program to find the largest number in an array without using built-in functions class Main { public static void main(String[] args) { int[] numbers = {3,8,1,7,2,9,5,4}; int largest = numbers[0]; int position = 0; for(int i=0;i<numbers.length;i++){ if(numbers[i]>largest){ largest = numbers[i]; position = i; } } System.out.println("The largest element is "+largest+" which is found at position "+position); } } 25. Java program to insert a number to any position in an array import java.util.Scanner; import java.util.Arrays; class Main { public static void main(String[] args) { int[] numbers = {3,4,1,9,6,2,8}; System.out.println(Arrays.toString(numbers)); System.out.println("Enter the number to be inserted: "); Scanner sc = new Scanner(System.in); int x = Integer.parseInt(sc.nextLine()); System.out.println("Enter the position: "); int y = Integer.parseInt(sc.nextLine()); for(int i=numbers.length-1;i>y;i--){ numbers[i] = numbers[i-1]; } numbers[y] = x; System.out.println(Arrays.toString(numbers)); } }
  • 70. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 67 2022-23 26. Java program to delete an element from an array by index import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(5); numbers.add(3); numbers.add(7); numbers.add(1); numbers.add(4); System.out.println(numbers); System.out.println("Enter the position of the element to be deleted: "); Scanner sc = new Scanner(System.in); int x = Integer.parseInt(sc.nextLine()); numbers.remove(x); System.out.println(numbers); } } 27. Java program to check whether a string is palindrome or not import java.util.Scanner; class Main { public static void main(String[] args) { String a, b = ""; Scanner s = new Scanner(System.in); System.out.print("Enter the string you want to check: "); a = s.nextLine(); int n = a.length(); for(int i = n - 1; i >= 0; i--){ b = b + a.charAt(i); } if(a.equalsIgnoreCase(b)){ System.out.println("The string is palindrome."); }else{ System.out.println("The string is not palindrome."); } } }
  • 71. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 68 2022-23 28. Java program to implement matrix addition class Main { public static void main(String[] args) { //creating two matrices int a[][]={{8,5,1},{9,3,2},{4,6,3}}; int b[][]={{8,5,3},{9,5,7},{9,4,1}}; //matrix to store the sum of two matrices int c[][]=new int[3][3]; //3 rows and 3 columns //adding 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=a[i][j]+b[i][j]; System.out.print(c[i][j]+" "); } System.out.print("n"); } } } 29. Java program to implement matrix multiplication class Main { public static void main(String[] args) { //creating two matrices int a[][]={{8,5,1},{9,3,2},{4,6,3}}; int b[][]={{8,5,3},{9,5,7},{9,4,1}}; //matrix to store the product of two matrices int c[][]=new int[3][3]; //multiplying 2 matrices for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ c[i][j]=0; for(int k=0;k<3;k++){ c[i][j]+=a[i][k]*b[k][j]; } System.out.print(c[i][j]+" "); } System.out.print("n"); } } } 30. Java program to check leap year import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the year you want to check: "); int year = Integer.parseInt(sc.nextLine());
  • 72. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 69 2022-23 boolean leap = false; // if the year is divided by 4 if (year % 4 == 0) { // if the year is century if (year % 100 == 0) { // if year is divided by 400, then it is a leap year if (year % 400 == 0) leap = true; else leap = false; } // if the year is not century else leap = true; } else leap = false; if (leap) System.out.println(year + " is a leap year."); else System.out.println(year + " is not a leap year."); } } 31. Java program to find the Nth term in a Fibonacci series using recursion import java.util.Scanner; class Main { public static void main(String[] args) { Scanner cs=new Scanner(System.in); int n; System.out.print("Enter the position(N): "); n=cs.nextInt(); System.out.print("Nth Fibonacci Number is: "+NthFibonacciNumber(n)); } static int NthFibonacciNumber(int n){ if(n==1) return 0; else if(n==2) return 1; else return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2); } } 32. Java program to print Fibonacci series using iteration import java.util.Scanner; class Main { public static void main(String[] args) { int n1=0,n2=1; Scanner cs=new Scanner(System.in); System.out.print("Enter the number of terms in the sequence: ");
  • 73. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 70 2022-23 int count = cs.nextInt(); int n3,i; System.out.print(n1+" "+n2);//printing 0 and 1 //printing from 2 because 0 and 1 are already printed for(i=2;i<count;++i){ n3=n1+n2; System.out.print(" "+n3); n1=n2; n2=n3; } } } 33. Java program to implement a calculator to do basic operations import java.util.Scanner; class Main { public static void main(String[] args) { int firstNumber, secondNumber, opt, add, sub, mul; double div; Scanner s = new Scanner(System.in); System.out.print("Enter first number: "); firstNumber = s.nextInt(); System.out.print("Enter second number: "); secondNumber = s.nextInt(); while(true){ System.out.println("Enter 1 for addition"); System.out.println("Enter 2 for subtraction"); System.out.println("Enter 3 for multiplication"); System.out.println("Enter 4 for division"); System.out.println("Enter 5 to Exit"); int option = s.nextInt(); switch(option){ case 1: add = firstNumber + secondNumber; System.out.println("Result:"+add); break; case 2: sub = firstNumber - secondNumber; System.out.println("Result:"+sub); break; case 3: mul = firstNumber * secondNumber; System.out.println("Result:"+mul); break; case 4: div = (double)firstNumber / secondNumber; System.out.println("Result:"+div); break; case 5: System.exit(0); }
  • 74. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 71 2022-23 } } } 34. Java Program to Find Your Weight on Mars Mars’ gravity is about 38% of Earth’s. Write a program that will calculate your weight on Mars. Declare all variables at the top of the class. Initial variables are to be of float type. After making the calculations, assign the result to a new variable, this time of the double type. After assigning the assignment, write the variable double to the console, limiting its length to 4 decimal places. Cast the above variable of double type to a new variable of int type. Cast the above variable of type int to a new variable of type char. Do any math operation on this variable char type and assign the value of this activity to the new variable int type. Each of the above actions should be written to the console, adding some text explaining what has been done. import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("How many pounds (lbs) do you weigh? ") ; float weight = input.nextFloat(); // computing the weight on mars double weightOnMars = (weight * .38); // displaying results with 4 decimal places System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on Mars"); System.out.println("Converting the variable into integer"); int weightOnMarsInt = (int)weightOnMars; System.out.println(weightOnMarsInt); System.out.println("Converting the variable into char"); char weightOnMarsChar = (char)weightOnMars; System.out.println(weightOnMarsChar); System.out.println("Converting the variable into Int and doing an operation on it"); int newIntVariable = weightOnMarsChar * 2; System.out.println(newIntVariable); } }
  • 75. OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35] SJCIT, Chickballapur 72 2022-23 35. Java Program to Check Whether the Generated Random Number Is Even or Odd Write a program that generates a random number between 1 and 100 (you can use the Random () method from the Math class. In the next step check whether it is an even or an odd number. Each of the above actions should be written to the console. import java.util.Random; class Main { public static void main(String[] args) { int min = 1; int max = 100; //Generating a random number Random r = new Random(); int randomNumber = min + r.nextInt(max); System.out.println("Generated random number is: "+randomNumber); //Checking whether the number is odd or even if(randomNumber%2==0){ System.out.println("The generated random number is even."); }else{ System.out.println("The generated random number is odd."); } } } 36. Java Program to Find the Number of Containers You Need Choose an odd number between 50 and 100 and save it as an int variable telling us how many Lego bricks we have (e.g. amountOfBricks ), then select an even number between 5 and 10 stating how many Lego blocks fit in one container (e.g.: containerCapacity ) and save it as an int variable as well. Write a program that will calculate how many full containers we have, how many containers, in general, are full and not full, and how many blocks are in the container that is not completely full (use the modulo operator for this). import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("How many Lego bricks do we have? Choose an odd number between 50 and 100: "); int amountOfBricks = Integer.parseInt(sc.nextLine()); System.out.println("How many Lego blocks fit in one container? Choose an even number between 5 and 10: "); int containerCapacity = Integer.parseInt(sc.nextLine()); int noOfFullContainers = amountOfBricks/containerCapacity; int noOfTotalContainers; int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;