Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Java Lab File

Java Lab File for colleges

Uploaded by

imabhishek5677
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Java Lab File

Java Lab File for colleges

Uploaded by

imabhishek5677
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

INDEX

S.No. Topic

1. Sum of first 10 natural numbers

2. Calculate the Area of Rectangle and the Area of the


circle

3. Implementing static functions and static methods

4. Calculate the perimeter of Circle, Rectangle and


Square

5. Implement the Abstract class

6. Program to show the Access Specifiers in Java

7. Implement the Dynamic Method Dispatch in Java

8. Implementing the final variable and final class in


java

9. Java program implementing the var args

10. Java Program implementing the Exception Handling code

11. Java Program to implement the String operations

12. Program to copy bytes from one file to another file.

13. Program to read bytes from the file and display the
content on the screen.

14. Stream class to copy the contents of a file from one


to another

15. Multi Thread program in which every thread increment


the shared variable

16. Create a package and use it


1. Program to give sum of first 10 natural numbers.

Code:-

public class SumOfNaturalNumbers {


public static void main(String[] args) {
int sum = 0;
int n = 10; // Number of natural numbers to sum up

for (int i = 1; i <= n; i++) {


sum += i;
}

System.out.println("The sum of the first " + n + " natural numbers


is: " + sum);
}
}

Output:-

2. Program to calculate the Area of Rectangle and the Area of the circle.

Code:-

public class SimpleAreaCalculator {


public static void main(String[] args) {

double length = 5.0; // Length of the rectangle


double width = 3.0; // Width of the rectangle

// Calculate the area of the rectangle


double rectangleArea = length * width;
System.out.println("The area of the rectangle is: " +
rectangleArea);

// Predefined value for the circle


double radius = 4.0; // Radius of the circle

// Calculate the area of the circle


double circleArea = 3.14 * radius * radius;
System.out.println("The area of the circle is: " + circleArea);
}
}

Output:-

3. Program implementing static functions and static methods.

Code:-

public class StaticExample {


// Static variable
static int counter = 0;

// Static method to increment the counter


public static void incrementCounter() {
counter++;
}

// Static method to display the counter


public static void displayCounter() {
System.out.println("Counter value: " + counter);
}

public static void main(String[] args) {


// Call static methods
StaticExample.incrementCounter();
StaticExample.displayCounter();

StaticExample.incrementCounter();
StaticExample.displayCounter();
}
}

Output:-

4. Program to calculate the perimeter of Circle, Rectangle and Square.

Code:-

public class PerimeterCalculator {

// Method to calculate the perimeter of a rectangle


public static double calculateRectanglePerimeter(double length, double
width) {
return 2 * (length + width);
}

// Method to calculate the perimeter of a square


public static double calculateSquarePerimeter(double side) {
return 4 * side;
}

// Method to calculate the perimeter of a circle


public static double calculateCirclePerimeter(double radius) {
return 2 * Math.PI * radius;
}

public static void main(String[] args) {


// Predefined values
double length = 5.0; // Length of the rectangle
double width = 3.0; // Width of the rectangle
double side = 4.0; // Side of the square
double radius = 6.0; // Radius of the circle

// Calculate and display the perimeters


double rectanglePerimeter = calculateRectanglePerimeter(length,
width);
System.out.println("The perimeter of the rectangle is: " +
rectanglePerimeter);

double squarePerimeter = calculateSquarePerimeter(side);


System.out.println("The perimeter of the square is: " +
squarePerimeter);

double circlePerimeter = calculateCirclePerimeter(radius);


System.out.println("The perimeter of the circle is: " +
circlePerimeter);
}
}

Output:-
5. Program to implement the Abstract class.

Code:-

abstract class Shape {


// Abstract method for calculating the area
abstract double calculateArea();

// Abstract method for calculating the perimeter


abstract double calculatePerimeter();

// Concrete method for displaying shape details


public void display() {
System.out.println("Area: " + calculateArea());
System.out.println("Perimeter: " + calculatePerimeter());
}
}

// Subclass Rectangle extending Shape


class Rectangle extends Shape {
private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

// Implementing the abstract method calculateArea


@Override
double calculateArea() {
return length * width;
}

// Implementing the abstract method calculatePerimeter


@Override
double calculatePerimeter() {
return 2 * (length + width);
}
}
// Subclass Circle extending Shape
class Circle extends Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

// Implementing the abstract method calculateArea


@Override
double calculateArea() {
return Math.PI * radius * radius;
}

// Implementing the abstract method calculatePerimeter


@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

public class AbstractClassExample {


public static void main(String[] args) {
// Create a rectangle and a circle
Shape rectangle = new Rectangle(5.0, 3.0);
Shape circle = new Circle(4.0);

// Display the details of the rectangle


System.out.println("Rectangle:");
rectangle.display();

// Display the details of the circle


System.out.println("Circle:");
circle.display();
}
}
Output:-

6. Program to show the Access Specifiers in Java

Code:-

class AccessSpecifierExample {
// Public variable - accessible from anywhere
public int publicVar = 10;

protected int protectedVar = 20;

private int privateVar = 30;

int defaultVar = 40;

// Public method - accessible from anywhere


public void showPublic() {
System.out.println("Public Method. PublicVar: " + publicVar);
}

// Protected method - accessible within the same package and subclasses


protected void showProtected() {
System.out.println("Protected Method. ProtectedVar: " +
protectedVar);
}

// Private method - accessible only within this class


private void showPrivate() {
System.out.println("Private Method. PrivateVar: " + privateVar);
}

// Package-private (default) method - accessible within the same


package
void showDefault() {
System.out.println("Default Method. DefaultVar: " + defaultVar);
}

// Method to demonstrate access to private method


public void accessPrivate() {
showPrivate();
}
}

// Another class in the same package


public class AccessSpecifierDemo {
public static void main(String[] args) {
AccessSpecifierExample example = new AccessSpecifierExample();

// Accessing public variable and method


System.out.println("Public Variable: " + example.publicVar);
example.showPublic();

// Accessing protected variable and method


System.out.println("Protected Variable: " + example.protectedVar);
example.showProtected();

// Accessing private method through a public method


example.accessPrivate();

// Accessing default/package-private variable and method


System.out.println("Default Variable: " + example.defaultVar);
example.showDefault();
}
}

Output:-
7. Program to Implement the Dynamic Method Dispatch in Java

Code :-

// Superclass
class Animal {
// Overridden method
void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog
class Dog extends Animal {
// Overriding method
@Override
void sound() {
System.out.println("Dog barks");
}
}

// Subclass Cat
class Cat extends Animal {
// Overriding method
@Override
void sound() {
System.out.println("Cat meows");
}
}

public class DynamicMethodDispatch {


public static void main(String[] args) {
// Reference of type Animal and object of type Animal
Animal myAnimal = new Animal();
myAnimal.sound(); // Outputs: Animal makes a sound

// Reference of type Animal and object of type Dog


myAnimal = new Dog();
myAnimal.sound(); // Outputs: Dog barks

// Reference of type Animal and object of type Cat


myAnimal = new Cat();
myAnimal.sound(); // Outputs: Cat meows
}
}

Output:-

8. Program implementing the final variable and final class in java

Code:-

final class FinalClass {


// Final variable
final int finalVariable;

// Constructor to initialize the final variable


public FinalClass(int value) {
this.finalVariable = value;
}

// Method to display the value of the final variable


public void display() {
System.out.println("The value of the final variable is: " +
finalVariable);
}

// Method that cannot be overridden


public final void finalMethod() {
System.out.println("This is a final method and cannot be
overridden.");
}
}

public class FinalVariableAndClass {


public static void main(String[] args) {
// Creating an instance of FinalClass
FinalClass finalClassInstance = new FinalClass(10);

// Displaying the value of the final variable


finalClassInstance.display();

// Calling the final method


finalClassInstance.finalMethod();

// Demonstrating final local variable


final int localFinalVariable = 20;
System.out.println("The value of the local final variable is: " +
localFinalVariable);
}
}
Output:-
9. Java program implementing the var args

Code:-

public class VarArgsExample {

// Method to calculate the sum of integers using varargs


public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}

public static void main(String[] args) {


// Calling the sum method with different numbers of arguments
System.out.println("Sum of 1, 2, 3: " + sum(1, 2, 3));
System.out.println("Sum of 10, 20, 30, 40, 50: " + sum(10, 20, 30,
40, 50));
System.out.println("Sum of no arguments: " + sum());
System.out.println("Sum of 7: " + sum(7));
}
}

Output:-

10. Java Program implementing the Exception Handling code


Code:-

import java.util.Scanner;

public class ExceptionHandlingExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter denominator: ");
int denominator = scanner.nextInt();

try {
// Attempting to divide numerator by denominator
int result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
// Catching arithmetic exceptions (e.g., division by zero)
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
// Catching any other exceptions
System.out.println("An error occurred: " + e.getMessage());
} finally {
// Closing resources or doing cleanup tasks
scanner.close();
System.out.println("Program execution completed.");
}
}

// Method to perform division


public static int divide(int numerator, int denominator) {
// Division operation
return numerator / denominator;
}
}

