0% found this document useful (0 votes)
11 views52 pages

Sara Java

The document contains a series of Java programming exercises for students at Guru Nanak Khalsa College, focusing on basic programming concepts such as calculating area and perimeter, converting units, calculating sales tax, solving quadratic equations, and handling arrays. Each exercise includes sample code, user inputs, and expected outputs. The document serves as a practical guide for students to enhance their programming skills through hands-on coding tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views52 pages

Sara Java

The document contains a series of Java programming exercises for students at Guru Nanak Khalsa College, focusing on basic programming concepts such as calculating area and perimeter, converting units, calculating sales tax, solving quadratic equations, and handling arrays. Each exercise includes sample code, user inputs, and expected outputs. The document serves as a practical guide for students to enhance their programming skills through hands-on coding tasks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

GURU NANAK KHALSA COLLEGE

92

JAVA PRACTICAL 1 (A)(BASICS)

Q1) WAP program to find Area and Perimeter of circle.Accept radius


as from user.

INPUT:-

import java.util.Scanner;
public class AreaPerimeter
{ public static void main(String[] args)
{ double a,p,r;
System.out.println("Enter radius value");
Scanner sc = new Scanner(System.in);
r=sc .nextDouble();
a=Math.PI*r;
p=2*Math.PI*r;
System.out.println("Area="+a);
System.out.println("Perimeter="+p);
}
}

OUTPUT:-

Microsoft Windows [Version 10.0.22631.3737]


(c) Microsoft Corporation. All rights reserved.

C:\GargiProject>javac AreaPerimeter.java

C:\GargiProject>java AreaPerimeter
Enter radius value
2
Area=6.283185307179586
Perimeter=12.566370614359172

1
GURU NANAK KHALSA COLLEGE
92

Q2) There are exactly 2.54 centimeters to an inch . Write a program that
takes a number of inches from user and converts it to centimeters.

INPUT:-

import java.util.Scanner;
public class InchesToCentimeters
{ public static void main(String[] args)
{ double cm,in;
System.out.println("Enter the value of inches");
Scanner sc = new Scanner(System.in);
in=sc .nextDouble();
cm = in*2.54;
System.out.println(in +"inches = " + cm + "centimeters");
}
}

OUTPUT:-

Microsoft Windows [Version 10.0.22631.3737]


(c) Microsoft Corporation. All rights reserved.

C:\GargiProject>javac InchesToCentimeters.java

C:\GargiProject>java InchesToCentimeters
Enter the value of inches
10
10.0inches = 25.4centimeters

2
GURU NANAK KHALSA COLLEGE
92

Q3) Sales tax in some cities is 8.25%.Write a program that accepts a price
from the user and prints out the appropriate tax and total purchase price.

import java.util.Scanner;

public class SalesTaxCalculator {


public static void main(String[] args) {
// Define the sales tax rate (in percentage)
final double SALES_TAX_RATE = 8.25 / 100.0; // 8.25%

Scanner scanner = new Scanner(System.in);

// Input the price from the user


System.out.print("Enter the price of the item: $");
double price = scanner.nextDouble();

// Calculate the sales tax


double salesTax = price * SALES_TAX_RATE;

// Calculate the total purchase price


double total = price + salesTax;

// Output the results


System.out.printf("Sales Tax: $%.2f%n", salesTax);
System.out.printf("Total Purchase Price: $%.2f%n", total);

scanner.close();
}
}

OUTPUT:-

Enter the price of the item: $100


Sales Tax: $8.25
Total Purchase Price: $108.25
PS C:\GargiProject\cscorner>

3
GURU NANAK KHALSA COLLEGE
92

Q4) Write a program to find solution of quadratic equation. Accept a,b and
c from user.

INPUT:-

import java.util.Scanner;
public class CalQuad
{
public static void main(String[] args)
{
double a,b,c,root1,root2;
System.out.println("For given equation ax^2+bx+c");
System.out.println("\nEnter a: ");
Scanner sc = new Scanner(System.in);
a = sc .nextDouble();
System.out.println("\nEnter b: ");
b = sc .nextDouble();
System.out.println("\nEnter c: ");
c = sc .nextDouble();
double d=(b*b)-(4*a*c);
System.out.println("\nDiscrimination= "+d);
if(d>0)
{ System.out.println("Roots are real and they are unequal");
root1 = (-b+Math.sqrt(d))/(2*a);
root2 = (-b-Math.sqrt(d))/(2*a);
System.out.println("\nRoot1= "+root1);
System.out.println("\nRoot2= "+root2);
}
else if (d==0)
{
System.out.println("Roots are real and they are equal");
root1= (-b+Math.sqrt(d))/(2*a);
System.out.println("Root1="+root1);
}
else

4
{
GURU NANAK KHALSA COLLEGE
92

System.out.println("Roots are Imaginary");


}
}
}

OUTPUT:-

C:\GargiProject>javac CalQuad.java

C:\GargiProject>java CalQuad
For given equation ax^2+bx+c

Enter a:
10

Enter b:
20

Enter c:
30

Discrimination= -800.0
Roots are Imaginary

Q5) Write a program to calculate the Sum of Digits of Given any


Number.

import java.util.Scanner;

public class SumofDigits {


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

5
// Input number from the user
GURU NANAK KHALSA COLLEGE
92

System.out.print("Enter a number: ");


long number = scanner.nextLong();

// Calculate the sum of digits


int sum = sumOfDigits(number);

// Output the result


System.out.println("Sum of digits of " + number + " is: " + sum);

scanner.close();
}

// Method to calculate sum of digits of a number


public static int sumOfDigits(long number) {
// Ensure the number is non-negative
number = Math.abs(number);

int sum = 0;
while (number > 0) {
// Extract the last digit
int digit = (int)(number % 10);
sum += digit;
// Remove the last digit from number
number /= 10;
}

return sum;
}
}

OUTPUT:-

Enter a number: 12345


Sum of digits of 12345 is: 15
PS C:\GargiProject\cscorner>

6
GURU NANAK KHALSA COLLEGE
92

Q6) Write a program to find Whether Given Year is a Leap Year or Not.

import java.util.Scanner;

public class LeapYear {


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

// Input the year from the user


System.out.print("Enter a year: ");
int year = scanner.nextInt();

// Check if the year is a leap year


boolean isLeapYear = checkLeapYear(year);

// Output the result


if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}

scanner.close();
}

// Method to check if a year is a leap year


public static boolean checkLeapYear(int year) {
// Leap year logic
if ((year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)) {
return true;
} else {
return false;
}
}
}

7
OUTPUT:-

Enter a year: 2024


GURU NANAK KHALSA COLLEGE
92

2024 is a leap year.


PS C:\GargiProject\cscorner>

Q7) Write a program to check whether the entered character is a


vowel,consonant,number or a special character.

import java.util.Scanner;

public class CharacterType {


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

// Input a character from the user


System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);

// Check the type of character


if (isVowel(ch)) {
System.out.println(ch + " is a vowel.");
} else if (isConsonant(ch)) {
System.out.println(ch + " is a consonant.");
} else if (isDigit(ch)) {
System.out.println(ch + " is a number.");
} else {
System.out.println(ch + " is a special character.");
}

scanner.close();
}

// Method to check if a character is a vowel

8
public static boolean isVowel(char ch) {
ch = Character.toLowerCase(ch); // Convert to lowercase for case
insensitivity

return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==


'u';
GURU NANAK KHALSA COLLEGE
92

// Method to check if a character is a consonant


public static boolean isConsonant(char ch) {
// Check if it is a letter and not a vowel
return Character.isLetter(ch) && !isVowel(ch);
}

// Method to check if a character is a digit


public static boolean isDigit(char ch) {
return Character.isDigit(ch);
}
}

OUTPUT:-

Enter a character: a
a is a vowel.

Enter a character: 7
7 is a number.

Enter a character: %
% is a special character.

Enter a character: r
r is a consonant.

9
Q8) Write a program to check whether the entered character is uppercase or
lowercase.

import java.util.Scanner;
GURU NANAK KHALSA COLLEGE
92

public class UppercaseLowercaseCheck {


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

// Input a character from the user


System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);

// Check if the character is uppercase or lowercase


if (isUppercase(ch)) {
System.out.println(ch + " is an uppercase letter.");
} else if (isLowercase(ch)) {
System.out.println(ch + " is a lowercase letter.");
} else {
System.out.println(ch + " is neither uppercase nor
lowercase.");
}

scanner.close();
}

// Method to check if a character is uppercase


public static boolean isUppercase(char ch) {
return (ch >= 'A' && ch <= 'Z');
}

// Method to check if a character is lowercase


public static boolean isLowercase(char ch) {
return (ch >= 'a' && ch <= 'z');
}
}

10
OUTPUT:-

Enter a character: A
A is an uppercase letter.
GURU NANAK KHALSA COLLEGE
92

Enter a character: b
b is a lowercase letter.

11
GURU NANAK KHALSA COLLEGE
92

JAVA PRACTICAL NO:- 2 (B )(ARRAYS)

Q1)Write a program to accept marks of students from the user and


calculate the sum and average of the marks.

import java.util.Scanner;

public class MarksSumAverage {


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

// Input the number of students


System.out.print("Enter the number of students: ");
int numStudents = scanner.nextInt();

// Initialize variables for sum and average


int sum = 0;
double average;

// Input marks for each student and calculate sum


for (int i = 1; i <= numStudents; i++) {
System.out.print("Enter marks for student " + i + ": ");
int marks = scanner.nextInt();
sum += marks;
}

// Calculate average
average = (double) sum / numStudents;

// Output results
System.out.println("Sum of marks: " + sum);
System.out.println("Average marks: " + average);

scanner.close();
}
}

12
GURU NANAK KHALSA COLLEGE
92

OUTPUT:-

Enter the number of students: 5


Enter marks for student 1: 59
Enter marks for student 2: 69
Enter marks for student 3: 60
Enter marks for student 4: 79
Enter marks for student 5: 80
Sum of marks: 347
Average marks: 69.4
PS C:\GargiProject\cscorner>

Q2)Write a java program to find the maximum and minimum value of


an array

import java.util.Scanner;

public class ArrMatrix {


public static void main(String args[]) {
int temp;
Scanner sc = new Scanner(System.in);
System.out.print("Enter no of elements in array: ");
int a[]= new int[n];
System.out.print("Enter elements of array a: ");
for(int i=0 ; i<n ; i++)
{
a[i]=sc.nextInt();
}
System.out.println("array elements are:");
for(int i=0 ; i<n ; i++)
{
System.out.println(a[i] +"\t");

13
}
GURU NANAK KHALSA COLLEGE
92

for(int i=0 ;i<n : i++)


{
for(int j=i+1 ; j<n ; j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp; }
}
}

System.out.println("Minimum value="+a[0]+"\nMaximum
value:"+a[n-1]);
}
}

OUTPUT:-
Enter elements of array a:
2
3
4
Array elements are :
2 3 4 Minimum value=2nMaximum value:4
Minimum value value=2nMaximum value:4
Minimum value value=2nMaximum value:4
PS C:\Gargi>

Q3) Write a program to accept n names from user


and sort them in ascending order.

import java.util.Scanner;

public class string


{
GURU NANAK KHALSA COLLEGE
92

14
public static void main(String args[]) {
int n ;
String temp;
Scanner sc = new Scanner(System.in);
System.out.print("Enter no of names you want to enter: ");
n= sc.nextInt();
String a[]= new String[n];
System.out.print("Enter"+n+"names: ");
for(int i=0 ; i<n ; i++)
{
a[i]=sc.next();
}
System.out.println("array elements are:");
for(int i=0 ; i<n ; i++)
{
System.out.println(a[i] +"\t");
}
for(int i=0 ;i<n ; i++)
{
for(int j=i+1 ; j<n ; j++)
{
if(a[i].compareTo(a[j])>0)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}

System.out.println("Names in sorted order:");


for(int i=0;i<n;i++)
{
System.out.print(a[i]+",");

}
}
GURU NANAK KHALSA COLLEGE
92

15
OUTPUT:-

Enter no of names you want to enter: 4


Enter4names: gargi
sakshi
vanshita
rajeshwari
array elements are:
gargi
rajeshwari
array elements are:
gargi
sakshi
Names in sorted order:
gargi,rajeshwari,sakshi,vanshita,
PS C:\gargi\Java>

Q4) Write a java program to find the transpose of a matrix . Accept


matrix from user.

import java.util.Scanner;

public class MatrixTranspose {


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

// Input the number of rows and columns


System.out.print("Enter the number of rows in the matrix: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns in the matrix: ");
int columns = scanner.nextInt();

// Declare the matrix


int[][] matrix = new int[rows][columns];
GURU NANAK KHALSA COLLEGE
92

// Input the elements of the matrix


System.out.println("Enter the elements of the matrix:"); 16

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


for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}

// Print the original matrix


System.out.println("\nOriginal Matrix:");
printMatrix(matrix);

// Compute the transpose of the matrix


int[][] transpose = computeTranspose(matrix);

// Print the transpose matrix


System.out.println("\nTranspose of Matrix:");
printMatrix(transpose);

scanner.close();
}

// Method to compute the transpose of a matrix


public static int[][] computeTranspose(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;

int[][] transpose = new int[columns][rows];

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


for (int j = 0; j < columns; j++) {
transpose[j][i] = matrix[i][j];
}
}

return transpose;
}
GURU NANAK KHALSA COLLEGE
92

// Method to print a matrix


public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;

17
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT:-

Enter the number of rows in the matrix: 3


Enter the number of columns in the matrix: 3
Enter the elements of the matrix:
897
987
087

Original Matrix:
897
987
087

Transpose of Matrix:
890
988
777
GURU NANAK KHALSA COLLEGE
92

18
Q5) Write a java program to find the addition of two matrices.Accept
matrix from user.

import java.util.Scanner;

public class MatrixAddition {


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

// Input the number of rows and columns for matrices


System.out.print("Enter the number of rows in the matrices: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns in the matrices: ");
int columns = scanner.nextInt();

// Declare the matrices


int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];

// Input elements of the first matrix


System.out.println("Enter the elements of the first matrix:");
inputMatrixElements(scanner, matrix1);

// Input elements of the second matrix


System.out.println("Enter the elements of the second matrix:");
inputMatrixElements(scanner, matrix2);

// Print the original matrices


System.out.println("\nFirst Matrix:");
printMatrix(matrix1);
System.out.println("\nSecond Matrix:");
printMatrix(matrix2);
GURU NANAK KHALSA COLLEGE
92

// Compute the sum of the two matrices


int[][] sum = addMatrices(matrix1, matrix2);

// Print the resultant matrix (sum)


System.out.println("\nSum of the matrices:");

19
printMatrix(sum);

scanner.close();
}

// Method to input elements of a matrix


public static void inputMatrixElements(Scanner scanner, int[][]
matrix) {
int rows = matrix.length;
int columns = matrix[0].length;

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


for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
}

// Method to compute the sum of two matrices


public static int[][] addMatrices(int[][] matrix1, int[][] matrix2) {
int rows = matrix1.length;
int columns = matrix1[0].length;

int[][] sum = new int[rows][columns];

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


for (int j = 0; j < columns; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

return sum;
GURU NANAK KHALSA COLLEGE
92

// Method to print a matrix


public static void printMatrix(int[][] matrix) {
int rows = matrix.length;
int columns = matrix[0].length;

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

20
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT:-

Enter the number of rows in the matrices: 3


Enter the number of columns in the matrices: 2
Enter the elements of the first matrix:
678
965
Enter the elements of the second matrix:
965
098

First Matrix:
67
89
65

Second Matrix:
96
50
GURU NANAK KHALSA COLLEGE
92

98

Sum of the matrices:


15 13
13 9
15 13
PS C:\GargiProject\cscorner>

21
GURU NANAK KHALSA COLLEGE
92

JAVA PRACTICAL 3 (C) (OOP’S)

Aim:- Write the JAVA programs that illustrate the concepts: Class, Constructor
Overloading.

Q1) Write an arithmetic class that includes methods for operations


such as addition,subtraction,multiplication,division, etc and execute
it.

INPUT:-
import java.util.Scanner;
class Arithmetic
{
public String add(double i,double j)
{
return("Addition of "+i+" and "+j+" is"+(i+j));
}
public String sub(double i,double j)
{
return ("Subtraction of "+i+" and "+j+" is" +(i-j));
}
public String mul(double i,double j)
{
return("Multiplication of "+i+" and "+j+" is "+ (i*j));
}
public String div(double i,double j)
{
return("Division of "+i+" and "+j+" is "+(i/j));
}
}
public class Calc
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter no. 1");

22
double i=sc.nextDouble();
GURU NANAK KHALSA COLLEGE
92

System.out.println("Enter no. 2");


double j=sc.nextDouble();
Arithmatic a= new Arithmatic();
System.out.println(a.add(i,j));
System.out.println(a.sub(i,j));
System.out.println(a.mul(i,j));
System.out.println(a.div(i,j));
}
}

