java_practical
java_practical
*Output:
D:\javaprg>javac pro1.java
D:\javaprg>java pro1
Hello world
Pro 2: Write a program to pass Starting and Ending limit and print all prime
numbers and Fibonacci numbers between this ranges.
import java.util.Scanner;
import java.util.ArrayList;
class PrimeFibonacci
{
private int start;
private int end;
public PrimeFibonacci(int start, int end)
{
this.start = start;
this.end = end;
}
private boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++)
1
{
if (num % i == 0)
{
return false;
}
}
return true;
}
public ArrayList<Integer> generatePrimes()
{
ArrayList<Integer> primes = new ArrayList<>();
for (int num = start; num <= end; num++)
{
if (isPrime(num))
{
primes.add(num);
}
}
return primes;
}
*Output:
D:\javaprg>javac primefib.java
D:\javaprg>java Main
Enter the starting limit: 2
Enter the ending limit: 4
Prime numbers between 2 and 4: [2, 3]
Fibonacci numbers between 2 and 4: [2, 3]
3
public boolean isPalindrome()
{
int original = number;
int reversed = 0;
while (number > 0)
{
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
number = original;
return original == reversed;
}
}
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
PalindromeChecker checker = new PalindromeChecker(num);
if (checker.isPalindrome())
{
System.out.println(num + " is a palindrome.");
}
else
{
System.out.println(num + " is not a palindrome.");
}
scanner.close();
}
}
*Output:
4
D:\javaprg>javac pro3.java
D:\javaprg>java Main
Enter a number: 3
3 is a palindrome.
Pro 4: Write a java program to print value ofx^n. Input: x=5 Input: n=3 Output:
125
import java.util.Scanner;
class PowerCalculator
{
private double x;
private int n;
public PowerCalculator(double x, int n)
{
this.x = x;
this.n = n;
}
public double calculatePower()
{
double result = 1;
for (int i = 0; i < n; i++)
{
result *= x;
}
return result;
}
}
class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of x: ");
double x = scanner.nextDouble();
5
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
PowerCalculator calculator = new PowerCalculator(x, n);
double result = calculator.calculatePower();
System.out.println(x + "^" + n + " = " + result);
scanner.close();
}
}
*Output:
D:\javaprg>java Main
Enter the value of x: 2
Enter the value of n: 3
2.0^3 = 8.0
Pro 5:Write a java program to check Armstrong number. Input: 153 Output:
Armstrong number
Input: 22 Output: not Armstrong number
import java.util.*;
class ArmstrongNumber
{
int number, temp, remainder, result = 0, count = 0;
ArmstrongNumber(int num)
{
number = num;
}
void checkArmstrong()
{
temp = number;
while (temp != 0)
{
temp /= 10;
count++;
}
6
temp = number;
while (temp != 0)
{
remainder = temp % 10;
result += Math.pow(remainder, count);
temp /= 10;
}
if (result == number)
{
System.out.println(number + " is an Armstrong number.");
}
else
{
System.out.println(number + " is not an Armstrong number.");
}
}
*Output:
D:\javaprg>javac pro5.java
D:\javaprg>java ArmstrongNumber
153 is an Armstrong number.
*Output:
D:\javaprg>javac pro6.java
D:\javaprg>java MinimumNumber
The minimum number is: 5
Pro 7:Write a java program which should display maximum number of given 4
numbers.
import java.util.*;
class MaximumNumber
{
int num1, num2, num3, num4;
MaximumNumber(int a, int b, int c, int d)
{
num1 = a;
num2 = b;
num3 = c;
num4 = d;
8
}
void findMaximum()
{
if(num1>num2 && num1>num3 && num1>num4)
System.out.println("Number 1 is maximum ="+num1);
else if(num2>num1 && num2>num3 && num2>num4)
System.out.println("Number 2 is maximum ="+num2);
else if(num3>num1 && num3>num2 && num3>num4)
System.out.println("Number 3 is maximum ="+num3);
else
System.out.println("Number 4 is maximum ="+num4);
}
public static void main(String[] args)
{
int a = 10, b = 25, c = 5, d = 15;
MaximumNumber obj = new MaximumNumber(a, b, c, d);
obj.findMaximum();
}
}
*Output:
D:\javaprg>javac pro7.java
D:\javaprg>java MaximumNumber
Number 2 is maximum25
Pro 8: Write a program in Java to multiply two matrix. Declare a class Matrix
where 2D array is declared as instance variable and array should be initialized,
within class.
import java.util.Arrays;
class Matrix {
private int[][] matrix1;
private int[][] matrix2;
private int[][] result;
public Matrix()
{
matrix1 = new int[][]
{
{1, 2, 3}, {4, 5, 6}};
9
matrix2 = new int[][]
{
{7, 8},{9, 10},{11, 12}};
result = new int[matrix1.length][matrix2[0].length];
}
public void multiply()
{
for (int i = 0; i < matrix1.length; i++)
{
for (int j = 0; j < matrix2[0].length; j++)
{
for (int k = 0; k < matrix2.length; k++)
{
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
public void displayResult()
{
System.out.println("Resultant Matrix:");
for (int[] row : result)
{
System.out.println(Arrays.toString(row));
}
}
}
class Main
{
public static void main(String[] args)
{
Matrix matrix = new Matrix();
matrix.multiply();
matrix.displayResult();
}
}
*Output:
D:\javaprg>javac pro_8.java
D:\javaprg>java Main
10
Resultant Matrix:
[58, 64]
[139, 154]
Pro 9: Write a java program to create a class “Matrix” that would contain integer
values having varied Numbers of columns for each row. Print row-wise sum of
the integer values for each row.
import java.util.Scanner;
class Matrix {
int[][] matrix;
int rows;
public Matrix(int rows)
{
this.rows = rows;
matrix = new int[rows][];
}
public void setValues()
{
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < rows; i++)
{
System.out.print("Enter the number of columns for row " + (i + 1) + ": ");
int cols = scanner.nextInt();
matrix[i] = new int[cols];
System.out.println("Enter the values for row " + (i + 1) + ": ");
for (int j = 0; j < cols; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
}
public void printRowWiseSum()
{
System.out.println("Row-wise sums:");
for (int i = 0; i < rows; i++)
{
int sum = 0;
for (int j = 0; j < matrix[i].length; j++)
{
11
sum += matrix[i][j];
}
System.out.println("Sum of row " + (i + 1) + ": " + sum);
}
}
}
class Main
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int numRows = scanner.nextInt();
Matrix matrix = new Matrix(numRows);
matrix.setValues();
matrix.printRowWiseSum();
scanner.close();
}
}
*Output:
D:\javaprg>javac pro9.java
D:\javaprg>java Main
Enter the number of rows: 2
Enter the number of columns for row 1: 3
Enter the values for row 1:
23
45
5
Enter the number of columns for row 2: 2
Enter the values for row 2:
12
34
Row-wise sums:
Sum of row 1: 73
Sum of row 2: 46
12
Pro10 Write a Java application which takes several command line arguments,
which are supposed to be names of students and prints output as given below:
(Suppose we enter 3 names then output should be as follows).. Number of
arguments = 3
1. First Student Name is = Arun
2. Second Student Name is = Hiren
3. Third Student Name is = Hitesh
import java.util.*;
class StudentNames
{
String[] studentNames;
StudentNames(String[] names)
{
this.studentNames = names;
}
void displayNames()
{
int numberOfStudents = studentNames.length;
System.out.println("Number of arguments = " + numberOfStudents);
for (int i = 0; i < numberOfStudents; i++)
{
String s;
switch (i)
{
case 0: s = "First"; break;
case 1: s = "Second"; break;
case 2: s = "Third"; break;
default: s = (i + 1) + "th";
}
System.out.println(s + " Student Name is = " + studentNames[i]);
}
}
public static void main(String[] args)
{
13
*Output:
D:\javaprg>javac prde.java
D:\javaprg>java StudentNames Arun Hiren Hitesh
Number of arguments = 3
First Student Name is = Arun
Second Student Name is = Hiren
Third Student Name is = Hitesh
14
11.Write a Java application to count and display frequency of letters and digits
from the String given by user as command-line argument.
class Student {
private int enrollmentNo;
private String name;
private String gender;
private static int count = 0;
public Student(int enrollmentNo, String name, String gender) {
this.enrollmentNo = enrollmentNo;
this.name = name;
this.gender = gender;
count++;
}
public void display() {
System.out.println("Enrollment No: " + enrollmentNo);
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
}
public static int getCount() {
return count;
}
}
class StudentTest {
public static void main(String[] args) {
Student s1 = new Student(1, "Alice", "Female");
Student s2 = new Student(2, "Bob", "Male");
s1.display();
s2.display();
System.out.println("Total students: " + Student.getCount());
}
}
*Output:-
D:\MCA\java>javac pro11.java
D:\MCA\java>java StudentTest
Enrollment No: 1
Name: Alice
Gender: Female
15
Enrollment No: 2
Name: Bob
Gender: Male
Total students: 2
12. Create a class “Student” that would contain enrollment No, name, and
gender and marks as instance variables and count as static variable which stores
the count of the objects; constructors and display(). Implement constructors to
initialize instance variables. Also demonstrate constructor chaining. Create
objects of class “Student” and displays all values of objects.
class Student {
private int enrollmentNo;
private String name;
private String gender;
private static int count = 0;
public Student(int enrollmentNo, String name, String gender) {
this.enrollmentNo = enrollmentNo;
this.name = name;
this.gender = gender;
count++;
}
public void display() {
System.out.println("Enrollment No: " + this.enrollmentNo);
System.out.println("Name: " + this.name);
System.out.println("Gender: " + this.gender);
}
public static int getCount() {
return count;
}
}
class ThisKeywordTest {
public static void main(String[] args) {
Student s1 = new Student(1, "Alice", "Female");
s1.display();
System.out.println("Total students: " + Student.getCount());
}
}
16
*Output:-
D:\MCA\java>javac pro12.java
D:\MCA\java>java ThisKeywordTest
Enrollment No: 1
Name: Alice
Gender: Female
Total students: 1
13. Write a program in Java to demonstrate use of this keyword. Check whether
this can access the Static variables of the class or not. [Refer class student in Q12
to perform the task]
14. Create a class “Rectangle” that would contain length and width as an
instance variable and count as a static variable.
Define constructors [constructor overloading (default, parameterized and copy)]
to initialize variables of objects. Define methods to find area and to display
variables’ value of objects which are created.
[Note: define initializer block, static initializer block and the static variable and
method. Also demonstrate the sequence of execution of initializer block and
static initialize block]
class Rectangle {
private double length;
private double width;
private static int count = 0;
static {
System.out.println("Static initializer block executed.");
}
{
System.out.println("Instance initializer block executed.");
}
public Rectangle() {
this(1.0, 1.0);
}
public Rectangle(double length, double width) {
this.length = length;
17
this.width = width;
count++;
}
public Rectangle(Rectangle r) {
this(r.length, r.width);
}
public double area() {
return length * width;
}
public void display() {
System.out.println("Length: " + length + ", Width: " + width);
}
public static int getCount() {
return count;
}
}
class RectangleTest {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(5.0, 4.0);
Rectangle r3 = new Rectangle(r2);
r1.display();
r2.display();
r3.display();
System.out.println("Total rectangles created: " + Rectangle.getCount());
}
}
*Output:-
D:\MCA\java>javac pro14.java
D:\MCA\java>java RectangleTest
Static initializer block executed.
Instance initializer block executed.
Instance initializer block executed.
Instance initializer block executed.
Length: 1.0, Width: 1.0
Length: 5.0, Width: 4.0
Length: 5.0, Width: 4.0
Total rectangles created: 3
18
15. Write a java program static block which will be executed before main ( )
method in a
Class.
class StaticBlockDemo {
static {
System.out.println("Static block executed before main.");
}
public static void main(String[] args) {
System.out.println("Main method executed.");
}
}
*Output:-
D:\MCA\java>javac pro15.java
D:\MCA\java>java StaticBlockDemo
Static block executed before main.
Main method executed.
16. Write programs in Java to use Wrapper class of each primitive data types.
class WrapperDemo {
public static void main(String[] args) {
Integer intObj = Integer.valueOf(10);
Double doubleObj = Double.valueOf(10.5);
Character charObj = Character.valueOf('A');
System.out.println("Integer object: " + intObj);
System.out.println("Double object: " + doubleObj);
System.out.println("Character object: " + charObj);
}
}
*Output:-
D:\MCA\java>javac pro16.java
D:\MCA\java>java WrapperDemo
Integer object: 10
19
Double object: 10.5
Character object: A
17. Write a class “circle” with radius as data member and count the number of
instances created using default constructor only. [Constructor Chaining]
class Circle {
private static int count = 0;
private double radius;
public Circle() {
this(1.0);
}
public Circle(double radius) {
this.radius = radius;
count++;
}
public double area() {
return Math.PI * radius * radius;
}
public static int getCount() {
return count;
}
}
class CircleTest {
public static void main(String[] args) {
Circle c1 = new Circle();
Circle c2 = new Circle(5.0);
System.out.println("Circle 1 area: " + c1.area());
System.out.println("Circle 2 area: " + c2.area());
System.out.println("Total circles created: " + Circle.getCount());
}
}
*Output:-
D:\MCA\java>javac pro17.java
D:\MCA\java>java CircleTest
Circle 1 area: 3.141592653589793
Circle 2 area: 78.53981633974483
Total circles created: 2
20
18. Create a class “Vehicle” with instance variable vehicle_type. Inherit the class
in a class called “Car” with instance model_type, company name etc. display the
information of the vehicle by defining the display() in both super and sub class
[Method Overriding]
class Vehicle {
String vehicleType;
public Vehicle(String vehicleType) {
this.vehicleType = vehicleType;
}
public void display() {
System.out.println("Vehicle Type: " + vehicleType);
}
}
class Car extends Vehicle {
String modelType;
String companyName;
public Car(String vehicleType, String modelType, String companyName) {
super(vehicleType);
this.modelType = modelType;
this.companyName = companyName;
}
@Override
public void display() {
super.display();
System.out.println("Model Type: " + modelType);
System.out.println("Company Name: " + companyName);
}
}
class VehicleTest {
public static void main(String[] args) {
Car car = new Car("Car", "SUV", "Toyota");
car.display();
}
}
*Output:-
D:\MCA\java>javac pro18.java
D:\MCA\java>java VehicleTest
21
Vehicle Type: Car
Model Type: SUV
Company Name: Toyota
22
balance -= amount;
System.out.println("Withdrawal successful! New Balance: " + balance);
} else {
System.out.println("Insufficient balance.");
}
}
}
class Current extends Account {
private double overdraftLimit;
public Current(int accountNo, double balance, double overdraftLimit) {
super(accountNo, balance);
this.overdraftLimit = overdraftLimit;
}
@Override
public void checkBalance() {
System.out.println("Current Account Balance: " + balance);
}
@Override
public void withdraw(double amount) {
if (amount <= balance + overdraftLimit) {
balance -= amount;
System.out.println("Withdrawal successful! New Balance: " + balance);
} else {
System.out.println("Withdrawal exceeds overdraft limit.");
}
}
}
public class AccountTest {
public static void main(String[] args) {
Savings savings = new Savings(12345, 1000.0, 0.05);
Current current = new Current(67890, 500.0, 300.0);
savings.deposit(200);
savings.checkBalance();
savings.withdraw(100);
current.deposit(100);
current.checkBalance();
current.withdraw(800);
}
}
23
*Output:-
D:\MCA\java>javac pro19.java
D:\MCA\java>java AccountTest
Savings Account Balance: 1200.0
Withdrawal successful! New Balance: 1100.0
Current Account Balance: 600.0
Withdrawal successful! New Balance: -200.0
24
System.out.println("Savings Account created with Account No: " + savings.accountNo);
System.out.println("Current Account created with Account No: " + current.accountNo);
}
}
*Output:-
D:\MCA\java>javac pro20.java
D:\MCA\java>java AccountDemo
Savings Account created with Account No: 12345
Current Account created with Account No: 67890
21. Write a program in Java to demonstrate the use of 'final' keyword in the field
declaration. How it is accessed using the objects.
class FinalExample {
final int finalValue = 10;
public void display() {
System.out.println("Final Value: " + finalValue);
}
}
public class FinalDemo {
public static void main(String[] args) {
FinalExample example = new FinalExample();
example.display();
}
}
*Output:-
D:\MCA\java>javac pro21.java
D:\MCA\java>java FinalDemo
Final Value: 10
22. Write a java program to illustrate how to access a hidden variable. Class A
declares a static variable x. The class B extends A and declares an instance
variable x. display ( ) method in B displays both of these variables.
class A {
25
static int x = 10;
}
class B extends A {
int x = 20;
public void display() {
System.out.println("Superclass static x = " + A.x);
System.out.println("Subclass instance x = " + this.x);
}
}
public class HiddenVariableDemo {
public static void main(String[] args) {
B b = new B();
b.display();
}
}
*Output:-
D:\MCA\java>javac pro22.java
D:\MCA\java>java HiddenVariableDemo
Superclass static x = 10
Subclass instance x = 20
23. Describe abstract class called Shape which has three subclasses say Triangle,
Rectangle, and 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
26
}
@Override
double area() {
return 0.5 * base * height;
}
}
// Rectangle subclass
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double area() {
return length * width;
}
}
// Circle subclass
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double area() {
return Math.PI * radius * radius;
}
}
// Main class to test
public class Main {
public static void main(String[] args) {
Shape triangle = new Triangle(5, 10);
Shape rectangle = new Rectangle(4, 5);
Shape circle = new Circle(7);
System.out.println("Area of Triangle: " + triangle.area());
System.out.println("Area of Rectangle: " + rectangle.area());
System.out.println("Area of Circle: " + circle.area());
}
}
27
*Output:-
D:\MCA\java>javac pro23.java
D:\MCA\java>java Main
Area of Triangle: 25.0
Area of Rectangle: 20.0
Area of Circle: 153.93804002589985
24. Write a java program to implement an interface called Exam with a method
Pass (int mark) that returns a boolean. Write another interface called Classify
with a method Division (int average) which returns a String. Write a class called
Result which implements both Exam and Classify. The Pass method should
return true if the mark is greater than or equal to 50 else false. The Division
method must return “First” when the parameter average is 60 or more,
“Second” when average is 50 or more but below 60, “No division” when average
is less than 50.
interface Exam {
boolean Pass(int mark);
}
interface Classify {
String Division(int average);
}
class Result implements Exam, Classify {
@Override
public boolean Pass(int mark) {
return mark >= 50;
}
@Override
public String Division(int average) {
if (average >= 60) return "First";
else if (average >= 50) return "Second";
else return "No division";
}
public static void main(String[] args) {
Result result = new Result();
int mark = 55;
int average = 58;
28
System.out.println("Pass Status: " + (result.Pass(mark) ? "Passed" : "Failed"));
System.out.println("Division: " + result.Division(average));
}
}
*Output:-
D:\MCA\java>javac pro24.java
D:\MCA\java>java Result
Pass Status: Passed
Division: Second
25. Assume that there are two packages, student and exam. A student package
contains Student class and the exam package contains Result class. Write a
program that generates mark sheet for students.
package student;
public class Student {
public int rollNo;
public String name;
public Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public void displayStudentInfo() {
System.out.println("Roll No: " + rollNo);
System.out.println("Name: " + name);
}
}
java
Copy code
// File: exam/Result.java
package exam;
import student.Student;
public class Result extends Student {
private int marks;
public Result(int rollNo, String name, int marks) {
super(rollNo, name);
this.marks = marks;
29
}
public void displayMarksheet() {
super.displayStudentInfo();
System.out.println("Marks: " + marks);
System.out.println("Status: " + (marks >= 50 ? "Pass" : "Fail"));
}
}
java
Copy code
// File: Main.java
import exam.Result;
public class Main {
public static void main(String[] args) {
Result studentResult = new Result(1, "John Doe", 75);
studentResult.displayMarksheet();
}
}
26. Define a class A in package apack. In class A, three variables are defined of
access modifiers protected, private and public. Define class B in package bpack
which extends A and write display method which accesses variables of class A.
Define class C in package cpack which has one method display() in that create
one object of class A and display its variables. Define class ProtectedDemo in
package dpack in which write main () method. Create objects of class B and C
and class display method for both these objects.
// File: apack/A.java
package apack;
public class A {
public int publicVar = 1;
protected int protectedVar = 2;
private int privateVar = 3;
public void displayA() {
System.out.println("Public: " + publicVar);
System.out.println("Protected: " + protectedVar);
System.out.println("Private: " + privateVar);
}
}
30
java
Copy code
// File: bpack/B.java
package bpack;
import apack.A;
public class B extends A {
public void display() {
System.out.println("Public: " + publicVar);
System.out.println("Protected: " + protectedVar);
}
}
java
Copy code
// File: cpack/C.java
package cpack;
import apack.A;
public class C {
public void display() {
A a = new A();
System.out.println("Public: " + a.publicVar);
}
}
java
Copy code
// File: dpack/ProtectedDemo.java
package dpack;
import bpack.B;
import cpack.C;
public class ProtectedDemo {
public static void main(String[] args) {
B b = new B();
b.display();
C c = new C();
c.display();
}
}
31
27. Write a java program to implement Generic class Number_1 for both data
type int and float in java.
*Output:-
D:\MCA\java>javac Number_1.java
D:\MCA\java>java Number_1
Value: 10
Value: 5.5
class changeCase {
public static void main(String[] args) {
32
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
//Checks for upper case character
else if(Character.isUpperCase(str1.charAt(i))) {
//Convert it into upper case using toLowerCase() function
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after case conversion : " + newStr);
}
}
*Output:-
D:\MCA\java>javac CaseReverser.java
D:\MCA\java>java changeCase
String after case conversion : gREAT pOWER
class Stringoperation1
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
*Output:-
D:\MCA\java>javac Stringoperation1.java
D:\MCA\java>java Stringoperation1
SACHIN
33
sachin
Sachin
30. Write a program in Java to demonstrate use of final class, final variable and
final method .
*Final Class:-
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
*Final Method:-
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
*Final Variable:-
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
34
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
35