Output:-
11. Java Program to implement the String operations

Code:-

public class StringOperationsExample {


public static void main(String[] args) {
// Example strings
String str1 = "Hello";
String str2 = "World";
String str3 = "hello";
String str4 = "Hello";

// Concatenation
String concatenatedString = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenatedString);

// Length
System.out.println("Length of str1: " + str1.length());

// Comparison
System.out.println("Comparison of str1 and str2: " +
str1.equals(str2)); // false
System.out.println("Comparison of str1 and str4: " +
str1.equals(str4)); // true
System.out.println("Case insensitive comparison of str1 and str3: "
+ str1.equalsIgnoreCase(str3)); // true

// Substring
String substr = str1.substring(1, 3); // from index 1 to 2
System.out.println("Substring of str1: " + substr);
// Uppercase and lowercase
System.out.println("Uppercase of str1: " + str1.toUpperCase());
System.out.println("Lowercase of str2: " + str2.toLowerCase());

// Index of
System.out.println("Index of 'e' in str1: " + str1.indexOf('e'));
// returns first occurrence

// Replace
String replacedString = str1.replace('l', 'w');
System.out.println("String after replacement: " + replacedString);

// Trim
String str5 = " Hello ";
System.out.println("Trimmed String of str5: " + str5.trim());

// Split
String sentence = "Java is a powerful programming language";
String[] words = sentence.split(" ");
System.out.println("Words in the sentence:");
for (String word : words) {
System.out.println(word);
}
}
}

