Java Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Experiment No: 01

Experiment Name: Write a program to display default value of all primi ve data types of java.

CODE :

public class DefaultPrimitiveValues {


public static void main(String[] args) {
// Default values of primitive data types
byte defaultByte;
short defaultShort;
int defaultInt;
long defaultLong;
float defaultFloat;
double defaultDouble;
char defaultChar;
boolean defaultBoolean;

// Printing default values


System.out.println("Default values of primitive data types:");
System.out.println("Default byte: " + (defaultByte = 0));
System.out.println("Default short: " + (defaultShort = 0));
System.out.println("Default int: " + (defaultInt = 0));
System.out.println("Default long: " + (defaultLong = 0L));
System.out.println("Default float: " + (defaultFloat = 0.0f));
System.out.println("Default double: " + (defaultDouble = 0.0));
System.out.println("Default char: " + (defaultChar = '\u0000'));
System.out.println("Default boolean: " + (defaultBoolean = false));
}
}

OUTPUT :

Default values of primi ve data types:

Default byte: 0

Default short: 0

Default int: 0

Default long: 0

Default float: 0.0

Default double: 0.0

Default char:

Default boolean: false


Experiment No: 02

Experiment Name: Write a program to input and display all primi ve data types of java.

CODE:

import java.util.Scanner;
public class print_2 {
static byte b;
static short s;
static int i ;
static long l;
static float f ;
static double d;
static char c;
static boolean tf ;
public static void display(){
System.out.println("byte: "+b);
System.out.println("short: "+s);
System.out.println("int: "+i);
System.out.println("long: "+l);
System.out.println("float: "+f);
System.out.println("double: "+d);
System.out.println("char : "+c);
System.out.println("boolean: "+tf);
} public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter byte data: ");
b = input.nextByte();
System.out.println("enter short data: ");
s = input.nextShort();
System.out.println("enter the int value: ");
i = input.nextInt();
System.out.println("enter the long value: ");
l = input.nextLong();
System.out.println("enter the float value: ");
f = input.nextFloat();
System.out.println("enter the double value: ");
d = input.nextDouble();
System.out.println("enter char type value: ");
c = input.next().charAt(0);
System.out.println("enter the boolean type value: ");
tf = input.nextBoolean();
input.close();
display();
}
}
OUTPUT :

byte: -128

short: -32768

int: 2341645

long: 123456789

float: 123.34

double: 12345.23456

char : a

boolean: true

Experiment No: 03

Experiment Name: Write a java program to demonstrate the concept of :

a. Increment and decrement operators


b. Arithmetic Operator
c. Relational Operator
d. Bitwise Operator
e. Conditional Operator

CODE :
public class OperatorDemo {
public static void main(String[] args) {
// Increment and decrement operators
int a = 5;
System.out.println("Initial value of a: " + a);
a++; // Increment a by 1
System.out.println("After incrementing a: " + a);
a--; // Decrement a by 1
System.out.println("After decrementing a: " + a);

// Arithmetic operators
int x = 10;
int y = 3;
System.out.println("x + y = " + (x + y)); // Addition
System.out.println("x - y = " + (x - y)); // Subtraction
System.out.println("x * y = " + (x * y)); // Multiplication
System.out.println("x / y = " + (x / y)); // Division
System.out.println("x % y = " + (x % y)); // Modulus

// Relational operators
int num1 = 10;
int num2 = 20;
System.out.println("num1 == num2: " + (num1 == num2)); // Equal to
System.out.println("num1 != num2: " + (num1 != num2)); // Not equal to
System.out.println("num1 > num2: " + (num1 > num2)); // Greater than
System.out.println("num1 < num2: " + (num1 < num2)); // Less than
System.out.println("num1 >= num2: " + (num1 >= num2)); // Greater than or
equal to
System.out.println("num1 <= num2: " + (num1 <= num2)); // Less than or
equal to

// Bitwise operators
int m = 5; // Binary: 101
int n = 3; // Binary: 011
System.out.println("m & n = " + (m & n)); // Bitwise AND
System.out.println("m | n = " + (m | n)); // Bitwise OR
System.out.println("m ^ n = " + (m ^ n)); // Bitwise XOR
System.out.println("~m = " + (~m)); // Bitwise Complement
System.out.println("n << 1 = " + (n << 1)); // Left shift
System.out.println("n >> 1 = " + (n >> 1)); // Right shift

// Conditional operator (Ternary operator)


int p = 10;
int q = 5;
int result = (p > q) ? p : q;
System.out.println("Result: " + result);
}
}
OUTPUT :

