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

Java Programming Lab Exercises

java

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 PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views39 pages

Java Programming Lab Exercises

java

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 PDF, TXT or read online on Scribd

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[]){

[Link]("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;
[Link]("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 [Link].*;
public class prime{
public static void main(String args[]){
Scanner ab=new Scanner([Link]);
[Link](" Enter any number");
int n=[Link]();
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){

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

[Link]("enter for the operation");


[Link]("1 for addition");
[Link]("2 for Subraction");
[Link]("3 for Multiplication");
[Link]("4 for Division");
int choice= [Link]();
int result=0;
boolean operation=true;

switch (choice) {
case 1:
int add=a+b;
[Link]("the sum is\t"+add);
break;

case 2:
int sub=a-b;
[Link]("the subraction is"+sub);
break;
case 3:
int mul=a*b;
[Link]("the multipication is"+mul);
break;
case 4:
int div=a/b;
[Link]("the division is"+div);
break;
default:

[Link]("Please enter the correct number");


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

Scanner scanner = new Scanner([Link]);

[Link]("Enter the first number: ");


int num1 = [Link]();
[Link]("Enter the second number: ");
int num2 = [Link]();
[Link]("Enter the third number: ");
int num3 = [Link]();

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

[Link]("The maximum of the three numbers is: " + max);

[Link]();
}
}

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 [Link].*;
public class text{
public static void main(String args[]){
Scanner ab=new Scanner([Link]);
[Link]("Enter any string\n");
String str=[Link]();
[Link]();
int v_count=0,c_count=0;
for(int i=0;i<[Link]();i++){
char ch=[Link](i);
if(ch=='a'|| ch=='e'||ch=='i'|| ch=='o'|| ch=='u'){ v_count++;
}
else{ c_count++;
}
}
[Link]("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--){
[Link](" ");
}
for(int j=0;j<i; j++){
[Link]([Link](j)+" ");
}
[Link]();
}
}
}
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);

[Link]("The largest number in the array is: " + largest);


}

public static int findLargest(int[] array) {


int max = array[0];

for (int i = 1; i < [Link]; 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 [Link];

public class MatrixOperations {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of rows for matrices: ");


int rows = [Link]();
[Link]("Enter the number of columns for matrices: ");
int cols = [Link]();

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


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

[Link]("Enter elements of matrix A:");


inputMatrix(scanner, matrixA);

[Link]("Enter elements of matrix B:");


inputMatrix(scanner, matrixB);

addMatrices(matrixA, matrixB, resultAddition);


[Link]("Matrix A + Matrix B:");
printMatrix(resultAddition);

multiplyMatrices(matrixA, matrixB, resultMultiplication);


[Link]("Matrix A * Matrix B:");
printMatrix(resultMultiplication);

[Link]();
}

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


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

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


for (int i = 0; i < [Link]; 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 = [Link];
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 < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
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);
[Link]("Distance 1: " + [Link]());
[Link]("Distance 2: " + [Link]());
}
}

class Distance {
private int feet;
private int inches;

public Distance(int feet, int inches) {


[Link] = feet;
[Link] = inches;
}
public void setDistance(int feet, int inches) {
[Link] = feet;
[Link] = 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 [Link].*;
class Distance{
public static void main(String args[]){ Dist d1=new Dist(6,9);
[Link]();
Dist d2=new Dist(); [Link]();
[Link](); Dist d3=d2;
[Link]();
[Link]=4;
[Link]();
}
}

class Dist{
int feet,inch; Dist(){
feet=9; inch=4;
}
Dist(int a,int b){ [Link]=a;
[Link]=b;
}
public void display(){
[Link](" 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();[Link]="NP";
[Link]([Link]);
[Link](123);
[Link]([Link]);
}
}
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){
[Link]=a;
[Link]=b;
[Link]([Link]);
[Link]([Link]);
}
}
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(){
[Link]("deafult non paramterized ");
}
Student(String name){ [Link]=name;
[Link]([Link]);
}
Student(String name,int no){ [Link]=name;
[Link]=no;
[Link]([Link]); [Link]([Link]);
}
Student(Student s2){ [Link]=[Link]; [Link]=[Link];
[Link]("for s4 : "+[Link]+" "+[Link]);
}
}
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 [Link].*;
public class Inheritanceexample{
public static void main(String[] args) {
[Link]("Single Inheritance:");
Dog myDog = new Dog();
[Link]();
[Link]();
[Link]("\nMultilevel Inheritance:");
Mammal myDogInMultilevel = new Mammal();
[Link]();
[Link]();
[Link]("\nHierarchical Inheritance:");
Car myCar = new Car();
[Link]();
[Link]();
Bike myBike = new Bike();
[Link]();
[Link]();
}
}
class Animal {
public void eat() {
[Link]("This animal eats food.");
}
}
class Dog extends Animal {
public void bark() {
[Link]("The dog barks.");
}
}
class Mammal extends Animal{
public void breathe() {
[Link]("This mammal breathes air.");
}
}
class Vehicle {
public void start() {
[Link]("The vehicle starts.");
}
}
class Car extends Vehicle {
public void drive() {
[Link]("The car is driving.");
}
}
class Bike extends Vehicle {
public void ride() {
[Link]("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();

[Link]();
[Link]();

[Link]();
[Link]();

[Link](); [Link]();
}

class Student {
void displayInfo() {
[Link]("This is a student.");
}
}
class MathStudent extends Student { void displayMathMarks() {
[Link]("Math Student marks: 85");

}
}
class ScienceStudent extends Student { void displayScienceMarks() {
[Link]("Science Student marks: 90");
}
}
class ArtStudent extends Student { void displayArtMarks() {
[Link]("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()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
[Link]("weeping...");
}
}
class Polymorphism
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}}
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();

[Link]([Link]("pit", "tip")); // Output: true


[Link]([Link]("hello", "llohe")); // Output: true
[Link]([Link]("abc", "bca")); // Output: true
[Link]([Link]("abc", "cab")); // Output: true
[Link]([Link]("abcd", "dabc")); // Output: true
[Link]([Link]("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 ([Link]() != [Link]()) {
return false;
}

// Check if s2 is a rotation of s1
int n = [Link]();
for (int i = 0; i < n; i++) {
// Create a rotated version of s1
String rotated = [Link](i) + [Link](0, i);
if ([Link](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);

[Link]([Link]());
[Link]([Link]());
[Link]([Link]());

}
}

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()
{
[Link]("Area of Triangle is ");
return (dim1*dim2)/2;
}
}
class Rectangle extends Shape
{
Rectangle(float d1, float d2)
{
dim1=d1;
dim2=d2;
}
float area()
{
[Link]("Area of Rectangle is ");
return dim1*dim2;
}
}
class Circle extends Shape
{
Circle(float d1)
{
radius=d1;
}
float area()
{
[Link]("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);

[Link]("Manager Information:");
[Link]();
[Link]();

[Link]("Programmer Information:");
[Link]();
}
}

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) {


[Link] = baseSalary;
[Link] = bonus;
}

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

public Programmer(double baseSalary, int numberOfProjects) {


[Link] = baseSalary;
[Link] = numberOfProjects;
}

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

void displayInfo() {
[Link]("Programmer's Salary: " + calculateSalary());
[Link]("Base Salary: " + baseSalary);
[Link]("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);

[Link]("Rectangle Area: " + [Link]());


[Link]("Circle Area: " + [Link]());
[Link]("Triangle Area: " + [Link]());
}
}

interface Shape {
double getArea();
}

class Rectangle implements Shape {


private double width;
private double height;

public Rectangle(double width, double height) {


[Link] = width;
[Link] = height;
}

public double getArea() {


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

public Circle(double radius) {


[Link] = radius;
}

public double getArea() {


return [Link] * radius * radius;
}
}

class Triangle implements Shape {


private double base;
private double height;

public Triangle(double base, double height) {


[Link] = base;
[Link] = height;
}

public double getArea() {


return 0.5 * base * height;
}
}

OUTPUT

Common questions

Powered by AI

Method overriding allows a subclass to provide a specific implementation for a method already defined in its superclass, supporting dynamic polymorphism. In the example of Java inheritance, the method eat() is defined in Animal but overridden in Dog and BabyDog, each providing a particular behavior. At runtime, the method that gets executed depends on the object type, facilitating dynamic method invocation and allowing for more flexible and reusable code design .

Access specifiers in Java (public, private, protected) control the visibility of class members, enhancing program security and data integrity by limiting unauthorized access. In the bank account example, the idname is public, whereas password is private, preventing direct access from outside the class. By using access specifiers, sensitive data such as passwords remain protected, and encapsulation is strengthened, forcing controlled access through public methods like changepassword(), demonstrating good practice in secure coding .

The 'this' keyword in Java is used within a constructor to call another constructor within the same class. It helps to reduce code duplication and manages object initialization efficiently by allowing constructors to delegate new object instantiation tasks to other constructors. In the provided example, the default constructor uses 'this(91,8.7);' to invoke an overloaded constructor, passing parameters for initialization .

Matrix operations in Java, such as addition and multiplication, are significant as they form the basis for computations in various fields like computer graphics, simulations, and scientific computations. The implementation involves iterating over elements in matrices and applying arithmetic operations per element or based on mathematical rules. Using nested loops and systematic indexing, as demonstrated in the sources, ensures accurate calculations. Such operations highlight computational efficiency and accuracy essential for handling mathematical problems programmatically .

Inheritance in the provided Java examples is demonstrated via single inheritance, multilevel inheritance, and hierarchical inheritance. Single inheritance is shown when the class Dog extends Animal, allowing Dog to inherit methods like eat(). Multilevel inheritance is explained when the class Mammal extends Animal. Hierarchical inheritance is visible where Vehicle is a superclass with Car and Bike as subclasses. These inheritance types allow code reuse, polymorphism, and a structured hierarchy of the object design .

Abstract classes and interfaces play a crucial role in polymorphism and code organization. Abstract classes, like Shape with subclasses Triangle, Rectangle, and Circle, define a common template with possibly shared code while requiring specific method implementations in subclasses. Interfaces, like Shape with method getArea(), allow classes such as Rectangle, Circle, and Triangle to adhere to a strict contract for behavior, promoting polymorphic design. Together, these constructs enable flexibility and reuse by decoupling interface from implementation, allowing objects to be manipulated uniformly .

Encapsulation is implemented in the "distance" class through the use of private fields for feet and inches, and public methods for accessing and modifying these fields. The class design encapsulates the data by providing a constructor to initialize these fields and methods like setDistance() and getDistance() to modify and access the data, respectively, ensuring that the access to these fields is controlled and can be validated within the class itself .

Abstract methods in Java enforce a design contract by requiring subclasses to provide specific functionality that is defined at a high level in the abstract class. In the Employee class structure, the abstract methods calculateSalary() and displayInfo() do not have implementations, mandating subclasses like Manager and Programmer to define these for their specific contexts. This enforces consistency and ensures that all subclasses adhere to the intended use, providing clarity and enforcing a structured hierarchy that aligns with the expectations of handling employee-related operations .

Constructor overloading in Java allows a class to have more than one constructor with different sets of parameters, providing multiple methods of initializing an object with different data. In the examples, the overloaded constructor feature is used in the class XYZ, which has a default constructor and an overloaded constructor that accepts parameters. This flexibility supports object instantiation with default or specific initial conditions, enhancing code usability and robustness .

Challenges in implementing a string rotation checker include handling edge cases where strings have different lengths, dealing with empty strings, or inefficient string concatenation leading to high time complexity. The example provided efficiently handles rotations by checking if concatenating the string to itself contains the target rotation, using substring checks for rotation validation, which offers an O(n) complexity solution. This method overcomes inefficiencies by ensuring that comparisons only occur if string lengths match, streamlining the process .

You might also like