NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

JAVA Practical File
1.1 : Write a program to display “Welcome To Java World”.
Code:
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome To Java World");
}
}
Output:


1.2 Write a program to find whether the number is prime or not.
Code:
public class PrimeNumber {
public static void main(String[] args) {
int number = 7;
boolean isPrime = true;
if (number <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}
Output:


1.3 : Write a program to find a greater number among given three numbers using
a) ternary operator
b) nested if.
Code:
public class GreaterNumber {
public static void main(String[] args) {
int num1 = 123;
int num2 = 758;
int num3 = 498;

// Using Ternary Operator
int greater1 = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
System.out.println("Using Ternary Operator, the greater number is: " + greater1);

// Using Nested if
int greater2;
if (num1 > num2) {
if (num1 > num3) {
greater2 = num1;
} else {
greater2 = num3;
}
} else {
if (num2 > num3) {
greater2 = num2;
} else {
greater2 = num3;
}
}
System.out.println("Using Nested if, the greater number is: " + greater2);
}
}
Output:


1.4 : Write a program to print the Fibonacci series.
Code:
public class Fibonacci {
public static void main(String[] args) {
int numTerms = 15;

int firstTerm = 0, secondTerm = 1;
System.out.print(firstTerm + " " + secondTerm + " ");

for (int i = 3; i <= numTerms; i++) {
int nextTerm = firstTerm + secondTerm;
System.out.print(nextTerm + " ");
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}
Output:


2.1 : Write a program to find the average of n numbers stored in an Array.
Code:
public class AverageOfNumbers {
public static void main(String[] args) {
int[] numbers = { 5, 10, 15, 20, 25 }; // Fixed array containing n numbers
int sum = 0;
double average;

for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}

average = (double) sum / numbers.length;

System.out.println("The average of the numbers is: " + average);
}
}
Output:



3.1 : Write a program to replace substring with other substring in the given string.
Code:
public class ReplaceSubstring {
public static void main(String[] args) {
String originalString = "The quick brown fox jumps over the lazy dog";
String substringToReplace = "quick";
String newSubstring = "slow";

String modifiedString = originalString.replace(substringToReplace, newSubstring);

System.out.println("Original String: " + originalString);
System.out.println("Modified String: " + modifiedString);
}
}
Output:


3.2 : Write a program that to sort given strings into alphabetical order.
Code:
import java.util.Arrays;

public class SortStrings {
public static void main(String[] args) {
String[] names = { "John", "Alice", "Bob", "Daniel", "Cathy" };

Arrays.sort(names);

System.out.println("Names in alphabetical order:");
for (String name : names) {
System.out.println(name);
}
}
}
Output:


3.3 : Create a String Buffer with some default string. Append any string to ith position of original string and display the modified string. Also display the reverse of modified string.
Code:
public class ModifyStringBuffer {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer("Hello, World!");
String newString = " Welcome to Java";

// Append newString to the 7th position of buffer
buffer.insert(7, newString);

System.out.println("Modified String: " + buffer);

// Reverse the modified string
buffer.reverse();

System.out.println("Reversed String: " + buffer);
}
}


Output:


4.1 : a) Write a program that declares a class named Person. It should have instance variables to record name, age and salary. Use new operator to create a Person object. Set and display its instance variables.
b) Add a constructor to the Person class developed above.

Code:
public class Person {
String name;
int age;
double salary;

public Person(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}

public static void main(String[] args) {
Person person = new Person("John", 30, 50000.0);

System.out.println("Name: " + person.name);
System.out.println("Age: " + person.age);
System.out.println("Salary: " + person.salary);
}
}




Output:


4.2 : The employee list for a company contains employee code, name, designation and basic pay. The employee is given HRA of 10% of the basic and DA of 45%of the basic pay. The total pay of the employee is calculated as Basic pay + HRA + DA. Write a class to define the details of the employee. Write a constructor to assign the required initial values. Add a method to calculate HRA,DA and Total pay and print them out. Write another class with a main method. Create objects for three different employees and calculate the HRA, DA and total pay.
Code:

public class Employee {
int code;
String name;
String designation;
double basicPay;

public Employee(int code, String name, String designation, double basicPay) {
this.code = code;
this.name = name;
this.designation = designation;
this.basicPay = basicPay;
}

public void calculatePay() {
double hra = 0.1 * basicPay;
double da = 0.45 * basicPay;
double totalPay = basicPay + hra + da;

System.out.println("Employee Code: " + code);
System.out.println("Name: " + name);
System.out.println("Designation: " + designation);
System.out.println("Basic Pay: " + basicPay);
System.out.println("HRA: " + hra);
System.out.println("DA: " + da);
System.out.println("Total Pay: " + totalPay);
}
public static void main(String[] args) {
Employee emp1 = new Employee(1001, "John Doe", "Manager", 50000.0);
emp1.calculatePay();

Employee emp2 = new Employee(1002, "Jane Smith", "Assistant Manager", 40000.0);
emp2.calculatePay();

Employee emp3 = new Employee(1003, "Bob Johnson", "Clerk", 25000.0);
emp3.calculatePay();
}
}
Output:


5.1 : Write a program which defines base class Employee having three data members, namely name[30], emp_numb and gender and two methods namely input_data() and show_data(). Derive a class SalariedEmployee from Employee and adds a new data member, namely salary. It also adds two member methods,namely allowance (if gender is female HRA=0.1 *salary else 0.09* salary. DA=0.05*salary) and increment (salary= salary+0.1*salary). Display the gross in main class. (Tip: Use super to call base class’s constructor0).
Code:
class Employee {
String name;
int empNum;
char gender;

public void inputData(String name, int empNum, char gender) {
this.name = name;
this.empNum = empNum;
this.gender = gender;
}

public void showData() {
System.out.println("Name: " + name);
System.out.println("Employee Number: " + empNum);
System.out.println("Gender: " + gender);
}
}
class SalariedEmployee extends Employee {
double salary;
public SalariedEmployee(String name, int empNum, char gender, double salary) {
super.inputData(name, empNum, gender);
this.salary = salary;
}
public double allowance() {
double hra = gender == 'F' ? 0.1 * salary : 0.09 * salary;
double da = 0.05 * salary;
return hra + da;
}
public void increment() {
salary += 0.1 * salary;
}
public double gross() {
return salary + allowance();
}
public static void main(String[] args) {
SalariedEmployee emp = new SalariedEmployee("John Doe", 1001, 'M', 50000.0);
emp.increment();
System.out.println("Gross Salary: " + emp.gross());
}
}
Output:


5.2 : WAP that illustrates method overriding. Class A3 is extended by Class B3. Each of these classes defines a hello(string s) method that outputs the string“A3:Hello From” or “B3: Hello From” respectively. Use the Method Dispatch and keyword super concept Dynamic
Code:
class A3 {
public void hello(String s) {
System.out.println("A3: Hello From " + s);
}
}

class B3 extends A3 {
@Override
public void hello(String s) {
super.hello(s);
System.out.println("B3: Hello From " + s);
}
}

public class DynamicMethodDispatchDemo {
public static void main(String[] args) {
A3 a = new B3();
B3 b = new B3();

a.hello("A3");
b.hello("B3");
}
}
Output:

6 1. Write an abstract class shape, which defines abstract method area. Deriveclass circle from shape. It has data member radius and implementationforfunction. Derive class Triangle from shape. It has data members height, baseandimplementation for area function. Derive class Square fromshape. It hasmember side and implementation for area function. In main class, use dynamicmethod dispatch in order to call correct version of method.
Code:
abstract class Shape {
abstract double area();
}
class Circle extends Shapes {
double radius;

Circle(double r) {
radius = r;
}
double area() {
return Math.PI * radius * radius;
}
}
class Triangle extends Shapes {
double height, base;

Triangle(double h, double b) {
height = h;
base = b;
}

double area() {
return 0.5 * base * height;
}
}
class Square extends Shapes {
double side;

Square(double s) {
side = s;
}

double area() {
return side * side;
}
}
public class Lab6_1 {
public static void main(String[] args) {
Shapes[] shapes = new Shapes[3];
shapes[0] = new Circle(2);
shapes[1] = new Triangle(4, 5);
shapes[2] = new Square(3);
for (Shapes s : shapes) {
System.out.println("Area = " + s.area());
}
}
}
Output:

