Core Java Practical
Core Java Practical
Core Java Practical
PRACTICAL
Index
Sr. Title Date of Sign.
No. Assessment
1 Java Basics
2 Use of Operators
5 Inheritance
8 File Handling
9 Exception Handling
10 GUI Programming.
Code:
class SwapVariables {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println("Before swapping: ");
System.out.println("a = " + a);
System.out.println("b = " + b);
int temp = a;
a = b;
b = temp;
System.out.println("After swapping: ");
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
Output:
Code:
class CircleArea {
public static void main(String[] args) {
double radius = 5.0;
double area = Math.PI * radius * radius;
System.out.println("The area of the circle is: " + area);
}
}
Output:
c) Write a Java program to print the sum (addition), multiply, subtract, divide and
remainder of two numbers.
Code:
class MathOperations {
public static void main(String[] args) {
int num1 = 20;
int num2 = 5;
int sum = num1 + num2;
System.out.println("Addition: " + sum);
int product = num1 * num2;
System.out.println("Multiplication: " + product);
int difference = num1 - num2;
System.out.println("Subtraction: " + difference);
double quotient = (double) num1 / num2;
System.out.println("Division: " + quotient);
int remainder = num1 % num2;
System.out.println("Remainder: " + remainder);
}
}
Output:
d) Write a Java program that takes three numbers as input to calculate and print
the average of the numbers.
Code:
import java.util.Scanner;
class AverageCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.print("Enter third number: ");
double num3 = scanner.nextDouble();
double average = (num1 + num2 + num3) / 3.0;
System.out.println("The average is: " + average);
}
}
Output:
Practical 2
a) Write a Java program to check number is divisible by 7 or not.
Code:
import java.util.Scanner;
class DivisibleBySeven {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 7 == 0) {
System.out.println(num + " is divisible by 7");
} else {
System.out.println(num + " is not divisible by 7");
}
}
}
Output:
Code:
import java.util.Scanner;
class MaxOfThree {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
int max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
System.out.println("The maximum number is: " + max);
}
}
Output:
c) Write a Java program to read day code and display day name using switch
case.
Code:
import java.util.Scanner;
class DayName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a day code (1-7): ");
int dayCode = scanner.nextInt();
String dayName;
switch (dayCode) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day code";
break;
}
System.out.println(dayName);
}
}
Output:
d) Write a Java program that takes a number as input and prints its multiplication
table up to 10.
Code:
import java.util.Scanner;
class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
for (int i = 1; i <= 10; i++) {
int product = num * i;
System.out.println(num + " x " + i + " = " + product);
}
}
}
Output:
e) Write a Java program and compute the sum of the digits of an integer.
Code:
import java.util.Scanner;
class SumOfDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
int sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
}
}
Output:
Practical 3
a) Write a Java program to find sum of array elements of size 10.
Code:
class SumOfArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println("Sum of array elements: " + sum);
}
}
Output:
b) Designed a class SortData that contains the method asec() and desc() to sort
array elements.
Code:
SortData.java
public class SortData {
public void asec(int[] arr) {
int temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
public void desc(int[] arr) {
int temp;
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}
Main.java
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
SortData sorter = new SortData();
sorter.asec(arr);
System.out.println("Sorted array in ascending order:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
sorter.desc(arr);
System.out.println("Sorted array in descending order:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
Output:
Code:
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1, 9};
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("Smallest element: " + min);
System.out.println("Largest element: " + max);
}
}
Output:
Practical 4
a) Designed a Box class to find volume of a Box using class method.
Code:
Box.java
public class Box {
private double length;
private double width;
private double height;
public static double volume(double length, double width, double height) {
return length * width * height;
}
}
Main.java
public class Main {
public static void main(String[] args) {
double length = 5;
double width = 4;
double height = 3;
double volume = Box.volume(length, width, height);
System.out.println("Volume of box: " + volume);
}
}
Output:
b) Designed a Box class, initialize object using constructor and find volume of a
box.
Code:
Box.java
public class Box {
private double length;
private double width;
private double height;
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public double volume() {
return length * width * height;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Box box = new Box(5, 4, 3);
double volume = box.volume();
System.out.println("Volume of box: " + volume);
}
}
Output:
c) Designed a Box class with multiple constructor to initialize class object and
find volume of a box.
Code:
Box.java
public class Box {
private double length;
private double width;
private double height;
public Box(double length, double width, double height) {
this.length = length;
this.width = width;
this.height = height;
}
public Box() {
this.length = 0;
}
public Box(double length) {
this.width = 0;
}
public Box(double length, double width) {
this.height = 0;
}
public double volume() {
return length * width * height;
}
}
Main.java
public class Main2 {
public static void main(String[] args) {
Box box1 = new Box(5, 4, 3);
double volume1 = box1.volume();
System.out.println("Volume of box1: " + volume1);
}
}
Output:
Practical 5
a) Write a java program to implement single level inheritance.
Code:
class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog is barking.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}
Output:
Code:
class Animal {
public void eat() {
System.out.println("The animal is eating.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog is barking.");
}
}
class Labrador extends Dog {
public void fetch() {
System.out.println("The Labrador is fetching.");
}
}
public class Main {
public static void main(String[] args) {
Labrador myLabrador = new Labrador();
myLabrador.eat();
myLabrador.bark();
myLabrador.fetch();
}
}
Output:
Code:
interface Animal {
public void eat();
}
interface Mammal {
public void bark();
}
class Dog implements Animal, Mammal {
public void eat() {
System.out.println("The dog is eating.");
}
Output:
Practical 6
a) Create a package MyMath, Add the necessary classes and import the package
in java class.
Code:
MyMath.java
package MyMath;
public class MyMath {
public static int add(int x, int y) {
return x + y;
}
public static int subtract(int x, int y) {
return x - y;
}
}
MyMathTest.java
import MyMath.MyMath;
public class MyMathTest {
public static void main(String[] args) {
int result1 = MyMath.add(5, 3);
int result2 = MyMath.subtract(5, 3);
System.out.println("5 + 3 = " + result1);
System.out.println("5 - 3 = " + result2);
}
}
Output:
b) Write a java program to add two matrices and print the resultant matrix.
Code:
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] matrix2 = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
Output:
c) Write a java program for multiplying two matrices and print the product for the
same.
Code:
import java.util.Scanner
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of rows of first matrix: ");
int rows1 = input.nextInt();
System.out.print("Enter the number of columns of first matrix: ");
int columns1 = input.nextInt();
int[][] matrix1 = new int[rows1][columns1];
System.out.println("Enter the elements of first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns1; j++) {
matrix1[i][j] = input.nextInt();
}
}
System.out.print("Enter the number of rows of second matrix: ");
int rows2 = input.nextInt();
System.out.print("Enter the number of columns of second matrix: ");
int columns2 = input.nextInt();
int[][] matrix2 = new int[rows2][columns2];
System.out.println("Enter the elements of second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < columns2; j++) {
matrix2[i][j] = input.nextInt();
}
}
if (columns1 != rows2) {
System.out.println("Matrix multiplication not possible.");
return;
}
int[][] product = new int[rows1][columns2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
for (int k = 0; k < columns1; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("The product of the two matrices is:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < columns2; j++) {
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Practical 7
a) Write a java program to implement the vectors.
Code:
Vector.java
public class Vector {
private double[] data;
public Vector(double... data) {
this.data = data;
}
public double get(int index) {
return data[index];
}
public void set(int index, double value) {
data[index] = value;
}
public int size() {
return data.length;
}
public double dotProduct(Vector other) {
double result = 0;
for (int i = 0; i < size(); i++) {
result += get(i) * other.get(i);
}
return result;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Vector v1 = new Vector(1.0, 2.0, 3.0);
Vector v2 = new Vector(4.0, 5.0, 6.0);
Output:
b) Write a java program to implement thread life cycle.
Code:
public class ThreadLifeCycle implements Runnable {
public void run() {
try {
System.out.println("Thread is created and in " +
Thread.currentThread().getState() + " state.");
Thread.sleep(2000);
System.out.println("Thread has completed sleeping and is in " +
Thread.currentThread().getState() + " state.");
System.out.println("Thread is executing some task.");
Thread.sleep(5000);
System.out.println("Thread has completed the task and is in " +
Thread.currentThread().getState() + " state.");
} catch (InterruptedException e) {
System.out.println("Thread Interrupted");
}
}
public static void main(String[] args) {
Thread thread = new Thread(new ThreadLifeCycle());
System.out.println("Thread is created and in " + thread.getState() + " state.");
thread.start();
System.out.println("Thread is started and in " + thread.getState() + " state.");
try {
thread.join();
} catch (InterruptedException e) {
System.out.println("Thread Interrupted");
}
System.out.println("Thread has completed execution and is in " + thread.getState()
+ " state.");
}
}
Output:
c) Write a java program to implement multithreading.
Code:
class MyThread implements Runnable {
private int threadId;
public MyThread(int id) {
this.threadId = id;
}
public void run() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == this.threadId) {
System.out.println("Thread " + this.threadId + ": " + i);
}
}
}
}
public class MultithreadingExample {
public static void main(String[] args) {
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(0);
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();
thread2.start();
}
}
Output:
Practical 8
a) Write a java program to open a file and display the contents in the console
window.
Code:
FileDemo.java
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
String fileName = "example.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
example.txt
Hello
Output:
b) Write a java program to copy the contents from one file to other file.
Code:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
FileInputStream input = null;
FileOutputStream output = null;
try {
input = new FileInputStream("input.txt");
output = new FileOutputStream("output.txt");
int data;
while ((data = input.read()) != -1) {
output.write(data);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output:
Practical 9
a) Write a java program to implement exception handling.
Code:
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
try {
int num = scanner.nextInt();
System.out.println("The number entered is: " + num);
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
scanner.close();
System.out.println("Program execution completed.");
}
}
}
Output:
Code:
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numerator, denominator, result;
try {
System.out.print("Enter numerator: ");
numerator = sc.nextInt();
System.out.print("Enter denominator: ");
denominator = sc.nextInt();
result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Program execution complete.");
}
}
}
Output:
Practical 10
a) Construct a simple calculator using the JAVA awt with 3 text fields (the 3rd text
field should be read-only) and 4 buttons to add, subtract, multiply, divide with
minimum functionality.
Code:
import java.awt.*;
import java.awt.event.*;
public class Calculator extends Frame implements ActionListener {
TextField textField1, textField2, textField3;
public Calculator() {
setLayout(new GridLayout(4, 2));
textField1 = new TextField();
add(textField1);
textField2 = new TextField();
add(textField2);
textField3 = new TextField();
textField3.setEditable(false);
add(textField3);
Button addButton = new Button("+");
addButton.addActionListener(this);
add(addButton);
Button subButton = new Button("-");
subButton.addActionListener(this);
add(subButton);
Button mulButton = new Button("*");
mulButton.addActionListener(this);
add(mulButton);
Button divButton = new Button("/");
divButton.addActionListener(this);
add(divButton);
setTitle("Calculator");
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double num1 = Double.parseDouble(textField1.getText());
double num2 = Double.parseDouble(textField2.getText());
double result = 0;
if (e.getActionCommand().equals("+")) {
result = num1 + num2;
} else if (e.getActionCommand().equals("-")) {
result = num1 - num2;
} else if (e.getActionCommand().equals("*")) {
result = num1 * num2;
} else if (e.getActionCommand().equals("/")) {
result = num1 / num2;
}
textField3.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
textField3.setText("Invalid input");
}
}
public static void main(String[] args) {
new Calculator();
}
}
Output:
b) Create an application using Java awt that accepts Principal Amount, No. of
Years & Rate of Interest from 3 text fields, when you click “Calculate Interest”
button, the calculated interest should be displayed in a readonly text field. When
you click on “Final Amount” button, the final amount by adding principal amount
and interest should also be displayed in a read-only text field.
Code:
import java.awt.*;
import java.awt.event.*;
public class InterestCalculator extends Frame implements ActionListener {
Label principalLabel, yearsLabel, rateLabel, interestLabel, finalAmtLabel;
TextField principalField, yearsField, rateField, interestField, finalAmtField;
Button calculateBtn, finalAmtBtn;
public InterestCalculator() {
setLayout(new GridLayout(6, 2));
principalLabel = new Label("Principal Amount:");
add(principalLabel);
principalField = new TextField(10);
add(principalField);
yearsLabel = new Label("No. of Years:");
add(yearsLabel);
yearsField = new TextField(10);
add(yearsField);
rateLabel = new Label("Rate of Interest:");
add(rateLabel);
rateField = new TextField(10);
add(rateField);
interestLabel = new Label("Calculated Interest:");
add(interestLabel);
interestField = new TextField(10);
interestField.setEditable(false);
add(interestField);
calculateBtn = new Button("Calculate Interest");
add(calculateBtn);
calculateBtn.addActionListener(this);
finalAmtLabel = new Label("Final Amount:");
add(finalAmtLabel);
finalAmtField = new TextField(10);
finalAmtField.setEditable(false);
add(finalAmtField);
finalAmtBtn = new Button("Final Amount");
add(finalAmtBtn);
finalAmtBtn.addActionListener(this);
setTitle("Interest Calculator");
setSize(400, 250);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == calculateBtn) {
double principal = Double.parseDouble(principalField.getText());
double years = Double.parseDouble(yearsField.getText());
double rate = Double.parseDouble(rateField.getText());
double interest = (principal * years * rate) / 100;
interestField.setText(String.valueOf(interest));
} else if (ae.getSource() == finalAmtBtn) {
double principal = Double.parseDouble(principalField.getText());
double years = Double.parseDouble(yearsField.getText());
double rate = Double.parseDouble(rateField.getText());
double interest = (principal * years * rate) / 100;
double finalAmt = principal + interest;
finalAmtField.setText(String.valueOf(finalAmt));
}
}
public static void main(String[] args) {
new InterestCalculator();
}
}
Output:
c) Design a AWT program to print the factorial for an input value.
Code:
import java.awt.*;
import java.awt.event.*;
public class FactorialCalculator extends Frame implements ActionListener {
Label inputLabel, outputLabel;
TextField inputField, outputField;
Button calculateButton;
public FactorialCalculator() {
setTitle("Factorial Calculator");
setLayout(new FlowLayout());
inputLabel = new Label("Enter a number:");
add(inputLabel);
inputField = new TextField(10);
add(inputField);
calculateButton = new Button("Calculate Factorial");
add(calculateButton);
calculateButton.addActionListener(this);
outputLabel = new Label("Factorial:");
add(outputLabel);
outputField = new TextField(10);
outputField.setEditable(false);
add(outputField);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int num = Integer.parseInt(inputField.getText());
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
outputField.setText(String.valueOf(factorial));
}
public static void main(String[] args) {
new FactorialCalculator();
}
}
Output: