[go: up one dir, main page]

0% found this document useful (0 votes)
58 views41 pages

23BCP113 Java File

java file

Uploaded by

mallasagar8080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views41 pages

23BCP113 Java File

java file

Uploaded by

mallasagar8080
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 41

1|Page

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SCHOOL OF TECHNOLOGY

PANDIT DEENDAYAL ENERGY UNIVERSITY

SESSION 2024-25

SUBMITTED BY
NAME : Harsh Rana

ROLL NO. : 23BCP113


DIVISION : 2 (G4)
COURSE NAME : Object Oriented Programming with
JAVA LAB
COURSE CODE : 23CP201P

SUBMITTED TO

Dr. Nandini Modi

Assistant Professor

Department of Computer Science and Engineering

Pandit Deendayal Energy University

****************

INDEX
2|Page

Exp. Title of Lab Work Date Page Signature


No. of
Lab
Work
1 Set up and get familiar with Java
programming environment;
2 Study language features of Java
(variables, data types, declarations, loop
and branch constructs, etc.)
3 Class and Objects: study and implement
classes based application using Java
4 Inheritance: study and implement various
types of inheritance in Java.
5 Polymorphism: study and implement
various types of Polymorphism in java.
6 Study and implement Abstract class and
Interfaces in Java
3|Page

LAB 1

1. Set up and get familiar with Java programming environment;


i. Install JDK, setup Java environment and write a program to print
―CODING IS FUN, ENJOY IT!.

Code:
class lab1_1
{
public static void main(String[] args)
{ System.out.print("coding is fun , enjoy
it"); }}

OUTPUT:

ii. Write a Java program to print the sum of two


numbers CODE:
class lab1_2
{
public static void main(String[] args)
{
int x = 5;
int y = 6;
int sum = x + y;
4|Page

System.out.println(sum);
}
}
OUTPUT:
5|Page

LAB 2
Study language features of Java (variables, data types, declarations, loop
and branch constructs, etc.)
I. You are developing a mathematical tool that requires generating a list
of prime numbers. How would you implement a Java program to
generate the first n prime numbers?
CODE:
import java.util.Scanner;

class lab2_1 {
public static void main(String[] args)
{ Scanner myObj = new
Scanner(System.in);
System.out.println("Enter the number up to you want to find prime
numbers");
int prime = myObj.nextInt();
for (int i = 2; i <= prime; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}
6|Page

OUTPUT:

II. Write a program to enter two numbers and perform mathematical


operations on them.

CODE:
import java.util.Scanner;
class lab2_3{
public static void main(String[] args) {
Scanner num = new Scanner(System.in);
System.out.println("Enter the 1st number :");
float a = num.nextFloat();
System.out.println("Enter the 2nd number :");
float b = num.nextFloat();
System.out.println("Enter 1 if you want to do addition operation\nEnter 2 if
you want to do subtraction operation\nEnter 3 if you want to do
multiplication operation\nEnter 4 if you want to do division operation\n");
float c = num.nextFloat();
if(c==1)
{
System.out.println(a+"+" + b + "=" + (a+b));
}

else if (c==2)
{
7|Page

System.out.println(a + "-"+ b + "=" + (a-b));


}
else if(c==3)
{
System.out.println(a + "*"+ b + "=" + (a*b));
}
else if(c==4)
{
System.out.println(a + "/"+ b + "=" + (a/b));
}
else
{
System.out.println("invalid entry");
}
}
}

OUTPUT:
8|Page

III. Write a program in Java to find maximum of three numbers


using conditional operator.

CODE:

import java.util.Scanner;
class lab2_2 {
public static void main(String[] args)
{ Scanner num = new
Scanner(System.in);
System.out.println("Enter the 1st number you want to
compare:"); int a = num.nextInt();
System.out.println("Enter the 2nd number you want to compare:");
int b = num.nextInt();
System.out.println("Enter the 3rd number you want to compare:");
int c = num.nextInt();

if (a > b && a > c) {


System.out.println("The greatest number is " + a); } else
if (b > a && b > c) {
System.out.println("The greatest number is " +
b); } else {
System.out.println("The greatest number is " + c);
}

}
}

OUTPUT:
9|Page

IV. You're working on a text analysis feature that counts the number of
vowels
and consonants in a given line of text. Write a program to accept a line
and check how many consonants and vowels are there in line.

CODE:
import java.util.Scanner;

class lab2_4 {
public static void main(String[] args) { Scanner
scanner = new Scanner(System.in);

System.out.println("Enter a line of
text:"); String line = scanner.nextLine();

int vowelCount = 0;
int consonantCount = 0;

line = line.toLowerCase();

for (int i = 0; i < line.length(); i++) {


char ch = line.charAt(i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {


vowelCount++;
}
10 | P a g e

else if (ch >= 'a' && ch <= 'z') {


consonantCount++;
}
}

System.out.println("Number of vowels: " + vowelCount);


System.out.println("Number of consonants: " + consonantCount);

scanner.close();
}
}

OUTPUT:

V. Write an interactive program to print a string entered in a pyramid


form. For instance, the string “stream” has to be displayed as follows:

CODE:
import java.util.Scanner;

public class lab2_4


{
public static void main(String[] args) {
11 | P a g e

Scanner scanner = new Scanner(System.in);


System.out.print("Enter a string: ");
String input = scanner.nextLine().toUpperCase();
int length = input.length();

for (int i = 0; i < length; i++) {


for (int j = 0; j < length - i - 1; j++) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0) {
System.out.print(" ");
}
System.out.print(input.charAt(j));
}
System.out.println();
}

}
}

OUTPUT:
12 | P a g e

VI. Java Program to Find Largest Number in an array

CODE:

public class lab2_5 {

public static void main(String[] args)

{ int[] numbers = {5, 8, 12, 3, 9, 21,

6}; int largest = numbers[0];

for (int i = 1; i < numbers.length; i++) {

if (numbers[i] > largest) {

largest = numbers[i];

System.out.println("The largest number is: " + largest);

OUTPUT:
13 | P a g e

VII. Write a java program to perform addition and multiplication of


Two Matrices.

CODE:

public class lab2_6 {

public static void main(String[] args) {

int[][] matrixA = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int[][] matrixB = {

{9, 8, 7},

{6, 5, 4},

{3, 2, 1}

};

int[][] sum = new int[3][3];

int[][] product = new int[3][3];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {


14 | P a g e

sum[i][j] = matrixA[i][j] + matrixB[i][j];

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

product[i][j] = 0;

for (int k = 0; k < 3; k++) {

product[i][j] += matrixA[i][k] * matrixB[k][j];

System.out.println("Sum of the
matrices:"); for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(sum[i][j] + " ");

System.out.println();

System.out.println("Product of the
matrices:"); for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {


15 | P a g e

System.out.print(product[i][j] + " ");

System.out.println();

OUTPUT:
16 | P a g e

LAB 3

i. Write a program to create a “distance” class with methods where


distance is computed in terms of feet and inches, how to create objects of a
class.

CODE:

import java.util.Scanner;

class lab3_1{

public int inch,feet;

Scanner sc=new Scanner(System.in);

public void distance_method(){

System.out.println("Enter the distance in feet");

feet=sc.nextInt();

System.out.println("Enter the distance in inch");

inch=sc.nextInt();

public void feet_inch(){

int ans=feet*12;

System.out.println("The distance of " +feet+ " feet in inch is : "+ans);


}

public void inch_feet(){

float ans1=inch/12;

System.out.println("The distance of " +inch+ " inch in feet is : "+ans1);


}
17 | P a g e

class distance{

public static void main(String args[]){

distance d1=new distance();

d1.distance_method();

d1.feet_inch();

d1.inch_feet();

OUTPUT:

ii. Modify the “distance” class by creating constructor for assigning values

(feet and inches) to the distance object. Create another object and assign

second object as reference variable to another object reference variable.

Further create a third object which is a clone of the first object.

CODE:

import java.util.Scanner;

class lab3_2 implements Cloneable {

public int inch, feet;


18 | P a g e

Scanner sc = new Scanner(System.in);

public lab3_2(int feet, int inch) {

this.feet = feet;

this.inch = inch;

public lab3_2() {

public void distanceMethod() {

System.out.println("Enter the distance in feet:");

feet = sc.nextInt();

System.out.println("Enter the distance in inches:");

inch = sc.nextInt();

public void feetToInch() {

int ans = feet * 12;

System.out.println("The distance of " + feet + " feet in inches is: " + ans);

public void inchToFeet() {

float ans1 = inch / 12.0f;


19 | P a g e

System.out.println("The distance of " + inch + " inches in feet is: " + ans1);

@Override

protected Object clone() {

try {

return super.clone();

} catch (CloneNotSupportedException e)
{ e.printStackTrace();

return null;

public static void main(String[] args) {

lab3_2 d1 = new lab3_2(5, 8); // Creating first object with


constructor lab3_2 d2 = d1; // Assigning d1 as reference to d2

lab3_2 d3 = (lab3_2) d1.clone();

System.out.println("Original object:");

d1.feetToInch();

d1.inchToFeet();

System.out.println("Assigned object:");
20 | P a g e

d2.feetToInch();

d2.inchToFeet();

System.out.println("Cloned object:");

d3.feetToInch();

d3.inchToFeet();

OUTPUT:

iii. Write a program to show the difference between public and private
access specifiers. The program should also show that primitive data
types are passed by value and objects are passed by reference and to
learn use of final keyword

Code:
class Example {
public int publicVar = 10;
private int privateVar = 20;
final int finalVar = 30;
21 | P a g e

public void showPublic() {


System.out.println("Public Variable: " + publicVar);
}

private void showPrivate()


{ System.out.println("Private Variable: " +
privateVar);
}

void changeValue(int x) {
x = 100;
}

void changeObjectValue(Example obj) {


obj.publicVar = 200;
}
}

public class lab3_3 {


public static void main(String[] args) {
Example obj = new Example();
obj.showPublic();
int number = 50;
obj.changeValue(number);
System.out.println("Primitive passed by value: " + number);
obj.changeObjectValue(obj);
System.out.println("Object passed by reference: " + obj.publicVar);
}
22 | P a g e

}
Output:

iv. Write a program that implements two constructors in the class. We call
the other constructor using ‘this’ pointer, from the default constructor of the
class.

Code:
class MyClass {
int value;

MyClass() {
this(100);
}

MyClass(int value) {
this.value = value;
System.out.println("Value: " + this.value);
}
}

public class lab3_4 {


23 | P a g e

public static void main(String[] args) {


MyClass obj = new MyClass();
}
}
Output:

v. Write a program in Java in which a subclass constructor invokes the


constructor of the super class and instantiate the values.

Code:
class SuperClass {
int number;

SuperClass(int num) {
number = num;
System.out.println("Superclass constructor called. Number: " + number);
}
}

class SubClass extends SuperClass {


SubClass(int num) {
super(num);
24 | P a g e

System.out.println("Subclass constructor called.");


}
}

public class lab3_5 {


public static void main(String[] args) {
SubClass obj = new SubClass(50);
}
}

Output:

vi. Write a program in Java to develop overloaded constructor. Also develop the
copy constructor to create a new object with the state of the existing object.

Code:
class Example {
int number;

Example() {
number = 0;
}
25 | P a g e

Example(int num) {
number = num;
}

Example(Example obj) {
this.number = obj.number;
}
}

public class lab3_6 {


public static void main(String[] args) { Example original =
new Example(50); Example copy = new
Example(original); System.out.println("Original number: "
+ original.number); System.out.println("Copied number: "
+ copy.number);
}
}

Output:
26 | P a g e

LAB-4

i. Write a program in Java to demonstrate single inheritance, multilevel


inheritance and hierarchical inheritance.

Code:
class Object{
String color;
int size;
public void area(){
System.out.println("It displays area");
}
}
class Triangle extends Object {
public void area (int l,int h)
{
System.out.println(1/2*l*h);
}

public void display(){


System.out.println(this.color);
}

class EqTriangle extends Triangle {


public void area(int l, int h){
System.out.println(1/2*l*h);
}
27 | P a g e

class Circle extends Object{


public void area(int r){
System.out.println((3.14)*r*r);
}
}

public class Shape {


public static void main(String[] args) {
Triangle t1 =new Triangle();
t1.color="red";
t1.display();
EqTriangle e1=new EqTriangle();
e1.color="Blue";
e1.display();
Circle c1 =new Circle();
c1.size=15;
System.out.println(c1.size);

Output:
28 | P a g e

ii. Java Program to demonstrate the real scenario (e.g., bank) of Java
Method Overriding where three classes are overriding the method of a
parent class. Creating a parent class.

Code:
class BankAccount {

void accountType() {

System.out.println("This is a generic bank account.");

class SavingsAccount extends BankAccount {


@Override

void accountType() {

System.out.println("This is a savings account.");

class CheckingAccount extends BankAccount {


@Override

void accountType() {
29 | P a g e

System.out.println("This is a checking account.");

class BusinessAccount extends BankAccount


{ @Override

void accountType() {

System.out.println("This is a business account.");

public class lab4_2{

public static void main(String[] args) { BankAccount

savings = new SavingsAccount(); BankAccount

checking = new CheckingAccount();

BankAccount business = new BusinessAccount();

savings.accountType();

checking.accountType();

business.accountType();

OUTPUT:
30 | P a g e

iii. Write a java program for the use of super and this keyword.

Code:
class Parent {
int value = 10;
}

class Child extends Parent {


int value = 20;

Child() {
System.out.println("Child Constructor");
}

void showValues() {
System.out.println("Parent value: " + super.value);
System.out.println("Child value: " + this.value);
}
}

public class lab4_3 {


public static void main(String[] args) {
Child child = new Child();
31 | P a g e

child.showValues();
}
}

Output:

iv. Write a java program for the use of final

keyword. Code:

final class FinalClass {


final int finalVar = 100;

final void show() {


System.out.println("Final Method in Final Class. Final Variable: " +
finalVar);
}
}

public class lab4_4 {


public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.show();
}
}

Output:
32 | P a g e

LAB-5

i. Write a program that implements simple example of Runtime


Polymorphism with multilevel inheritance. (e.g., Animal or Shape)

Code:

class Animal {

void sound() {

System.out.println("Some sound");

class Dog extends Animal {

void sound() {

System.out.println("Bark");

class BabyDog extends Dog {

void sound() {

System.out.println("Yelp");

public class lab5_1 {

public static void main(String[] args) {


33 | P a g e

Animal animal1 = new Animal();

Animal animal2 = new Dog();

Animal animal3 = new BabyDog();

animal1.sound();

animal2.sound();

animal3.sound();

Output:

ii. Write a program to compute if one string is a rotation of another. For


example, pit is rotation of tip as pit has same character as tip.

Code:

public class lab5_2 {

static boolean isRotation(String s1, String s2)


{ if (s1.length() != s2.length())

return false;

String combined = s1 + s1;

return combined.contains(s2);

}
34 | P a g e

public static void main(String[] args) {

String s1 = "java";

String s2 = "avaj";

System.out.println(isRotation(s1, s2));

Output:
35 | P a g e

LAB-6

i. Describe abstract class called Shape which has three subclasses say
Triangle, Rectangle, Circle. Define one method area() in the abstract
class and override this area() in these three subclasses to calculate for
specific object i.e. area() of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle.

Code:
abstract class Shape {
abstract double area();
}

class Triangle extends Shape {


double base, height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

double area() {
return 0.5 * base * height;
}
}

class Rectangle extends Shape {


double length, width;

Rectangle(double length, double width) {


36 | P a g e

this.length = length;
this.width = width;
}

double area() {
return length * width;
}
}

class Circle extends Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

double area() {
return Math.PI * radius * radius;
}
}

public class lab6_1 {


public static void main(String[] args) { Shape triangle =
new Triangle(30, 10); Shape rectangle = new
Rectangle(15, 8); Shape circle = new Circle(10);
System.out.println("Triangle area: " + triangle.area());
System.out.println("Rectangle area: " + rectangle.area());
37 | P a g e

System.out.println("Circle area: " + circle.area());


}
}

Output:

ii. Write a Java program to create an abstract class Employee with abstract
methods calculateSalary() and displayInfo(). Create subclasses Manager
and Programmer that extend the Employee class and implement the
respective methods to calculate salary and display information for each
role.

Code:
abstract class Employee {
abstract void calculateSalary();
abstract void displayInfo();
}

class Manager extends Employee {


double baseSalary = 50000;

void calculateSalary() {
System.out.println("Manager Salary: " + (baseSalary + 20000));
}

void displayInfo() {
38 | P a g e

System.out.println("Role: Manager");
}
}

class Programmer extends Employee {


double baseSalary = 40000;

void calculateSalary() {
System.out.println("Programmer Salary: " + (baseSalary + 10000));
}

void displayInfo() {
System.out.println("Role: Programmer");
}
}

public class lab6_2{


public static void main(String[] args) {
Employee manager = new Manager();
Employee programmer = new Programmer();
manager.displayInfo();
manager.calculateSalary();
programmer.displayInfo();
programmer.calculateSalary();
}
}
39 | P a g e

Output:

iii. Write a Java program to create an interface Shape with the getArea()
method. Create three classes Rectangle, Circle, and Triangle that
implement the Shape interface. Implement the getArea() method for each
of the three classes.

Code:
interface Shape {
double getArea();
}

class Rectangle implements Shape {


double length, width;

Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

public double getArea() {


return length * width;
}
}
40 | P a g e

class Circle implements Shape {


double radius;

Circle(double radius) {
this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}
}

class Triangle implements Shape {


double base, height;

Triangle(double base, double height) {


this.base = base;
this.height = height;
}

public double getArea() {


return 0.5 * base * height;
}
}

public class lab6_3 {


public static void main(String[] args)
{ Shape rectangle = new Rectangle(4,
5);
41 | P a g e

Shape circle = new Circle(3);


Shape triangle = new Triangle(6, 8);
System.out.println("Rectangle area: " + rectangle.getArea());
System.out.println("Circle area: " + circle.getArea());
System.out.println("Triangle area: " + triangle.getArea());
}
}

Output:

You might also like