0% found this document useful (0 votes)
13 views58 pages

Java Practical

The document contains a series of Java programming exercises demonstrating various concepts such as Boolean values, loops, arithmetic operations, conditional statements, classes, inheritance, and interfaces. Each practical includes a program code snippet along with its output. The exercises cover a range of topics from basic programming to object-oriented principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views58 pages

Java Practical

The document contains a series of Java programming exercises demonstrating various concepts such as Boolean values, loops, arithmetic operations, conditional statements, classes, inheritance, and interfaces. Each practical includes a program code snippet along with its output. The exercises cover a range of topics from basic programming to object-oriented principles in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical No.

a. Write a program in Java to demonstrate Boolean value.


Program:-
import [Link].*;
class FindBoolean
{
public static void main(String[] args){
int x=10;
int y=9;
[Link](x<y);
}
}

Output:
b. Print a string 10 times using a for loop.
Program:-
import [Link].*;
class Looping
{
public static void main(String[] args)
{
for(int i=1;i<10;i++)
[Link]("Hello World");
}
}
Output:
c. Write a program in Java to evaluate a + b * c % d.
Program:
import [Link].*;
class Calculation {
public static void main(String [] args ){
int a=1;
int b=2;
int c=3;
int d=4;
int result=a + b * c % d;
[Link](result);
}
}
Output:
Practical No.2

a. Write a program in Java to find the biggest element among three numbers
using if else.
Program:
public class FindBiggestElement {
public static void main(String[] args) {
int num1 = 10;
int num2 = 25;
int num3 = 15;
int max;

if (num1 >= num2) {


// If num1 is greater than or equal to num2, compare num1 with
num3
if (num1 >= num3) {
max = num1;
} else {
max = num3;
}
} else {
// If num2 is greater than num1, compare num2 with num3
if (num2 >= num3) {
max = num2;
} else {
max = num3;
}
}

[Link]("The three numbers are: " + num1 + ", " + num2


+ ", " + num3);
[Link]("The biggest number is: " + max);
}
}

Output:
b. Write a program in Java to find the biggest element among three numbers
using the ternary operator.
Program: public class BiggestNumber {
public static void main(String[] args) {
int a = 66;
int b = 69;
int c = 79;
int biggest = ( a >= b ) ? (( a >= c ) ? a : c ) : (( b >= c ) ? b : c) ;
[Link]("The numbers are: a = " + a + ", b = " + b + ", c = " + c);
[Link]("The biggest number is: " + biggest);
}
}
Output:
c. Write a program in Java to check the grade of marks using a switch case.
Program:
import [Link];
public class GradeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter marks (0–100): ");
int marks = [Link]();
int grade = marks / 10; // Convert marks into grade range
switch (grade) {
case 10:
case 9:
[Link]("Grade: A");
break;
case 8:
[Link]("Grade: B");
break;
case 7:
[Link]("Grade: C");
break;
case 6:
[Link]("Grade: D");
break;
case 5:
[Link]("Grade: E");
break;
default:
if (marks < 0 || marks > 100)
[Link]("Invalid marks");
else
[Link]("Grade: F");
}
[Link]();
}
}
Output:
PRACTICAL NO. 3
a) Write a program in Java to demonstrate dynamic initialization.

Program:

// Program to demonstrate Dynamic Initialization in Java

import [Link].*;