6.2 Create an interface Shape2D which declares a getArea() method. Point 3D contains coordinates of a point. The abstract class Shape declares abstract
display() method and is extended by Circle class. it implements the Shape2D
interface. The Shapes class instantiates this class and exercises its methods.
Code:
interface Shape2D
{
void getArea();
}
abstract class Shape
{
abstract void display();
}
class Point3D
{
double x,y,z;
Point3D(double x,double y,double z)
{
this.x = x;
this.y = y;
this.z = z;
}
}
class Circle extends Shape implements Shape2D
{
Point3D CenterPoint, OtherPoint;
double area;
Circle(Point3D P1, Point3D P2)
{
CenterPoint = P1;
OtherPoint = P2;
}
public void getArea()
{
double d1 = CenterPoint.x - OtherPoint.x;
double d2 = CenterPoint.y - OtherPoint.y;
double d = (d1*d1) + (d2*d2);
double radius = Math.sqrt(d);
area = Math.PI*radius*radius;
}
public void display()
{
System.out.println("nGiven points-> Center Point: ("+CenterPoint.x+", "+CenterPoint.y+", "+CenterPoint.z+") , Other Point: ("+OtherPoint.x+", "+OtherPoint.y+", "+OtherPoint.z+")nArea for a circle having given points: "+area+" __n");
}
}
class Shapes_Class
{
public static void main(String args[])
{
Point3D point1 = new Point3D(7,4,6);
Point3D point2 = new Point3D(5,2,8);
Circle obj = new Circle(point1 , point2);
obj.getArea();
obj.display();
}
}
Output:

7.1 . Create a package “employee” and define a Class Employee having threedatamembers, name, emp_num, and gender and two methods- input_data andshow_data. Inherit class SalariedEmployee from this class and keep it inpackage “employee”. Add new variable salary and methods allowance (if femalehra=0.1* salary else 0.09* salary. DA= 0.05*salary) and increment (salary=salary+0.01 * salary). Calculate gross salary in main class defined in the samepackage.

Code:
package Lab7.employee;
import java.util.Scanner;
public class Employee {
protected String name, gender;
protected int emp_num;
public void input_data() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
name = sc.nextLine();
System.out.println("Enter emp_num:");
emp_num = sc.nextInt();
sc.nextLine();
System.out.println("Enter gender:");
gender = sc.nextLine();
}
public void show_data() {
System.out.println("Name: " + name);
System.out.println("Employee Number: " + emp_num);
System.out.println("Gender: " + gender);
}
}

Output:

8.1 Write a program using try catch block. User should enter two command line arguments. If only one argument is entered then exception should be caught. Incase of two command line arguments, if fist is divided by second and if second command line argument is 0 then catch the appropriate exception.
Code:
package Lab8;
public class CommandLineArguments {
public static void main(String[] args) {
try {
if(args.length == 1) {
throw new IllegalArgumentException("Only one argument is entered");
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
if(num2 == 0) {
throw new ArithmeticException("Divide by zero error");
}
int result = num1/num2;
System.out.println("Result: " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
Output:

8.2 Define an exception called “No Match Exception” that is thrown when a string is not equal to “India”. Write a program that uses this exception.
Code:
package Lab8;
class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message);
}
}
public class StringMatcher {
public static void main(String[] args) {
String inputString = "USA";
try {
if (!inputString.equals("India")) {
throw new NoMatchException("Input string does not match India");
} else {
System.out.println("Input string matches India");
}
} catch (NoMatchException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}
Output:

9 1. The program to creates and run the following three threads. The first thread prints the letter ‘a’ 100 times. The second thread prints the letter ‘b’ 100 times. The third thread prints the integer 1 to 100.
Code:
package Lab9;
class PrintThread extends Thread {
private char c;
private int count;
public PrintThread(char c, int count) {
this.c = c;
this.count = count;
}
public void run() {
for (int i = 0; i < count; i++) {
System.out.print(c);
}
}
}
class NumberThread extends Thread {
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.print(i + " ");
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
PrintThread thread1 = new PrintThread('a', 100);
PrintThread thread2 = new PrintThread('b', 100);
NumberThread thread3 = new NumberThread();
thread1.start();
thread2.start();
thread3.start();
}
}
Output:

9.2 Write the thread program -1using Runnable interface.
Code:
package Lab9;

public class RunnableThreadDemo {

public static void main(String[] args) {
PrintATask printA = new PrintATask();
PrintBTask printB = new PrintBTask();
PrintNumbersTask printNumbers = new PrintNumbersTask();
Thread threadA = new Thread(printA);
threadA.start();
Thread threadB = new Thread(printB);
threadB.start();
Thread threadNumbers = new Thread(printNumbers);
threadNumbers.start();
}
private static class PrintATask implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print("a");
}
}
}
private static class PrintBTask implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.print("b");
}
}
}
private static class PrintNumbersTask implements Runnable {

@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.print(i + " ");
}
}
}
}
Output:

10. 1. Write a program that takes two files names (source and destination) as command line argument .Copy source file’s content to destination file. Use character stream class. Also do same using byte stream and buffer stream.
Code:
package Lab10;
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java FileCopy <source-file> <destination-file>");
System.exit(0);
}
String sourceFile = args[0];
String destFile = args[1];
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(destFile))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
System.out.println("Error copying file: " + e.getMessage());
}
try (InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.out.println("Error copying file: " + e.getMessage());
}

try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.out.println("Error copying file: " + e.getMessage());
}

System.out.println("File copy complete.");
}
}
Output:


10.2 Write a program which generates random integers and stores them in a file named “rand.dat”. The program then reads the integers from the file and displays on the screen.
Code:
package Lab10;
import java.io.*;
import java.util.*;
public class RandomIntegers {
public static void main(String[] args) {
try {
Random rand = new Random();
int[] numbers = new int[10];
for (int i = 0; i < 10; i++) {
numbers[i] = rand.nextInt(100) + 1;

FileOutputStream fos = new FileOutputStream("rand.dat");
DataOutputStream dos = new DataOutputStream(fos);
for (int i = 0; i < 10; i++) {
dos.writeInt(numbers[i]);
}
dos.close();
FileInputStream fis = new FileInputStream("rand.dat");
DataInputStream dis = new DataInputStream(fis);
for (int i = 0; i < 10; i++) {
int num = dis.readInt();
System.out.print(num + " ");
}
dis.close();

} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:

11.1 Write the program that demonstrate the use of Stack, Vector and Array List classes
Code:
package Lab11;
import java.util.Stack;
import java.util.Vector;
import java.util.ArrayList;
public class CollectionDemo {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
stack.push("Java");
stack.push("is");
stack.push("awesome");
System.out.println("Stack: " + stack);
Vector<Integer> vector = new Vector<Integer>();
vector.add(10);
vector.add(20);
vector.add(30);
System.out.println("Vector: " + vector);
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Hello");
arrayList.add("world");
arrayList.add("!");
System.out.println("ArrayList: " + arrayList);
System.out.println("Stack top: " + stack.peek());
System.out.println("Stack size: " + stack.size());
System.out.println("Vector element at index 1: " + vector.get(1));
System.out.println("Vector size: " + vector.size());
System.out.println("ArrayList element at index 2: " + arrayList.get(2));
System.out.println("ArrayList size: " + arrayList.size());
}
}
Output:

12.1 1. Write a Network program that client sends the data as redius of circle to server and server received that data and send the resultant area of circle to requested client.
Code:
package Lab12;
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverHostname = "localhost";
int port = 8080;
System.out.println("Connecting to " + serverHostname + " on port " + port);
Socket clientSocket = null;
try {
clientSocket = new Socket(serverHostname, port);
System.out.println("Connection established with " + clientSocket);
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: " + serverHostname);
System.exit(1);
}
OutputStream out = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
InputStream in = clientSocket.getInputStream();
DataInputStream dis = new DataInputStream(in);
double radius = 5.0;
dos.writeDouble(radius);
double area = dis.readDouble();
System.out.println("The area of circle with radius " + radius + " is " + area);
dis.close();
dos.close();
in.close();
out.close();
clientSocket.close();
}
}
Output:

13. Write a program to count occurrence of character in a string.
Code:
package Lab13;
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.print("Enter a character to count: ");
char c = scanner.nextLine().charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
System.out.println("The character '" + c + "' occurs " + count + " times in the string.");
}
}
Output:
     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.