1. WAP to print first 15 odd numbers.
class OddNumbers
{
public static void main(String[] args) {
int count = 0;
int number = 1;
[Link]("First 15 odd numbers:");
while (count < 15) {
if (number % 2 != 0) {
[Link](number+" ");
count++;
}
number++;
}
}
}
Output:
1
2. WAP to show the use of different operators in java.
Class JasleenFile{
public static void main(String[] args)
int a = 10;
int b = 5;
[Link](“Arithmetic Operators:”);
[Link](“Sum: “ + a+b);
[Link](“Difference: “ + a-b);
[Link](“Product: “ + a*b);
[Link](“Quotient: “ + a/b);
[Link](“Remainder: “ + a%b);
[Link](“\nRelational Operators:”);
[Link](a + “ > “ + b + “: “ + (a > b));
[Link](a + “ < “ + b + “: “ + (a < b));
[Link](a + “ >= “ + b + “: “ + (a >= b));
[Link](a + “ <= “ + b + “: “ + (a <= b));
[Link](a + “ == “ + b + “: “ + (a == b));
[Link](a + “ != “ + b + “: “ + (a != b));
Boolean x = true;
Boolean y = false;
[Link](“\nLogical Operators:”);
[Link](“x && y: “ + (x && y));
[Link](“x || y: “ + (x || y));
[Link](“!x: “ + (!x));
int num = 5;
[Link](“\nIncrement and Decrement Operators:”);
[Link](“Original value of num: “ + num);
num++;
[Link]("After increment: " + num);
num--;
[Link]("After decrement: " + num);
int value1 = 10;
int value2 = 20;
int max = (value1 > value2) ? value1 : value2;
[Link]("\nConditional (Ternary) Operator:");
[Link]("Max value: " + max);
}
}
Output:
2
3
3. WAP to demonstrates various datatypes in java.
class JasleenFile{
public static void main(String[] args) {
// Integer data types
byte byteVar = 10;
short shortVar = 10000;
int intVar = 1000000;
long longVar = 1000000000L; // Note the 'L' suffix for long
// Floating-point data types
float floatVar = 3.14f; // Note the 'f' suffix for float
double doubleVar = 3.14159;
// Character data type
char charVar = 'A';
// Boolean data type
boolean boolVar = true;
// Displaying the values
[Link]("Byte Variable: " + byteVar);
[Link]("Short Variable: " + shortVar);
[Link]("Int Variable: " + intVar);
[Link]("Long Variable: " + longVar);
[Link]("Float Variable: " + floatVar);
[Link]("Double Variable: " + doubleVar);
[Link]("Char Variable: " + charVar);
[Link]("Boolean Variable: " + boolVar);
}
}
Output:
4
4. WAP to show how to take input at run time.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Enter your salary: ");
double salary = [Link]();
[Link]("Hello, " + name + "!");
[Link]("Your age is: " + age);
[Link]("Your salary is: " + salary);
}
}
Output:
5
5. WAP to print all even numbers between 250 to 200. (Decreasing order).
public class JasleenFile{
public static void main(String[] args) {
[Link]("Even numbers between 250 and 200 in decreasing order:");
for (int i = 250; i >= 200; i--) {
if (i % 2 == 0) {
[Link](i+" ");
}
}
}
}
Output:
6
6. WAP to do the conversion of temperature accepted and the mode
through command line… mode can be deg Celsius or
farenheit(F=9C/5+32)
public class JasleenFile{
public static void main(String[] args) {
if ([Link] < 2) {
[Link]("Usage: java TemperatureConverter <temperature> <mode>");
[Link]("Mode can be 'C' for Celsius or 'F' for Fahrenheit.");
return;
}
double temperature = [Link](args[0]);
char mode = args[1].toUpperCase().charAt(0);
double convertedTemperature;
if (mode == 'C') {
convertedTemperature = (temperature - 32) * 5 / 9;
[Link]("Temperature in Celsius: " + convertedTemperature + " °C");
} else if (mode == 'F') {
convertedTemperature = (temperature * 9 / 5) + 32;
[Link]("Temperature in Fahrenheit: " + convertedTemperature + " °F");
} else {
[Link]("Invalid mode. Mode can be 'C' for Celsius or 'F' for Fahrenheit.");
}
}
}
Output:
7
7. WAP to accept a number and display its reverse (1234 4321)
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int reversedNumber = reverseNumber(number);
[Link]("Reverse of the number: " + reversedNumber);
}
public static int reverseNumber(int number) {
int reversedNumber = 0;
while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
return reversedNumber;
}
}
Output:
8
8. WAP to display the sum of digits of number accepted.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
int sum = 0;
int originalNumber = number;
while (number != 0) {
int digit = number % 10;
sum += digit;
number /= 10;
}
[Link]("The sum of digits of " + originalNumber + " is " + sum);
}
}
Output:
9
9. WAP to display the series as following (using single loop)
1,2,3,4,5,6,7,8,9,10…
public class JasleenFile{
public static void main(String[] args) {
int n = 10; // Change this value to adjust the series length
[Link]("Number series: ");
for (int i = 1; i <= n; i++) {
[Link](i);
if (i != n) {
[Link](", ");
}
}
[Link]();
}
}
Output:
10
10. WAP to create an application to generate electricity bill. Application
should accept bill no, customer name, old meter reading & New meter
reading and display details of customer along with bill amount to be
paid. Bill has to be calculated as per the following validations.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter bill number: ");
int billNumber = [Link]();
[Link]();
[Link]("Enter customer name: ");
String customerName = [Link]();
[Link]("Enter old meter reading: ");
int oldReading = [Link]();
[Link]("Enter new meter reading: ");
int newReading = [Link]();
int unitsConsumed = newReading - oldReading;
double billAmount = calculateBill(unitsConsumed);
[Link]("\nElectricity Bill Details:");
[Link]("Bill Number: " + billNumber);
[Link]("Customer Name: " + customerName);
[Link]("Units Consumed: " + unitsConsumed);
[Link]("Bill Amount: Rs. " + billAmount); }
public static double calculateBill(int unitsConsumed) {
double billAmount = 0;
if (unitsConsumed <= 100) {
billAmount = unitsConsumed * 1.5; // Rs. 1.5 per unit for first 100 units
} else if (unitsConsumed <= 200) {
billAmount = 100 * 1.5 + (unitsConsumed - 100) * 2; // Rs. 2 per unit for next 100 units
} else {
billAmount = 100 * 1.5 + 100 * 2 + (unitsConsumed - 200) * 3; // Rs. 3 per unit for remaining
units }
return billAmount; }
}
Output:
11
[Link] to create an application to store student information application
should accept rollno, name and marks of three subjects and calculate
total, percentage and division using functions.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter roll number: ");
int rollNo = [Link]();
[Link]();
[Link]("Enter student name: ");
String name = [Link]();
[Link]("Enter marks of three subjects:");
[Link]("Subject 1: ");
int subject1 = [Link]();
[Link]("Subject 2: ");
int subject2 = [Link]();
[Link]("Subject 3: ");
int subject3 = [Link]();
int totalMarks = calculateTotalMarks(subject1, subject2, subject3);
double percentage = calculatePercentage(totalMarks);
String division = calculateDivision(percentage);
// Display student information and results
[Link]("\nStudent Information:");
[Link]("Roll Number: " + rollNo);
[Link]("Name: " + name);
[Link]("Total Marks: " + totalMarks);
[Link]("Percentage: " + percentage + "%");
[Link]("Division: " + division); }
public static int calculateTotalMarks(int subject1, int subject2, int subject3) {
return subject1 + subject2 + subject3; }
public static double calculatePercentage(int totalMarks) {
return (totalMarks / 3.0); // Assuming each subject carries equal weight }
public static String calculateDivision(double percentage) {
if (percentage >= 60) {
return "First Division";
} else if (percentage >= 45) {
return "Second Division";
} else if (percentage >= 33) {
return "Third Division";
} else {
return "Fail";
}}}
Output:
12
13
[Link] to accept a number and a digit from user and find the number of
occurrences of a given digit in the number for ex: entered number is
1242526 and the digit to be checked is 2 then output should be 3.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a number: ");
int number = [Link]();
[Link]("Enter the digit to check: ");
int digit = [Link]();
int count = countDigitOccurrences(number, digit);
[Link]("Number of occurrences of digit " + digit + " in " + number + ": " +
count);
}
public static int countDigitOccurrences(int number, int digit) {
int count = 0;
while (number > 0) {
int lastDigit = number % 10;
if (lastDigit == digit) {
count++;
}
number /= 10;
}
return count;
}
}
Output:
14
[Link] to accept three numbers and find the highest among three
numbers using conditional operator.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
[Link]("Enter third number: ");
int num3 = [Link]();
int highest = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2
> num3) ? num2 : num3);
[Link]("The highest number among " + num1 + ", " + num2 +
", and " + num3 + " is: " + highest);
}
}
Output:
15
[Link] to demonstrate the concept of class and object.
class Person
{
String name;
int age;
public Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
public class JasleenFile{
public static void main(String[] args) {
Person person1 = new Person("ABCD", 30);
[Link]();
}
}
Output:
16
[Link] that illustrates the use of constructor.
class JasleenFile{
String name;
int age;
double salary;
JasleenFile(String name, int age, double salary) {
[Link] = name;
[Link] = age;
[Link] = salary;
}
String getName() {
return name;
}
int getAge() {
return age;
}
double getSalary() {
return salary;
}
public static void main(String[] args) {
JasleenFile J = new JasleenFile("ABCD", 30, 50000.0);
[Link]("Employee Name: " + [Link]());
[Link]("Employee Age: " + [Link]());
[Link]("Employee Salary: $" + [Link]());
}
}
Output:
17
[Link] that illustrates constructor overloading.
class JasleenFile{
int length;
int width;
JasleenFile(int length, int width) {
[Link] = length;
[Link] = width;
}
JasleenFile(int side) {
[Link] = side;
[Link] = side;
}
int calculateRectangleArea() {
return length * width;
}
int calculateSquareArea() {
return length * length;
}
public static void main(String[] args) {
JasleenFile rectangle = new JasleenFile(5, 3); // Rectangle
JasleenFile square = new JasleenFile(4); // Square
[Link]("Area of Rectangle: " + [Link]());
[Link]("Area of Square: " + [Link]());
}
}
Output:
18
[Link] for single inheritance using super keyword.
class TwoVar{
int var1;
int var2;
TwoVar(int var1, int var2) {
this.var1 = var1;
this.var2 = var2;
}
void display() {
[Link]("Sum of two variables: " + (var1 + var2));
}
}
class ThreeVar extends TwoVar {
int var3;
ThreeVar(int var1, int var2, int var3) {
super(var1, var2);
this.var3 = var3;
}
void display() {
[Link]();
[Link]("Sum of three variables: " + (var1 + var2 + var3));
}
}
class JasleenFile{
public static void main(String[] args) {
ThreeVar obj = new ThreeVar(5, 10, 15);
[Link]();
}
}
Output:
19
[Link] for multilevel inheritance.
class Vehicle {
void display() {
[Link]("This is a vehicle.");
}
}
class Car extends Vehicle {
void display() {
[Link]("This is a car.");
}
}
class BMW extends Car {
void display() {
[Link]("This is a BMW car.");
}
}
public class JasleenFile{
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
Car car = new Car();
BMW bmw = new BMW();
[Link]();
[Link]();
[Link]();
}
}
Output:
20
[Link] to demonstrate method overriding.
class Animal {
void sound() {
[Link]("Animal makes a sound.");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks.");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows.");
}
}
public class JasleenFile{
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
[Link]();
[Link]();
[Link]();
}
}
Output:
21
[Link] to implement multiple inheritance through interface.
interface Vehicle {
void start();
}
interface MusicPlayer {
void playMusic();
}
class Car implements Vehicle, MusicPlayer {
public void start() {
[Link]("Car started");
}
public void playMusic() {
[Link]("Playing music in the car");
}
}
class JasleenFile{
public static void main(String[] args) {
Car myCar = new Car();
[Link]();
[Link]();
}
}
Output:
22
[Link] to demonstrate importing multiple packages.
import [Link];
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();
[Link]("Enter your name: ");
String name = [Link]();
int randomNumber = [Link](100);
[Link]("Hello, " + name + "!");
[Link]("Your random number is: " + randomNumber);
}
}
Output:
23
[Link] that illustrates the use of exception handling.
class JasleenFile{
public static void main(String args[]){
int a=10,b=0;
int x=0;
try{
x=a/b;
}
catch(ArithmeticException e){
[Link]("You are trying to divide by zero!");
}
[Link]("value of x="+ x);
}
}
Output:
24
[Link] to demonstrate creating threads by extending thread class.
class ThreadDemo extends Thread
{ ThreadDemo()
{
super("My Thread"); // calls the superclass constructor
[Link]("Child Thread: " + this);
start();
}
public void run()
{
[Link]("The child thread started");
[Link]("The child thread sleeping");
try
{
sleep(3000);
}
catch(InterruptedException ob)
{
[Link]("Exception occured");
}
[Link]("Exiting the child thread");}}
class JasleenFile{
public static void main(String args[]) {
new ThreadDemo();
[Link]("The main thread started");
try{
[Link](5000);
}
catch(InterruptedException ob){
}
[Link]("The main thread exiting");}
}
Output:
25
[Link] to demonstrate creating threads by implementing Runnable
interface.
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "My Thread");
[Link]("Child Thread: " + t);
[Link]();
}
public void run()
{ // Implementing the run() method of the Runnable interface
[Link]("Child Thread Started");
[Link]("The child thread sleeping");
try
{
[Link](3000);
}
catch(InterruptedException ob)
{
[Link]("Exception occured");
}
[Link]("Exiting the child thread");
}
}
class JasleenFile
{
public static void main(String args[])
{
new NewThread();
[Link]("Main thread Started");
[Link]("Exiting the main thread");
}
}
Output:
26
25. Write a Class Date that takes day, month and year while creating an
object of this class. Find a new date when the new date when the
number of days is given.
class Date {
private int day;
private int month;
private int year;
public Date(int day, int month, int year) {
[Link] = day;
[Link] = month;
[Link] = year;
}
public void setDay(int day) {
[Link] = day;
}
public void setMonth(int month) {
[Link] = month;
}
public void setYear(int year) {
[Link] = year;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public void displayDate() {
[Link]("Date: " + day + "/" + month + "/" + year);
}
public void findNewDate(int daysToAdd) {
int totalDays = day + daysToAdd;
int maxDaysInMonth;
while (totalDays > 0) {
maxDaysInMonth = getMaxDaysInMonth(month, year);
if (totalDays > maxDaysInMonth) {
27
totalDays -= maxDaysInMonth;
month++;
if (month > 12) {
month = 1;
year++;
}
} else {
day = totalDays;
break;
}
}
[Link]("New Date after adding " + daysToAdd + " days:");
displayDate();
}
private int getMaxDaysInMonth(int month, int year) {
switch (month) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return 31;
}
}
private boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
public class JasleenFile {
public static void main(String[] args) {
Date date = new Date(15, 3, 2024);
[Link]();
[Link](20); // Find a new date after adding 20 days
}
}
28
Output:
29
26. Write a program to implement Boolean AND, OR, XOR and NOT
operations.
public class JasleenFile{
public static boolean booleanAnd(boolean a, boolean b) {
return a && b;
}
public static boolean booleanOr(boolean a, boolean b) {
return a || b;
}
public static boolean booleanXor(boolean a, boolean b) {
return a ^ b;
}
public static boolean booleanNot(boolean a) {
return !a;
}
public static void main(String[] args) {
boolean a = true;
boolean b = false;
[Link]("a AND b: " + booleanAnd(a, b));
[Link]("a OR b: " + booleanOr(a, b));
[Link]("a XOR b: " + booleanXor(a, b));
[Link]("NOT a: " + booleanNot(a));
[Link]("NOT b: " + booleanNot(b));
}
}
Output:
30
[Link] to Add, Sub and Multiply two matrices using switch statement.
This Program must also validate the sizes of two matrices before
performing the operation and should raise expectation in case the
operation cannot be performed.
import [Link];
public class JasleenFile {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the dimensions of the first matrix:");
int rows1 = [Link]();
int cols1 = [Link]();
[Link]("Enter the dimensions of the second matrix:");
int rows2 = [Link]();
int cols2 = [Link]();
if (cols1 != rows2) {
[Link]("Matrix multiplication not possible. Number of columns in first
matrix must be equal to number of rows in second matrix.");
return;}
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2];
[Link]("Enter elements of first matrix:");
enterMatrixElements(scanner, matrix1);
[Link]("Enter elements of second matrix:");
enterMatrixElements(scanner, matrix2);
[Link]("Select operation:");
[Link]("1. Add");
[Link]("2. Subtract");
[Link]("3. Multiply");
int choice = [Link]();
switch (choice) {
case 1:
addMatrices(matrix1, matrix2, result);
break;
case 2:
subtractMatrices(matrix1, matrix2, result);
break;
case 3:
multiplyMatrices(matrix1, matrix2, result);
break;
default:
[Link]("Invalid choice!");
return; }
[Link]("Resultant matrix:");
printMatrix(result);
}
public static void enterMatrixElements(Scanner scanner, int[][] matrix) {
for (int i = 0; i < [Link]; i++) {
31
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = [Link]();
} }}
public static void addMatrices(int[][] matrix1, int[][] matrix2, int[][] result) {
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}}}
public static void subtractMatrices(int[][] matrix1, int[][] matrix2, int[][] result) {
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
result[i][j] = matrix1[i][j] - matrix2[i][j];
}}}
public static void multiplyMatrices(int[][] matrix1, int[][] matrix2, int[][] result) {
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
for (int k = 0; k < [Link]; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}}}}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int element : row) {
[Link](element + " ");
}
[Link]();
}}}
Output:
32
[Link] to store and then prints sorted names of students according to
their length of name using arrays with variable sized rows.
import [Link];
public class JasleenFile{
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of rows: ");
int rows = [Link]();
[Link]();
String[][] namesArray = new String[rows][];
for (int i = 0; i < rows; i++) {
[Link]("Enter the number of names in row " + (i + 1) + ": ");
int cols = [Link]();
[Link]();
namesArray[i] = new String[cols];
for (int j = 0; j < cols; j++) {
[Link]("Enter name " + (j + 1) + " in row " + (i + 1) + ": ");
namesArray[i][j] = [Link]();
}}
for (String[] row : namesArray) {
for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - i - 1; j++) {
if (row[j].length() > row[j + 1].length()) {
String temp = row[j];
row[j] = row[j + 1];
row[j + 1] = temp;
}}}}
[Link]("Sorted names:");
for (String[] row : namesArray) {
for (String name : row) {
[Link](name);
}}}}
Output:
33
[Link] to find the area of all the types of triangles using principle of
constructor overloading and inheritance depending on the number of
dimensions given in the input parameter list using super to call the
super class constructor.
import [Link];
class Triangle {
double base, height;
Triangle(double base, double height) {
[Link] = base;
[Link] = height; }
double calculateArea() {
return 0.5 * base * height; }}
public class JasleenFile {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of dimensions (2 or 3): ");
int dimensions = [Link]();
[Link]();
double area;
if (dimensions == 2) {
[Link]("Enter the base of the triangle: ");
double base = [Link]();
[Link]();
[Link]("Enter the height of the triangle: ");
double height = [Link]();
[Link]();
area = new Triangle(base, height).calculateArea();
} else if (dimensions == 3) {
[Link]("Enter the type of triangle (1 - Equilateral, 2 - Right Angle, 3 - Scalene): ");
int type = [Link]();
[Link]();
switch (type) {
case 1:
[Link]("Enter the side length of the equilateral triangle: ");
double side = [Link]();
[Link]();
area = new Triangle(side, [Link](3) / 2 * side).calculateArea();
break;
case 2:
[Link]("Enter the base of the right angle triangle: ");
double base = [Link]();
[Link]();
[Link]("Enter the height of the right angle triangle: ");
double height = [Link]();
[Link]();
area = new Triangle(base, height).calculateArea();
break;
case 3:
[Link]("Enter the base of the scalene triangle: ");
double scaleneBase = [Link]();
34
[Link]();
[Link]("Enter the first side of the scalene triangle: ");
double side1 = [Link]();
[Link]();
[Link]("Enter the second side of the scalene triangle: ");
double side2 = [Link]();
[Link]();
double s = (scaleneBase + side1 + side2) / 2;
area = 2 * [Link](s * (s - scaleneBase) * (s - side1) * (s - side2)) / scaleneBase;
break;
default:
[Link]("Invalid triangle type.");
[Link]();
return; }
} else {
[Link]("Invalid number of dimensions. Must be 2 or 3.");
[Link]();
return;}
[Link]("Area of the triangle: " + area);}}
Output:
35
30. WAP to find the area of rectangle using an abstract super class figure
and also override method use to compute the area of rectangle.
import [Link];
abstract class Figure {
abstract double calculateArea();
}
class Rectangle extends Figure {
double length;
double width;
Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}
double calculateArea() {
return length * width;
}
}
public class JasleenFile {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the length of the rectangle: ");
double length = [Link]();
[Link]();
[Link]("Enter the width of the rectangle: ");
double width = [Link]();
[Link]();
Rectangle rectangle = new Rectangle(length, width);
double area = [Link]();
[Link]("Area of the rectangle: " + area);
[Link]();
}
}
Output:
36
31. WAP to demonstrate static variables, methods and blocks.
public class JasleenFile {
// Static variable
static int staticVar;
// Static block
static {
[Link]("Static block executed.");
staticVar = 10;
}
// Static method
static void staticMethod() {
[Link]("Static method called. staticVar = " + staticVar);
}
public static void main(String[] args) {
[Link]("Main method started.");
// Accessing static variable and method without creating an instance of the class
[Link]("Accessing static variable directly: " + [Link]);
[Link]();
// Modifying static variable directly
[Link] = 20;
[Link]("Static variable modified: " + [Link]);
[Link]();
}
}
Output:
37
32. WAP to swap two items belonging to an object using returning of
object by a function.
class Item {
int a;
int b;
Item(int a, int b) {
this.a = a;
this.b = b;
}
// Method to swap the values of a and b
Item swap() {
int temp = this.a;
this.a = this.b;
this.b = temp;
return this; // Returning the current object after swapping
}
// Method to display the values of a and b
void display() {
[Link]("a = " + a + ", b = " + b);
}
}
public class JasleenFile {
public static void main(String[] args) {
Item item = new Item(10, 20);
[Link]("Before swap:");
[Link]();
// Swapping the values using the swap method
item = [Link]();
[Link]("After swap:");
[Link]();
}
}
Output:
38
33. WAP to count the frequency of each vowel in a given string.
public class JasleenFile {
public static void main(String[] args) {
String input = "This is a simple example string.";
countVowels(input);
}
static void countVowels(String str) {
int aCount = 0, eCount = 0, iCount = 0, oCount = 0, uCount = 0;
str = [Link]();
for (char ch : [Link]()) {
switch (ch) {
case 'a':
aCount++;
break;
case 'e':
eCount++;
break;
case 'i':
iCount++;
break;
case 'o':
oCount++;
break;
case 'u':
uCount++;
break;
}
}
[Link]("Vowel frequencies:");
[Link]("a: " + aCount);
[Link]("e: " + eCount);
[Link]("i: " + iCount);
[Link]("o: " + oCount);
[Link]("u: " + uCount);
}
}
Output:
39
34. Demonstrate the use of static and non-static nested classes.
public class JasleenFile {
// Static nested class
static class StaticNestedClass {
void display() {
[Link]("Inside static nested class.");
}
}
// Non-static nested class (inner class)
class InnerClass {
void display() {
[Link]("Inside inner class.");
}
}
public static void main(String[] args) {
// Creating an instance of the static nested class
[Link] staticNested = new [Link]();
[Link]();
// Creating an instance of the outer class
JasleenFile outer = new JasleenFile();
// Creating an instance of the inner class
[Link] inner = [Link] InnerClass();
[Link]();
}
}
Output:
40
35. Create a package containing a class to print your name, roll no,
marks and use this package in another program using import
statement.
student/[Link]
package student;
public class StudentInfo {
private String name;
private String rollNo;
private int marks;
public StudentInfo(String name, String rollNo, int marks) {
[Link] = name;
[Link] = rollNo;
[Link] = marks;
}
public void displayInfo() {
[Link]("Name: " + name);
[Link]("Roll No: " + rollNo);
[Link]("Marks: " + marks);
}}
[Link]
import [Link];
public class Main {
public static void main(String[] args) {
StudentInfo student = new StudentInfo("Jasleen kaur", "BCA", 503);
[Link]();
}
}
Output:
41