0% found this document useful (0 votes)
6 views15 pages

Java Lab Assignments for B.Tech Students

ouioiu

Uploaded by

lucifergamlng2k1
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)
6 views15 pages

Java Lab Assignments for B.Tech Students

ouioiu

Uploaded by

lucifergamlng2k1
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

Manish Saini

Sainimk4735@[Link]

Java Lab Assignments for [Link]. 4th sem.


CS(CA1,CA2,CB1)

[Link] to print “Hello World”.

class Hello
{
public static void main(String args[])
{
[Link]("Hello world!");
}
}

output:
Hello world!

[Link] that takes five integer numbers from command line arguments and
print their sum.

public class Addition


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

if([Link]!=5)
{
[Link]("please provide exectly 5 integer as
command line arugment:");

return;
}
int sum=0;

for(String arg:args)
{
sum+=[Link](arg);
}

[Link]("sum="+sum);
}

output:

please provide exectly 5 integer as command line arugment:1 2 3 4 5


sum=15

[Link] that input three floating point numbers and print maximum among
them.(Use
Scanner class)

import [Link];
class Maximum
{
public static void main(String args[])
{
Scanner s=new Scanner([Link]);

float a,b,c;

[Link]("enter a three numbers");

a=[Link]();
b=[Link]();
c=[Link]();

if(a>b && a>c)


{
[Link]("a is maximum:"+a);
}
else if(b>a && b>c)
{
[Link]("b is maximum:"+b);
}
else
{
[Link]("c is maximum:"+c);
}
}
}

output:
enter a three numbers
1.1
1.2
1.3
c is maximum:1.3

[Link] a menu driven program to perform the following operations on an


array of 10 integer
elements1. Display 2. Searching 3. Sorting 4. Reverse 5. Find maximum