Output:-
12. Write a program to copy bytes from one file to another file.

Code:-

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytesFromFile {


public static void main(String[] args) {
// Specify the source and destination file paths
String sourceFilePath = "source.txt";
String destinationFilePath = "destination.txt";

// FileInputStream to read the source file


FileInputStream fileInputStream = null;
// FileOutputStream to write to the destination file
FileOutputStream fileOutputStream = null;

try {
fileInputStream = new FileInputStream(sourceFilePath);
fileOutputStream = new FileOutputStream(destinationFilePath);

// Buffer to hold bytes during the copying process


byte[] buffer = new byte[1024];
int bytesRead;

// Read from the source file and write to the destination file
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}

System.out.println("File copied successfully.");


}
catch (IOException e) {
// Handle possible I/O errors
System.err.println("Error during file copy: " +
e.getMessage());
}
finally {
// Close the FileInputStream and FileOutputStream
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
System.err.println("Error closing files: " +
e.getMessage());
}
}
}
}

Output:-
13. Write a program to read bytes from the file and display the content on
the screen.

Code:-

import java.io.FileInputStream;
import java.io.IOException;

public class ReadBytesFromFile {


public static void main(String[] args) {
// Specify the path to the file
String filePath = "example.txt";

// FileInputStream to read the file


FileInputStream fileInputStream = null;

try {
fileInputStream = new FileInputStream(filePath);

// Read bytes from the file and display them


int byteData;
while ((byteData = fileInputStream.read()) != -1) {
// Convert byte to character and print it
System.out.print((char) byteData);
}
}
catch (IOException e) {
// Handle possible I/O errors
System.err.println("Error reading the file: " +
e.getMessage());
}
finally {
// Close the FileInputStream
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
System.err.println("Errorclosingthefile: " +
e.getMessage());
}
}
}
}
}

Output:-

14. Using Stream class to copy the contents of a file from one to another.

Code:-

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCopyExample {


public static void main(String[] args) {
// Source and destination file paths
Path sourceFile = Paths.get("source.txt");
Path destinationFile = Paths.get("destination.txt");

// Copy file using streams


try {
// Ensure the destination file exists (create if it does not)
if (!Files.exists(destinationFile)) {
Files.createFile(destinationFile);
}

// Copy the content from source to destination


Files.copy(sourceFile, destinationFile,
java.nio.file.StandardCopyOption.REPLACE_EXISTING);

System.out.println("File copied successfully!");


} catch (IOException e) {
System.err.println("I/O Error: " + e.getMessage());
}
}
}

Output:-

15. Multi Thread program in which every thread increment the shared
variable

Code:-

class SharedResource {
private int counter = 0;

// Method to increment the counter


public synchronized void increment() {
counter++;
}

// Method to get the counter value


public synchronized int getCounter() {
return counter;
}
}

class IncrementThread extends Thread {


private final SharedResource sharedResource;

public IncrementThread(SharedResource sharedResource) {


this.sharedResource = sharedResource;
}

@Override
public void run() {
for (int i = 0; i < 1000; i++) {
sharedResource.increment();
}
}
}

public class MultithreadIncrement {


public static void main(String[] args) {
SharedResource sharedResource = new SharedResource();
int numThreads = 10;

// Create and start threads


Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = new IncrementThread(sharedResource);
threads[i].start();
}

// Wait for all threads to complete


for (int i = 0; i < numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Print the final value of the counter
System.out.println("Final counter value: " +
sharedResource.getCounter());
}
}

Output:-

16. Create a package and use it

Code:-

// File: Emp.java
package employee;

public class Emp {

private String name;


private int empid;
private String category;
private double bpay;
private double hra;
private double da;
private double npay;
private double pf;
private double grosspay;
private double incometax;
private double allowance;
public Emp(String name, int empid, String category, double bpay, double
hra, double da) {
this.name = name;
this.empid = empid;
this.category = category;
this.bpay = bpay;
this.hra = hra;
this.da = da;
}

public void calculateNetPay() {


grosspay = bpay + hra + da;
pf = 0.12 * grosspay;
incometax = 0.1 * grosspay;
allowance = 0.05 * grosspay;
npay = grosspay - (pf + incometax - allowance);
}

public void printPayrollDetails() {


System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + empid);
System.out.println("Category: " + category);
System.out.println("Basic Pay: " + bpay);
System.out.println("HRA: " + hra);
System.out.println("DA: " + da);
System.out.println("Gross Pay: " + grosspay);
System.out.println("PF: " + pf);
System.out.println("Income Tax: " + incometax);
System.out.println("Allowance: " + allowance);
System.out.println("Net Pay: " + npay);
}
}

// Importing the above package


import employee.Emp;

public class Emppay {


public static void main(String[] args) {

Emp e = new Emp("RAJ", 1001, "Regular", 50000, 20000, 15000);

e.calculateNetPay();

e.printPayrollDetails();
}
}

Output:-

You might also like