OUTPUT:-

Enter no. 1
53
Enter no. 2
50
Addition of 53.0 and 50.0 is103.0
Subtraction of 53.0 and 50.0 is3.0
Multiplication of 53.0 and 50.0 is 2650.0
Division of 53.0 and 50.0 is 1.06

Q2) Write a java program to design a class Area for calculating area of
rectangle. Use the concept of constructor(default and parameterized
constructor).

INPUT:-
import java.util.Scanner;
class Area
{
double l,b;
Area()
{
l=25.3;
b=67;

23
GURU NANAK KHALSA COLLEGE
92

}
Area(double l,double b)
{
this.l=l;
this.b=b;
}
public String calArea()
{
return("Area of rect with len="+l+" and Breadth="+b+" is"+(l*b));
}
}
class TestArea
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter length:");
double i=sc.nextDouble();
System.out.println("Enter breadth:");
double j=sc.nextDouble();
Area a=new Area();
System.out.println("Default Constructor: "+a.calArea());
a=new Area(i,j);
System.out.println("Parameterized Constructor: "+a.calArea());
}
}

OUTPUT:-
Enter length:
10
Enter breadth:
5
Default Constructor: Area of rect with len=25.3 and Breadth=67.0
is1695.1000000000001
Parameterized Constructor: Area of rect with len=10.0 and Breadth=5.0
is50.0
GURU NANAK KHALSA COLLEGE
92

24
Q3) Create a class Vehicle with attributes color, speed and size. Create a subclass
of it say Car with special attributes such as cc and gears. Create a VehicleCheck
class to test its working.

INPUT:-
class Vehicle
{
String color;
int speed;
int size;
Vehicle(String c,int s,int sz)
{
color=c;
speed=s;
size=sz;
}
void printattributes()
{
System.out.println("Color:"+color);
System.out.println("Speed:"+speed);
System.out.println("Size:"+size);
}
}
//Car.java
class Car extends Vehicle
{
int CC;
int gears;
Car(String c,int s,int cc,int g)
{
super(c,s,sz);
CC=cc;
gears=g;
}
void Carattribute()
{
GURU NANAK KHALSA COLLEGE
92

System.out.println("NO of cc"+CC);

25
System.out.println("NO of gears"+gears);
}
}
//VehicleCheck.java
public class VehicleCheck
{
public static void main(String args[])
{
Car c= new Car("blue,200,20,150,5");
c.printattributes();
c.carattribute();
}
}

OUTPUT:-
Color:blue
Speed:200
Size:20
NO of cc150
NO of gears5

Q4) Create a class Animal with few methods in it. Create its child classes such as
Dog and Cat which overrides methods of its parent class. reate an AnimalWorld
class test working program.

INPUT:-
//Animal.java
class Animal
{
public Animal()
{
System.out.println("New animal has been created");
}
GURU NANAK KHALSA COLLEGE
92

26
public void sleep()
{
System.out.println("Animal Sleeps.....");
}
public void eat()
{
System.out.println("Animal is eating.....");
}
}
//Cat.java
class Cat extends Animal
{
public Cat()
{
super();
System.out.println("Cat class is Created");
}
public void sleep()
{
System.out.println("Cat is Sleeping.....");
}
public void meaw()
{
System.out.println("Cat meaws.....");
}
}
//Dog.java
class Dog extends Animal
{
public Dog()
{
super();
System.out.println("Dog class is Created");
}
public void Sleep()
{
System.out.println("Dog is Sleeping.....");
}
GURU NANAK KHALSA COLLEGE
92

public void bark()


{

27
System.out.println("Dog is Barking.....");
}
}
//AnimalWorld.java
public class Animalworld
{
public static void main(String[] args)
{
Cat c=new Cat();
Dog d=new Dog();
c.meaw();
c.eat();
d.bark();
d.eat();

}
}

OUTPUT:-
New animal has been created
Cat class is Created
New animal has been
created Dog class is
Created Cat meaws.....
Animal is eating.....
Dog is Barking.....
Animal is eating.....
GURU NANAK KHALSA COLLEGE
92

PRACTICAL NO:-4 CAT (D) (ABSTRACT AND INTERFACE)

Q1)Aim: Implement concept of abstract class in Java


D1- Write a Java program to create an abstract class Animal with an abstract method
called sound(). Create subclasses Lion and Tiger that extend the Animal class and
implement the sound() method to make a specific sound for each animal.

CODE:-

// Animal.java
abstract class Animal {
public abstract void sound();
}
// Lion.java
class Lion extends Animal {
public void sound() {
System.out.println("Lion roars!");
}
}
// Tiger.java
class Tiger extends Animal {
public void sound() {
System.out.println("Tiger growls");
}
}
// Test.java
public class Test1 {
public static void main(String[] args) {
Animal lion = new Lion();
lion.sound();
Tiger tiger = new Tiger();
tiger.sound();
}
}

OUTPUT:-

Lion roars!

29
Tiger growls
GURU NANAK KHALSA COLLEGE
92

Q2)Write a Java program to create an abstract class BankAccount with abstract methods
deposit() and withdraw(). Create a subclass SavingsAccount that extend the
BankAccount class and implement the respective methods to handle deposits and
withdrawals for each account type.

CODE:-

// BankAccount.java
abstract class BankAccount {
private int accountNumber;
private double balance;

public BankAccount(int a, double b) {


accountNumber = a;
balance =b;
}
public int getAccountNumber() {
return accountNumber;

}
public double getBalance() {
return balance;
}
protected void setBalance(double b) {
balance = b;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}
// SavingsAccount.java
class SavingsAccount extends BankAccount {

public SavingsAccount(int a, double b) {


super(a, b);

30
}
GURU NANAK KHALSA COLLEGE
92

public void deposit(double amount) {


setBalance(getBalance() + amount);
System.out.println("Deposit of RS." + amount + "sucessful. Current
balance:Rs." + getBalance());
}
public void withdraw(double amount) {
if (getBalance() >= amount) {
setBalance(getBalance() - amount) ;
System.out.println("Withdrawal of Rs." + amount + "
successful. Current balance: Rs. " + getBalance());
} else {
System.out.println("Insufficient funds. Withdrawal failed.");

}
}
}
// Main.java
public class Main1{
public static void main(String[] args) {
SavingsAccount sa = new SavingsAccount(1, 1000);
sa.deposit(2000);
sa.withdraw(500);
sa.withdraw(2000);

}
}

OUTPUT:-

Deposit of RS.2000.0 successful. Current balance:Rs.3000.0


Withdrawal of Rs.500.0 successful. Current balance: Rs. 2500.0
Withdrawal of Rs.2000.0 successful. Current balance: Rs. 500.0
GURU NANAK KHALSA COLLEGE
92

31
Q3) Create an interface name like Square, Rectangle, Circle which defines
incomplete methods such as calArea and calCircum. Create class Shapes
which uses all interface for implementing unimplemented method.

CODE:-

interface Circle
{
void area_circle(int r);
void circum_circle(int r);
}
interface Rectangele
{
void area_rect(int l,int b);
void circum_rect(int l,int b);
} interface Square
{
void area_square(int a);
void circum_rect(int l,int b);
} class Shapes implements Circle, Square, Rectangele
{
public void area_circle(int r)
{
double area=Math.PI*Math.sqrt(r);
System.out.println("Area of circle : "+area);

}
public void circum_circle(int r)
{
double circum=6.28*r;
System.out.println("Circumference of circle:"+circum);

}
public void area_square(int a)
{
int area=a*a;
System.out.println("area of square:"+area);
}
GURU NANAK KHALSA COLLEGE
92

32
public void circum_square(int a)
{
int circum=4*a;
System.out.println("Circumference of square:"+circum);

}
public void circum_rect(int l, int b)
{
int circum=2*(l+b);
System.out.println("Circumference of rectangle:"+circum);
}
public void area_rect(int l, int b)
{
int area=l*b;
System.out.println("Area of rectangle:"+area);
}
}
class Shapetest
{
public static void main(String args[])
{
Shapes sh=new Shapes();
sh.area_circle(3);
sh.circum_square(3);
sh.area_square(4);
sh.circum_square(4);
sh.area_rect(10,20);
sh.circum_rect(10,20);
}
}
GURU NANAK KHALSA COLLEGE
92

OUTPUT:-

33
Area of circle : 5.441398092702653
Circumference of square:12
area of square:16
Circumference of square:16
Area of rectangle:200
Circumference of rectangle:60
GURU NANAK KHALSA COLLEGE
92

JAVA GUI CAT :-5(E)(GUI BASED)

Q1) Write a program which takes name and age from the user on click of the
button and display a message on label, user is eligible to vote or not.

35
GURU NANAK KHALSA COLLEGE
92

36
GURU NANAK KHALSA COLLEGE
92

37
GURU NANAK KHALSA COLLEGE
92

Q2) Write a program to create two textfield and four radio buttons
(+,-,*,%)and on selecting the radiobutton the operation should be performed
and the result should be displayed in JOptionPane.