class DynamicInitializationDemo {

public static void main(String[] args) {

// Dynamic initialization using expressions

int a = 5;

int b = 3;

// Variables initialized at runtime using expressions

int addition = a + b;

int subtraction = a - b;

int multiplication = a * b;

int division = a / b;

[Link]("Value of a: " + a);

[Link]("Value of b: " + b);

[Link]("Addition: " + addition);

[Link]("Subtraction: " + subtraction);


[Link]("Multiplication: " +multiplication);

[Link]("Division: " + division);

Output:
b) Write a program in Java to create a class and access all data members
and methods using the object and compute the area and perimeter of a
circle.

Program:

// Program to calculate area and perimeter of a circle using a class and object

import [Link].*;

class Circle {

double radius; // Data member

// Method to calculate area

double area() {

return 3.14 * radius * radius;

// Method to calculate perimeter (circumference)

double perimeter() {

return 2 * 3.14 * radius;

public class CircleDemo {

public static void main(String[] args) {

Circle c = new Circle(); // Creating object


[Link] = 7; // Accessing data member using object

// Accessing methods using object

[Link]("Radius: " + [Link]);

[Link]("Area of Circle: " + [Link]());

[Link]("Perimeter of Circle: " + [Link]());

Output:
c) Write a program in Java to access member variables using the
constructor.
Program:

import [Link].*;
class Student {
// Member variables
int rollNo;
String name;

// Constructor to initialize member variables


Student(int r, String n) {
rollNo = r;
name = n;
}

// Method to display values


void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}
}

public class Main {


public static void main(String[] args) {

// Creating object and passing values to constructor


Student s1 = new Student(258007, "Rushiikesh");
// Accessing member variables through method
[Link]();
}
}

Output :
PRACTICAL NO. 4
a) Write a program in Java to multiply two matrices.

Program:

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

int a[][] = {
{1, 2, 3},
{4, 5, 6}
};

int b[][] = {
{7, 8},
{9, 10},
{11, 12}
};

int result[][] = new int[2][2];

// Multiplying matrices
for (int i = 0; i < 2; i++) { // rows of matrix a
for (int j = 0; j < 2; j++) { // columns of matrix b
for (int k = 0; k < 3; k++) { // columns of a / rows of b
result[i][j] += a[i][k] * b[k][j];
}
}
}
// Display result
[Link]("Result of Matrix Multiplication:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
[Link](result[i][j] + " ");
}
[Link]();
}
}
}

Output:
b) Write a program in Java to calculate the area of a rectangle using single

inheritance.

Program:

import [Link].*;