import [Link];
import [Link].*;
class Menudrivenprogram
{
public static void main(String[] args)
{
Scanner s=new Scanner([Link]);
int choice,i;
[Link]("Enter 1 to Display");
[Link]("Enter 2 to Searching");
[Link]("Enter 3 to Sorting");
[Link]("Enter 4 to Reverse");
[Link]("Enter 5 to maximum");
[Link]("Enter 6 to exit");
while(true)
{
int arr[]={2,4,7,9,5,6,10,1,8,3};
choice=[Link]([Link]("enter
your choice"));
switch(choice)
{
case 1:
[Link]("Display Array numbers");
for(i=0;i<[Link];i++)
{
[Link](arr[i]);
}
break;

case 2:
int value,loc=-1;

[Link]("Enter a value to be search");


value=[Link]();
for(i=0;i<[Link];i++)
{
if(arr[i]==value)
{
loc=i+1;
break;
}
}
if(loc==-1)
{
[Link]("Element is not Found");
}
else
{
[Link]("Element found at:"+loc);
}
break;

case 3:
int j;
for(i=0;i<=8;i++)
{
for(j=i+1;j<=9;j++)
{
if(arr[i]>arr[j])
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

[Link]("After the
sorting");
for(i=0;i<=9;i++)
{
[Link](arr[i]);
}
break;

case 4:
for(i=0;i<=8;i++)
{
for(j=i+1;j<=9;j++)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}

[Link]("After the rivers");


for(i=0;i<=9;i++)
{
[Link](arr[i]);
}
break;
case 5:
int max=0;
for(i=0;i<[Link];i++)
{
if(i==0)
{
max=arr[i];
}
else if(arr[i]>max)
{
max=arr[i];
}
}
[Link]("The maximum number is
:"+max);
break;
case 6:
[Link]("exit the program");
[Link]();
break;

default:
[Link]("Invalid choice");
}
}
}

output:
Enter 1 to Display
Enter 2 to Searching
Enter 3 to Sorting
Enter 4 to Reverse
Enter 5 to maximum
Enter 6 to exit
Enter your choice:1
Display Array numbers
2
4
7
9
5
6
10
1
8
3
Enter your choice:2
Enter a value to be search
5
Element found at:5
Enter your choice:3
After the sorting
1
2
3
4
5
6
7
8
9
10
Enter your choice:4
After the rivers
3
8
1
10
6
5
9
7
4
2
Enter your choice:5
The maximum number is :10
Enter your choice:6
exit the program

[Link] to create a two dimensional Zig-Zag array that store all prime
numbers from 1 to 100
in such way that prime numbers from 1 to 10 in first row, 11 to 20 in
second row and so
on. Print the final array.

import [Link].*;

class ZigzagPrimeArray
{

public static boolean isPrime(int n) {


if (n < 2) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);

List<Integer> primeNumbers = new ArrayList<>();


for (int num = 1; num <= 100; num++) {
if (isPrime(num)) {
[Link](num);
}
}
[Link]("Enter the number of rows: ");
int rows = [Link]();
[Link]();

int cols = 10;


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

int index = 0;
for (int i = 0; i < rows; i++) {
if (i % 2 == 0) {
for (int j = 0; j < cols; j++) {
if (index < [Link]() &&
[Link](index) <= (i + 1) * 10) {
zigzagArray[i][j] = [Link](index++);
} else {
zigzagArray[i][j] = 0; // Fill empty spaces with
0
}
}
} else {
for (int j = cols - 1; j >= 0; j--) {
if (index < [Link]() &&
[Link](index) <= (i + 1) * 10) {
zigzagArray[i][j] = [Link](index++);
} else {
zigzagArray[i][j] = 0;
}
}
}
}

for (int[] row : zigzagArray) {


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

output:
Zig-Zag Prime Number Array:
2 3 5 7
11 13 17 19
23 29
31 37
41 43 47
53 59
61 67
71 73 79
83 89
97

[Link] to create a class “Account” consist of account holder’s name,


account no. and
balance. A parameterized constructor, methods to deposit some amount and
to display the
details. Test your class for two accounts.

class Account
{
private String holderName;
private int accountNumber;
private double balance;

public Assignment6(String hn, int an, double b) {


holderName=hn;
accountNumber=an;
balance=b;
}

public void deposit(double amount) {


balance=amount+balance;
[Link](holderName + " deposited: " + amount);
}

public void display() {


[Link]("Account Holder name: " + holderName);
[Link]("Account Number: " + accountNumber);
[Link]("Balance: " + balance);
}
}

class Demo
{
public static void main(String[] args)
{
Account ass1 = new Account("manish", 101, 5000);
Account ass2 = new Account("pawan", 102, 3000);

[Link](2000);
[Link](1500);
[Link]();
[Link]();
[Link]();
[Link]();
}

output:
manish deposited: 2000.0
pawan deposited: 1500.0

Account Holder name: manish


Account Number: 101
Balance: 7000.0

Account Holder name: pawan


Account Number: 102
Balance: 4500.0

[Link] to create a class “Person”, consist of name and age and print the
record of elder one
using this reference.

class Person
{
private String name;
private int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}

public void display() {


[Link]("Name: " + name + ", Age: " + age);
}

public int getAge() {


return age;
}
}
public class Maximumage

public static void main(String[] args)


{
Person person1 = new Person("manish", 25);
Person person2 = new Person("Buddy", 30);
[Link]();
[Link]();

[Link]("Elder Person:");
if ([Link]() > [Link]())
{
[Link]();
}
else if ([Link]() < [Link]())
{
[Link]();
}
}
}

output:
Name: manish, Age: 25
Name: Buddy, Age: 30
Elder Person:
Name: Buddy, Age: 30

[Link] to create a class "Student" consist of name, rollno and percentage


and methods for
I/O. Enter the records of ten students and print them rank wise.(Use
array of objects)

import [Link];
import [Link];

class Student
{
private String name;
private int rollNo;
private double percentage;

public Student(String name, int rollNo, double percentage) {


[Link] = name;
[Link] = rollNo;
[Link] = percentage;
}

public double getPercentage() {


return percentage;
}

public void display(int rank) {


[Link]("Rank: " + rank + ", Name: " + name + ", Roll
No: " + rollNo + ", Percentage: " + percentage);
}
}
public class Studenttest
{

public static void main(String[] args)


{
Scanner scanner = new Scanner([Link]);
Student[] students = new Student[10];

for (int i = 0; i < 10; i++)


{
[Link]("Enter details for student " + (i + 1) +
":");
[Link]("Name: ");
String name = [Link]();
[Link]("Roll No: ");
int rollNo = [Link]();
[Link]("Percentage: ");
double percentage = [Link]();
students[i] = new Student(name, rollNo, percentage);
}
[Link]();

[Link](students, (s1, s2) ->


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

[Link]("\nStudents ranked by percentage:");


for (int i = 0; i < [Link]; i++) {
students[i].display(i + 1);
}
}
}

output:
Enter details for student 1:
Name: manish
Roll No: 1
Percentage: 89
Enter details for student 2:
Name: madhu
Roll No: 2
Percentage: 78
Enter details for student 3:
Name: ravi
Roll No: 3
Percentage: 78
Enter details for student 4:
Name: pawan
Roll No: 4
Percentage: 90
Enter details for student 5:
Name: buddy
Roll No: 5
Percentage: 99.99
Enter details for student 6:
Name: madhav
Roll No: 6
Percentage: 67
Enter details for student 7:
Name: amar
Roll No: 7
Percentage: 69
Enter details for student 8:
Name: dabbu
Roll No: 8
Percentage: 79
Enter details for student 9:
Name: ramesh
Roll No: 9
Percentage: 68
Enter details for student 10:
Name: anil
Roll No: 10
Percentage: 58

Students ranked by percentage:


Rank: 1, Name: buddy, Roll No: 5, Percentage: 99.99
Rank: 2, Name: pawan, Roll No: 4, Percentage: 90.0
Rank: 3, Name: manish, Roll No: 1, Percentage: 89.0
Rank: 4, Name: dabbu, Roll No: 8, Percentage: 79.0
Rank: 5, Name: madhu, Roll No: 2, Percentage: 78.0
Rank: 6, Name: ravi, Roll No: 3, Percentage: 78.0
Rank: 7, Name: amar, Roll No: 7, Percentage: 69.0
Rank: 8, Name: ramesh, Roll No: 9, Percentage: 68.0
Rank: 9, Name: madhav, Roll No: 6, Percentage: 67.0
Rank: 10, Name: anil, Roll No: 10, Percentage: 58.0

[Link] to overload “area()” method to compute area of circle, square,


rectangle and triangle

class Shape
{
public double area(double radius) {
return [Link] * radius * radius;
}

public int area(int side) {


return side * side;
}

public int area(int length, int breadth) {


return length * breadth;
}

public double area(double base, double height, boolean isTriangle) {


return 0.5 * base * height;
}
}
class Area
{
public static void main(String[] args)
{
Shape s = new Shape();
[Link]("Circle Area: " + [Link](5.0));
[Link]("Square Area: " + [Link](4));
[Link]("Rectangle Area: " + [Link](4, 6));
[Link]("Triangle Area: " + [Link](4.0, 6.0, true));
}
}

output:
Circle Area: 78.53981633974483
Square Area: 16
Rectangle Area: 24
Triangle Area: 12.0

[Link] to create a class “Number” consist of a number(int) and a static


variable count(int)
that count the number of instances created of the class and methods for
I/O and a static
method that print the value of count

class Number
{
private int number;
private static int count=0;

public Number(int n)
{
number=n;
count++;
}

public void displaynum()


{
[Link]("number="+number);

}
public static void displaycount()
{
[Link]("objected is created:"+count);
}
}

public class Numbertest


{
public static void main(String args[])
{
Number n1=new Number(10);
Number n2=new Number(20);
Number n3=new Number(30);
[Link]();
[Link]();
[Link]();
[Link]();

}
}
output:
number=10
number=20
number=30
objected is created:3

11.. WAP to create a class "Data" consist of two float type numbers and
methods for I/O. Create
an another class "Maximum" that inherits the "Data" class and consist of
a variable that
store the maximum of two inherited numbers and the methods for
I/O.(Single inheritance)

class Data
{
protected float x,y;

public void getdata(float a,float b)


{
x=a;
y=b;
}

public void showdata()


{
[Link]("x="+x);
[Link]("y="+y);
}
}
class Maximum extends Data
{
private float max;

public void max()


{
if(x>y)
{
max=x;
}
else
{
max=y;
}
}

public void showmax()


{
[Link]("Maximum is:"+max);
}

}
public class Maximumtest
{
public static void main(String args[])
{
Maximum m=new Maximum();
[Link]((float) 31.4, (float) 42.5);
[Link]();
[Link]();
[Link]();
}
}

output:
x=31.4
y=42.5
Maximum is:42.5

[Link] to create a class “Student” consist of name and rollno and methods
for I/O. Create
an another class “Test” that inherit the Student class and consist of
marks of two subjects
and methods for I/O. Create an another class “Result” that inherit the
Test class and consist
of total that stores the total marks of two subjects. Also override the
display() method in
Test and Result classes.(Multilevel inheritance/Method overriding)

class Student
{
private String name;
private int rollno;

public void getdata(String s,int r)


{
name=s;
rollno=r;
}
public void display()
{
[Link]("Name:"+name);
[Link]("Rollno:"+rollno);
}
}
class Marks extends Student
{
protected int marks1,marks2;

public void getmarks(int m1,int m2)


{
marks1=m1;
marks2=m2;
}

public void display()


{
[Link]();
[Link]("marks1:"+marks1);
[Link]("marks2:"+marks2);
}
}

class Totalmarks extends Marks


{
private int total;

public void display()


{
[Link]();
total=marks1+marks2;
[Link]("Total marks is:"+total);
}
}

public class Resulttest


{
public static void main(String[] args)
{
Totalmarks t=new Totalmarks();
[Link]("manish",123);
[Link](80,56);
[Link]();
}
}

output:
Name:manish
Rollno:123
marks1:80
marks2:56
Total marks is:136

[Link] to create a class "Person" consist of name and age and a


parameterized constructor
to input the values and display() method. Create another two classes
"Teacher" and
"Student" that inherits the "Person " class and consist of post and
standard instance
variables respectively and methods to display the details. (Hierarchical
inheritance)

class Person
{
private String name; buddy
private int age;

public Person(String s,int a)


{
name=s;
age=a;
}

public void display()


{
[Link]("name:"+name);
[Link]("age:"+age);
}
}
class Teacher extends Person
{
private String post;

public Teacher(String s,int a,String c)


{
super(s,a);
post=c;
}
public void display()
{
[Link]();
[Link]("post:"+post);
}
}
class Student extends Person
{
private int standard;
public Student(String s,int a,int st)
{
super(s,a);
standard=st;
}
public void display()
{
[Link]();
[Link]("Standard:"+standard);
}
}

public class persontest


{
public static void main(String[] args)
{
Teacher t=new Teacher("manish",23,"TGT");
Student s=new Student("madhu",56,10);
[Link]();
[Link]();
}
}

output:
name:manish
age:23
post:TGT
name:madhu
age:56
Standard:10

Common questions

Powered by AI

Method overloading in the 'Shape' class demonstrates polymorphism by allowing multiple definitions of the 'area()' method, each able to handle different parameter types or counts. This enables the class to compute areas for different shapes such as circles, squares, rectangles, and triangles. Overloading provides flexibility and reusability of method logic, enabling the same operation ('compute area') for different forms (shapes), which is a core principle of polymorphism .

Inheritance in the 'Person', 'Teacher', and 'Student' classes allows for code reuse, reducing redundancy by enabling derived classes ('Teacher' and 'Student') to inherit common attributes and methods from the 'Person' base class. This promotes maintainability and scalability. Hierarchical inheritance further distinguishes between different specialized classes, reducing complexity and allowing each class to implement or override functionality tailored to their specific needs, demonstrated by the 'display()' method adjustments in each subclass .

The 'menu-driven program' uses a 'while' loop alongside a 'switch' statement to provide a continuous control structure. Users can perform different array operations like displaying, searching, sorting, reversing, and finding the maximum by selecting options from a menu. The 'switch' statement facilitates branching based on user input, guiding the program flow to execute the specific case logic associated with each menu choice. These control structures ensure that the program can respond dynamically to multiple user requests without restarting .

The static variable 'count' in the 'Number' class effectively tracks the number of instances created, as it is shared across all objects of the class. Each time a new instance is created, the constructor increments this variable, providing a reliable method to maintain a count of objects. However, a potential limitation is concurrency in a multi-threaded environment, where simultaneous access might lead to inconsistent values unless properly synchronized. Furthermore, the count persists across the application lifespan, which might not always be desirable .

The creation of a zigzag array of prime numbers involves two core components: a prime-checking algorithm and the array population logic. The prime-checking uses a standard trial division up to the square root for efficiency, ensuring only prime numbers populate the list. The zigzag logic organizes these primes into a structured two-dimensional array in a row-by-row order, flipping direction with each row. This requires careful indexing to ensure correct placement, optimizing space by handling dynamic array length. The overall algorithm optimally balances computational steps with simplicity, but the nested structure could impact performance for larger ranges .

A class constructor in Java is a special method used to initialize objects. In the 'Account' class example, the constructor 'Assignment6(String hn, int an, double b)' is used to initialize the account holder's name, account number, and balance when an instance of 'Account' is created. This ensures that every 'Account' object is in a valid state upon creation, with essential attributes properly set as illustrated in .

Method overriding in multilevel inheritance is shown in the 'Student', 'Marks', and 'Totalmarks' classes by redefining the 'display()' method at each inheritance level, thereby modifying or extending the behavior it conveys. While 'Student' provides a basic 'display()', 'Marks' extends it by adding marks details, and 'Totalmarks' further incorporates the total calculation. This shows polymorphic behaviors, where each subclass refines the inherited method to suit new requirements, providing more detailed functionality while maintaining a clear hierarchy and relation .

The 'Maximum' class inherits from the 'Data' class, gaining access to its float number attributes and associated methods. By extending 'Data', 'Maximum' adds new functionality to calculate and store the maximum of the two inherited numbers. This demonstrates single inheritance by allowing 'Maximum' to use and build upon the existing framework ('getdata' and 'showdata' methods) while implementing additional logic ('max' and 'showmax' methods) to expand the class's capabilities .

The 'ZigzagPrimeArray' class uses a 'List' (ArrayList) to dynamically store prime numbers within a specified range before transferring them to a two-dimensional zigzag array for final display. This approach combines the flexibility of list data structures, which can grow dynamically as prime numbers are discovered, with the fixed structure of arrays for organized output. This is useful for operations where the amount of data is not fixed beforehand but needs to be formatted for specific uses, such as organizing primes in a zigzag pattern .

Using interface references for comparing 'Person' objects' ages offers flexibility and abstraction, allowing different implementations of comparability without altering the class itself. This would mean defining and implementing a 'Comparable' interface or similar structure. However, in 'Maximumage', simplicity is chosen by directly comparing attributes, balancing straightforward class design with requirements. Using interfaces might introduce overhead and complexity but benefits scalability and aligns with principles of OOP, promoting more modular and extensible code .

You might also like