x%y=1

num1 == num2: false

num1 != num2: true

num1 > num2: false

num1 < num2: true

num1 >= num2: false

num1 <= num2: true

m&n=1

m|n=7

m^n=6

~m = -6

n << 1 = 6

n >> 1 = 1

Result: 10

Experiment No: 04

Experiment Name: Write a java program to demonstrate the concept of :

a. iff, if .. else and switch statements


b. For, while and do..while loop

CODE :
public class controlFlow {
public static void main(String[] args) {
int a = 10 ;
int b = 15;
//if-else if-else statement
if(a == 10){
System.out.println("value of a is 10");
}else if(a < b){
System.out.println("a is less then b");
}else{
System.out.println("a is gratter then b");
}
// switch statement

char grade = 'B';

switch (grade) {

case 'A':

System.out.println("Excellent!");

break;

case 'B':

System.out.println("Well done!");

break;

default:

System.out.println("Invalid grade.");

//for loop

int i;

System.out.println("using for loop");

for(i = 0 ; i < 5 ; i++){

System.out.print(i+" ");

//while loop

System.out.println("using while loop");

while(i < 5) {

System.out.print(i +" ");

//do-while loop

System.out.println("using do-while");

do {

System.out.println(i + " ");

} while (i < 4);

}
OUTPUT :

value of a is 10

Well done!

using for loop

01234

using while loop

using do-while

Experiment No: 05

Experiment Name: Write a java program to :

a. Input and display an one dimensional array


b. Input and display a two dimensional array
c. Find the length of an array

CODE :
import java.util.Scanner;
public class Arraytpe {
public static void displayOneDarray(int[] arr,int size){
System.out.println("OUTPUT FOR 1D: ");
for(int i = 0 ; i < size ; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void displayTDarray(int [][]arr , int row,int col){
System.out.println("OUTPUT FOR 2D: ");
for(int i = 0 ; i < row ; i++){
for(int j = 0 ; j < col ; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size , row , colum;
System.out.print("enter the size of OD arry: ");
size = input.nextInt();
int[] OD = new int[size];
System.out.print("enter array values: ");
for(int i =0 ; i < size ; i++){
OD[i] = input.nextInt();
}
System.out.print("enter the row and colum of an arry (using space): ");
row = input.nextInt();
colum = input.nextInt();
int[][] TD = new int[row][colum];
for(int i = 0 ; i < row ; i++){
System.out.println("enter "+colum+" ammount value (using space): ");
for(int j = 0 ; j < colum ; j++){
TD[i][j] = input.nextInt();
}
}
input.close();
displayOneDarray(OD , size);
displayTDarray(TD , row ,colum);

}
}

OUTPUT:

enter the size of OD arry: 5

enter array values: 1 2 3 4 5

enter the row and colum of an arry (using space): 2 2

enter 2 ammount value (using space):

12

enter 2 ammount value (using space):

34

56

OUTPUT FOR 1D:

12345
Experiment No: 06

Experiment Name: Write a java program to demonstrate the concept of encapsula on.

CODE :

public class Encapsulation{


public static class EncapsulationData {
private int age ;
private String name;
public void setName(String n){
name = n;
}
public void setAge(int a){
age = a;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
public static void main(String[] args){
EncapsulationData obj = new EncapsulationData();
obj.setName("yousuf");
obj.setAge(21);
String Name = obj.getName();
int Age = obj.getAge();
System.out.println("the name is: "+Name);
System.out.println("Age is: "+Age);
}
}

OUTPUT :

the name is: yousuf

Age is: 21
Experiment No: 08

Experiment Name: Write a java program to illustrate the concept of :

a. Single inheritance
b. Multilevel inheritance
c. Hierarchical inheritance
d. Multiple inheritance

CODE :

public class SingleInheritance {


public static class Animal {
private String name;

void setAnimalName(String n) {
name = n;
}

void printName() {
System.out.println("the name is: " + name);
}
}
// Single inheritance
public static class Dog extends Animal {
public void bark() {
System.out.println("the dog is barking");
}
}
// Multi-level inheritance
public static class BabyDog extends Dog {
public void weep() {
System.out.println("the baby dog is weeping");
}
}
// Hierarchical Inheritance
public static class Cat extends Animal {
public void meow() {
System.out.println("the cat is meowing");
}
}
// Multiple Inheritance
interface Cow {
public void eatGrass();
}

interface Goat {
public void eatGrass();
}

public static class VegetableEatingAnimal implements Cow, Goat {


public void eatGrass() {
System.out.println("they eat grass");
}
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.setAnimalName("DOGGY");
dog.printName();

dog.bark();
BabyDog bd = new BabyDog();
bd.setAnimalName("Baby Dggy");
bd.printName();
bd.bark();

bd.weep();
Cat c = new Cat();
c.setAnimalName("tommy");
c.printName();
c.meow();

VegetableEatingAnimal cow = new VegetableEatingAnimal();


cow.eatGrass();
}
}

OUTPUT :

the name is: DOGGY


the dog is barking
the name is: Baby Dggy
the dog is barking
the baby dog is weeping
the name is: tommy
the cat is meowing
they eat grass
Experiment No: 09

Experiment Name: Write a program to demonstrate the concept of private, public and protected access specifier.

CODE :

public class accessspecifier {


private int pri = 10 ;
public int pub = 20 ;
protected int prot = 30 ;
public void getPrivateValue(){
System.out.println("the private value is: "+pri);
}
private void pritaveMethod(){
System.out.println("this is a private Method with private variable:
"+pri);
}

public void publicMethod(){


System.out.println("this is a public Method with public variable:
"+pub);
}

protected void protectedMethod(){


System.out.println("this is a protected Method with protected
variable: "+prot);
}

public class MainAcces {


public static void main(String[] args) {
accessspecifier access = new accessspecifier();
access.getPrivateValue();
access.publicMethod();
access.protectedMethod();
}
}

OUTPUT :

the private value is: 10

this is a public Method with public variable: 20

this is a protected Method with protected variable: 30


Experiment No: 10

Experiment Name: Write a java program to demonstrate the concept of overloading (Constructor and Method)

CODE :

public class overload {


overload(){
System.out.println("default constructor");
}
overload(int data){
System.out.println("overloaded the constructor with data ="+data);
}

void display(){
System.out.println("default method");
}

void display(int d){


System.out.println("overloaded this method with data = "+d);
}
public static void main(String[] args) {
//constructor
overload obj = new overload();
overload obj2 = new overload(10);
//method
obj.display();
obj2.display(20);

}
}

OUTPUT :

default constructor

overloaded the constructor with data =10

default method

overloaded this method with data = 20


Experiment No: 11

Experiment Name: Write a java program to demonstrate the concept of overriding

CODE :

public class normal_method {


public void display(){
System.out.println("this method isn't override yet");
}
}

public class overrided extends normal_method{


@Override
public void display(){
System.out.println("Now it is overrided.");
}
public static void main(String[] args) {
normal_method nm = new normal_method();
nm.display();
overrided ov = new overrided();
ov.display();
}
}

OUTPUT :

this method isn't override yet

Now it is overrided.

Experiment No : 12

Experiment Name: Write a java program to demonstrate copy constructor

CODE :
public class cpy_constructor {
public String name;
public int age;

cpy_constructor(String n , int a){


System.out.println("creating a new consturctor");
name = n;
age = a;
}

cpy_constructor(cpy_constructor anotherConstructor){
System.out.println("using copy constructor");
name = anotherConstructor.name;
age = anotherConstructor.age;
}
public static void main(String[] args)
{
cpy_constructor obj = new cpy_constructor("David",22);
cpy_constructor obj2 = new cpy_constructor(obj);
}
}

OUTPUT :

crea ng a new consturctor

using copy constructor

Experiment No: 13

Experiment Name: Write a java program to demonstrate abstract class and interface.

CODE :

public class Abstract_and_interface {


abstract class Animal{
abstract void Sound();
public void sleep(){
System.out.println("Animal is sleeping");
}
}

interface swimmer{
void swim();
}
public class Dog extends Animal implements swimmer{
public void Sound(){
System.out.println("Dog barks");
}
public void swim(){
System.out.println("the animal is swimming");
}
}
public static void main(String[] args){
Dog d = new Dog();
}
}
public class Abstract_interface extends Dog {
public static void main(String[] args) {
Dog d = new Dog();
d.Sound();
d.swim();
}

}
OUTPUT :
Dog barks

the animal is swimming

Experiment No : 14

Experiment Name: Write a java program to demonstrate inner class concept

CODE :

public class outerClass {


int outer_variable = 10 ;
public class innerClass{
int ineer_variable = 20 ;
public void display(){
System.out.println("the inner variable value by ineer class:
"+ineer_variable);
}
}
void outer_display(){
innerClass in = new innerClass();
in.display();
System.out.println("Calling inner variable by outer class:
"+in.ineer_variable);
}
public static void main(String[] args) {
outerClass ot = new outerClass();
ot.outer_display();
}
}

OUTPUT :

the inner variable value by ineer class: 20

Calling inner variable by outer class: 20


Experiment No: 15

1. Experiment Name: Write a java program to demonstrate the concept of try, catch, finally, throw and
throws keyword.

CODE :
import java.util.Scanner;

public class ExceptionDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = scanner.nextInt();

try {
validateNumber(number);
System.out.println("Entered number is valid!");
} catch (InvalidNumberException e) {
System.out.println("Caught InvalidNumberException: " +
e.getMessage());
} finally {
System.out.println("Finally block executed.");
scanner.close();
}
}

public static void validateNumber(int number) throws


InvalidNumberException {
if (number <= 0) {
throw new InvalidNumberException("Number must be greater than
zero.");
}
}
}

class InvalidNumberException extends Exception {


public InvalidNumberException(String message) {
super(message);
}
}

OUTPUT :

Enter a number:
0
Caught InvalidNumberExcep on: Number must be greater than zero.
Finally block executed.
Experiment No : 16

Experiment Name: Write a java program to handle Arithme cExcep on, ArrayIndexOutOfBoundsExcep on,
NullPointerExcep on, StringIndexOutOfBoundExcep ons

CODE :

public class ExceptionHandlingDemo {


public static void main(String[] args) {
// ArithmeticException
try {
int result = divideByZero();
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " +
e.getMessage());
}

// ArrayIndexOutOfBoundsException
try {
accessArrayOutOfBounds();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}

// NullPointerException
try {
accessNullReference();
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " +
e.getMessage());
}

// StringIndexOutOfBoundsException
try {
accessStringOutOfBounds();
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught StringIndexOutOfBoundsException: " +
e.getMessage());
}
}
// Method to demonstrate ArithmeticException
public static int divideByZero() {
return 10 / 0;
}

// Method to demonstrate ArrayIndexOutOfBoundsException


public static void accessArrayOutOfBounds() {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
}

// Method to demonstrate NullPointerException


public static void accessNullReference() {
String str = null;
System.out.println(str.length());
}

// Method to demonstrate StringIndexOutOfBoundsException


public static void accessStringOutOfBounds() {
String str = "hello";
System.out.println(str.charAt(10));
}
}

OUTPUT :

Caught Arithme cExcep on: / by zero

Caught ArrayIndexOutOfBoundsExcep on: Index 5 out of bounds for length 3

Caught NullPointerExcep on: Cannot invoke "String.length()" because "str" is null

Caught StringIndexOutOfBoundsExcep on: Index 10 out of bounds for length 5


Experiment No : 17

Experiment Name: Write a program to illustrate the concept of generics in java.

CODE :

import java.util.ArrayList;
import java.util.List;

public class GenericsExample {


public static void main(String[] args) {
// Creating a list of integers using generics
List<Integer> integerList = new ArrayList<>();
integerList.add(10);
integerList.add(20);
integerList.add(30);

// Creating a list of strings using generics


List<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");

// Printing the contents of the integer list


System.out.println("Integer List:");
printList(integerList);

// Printing the contents of the string list


System.out.println("String List:");
printList(stringList);
}

// Generic method to print elements of a list


public static <T> void printList(List<T> list) {
for (T element : list) {
System.out.println(element);
}
}
}

OUTPUT :
Integer List:
10
20
30
String List:
Hello
World
Experiment No : 18

Experiment Name: Define a Student class with a ributes such as name, roll number, address and contact no.
Implement methods to set all the informa on and another method to display details.

CODE :

import java.util.Scanner;
public class Student {
String name;
String address;
int roll;
long contactNo;

public void setInformation(){


Scanner scanner = new Scanner(System.in);
System.out.print("Enter Your Name : ");
this.name = scanner.next();
System.out.print("Enter your Roll Number : ");
this.roll = scanner.nextInt();
System.out.print("Enter your Address : ");
this.address = scanner.next();
System.out.print("Enter your Contact Number : ");
this.contactNo = scanner.nextLong();
}

public void display(){


System.out.print("\n");
System.out.println("Name : " + name);
System.out.println("Roll : " + roll);
System.out.println("Address : " + address);
System.out.println("Contact Number : " + contactNo);
}
public static void main(String args[]) {
Student std = new Student();
std.setInformation();
std.display();
}
}

OUTPUT :

Enter Your Name : David


Enter your Roll Number : 42
Enter your Address : Bangladesh
Enter your Contact Number : 01335456234

Name : David
Roll : 42
Address : Bangladesh
Contact Number : 1335456234
Experiment No : 19

Experiment Name : Define an Employee class with a ributes such as name, ID, and salary. Develop methods to
calculate annual salary and display employee details.

CODE :
import java.util.Scanner;
public class Employee {
int ID;
int salary;
String name;

public void annualSalary(){


this.salary *= 12;
}
public void display(){
System.out.println("NAME : " + name);
System.out.println("ID : " + ID);
System.out.println("Annual SALARY : " + this.salary);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Employee emp = new Employee();
System.out.print("Enter employee's name : ");
emp.name = scanner.next();
System.out.print("Enter employee's ID : ");
emp.ID = scanner.nextInt();
System.out.print("Enter employee's Salary : ");
emp.salary = scanner.nextInt();
System.out.print("\n");
emp.annualSalary();
emp.display();
scanner.close();
}
}

OUTPUT :

Enter employee's name : lana


Enter employee's ID : 3
Enter employee's Salary : 10000

NAME : lana
ID : 3
Annual SALARY : 120000
Experiment No : 20

Experiment Name: Design classes for different geometric shapes like Circle, Rectangle, and Triangle.
Implementmethods to calculate area and perimeter for each shape (Apply method overloading

concept).

CODE :

import java.util.Scanner;
public class geometricShapes {
double area;
double parameter;
public void calculation() {
System.out.println("Area : " + area + "\n" + "Parameter : " +
parameter);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
float radius;
float length;
float width;
float a;
float b;
float c;
byte option;
s
do {
System.out.print("Which Operation do you want to Run? \n 1.Circle
\n 2.Rectangle \n 3.Triangle \n 4.Exit \n Enter : ");
option = scanner.nextByte();
switch (option) {
case 1 -> {
System.out.print("Enter Radius : ");
radius = scanner.nextFloat();
Circle circle = new Circle();
circle.calculation(radius);
break;
}
case 2 -> {
System.out.print("Enter Length : ");
length = scanner.nextFloat();
System.out.print("Enter width : ");
width = scanner.nextFloat();
Rectangle rec = new Rectangle();
rec.calculation(length, width);
break;
}
case 3 -> {
System.out.print("Enter the value of a : ");
a = scanner.nextFloat();
System.out.print("Enter the value of b : ");
b = scanner.nextFloat();
System.out.print("Enter the value of c : ");
c = scanner.nextFloat();
Triangle triangle = new Triangle();
triangle.calculation(a,b,c);
break;
}
case 4 -> {
break;
}
default -> {
System.out.println("Enter correct value");
}
}

} while (option != 4);


}
}
public class Rectangle extends geometricShapes {

public void calculation(float length, float width) {


area = length * width;
parameter = 2 * (length + width);
calculation();
}
}
public class Circle extends geometricShapes {
public void calculation(float radius){
area = 3.1416 * radius * radius;
parameter = 2 * 3.1416 * radius;
super.calculation();
}
}
public class Triangle extends geometricShapes{
public void calculation(float a, float b, float c) {
parameter = a + b + c;
area = Math.sqrt(parameter * (parameter - a) * (parameter - b) *
OUTPUT : - c));
(parameter
calculation();
}
}
Which Opera on do you want to Run?
1.Circle
2.Rectangle
3.Triangle
4.Exit
Enter : 1
Enter Radius : 5
Area : 78.54
Parameter : 31.416
Which Opera on do you want to Run?
1.Circle
2.Rectangle
3.Triangle
4.Exit
Enter : 2
Enter Length : 12
Enter width : 2
Area : 24.0
Parameter : 28.0
Which Opera on do you want to Run?
1.Circle
2.Rectangle
3.Triangle
4.Exit
Enter : 3
Enter the value of a : 4
Enter the value of b : 3
Enter the value of c : 5
Area : 77.76888838089432
Parameter : 12.0
Which Opera on do you want to Run?
1.Circle
2.Rectangle
3.Triangle
4.Exit
Experiment No: 21

Experiment Name : Create a BankAccount class with a ributes like account number, balance, and owner name.

CODE :

import java.util.Scanner;
public class BankAccount {
private long accountNumber ;
private int balance;
private String ownerName;
public BankAccount(long a , int b , String n){
accountNumber = a;
balance = b;
ownerName = n;
}
public void deposit(int ammount){
balance += ammount;
System.out.println("deposit successfull "+ammount+"$" );
}
public void withdraw(int ammount){
if(ammount > balance){
System.out.println("sorry, you can't withdraw");
return;
}
balance -= ammount;
System.out.println("withdraw successfull");
}
void balance(){
System.out.println("the balance is: "+balance);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter your account number and your name : " );
BankAccount bank = new BankAccount(input.nextLong(),
2000,input.nextLine());
bank.balance();
System.out.print("enter the ammount you want to deposit: ");
bank.deposit(input.nextInt());
System.out.println("enter the ammount you want to withdraw: ");
bank.withdraw(input.nextInt());
bank.balance();
}

}
OUTPUT:

enter your account number and your name : 1293480 Azad

the balance is: 2000

enter the ammount you want to deposit: 20

deposit successfull 20$

enter the ammount you want to withdraw:

withdraw successfull

the balance is: 2015

Experiment No : 22

Experiment Name : Create a Java class called BankAccount with proper es accountNumber (String),

accountHolderName (String), and balance (double). Implement a parameterized constructor that ini alizes these
proper es. Write a method to deposit money into the account and another method to withdraw money from
the account and a method to display the final balance.

CODE :

package lab3;
import java.util.Scanner;
public class BankAccount {

int accountNumber;
double balance;
String accountHolderName;

int withdraw = 0;
int deposit = 0;

public BankAccount(int accountNumber,String accountHolderName,double balance){


this.accountNumber = accountNumber;
this.accountHolderName = accountHolderName;
this.balance = balance;
}

public BankAccount(){
this.accountNumber = 0;
this.accountHolderName = "Unknown";
this.balance = 0.0;
}
public void deposit() {
balance += deposit;
}
public void withdraw() {
if(balance == 0){
System.out.println("Your account balance is Zero!!! \nWithdarwl is not
possible.");
}
else if(balance < withdraw){
System.out.println("Account balance is " + balance + ".\nwithdrawl is not
possible.");
}
else{
balance -= withdraw;
}
}

public void withdraw() {


if(balance == 0){
System.out.println("Your account balance is Zero!!! \nWithdarwl is not
possible.");
}
else if(balance < withdraw){
System.out.println("Account balance is " + balance + ".\nwithdrawl is not
possible.");
}
else{
balance -= withdraw;
}
}

public void display() {


System.out.println("Owner Name : " + accountHolderName);
System.out.println("Account Number : " + accountNumber);
System.out.println("Deposited Balance : " + deposit);
System.out.println("Withdrawl Balance : " + withdraw);
System.out.println("Current Account Balance : " + balance);
}
public static void main(String args[]) {
BankAccount ba = new BankAccount();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Owner Name : ");
ba.accountHolderName = scanner.next();
System.out.print("Enter Account Number : ");
ba.accountNumber = scanner.nextInt();
System.out.print("Enter Balance : ");
ba.balance = scanner.nextInt();

BankAccount bank = new


BankAccount(ba.accountNumber,ba.accountHolderName,ba.balance);

int option;
do {
System.out.print("Which service do you want? \n 1.Deposit \n 2.withdraw
\n 3.Display \n 4.Exit \n Enter : ");
option = scanner.nextInt();
switch (option) {
case 1 -> {
System.out.print("Enter ammount to deposit : ");
bank.deposit = scanner.nextInt();
bank.deposit();
break;
}
case 2 -> {
System.out.print("Enter ammount to withdraw : ");
bank.withdraw = scanner.nextInt();
bank.withdraw();
break;
}
case 3 -> {
bank.display();
break;
}
case 4 -> {
break;
}
default -> {
System.out.println("please!Enter correct value");
}
}

} while (option != 4);


}
}
OUTPUT :

Enter Owner Name : yousuf


Enter Account Number : 1232345
Enter Balance : 200
Which service do you want?
1.Deposit
2.withdraw
3.Display
4.Exit
Enter : 1
Enter ammount to deposit : 200
Which service do you want?
1.Deposit
2.withdraw
3.Display
4.Exit
Enter : 3
Owner Name : yousuf
Account Number : 1232345
Deposited Balance : 200
Withdrawl Balance : 0
Current Account Balance : 400.0
Which service do you want?
1.Deposit
2.withdraw
3.Display
4.Exit
Enter : 2
Enter ammount to withdraw : 100
Which service do you want?
1.Deposit
2.withdraw
3.Display
4.Exit
Enter : 3
Owner Name : yousuf
Account Number : 1232345
Deposited Balance : 200
Withdrawl Balance : 100
Current Account Balance : 300.0
Which service do you want?
1.Deposit
2.withdraw
3.Display
4.Exit
Enter : 4
Experiment No : 23

Experiment Name: Create a Java class called Employee with proper es id (int) and name (String) and a method
employeeDetails(). Implement a parameterized constructor that ini alizes these proper es. Create a subclass
Manager and a subclass Worker. Implement constructors in each subclass that call the superclass constructor to
ini alize the id and name. Demonstrate inheritance by crea ng instances of Manager and Worker and displaying
their details.

CODE :
package lab3;
import java.util.Scanner;
public class Main {
int id;
String name;
public void employeeinfo() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter ID : ");
id = scanner.nextInt();
System.out.print("Enter Name : ");
name = scanner.next();
}
public static void main(String args[]) {
Main main = new Main();
Scanner scanner = new Scanner(System.in);
byte op;
do {
System.out.println("Detail of \n 1.Manager \n 2.Worker \n 3.Exit \n
Enter : ");
op = scanner.nextByte();
switch (op) {
case 1 -> {
main.employeeinfo();
Manager manager = new Manager(main.id,main.name);
manager.employeeDetails();
}
case 2 -> {
main.employeeinfo();
Worker worker = new Worker(main.id, main.name);
worker.employeeDetails();
}
case 3 -> {
break;
}
default -> {
System.out.println("Enter correct value!");
}
}
} while (op != 3);
}
}
OUTPUT :

Detail of

1.Manager

2.Worker

3.Exit

Enter :

Enter ID : 2354

Enter Name : Yeasin Arafat

Empoyee's Id : 2354

Empoyee's Name : Yeasin

Detail of

1.Manager

2.Worker

3.Exit

Enter :

Enter ID : 4455

Enter Name : David

Empoyee's Id : 4455

Empoyee's Name : David

Detail of

1.Manager

2.Worker

3.Exit

Enter :

3
Experiment No : 24

Experiment Name : Create a Java class called Animal with proper es species (String). Implement a parameterized
constructor that ini alizes the species. Create subclasses Mammal, Bird, and Fish, each represen ng a specific
type of animal. Implement constructors in each subclass that call the superclass constructor to ini alize the
species. Demonstrate inheritance by crea ng instances of Mammal, Bird, and Fish and displaying their
proper es.

CODE :
package lab3;
public class MainAnimal {
public static void main(String args[]) {
Mammal mammal = new Mammal("Elephent");
Bird bird = new Bird("peacock");
Fish fish = new Fish("Dolphin");
}
}
public class Animal {
String species;
public Animal(String species){
this.species = species;
}
}
public class Bird extends Animal{
public Bird(String species){
super(species);
System.out.println("Bird : " + super.species);
}
}
public class Fish extends Animal{
public Fish(String species){
super(species);
System.out.println("Fish : " + super.species);
}
}
public class Mammal extends Animal{
public Mammal(String species){
super(species);
System.out.println("Mammal : " + super.species);
}
}

OUTPUT :

Mammal : Elephent
Bird : peacock
Fish : Dolphin
Experiment No : 25

Experimaent Name : Create a Java class called Account with proper es accountNumber (String) and balance
(double). Implement a parameterized constructor that ini alizes these proper es. Create subclasses
SavingsAccount and CheckingAccount, each represen ng a specific type of bank account. Implement
constructors in each subclass that call the superclass constructor to ini alize the account number and balance.
Demonstrate inheritance by crea ng instances of SavingsAccount and CheckingAccount and displaying their
proper es (i.e account number and balance).

CODE :

import java.util.Scanner;
public class Employee {

int id;
String name;
String department;
double salary;
public Employee(int id , String name, String department,double salary){
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
}
public Employee(){
this.id = 0;
this.name = "Unknown";
this.department = "Unknown";
this.salary = 0.0;
}

public void display(){


System.out.println("ID : " + id);
System.out.println("NAME : " + name);
System.out.println("DEPARTMENT : " + department);
System.out.println("SALARY : " + salary);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
Employee emp1 = new Employee();
emp1.display();

System.out.print("Enter ID : ");
emp1.id = scanner.nextInt();
System.out.print("Enter NAME : ");
emp1.name = scanner.next();
System.out.print("Enter DEPARTMENT : ");
emp1.department = scanner.next();
System.out.print("Enter SALARY : ");
emp1.salary = scanner.nextDouble();

Employee emp2 = new Employee(emp1.id,emp1.name,emp1.department,emp1.salary);


emp2.display();
}
}
OUTPUT :
ID : 0

NAME : Unknown

DEPARTMENT : Unknown

SALARY : 0.0

Enter ID : 50

Enter NAME : MDY

Enter DEPARTMENT : CSE

Enter SALARY : 200000

ID : 50

NAME : MDY

DEPARTMENT : CSE

SALARY : 200000.0

You might also like