class Shape {

int length;

int breadth;

class Rectangle extends Shape {

void calculateArea() {

int area = length * breadth;

[Link]("Area of Rectangle = " + area);

public class Main {

public static void main(String[] args) {

Rectangle r = new Rectangle();

[Link] = 10;

[Link] = 5;

[Link]();
}

Output:
c) Write a program in Java to demonstrate multilevel inheritance.

Program:

import [Link].*;
// Grandparent class
class Person {
void showName() {
[Link]("I am a person");
}
}

// Parent class
class Employee extends Person {
void showJob() {
[Link]("I am an employee");
}
}

// Child class
class Manager extends Employee {
void showRole() {
[Link]("I am a manager");
}
}

public class Main {


public static void main(String[] args) {

Manager m = new Manager(); // Object of child class


// Accessing methods from all levels
[Link](); // From Person
[Link](); // From Employee
[Link](); // From Manager
}
}
Output:
PRACTICAL NO. 5
a) Write a program a. in Java to demonstrate hierarchical inheritance.
Program:

import [Link].*;
class Animal {
void eat() {
[Link]("Animal eats food");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

class Cat extends Animal {


void meow() {
[Link]("Cat meows");
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();

[Link](); // From Animal


[Link](); // From Dog
[Link](); // From Animal
[Link](); // From Cat
}
}
Output:
b) Write a program in Java to find the area and perimeter of a circle using

an abstract class.

Program:

import [Link].*;
// Abstract class
abstract class Shape {
abstract void area();
abstract void perimeter();
}

// Child class
class Circle extends Shape {
double radius = 7;

void area() {
double a = 3.14 * radius * radius;
[Link]("Area of Circle = " + a);
}

void perimeter() {
double p = 2 * 3.14 * radius;
[Link]("Perimeter of Circle = " + p);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
}
}
Output :
c) Write a program in Java to show that a private member of a class
cannot be inherited.
Program:

import [Link].*;
// Parent class
class Parent {
private int number = 10;

void showNumber() {
[Link]("Number = " + number);
}
}

// Child class
class Child extends Parent {
void display() {
// [Link](number);
// This line will give error because 'number' is private
[Link]("Cannot access private member directly");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Child c = new Child();
[Link](); // Accessible through method
[Link]();
}
}
Output:
PRACTICAL NO. 6
a) Write a program in Java to find the volume of a box using this keyword.

Program :

import [Link].*;

class Box {

int length;

int breadth;

int height;

Box(int length, int breadth, int height) {

[Link] = length;

[Link] = breadth;

[Link] = height;

void calculateVolume() {

int volume = length * breadth * height;

[Link]("Volume of Box = " + volume);

public class BoxVolumeDemo {


public static void main(String[] args) {

Box b = new Box(5, 4, 3);

[Link]();

Output:
b) Write a program in Java to find the average of three numbers using the
method overloading.

Program:

import [Link].*;
class Average {
void findAverage(int a, int b, int c) {
int avg = (a + b + c) / 3;
[Link]("Average (int) = " + avg);
}

void findAverage(double a, double b, double c) {


double avg = (a + b + c) / 3;
[Link]("Average (double) = " + avg);
}
}

public class Main {


public static void main(String[] args) {

Average obj = new Average();


[Link](10, 20, 30); // Calls int method
[Link](10.5, 20.5, 30.5); // Calls double method
}
}
Output :
c) Write a program in Java to find average of three numbers using method
overriding.

Program :

import [Link].*;
class Average {
void findAverage(int a, int b, int c) {
int avg = (a + b + c) / 3;
[Link]("Average in Parent class = " + avg);
}
}

class ChildAverage extends Average {


@Override
void findAverage(int a, int b, int c) {
double avg = (a + b + c) / 3.0;
[Link]("Average in Child class = " + avg);
}
}

public class Main {


public static void main(String[] args) {
Average obj = new ChildAverage(); // Runtime polymorphism
[Link](10, 20, 30);
}
}
Output:
d) Create a class figure. Create two subclasses rectangle and triangle. Find
the area of a rectangle and half the area of the rectangle using the
reference of the figure.
Program :
import [Link].*;
class Figure {
void area() {
[Link]("Area not defined");
}
}
class Rectangle extends Figure {
int length = 10;
int breadth = 5;
@Override
void area() {
int area = length * breadth;
[Link]("Area of Rectangle = " + area);
}
}
class Triangle extends Figure {
int length = 10;
int breadth = 5;
@Override
void area() {
double area = 0.5 * length * breadth;
[Link]("Half area (Triangle) = " + area);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Figure f; // Reference of base class
f = new Rectangle(); // Rectangle object
[Link]();
f = new Triangle(); // Triangle object
[Link]();
}
}
Output:
PRACTICAL NO. 7
a) Write a program create an interface area. Find the area of a circle..
Program :
import [Link].*;
// Interface
interface Area {
void findArea();
}

// Class implementing interface


class Circle implements Area {
double radius = 7;
public void findArea() {
double area = 3.14 * radius * radius;
[Link]("Area of Circle = " + area);
}
}

// Main class
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();

}
}
Output:
b) Write a program in Java to find the sum and average of three numbers
using the super keyword.
Program :
import [Link].*;
class Numbers {
int a = 10;
int b = 20;
int c = 30;
void sum() {
int s = a + b + c;
[Link]("Sum = " + s);
}
}

class Result extends Numbers {


void average() {
[Link](); // Calling parent class method
double avg = (a + b + c) / 3.0;
[Link]("Average = " + avg);
}
}

public class SuperDemo {


public static void main(String[] args) {
Result r = new Result();
[Link]();
}
}

Output :
PRACTICAL NO. 8
a) Write a program in Java to find the volume of a box using constructor
overloading.

Program :

import [Link].*;
class Box {
int length;
int breadth;
int height;
Box() {
length = 1;
breadth = 1;
height = 1;
}
// Constructor 2 (three parameters)
Box(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
void calculateVolume() {
int volume = length * breadth * height;
[Link]("Volume of Box = " + volume);
}
}
// Main class
public class Main {
public static void main(String[] args) {
Box b1 = new Box(); // Calls first constructor
[Link]();

Box b2 = new Box(5, 4, 3); // Calls second constructor


[Link]();
}
}
Output :
b) Write a program in Java to demonstrate exception handling in case of
variable/constant divided by zero.

Program:
import [Link].*;
public class Main {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // This will cause exception
[Link]("Result = " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero");
}
[Link]("Program continues normally...");
}
}
Output :
PRACTICAL NO. 9
a) Write a program in Java to implement multiple inheritance using the
interface.
Program :
import [Link].*;
// First interface
interface A {
void showA();
}