38
GURU NANAK KHALSA COLLEGE
92

input();
JOptionPane.showMessageDialog(rdbtnMul, “Multiplication is “+(n1*n2));

input();
JOptionPane.showMessageDialog(rdbtnDiv, “Division is “+(n1/n2)); 39
GURU NANAK KHALSA COLLEGE
92

40
GURU NANAK KHALSA COLLEGE
92

Q3) Write a program that creates a list containing ice-cream flavours. On


selection of any flavour price should be displayed in text field

41
GURU NANAK KHALSA COLLEGE
92

42
GURU NANAK KHALSA COLLEGE
92

43
GURU NANAK KHALSA COLLEGE
92

Q4) Write a program to create a Combobox, textfield and button and on


click of button the value of textfield should be added to combobox.

44
GURU NANAK KHALSA COLLEGE
92

Q5)Create an application where user can place order for pizza. Accept
user-name, address, mobile- no from user. Give options for 4 types of pizza
(basic, thick & chewy, thin & crispy, Chicago deep dish). Also provide options
for multiple toppings (Pepperoni, sausage, black olives, and mushrooms).
Confirm the order by displaying all the details in a JOptionPane.

46
GURU NANAK KHALSA COLLEGE
92

47
GURU NANAK KHALSA COLLEGE
92

48
GURU NANAK KHALSA COLLEGE
92

49

50
GURU NANAK KHALSA COLLEGE
92

JAVA PRACTICAL NO:-6(F) (NETWORKING)

A)import java.io.*;
import java.net.*;
import java.util.Scanner;
class ClientDemoNo
{
public static void main(String a[]) throws IOException
{
Socket s=new Socket("127.0.0.1",5678);
System.out.println("enter any no:");
Scanner sc=new Scanner(System.in);
String no=sc.nextLine();
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(no);
Scanner sc1=new Scanner (s.getInputStream());
String msg=sc1.nextLine();
System.out.println(msg);
ps.flush();
s.close();
}
}

B)import java.util.Scanner;
import java.net.*;
import java.io.*;
class ServerDemoNo
{
public static void main(String a[]) throws IOException
{
Socket s;
ServerSocket ss=new ServerSocket(5678);
while(true)
{
s=ss.accept();
System.out.println("connection Established");
Scanner sc=new Scanner (s.getInputStream());
String msg=sc.nextLine();
int n=Integer.parseInt(msg);
PrintStream ps=new PrintStream(s.getOutputStream());
String st;
if(n<0)
{
st=n+" is -ve";
ps.println(st);
GURU NANAK KHALSA COLLEGE
92

}
else if(n>0)
{
st=n+" is +ve";
ps.println(st);
}
else
ps.println("zero");
s.close();
}}}

OUTPUT
on first cmd

on second cmd
GURU NANAK KHALSA COLLEGE
92

53

You might also like