0% found this document useful (0 votes)
22 views39 pages

23BCP420 Java Practical File

java

Uploaded by

mallasagar8080
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
22 views39 pages

23BCP420 Java Practical File

java

Uploaded by

mallasagar8080
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

PANDIT DEENDAYAL ENERGY UNIVERSITY

Raisan,Gandhinagar-382426,Gujarat,India

JAVA LAB

Name: Sagar Thapa

Roll Number: 23BCP420


Division: 6
Batch: G12
Subject: Java
Subject Code: 23CP201P
LAB-1

1. Write a program to print ―CODING IS FUN, ENJOY IT!

class first {

public static void main(String args[]){

System.out.println("CODING IS FUN, ENJOY IT!");

}}OUTPUT
2. Write a Java program to print the sum of two numbers.
public class lab2b{
public static void main(String[] args){
int a=10,b=20;
int c=a+b;
System.out.println("the sum is "+c);
}
}

OUTPUT
LAB-2

1. 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?

import java.util.*;
public class prime{
public static void main(String args[]){
Scanner ab=new Scanner(System.in);
System.out.print(" Enter any number");
int n=sc.nextInt();
int j=2; int i=1;
while(i<=n){
int count=0;
for(int k=1; k<=j;k++){
if(j%k==0){
count++;
}
}
if(count==2){

System.out.println(j);
i++;}
j++;
}
}
}
OUTPUT
2. Write a program to enter two numbers and perform mathematical operations
on them.
import java.util.*;
class operation{
public static void main(String[] args){
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the first number");
int a= scanner.nextInt();
System.out.println("Enter the second number");
int b= scanner.nextInt();

System.out.println("enter for the operation");


System.out.println("1 for addition");
System.out.println("2 for Subraction");
System.out.println("3 for Multiplication");
System.out.println("4 for Division");
int choice= scanner.nextInt();
int result=0;
boolean operation=true;

switch (choice) {
case 1:
int add=a+b;
System.out.println("the sum is\t"+add);
break;

case 2:
int sub=a-b;
System.out.println("the subraction is"+sub);
break;
case 3:
int mul=a*b;
System.out.println("the multipication is"+mul);
break;
case 4:
int div=a/b;
System.out.println("the division is"+div);
break;
default:

System.out.println("Please enter the correct number");


operation=false;
break;
}
if(operation=true){
System.out.println("Operation is successfully completed!");
}
}
}
OUTPUT
3. Write a program in Java to find maximum of three numbers using conditional
operator.
import java.util.Scanner;
public class MaxOfThree {
public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();

int max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ?
num2 : num3);

System.out.println("The maximum of the three numbers is: " + max);

scanner.close();
}
}

OUTPUT
4. 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.

import java.util.*;
public class text{
public static void main(String args[]){
Scanner ab=new Scanner(System.in);
System.out.print("Enter any string\n");
String str=ab.next();
str.toLowerCase();
int v_count=0,c_count=0;
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if(ch=='a'|| ch=='e'||ch=='i'|| ch=='o'|| ch=='u'){ v_count++;
}
else{ c_count++;
}
}
System.out.println("vowels = " +v_count+" and consonats = "+c_count);
}
}

OUTPUT
5. Write an interactive program to print a string entered in a pyramid form.
For instance, the string “stream” has to be displayed as follows:
S
S t
Str
Stre
S t r e am

public class stream{


public static void main(String args[]){
String str="Stream";
for(int i=1;i<=6 ;i++){
for(int j=6;j>i;j--){
System.out.print(" ");
}
for(int j=0;j<i; j++){
System.out.print(str.charAt(j)+" ");
}
System.out.println();
}
}
}
OUTPUT
6. Java Program to Find Largest Number in an array.

public class LargestNumberInArray {

public static void main(String[] args) {

int[] numbers = {10, 20, 4, 45, 99, 73, 34};

int largest = findLargest(numbers);

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


}

public static int findLargest(int[] array) {


int max = array[0];

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


if (array[i] > max) {
max = array[i];
}
}

return max;
}
}
OUTPUT
7. Write a java program to perform addition and multiplication of Two
Matrices.

import java.util.Scanner;

public class MatrixOperations {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows for matrices: ");


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

int[][] matrixA = new int[rows][cols];


int[][] matrixB = new int[rows][cols];
int[][] resultAddition = new int[rows][cols];
int[][] resultMultiplication = new int[rows][cols];

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


inputMatrix(scanner, matrixA);

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


inputMatrix(scanner, matrixB);

addMatrices(matrixA, matrixB, resultAddition);


System.out.println("Matrix A + Matrix B:");
printMatrix(resultAddition);

multiplyMatrices(matrixA, matrixB, resultMultiplication);


System.out.println("Matrix A * Matrix B:");
printMatrix(resultMultiplication);

scanner.close();
}

public static void inputMatrix(Scanner scanner, int[][] matrix) {


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

public static void addMatrices(int[][] A, int[][] B, int[][] result) {


for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[i].length; j++) {
result[i][j] = A[i][j] + B[i][j];
}
}
}

public static void multiplyMatrices(int[][] A, int[][] B, int[][] result) {


int rowsA = A.length;
int colsA = A[0].length;
int colsB = B[0].length;

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


for (int j = 0; j < colsB; j++) {
result[i][j] = 0; // Initialize the result cell
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
}

public static void printMatrix(int[][] matrix) {


for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
OUTPUT
LAB-3
Class and Objects: study and implement classes based application
using Java

1. 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.

//23BCP420

public class Main {


public static void main(String[] args) {
Distance distance1 = new Distance(5, 10);
Distance distance2 = new Distance(3, 8);
System.out.println("Distance 1: " + distance1.getDistance());
System.out.println("Distance 2: " + distance2.getDistance());
}
}

class Distance {
private int feet;
private int inches;

public Distance(int feet, int inches) {


this.feet = feet;
this.inches = inches;
}
public void setDistance(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}

public String getDistance() {


return feet + " feet " + inches + " inches";
}
}OUTPUT
2. 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.

//23BCP420
import java.util.*;
class Distance{
public static void main(String args[]){ Dist d1=new Dist(6,9);
d1.display();
Dist d2=new Dist(); d2.display();
System.out.println(); Dist d3=d2;
d3.display();
d2.inch=4;
d3.display();
}
}

class Dist{
int feet,inch; Dist(){
feet=9; inch=4;
}
Dist(int a,int b){ this.feet=a;
this.inch=b;
}
public void display(){
System.out.println(" Distance in inch and feet is "+inch+ " and "+feet);
}
}

OUTPUT
3. 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.

public class lab3c {


public static void main(String[] args)
{ bankaccount myid=new
bankaccount();myid.idname="NP";
System.out.println(myid.idname);
myid.changepassword(123);
System.out.println(myid.password);
}
}
class
bankaccount{ public
String idname; private
int password=9;
void changepassword(int
newpass){password=newpass;
}
}

// here password is of private type so we cant access it in main method

OUTPUT
// after changing password to public type

OUTPUT
4. 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.

public class STD{


public static void main(String args[]){
XYZ x= new XYZ();
}
}
class XYZ{
int marks;
double Cgpa;
XYZ(){
this(91,8.7);
}
XYZ(int a ,double b){
this.marks=a;
this.Cgpa=b;
System.out.println(this.marks);
System.out.println(this.Cgpa);
}
}
OUTPUT
6. 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.

public class CPY{


public static void main(String[] args) { Student s1= new Student();
Student s2= new Student("P");
Student s3= new Student("GENZ",18); Student s4=new Student(s2);
}
}

class Student{ int no;


String name;
Student(){
System.out.println("deafult non paramterized ");
}
Student(String name){ this.name=name;
System.out.println(this.name);
}
Student(String name,int no){ this.name=name;
this.no=no;
System.out.println(this.name); System.out.println(this.no);
}
Student(Student s2){ this.name=s2.name; this.no=s2.no;
System.out.println("for s4 : "+this.name+" "+this.no);
}
}
OUTPUT
LAB-4

Inheritance: study and implement various types of inheritance in Java.


1. Write a program in Java to demonstrate single inheritance, multilevel
inheritance and hierarchical inheritance.
import java.util.*;
public class Inheritanceexample{
public static void main(String[] args) {
System.out.println("Single Inheritance:");
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
System.out.println("\nMultilevel Inheritance:");
Mammal myDogInMultilevel = new Mammal();
myDogInMultilevel.eat();
myDogInMultilevel.breathe();
System.out.println("\nHierarchical Inheritance:");
Car myCar = new Car();
myCar.start();
myCar.drive();
Bike myBike = new Bike();
myBike.start();
myBike.ride();
}
}
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
class Mammal extends Animal{
public void breathe() {
System.out.println("This mammal breathes air.");
}
}
class Vehicle {
public void start() {
System.out.println("The vehicle starts.");
}
}
class Car extends Vehicle {
public void drive() {
System.out.println("The car is driving.");
}
}
class Bike extends Vehicle {
public void ride() {
System.out.println("The bike is being ridden.");
}
}
OUTPUT
2. 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.
public class Detail{
public static void main(String[] args) {

MathStudent mathStudent = new MathStudent(); ScienceStudent scienceStudent =


new ScienceStudent(); ArtStudent artStudent = new ArtStudent();

mathStudent.displayInfo();
mathStudent.displayMathMarks();

scienceStudent.displayInfo();
scienceStudent.displayScienceMarks();

artStudent.displayInfo(); artStudent.displayArtMarks();
}

class Student {
void displayInfo() {
System.out.println("This is a student.");
}
}
class MathStudent extends Student { void displayMathMarks() {
System.out.println("Math Student marks: 85");

}
}
class ScienceStudent extends Student { void displayScienceMarks() {
System.out.println("Science Student marks: 90");
}
}
class ArtStudent extends Student { void displayArtMarks() {
System.out.println("Art Student marks: 75");
}

}OUTPUT
LAB 5

5. Polymorphism: study and implement various types of


Polymorphism in java. i. Write a program that implements simple
example of Runtime Polymorphism with multilevel inheritance. (e.g.,
Animal or Shape)

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class Polymorphism
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
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.

public class Rotate {

public static void main(String[] args) {

StringRotationChecker checker = new StringRotationChecker();

System.out.println(checker.isRotation("pit", "tip")); // Output: true


System.out.println(checker.isRotation("hello", "llohe")); // Output: true
System.out.println(checker.isRotation("abc", "bca")); // Output: true
System.out.println(checker.isRotation("abc", "cab")); // Output: true
System.out.println(checker.isRotation("abcd", "dabc")); // Output: true
System.out.println(checker.isRotation("abcd", "acbd")); // Output: false
}
}

public class StringRotationChecker {

// Method to check if s2 is a rotation of s1


public boolean isRotation(String s1, String s2) {
// Check if lengths are equal
if (s1.length() != s2.length()) {
return false;
}

// Check if s2 is a rotation of s1
int n = s1.length();
for (int i = 0; i < n; i++) {
// Create a rotated version of s1
String rotated = s1.substring(i) + s1.substring(0, i);
if (rotated.equals(s2)) {
return true;
}
}

return false;
}
}
OUTPUT
LAB 6
6. Study and implement Abstract class and Interfaces in Java 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.

class AbstractClassEx
{
public static void main(String arg[])
{
Triangle t=new Triangle(4.3f,5.3f);
Rectangle r=new Rectangle(2.4f,4.2f);
Circle c=new Circle(10.5f);

System.out.println(t.area());
System.out.println(r.area());
System.out.println(c.area());

}
}

abstract class Shape


{
float dim1,dim2,radius;
abstract float area();
}
class Triangle extends Shape
{
Triangle(float d1, float d2)
{
dim1=d1;
dim2=d2;
}
float area()
{
System.out.println("Area of Triangle is ");
return (dim1*dim2)/2;
}
}
class Rectangle extends Shape
{
Rectangle(float d1, float d2)
{
dim1=d1;
dim2=d2;
}
float area()
{
System.out.println("Area of Rectangle is ");
return dim1*dim2;
}
}
class Circle extends Shape
{
Circle(float d1)
{
radius=d1;
}
float area()
{
System.out.println("Area of Circle is ");
return 3.14f*radius*radius;
}
}

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.
public class Company{
public static void main(String[] args) {

Employee manager = new Manager(5000, 2000);


Employee programmer = new Programmer(4000, 3);

System.out.println("Manager Information:");
manager.displayInfo();
System.out.println();

System.out.println("Programmer Information:");
programmer.displayInfo();
}
}

abstract class Employee {


abstract double calculateSalary();
abstract void displayInfo();
}
class Manager extends Employee {
private double baseSalary;
private double bonus;

public Manager(double baseSalary, double bonus) {


this.baseSalary = baseSalary;
this.bonus = bonus;
}

double calculateSalary() {
return baseSalary + bonus;
}
void displayInfo() {
System.out.println("Manager's Salary: " + calculateSalary());
System.out.println("Base Salary: " + baseSalary);
System.out.println("Bonus: " + bonus);
}
}class Programmer extends Employee {
private double baseSalary;
private int numberOfProjects;

public Programmer(double baseSalary, int numberOfProjects) {


this.baseSalary = baseSalary;
this.numberOfProjects = numberOfProjects;
}

double calculateSalary() {
return baseSalary + (numberOfProjects * 1000);
}

void displayInfo() {
System.out.println("Programmer's Salary: " + calculateSalary());
System.out.println("Base Salary: " + baseSalary);
System.out.println("Number of Projects: " + numberOfProjects);
}
}

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.

public class Shapes{


public static void main(String[] args) {

Shape rectangle = new Rectangle(5.0, 3.0);


Shape circle = new Circle(4.0);
Shape triangle = new Triangle(6.0, 2.5);

System.out.println("Rectangle Area: " + rectangle.getArea());


System.out.println("Circle Area: " + circle.getArea());
System.out.println("Triangle Area: " + triangle.getArea());
}
}

interface Shape {
double getArea();
}

class Rectangle implements Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


this.width = width;
this.height = height;
}

public double getArea() {


return width * height;
}
}
class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

public double getArea() {


return Math.PI * radius * radius;
}
}

class Triangle implements Shape {


private double base;
private double height;

public Triangle(double base, double height) {


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

public double getArea() {


return 0.5 * base * height;
}
}

OUTPUT

You might also like