// Second interface
interface B {
void showB();
}

// Class implementing both interfaces


class C implements A, B {
public void showA() {
[Link]("This is method of interface A");
}

public void showB() {


[Link]("This is method of interface B");
}
}
// Main class
public class Main {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}
Output :
b) Write a program in Java to check if a given string is palindrome or not.
Program :
import [Link].*;
import [Link];

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a string: ");


String str = [Link]();

String reverse = "";

// Reverse the string


for (int i = [Link]() - 1; i >= 0; i--) {
reverse = reverse + [Link](i);
}

// Check palindrome
if ([Link](reverse)) {
[Link]("The string is a Palindrome");
} else {
[Link]("The string is NOT a Palindrome");
}
[Link]();
}
}
Output :
PRACTICAL NO 10
a) Write a program in Java for sorting a given list of strings in ascending
order.
Program :
import [Link].*;
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of strings: ");


int n = [Link]();
[Link](); // clear buffer

String[] arr = new String[n];

[Link]("Enter the strings:");


for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Sorting
[Link](arr);
[Link]("Strings in Ascending Order:");
for (String s : arr) {
[Link](s);
}

[Link]();
}
}
Output :
b) Write a program in Java to find the factorial of a number using the
package.

Program :
Step 1: Creating a package class
File:[Link]
package mypack;
public class Factorial {
public int findFactorial(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}
}
Step 2: Main class (uses the package)
File: [Link]
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


int num = [Link]();
Factorial f = new Factorial();
int result = [Link](num);
[Link]("Factorial of " + num + " = " + result);
[Link]();
}
}
Output :
PRACTICAL NO 11
a) Write a program in Java to import the package.

Program :

Step 1: Creating a package


File: [Link]
package mypack;
public class Message {
public void show()
{
[Link]("Hello! This is from imported package.");
}
}

Step 2: Import and use the package


File: [Link]
import [Link];
public class Main {
public static void main(String[] args) {
Message m = new Message();
[Link]();
}
}
Output :
b) Write a program in Java to implement thread.

Program :
import [Link].*;
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link](); // starts the thread
}
}
Output :
c) Write program to implement Flow, Grid and Border Layout using
swing.
Program :
import [Link].*;
import [Link].*;

public class Main {


public static void main(String[] args) {

// ---------- FlowLayout ----------


JFrame f1 = new JFrame("Flow Layout");
[Link](new FlowLayout());

[Link](new JButton("One"));
[Link](new JButton("Two"));
[Link](new JButton("Three"));

[Link](300, 150);
[Link](true);

// ---------- GridLayout ----------


JFrame f2 = new JFrame("Grid Layout");
[Link](new GridLayout(2, 2));

[Link](new JButton("1"));
[Link](new JButton("2"));
[Link](new JButton("3"));
[Link](new JButton("4"));
[Link](300, 150);
[Link](true);

// ---------- BorderLayout ----------


JFrame f3 = new JFrame("Border Layout");
[Link](new BorderLayout());

[Link](new JButton("North"), [Link]);


[Link](new JButton("South"), [Link]);
[Link](new JButton("East"), [Link]);
[Link](new JButton("West"), [Link]);
[Link](new JButton("Center"), [Link]);

[Link](300, 200);
[Link](true);
}
}
Output :
d) Write program to demonstrate following events Action Mouse Key.

Program:
import [Link].*;
import [Link].*;
import [Link].*;

public class Main extends JFrame


implements ActionListener, MouseListener, KeyListener {

JButton btn;
JTextField tf;

public Main() {
// Button for Action Event
btn = new JButton("Click Me");
[Link](this);

// TextField for Key Event


tf = new JTextField(20);
[Link](this);

setLayout(new FlowLayout());
add(btn);
add(tf);

// Mouse Event for Frame


addMouseListener(this);
setTitle("Event Demo");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// Action Event
public void actionPerformed(ActionEvent e) {
[Link](this, "Button Clicked!");
}

// Mouse Events
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}

// Key Events
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public static void main(String[] args) {
new Main();
}
}
Output :

You might also like