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

Java

The document contains a series of Java programming exercises completed by Sahil Satish Gupta, including practicals on Java basics, operators, data types, inheritance, vectors, and multithreading. Each section includes a question, the corresponding Java program, and the expected output. The programs cover a variety of topics such as multiplication tables, pattern displays, area and perimeter calculations, binary addition, character counting, and thread lifecycle management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java

The document contains a series of Java programming exercises completed by Sahil Satish Gupta, including practicals on Java basics, operators, data types, inheritance, vectors, and multithreading. Each section includes a question, the corresponding Java program, and the expected output. The programs cover a variety of topics such as multiplication tables, pattern displays, area and perimeter calculations, binary addition, character counting, and thread lifecycle management.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

NAME – SAHIL SATISH GUPTA

ROLL NO – BS242021

PRACTICAL 1 – JAVA BASICS


Q.1 Write a java program that takes a number as input and print its
multiplication table upto 10.

PROGRAM
import java.util.Scanner;

public class MultiplicationTable {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number

System.out.print("Enter a number: ");

int number = scanner.nextInt();

// Print the multiplication table for the given number

System.out.println("Multiplication Table for " + number + ":");

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

System.out.println(number + " x " + i + " = " + (number * i));

// Close the scanner

scanner.close();

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.2 Write a java program to display the following pattern.


*****
****
***
**
*
PROGRAM
public class PatternDisplay {

public static void main(String[] args) {

// Number of rows for the pattern

int rows = 5;

// Loop to print the pattern

for (int i = rows; i >= 1; i--) {

// Print '*' for each column in the current row

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

System.out.print("*");

// Move to the next line after each row

System.out.println();

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.3 Write a java program to print the area and perimeter of a circle.

PROGRAM
import java.util.Scanner;

public class CircleCalculator {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the radius

System.out.print("Enter the radius of the circle: ");

double radius = scanner.nextDouble();

// Calculate the area and perimeter

double area = Math.PI * Math.pow(radius, 2);

double perimeter = 2 * Math.PI * radius;

// Print the results

System.out.printf("Area of the circle: %.2f\n", area);

System.out.printf("Perimeter (Circumference) of the circle: %.2f\n", perimeter);

// Close the scanner

scanner.close();

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

PRACTICAL 2 – USE OF OPERATORS


Q.1 Write a java program to add two binary number.

PROGRAM
import java.util.Scanner;

public class BinaryAddition {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter two binary numbers

System.out.print("Enter the first binary number: ");

String binary1 = scanner.nextLine();

System.out.print("Enter the second binary number: ");

String binary2 = scanner.nextLine();

// Convert binary strings to decimal integers

int num1 = Integer.parseInt(binary1, 2);

int num2 = Integer.parseInt(binary2, 2);

// Add the two decimal numbers

int sum = num1 + num2;

// Convert the sum back to binary

String binarySum = Integer.toBinaryString(sum);


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

// Print the result

System.out.println("Sum of " + binary1 + " and " + binary2 + " is: " + binarySum);

// Close the scanner

scanner.close();

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
Q.2 Write a java program to convert a decimal number to binary number or
vice versa.

PROGRAM
import java.util.Scanner;

public class NumberConverter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Choose conversion type:");

System.out.println("1. Decimal to Binary");

System.out.println("2. Binary to Decimal");

System.out.print("Enter your choice (1 or 2): ");

int choice = scanner.nextInt();

switch (choice) {

case 1:

// Decimal to Binary

System.out.print("Enter a decimal number: ");

int decimalNumber = scanner.nextInt();

String binaryString = Integer.toBinaryString(decimalNumber);

System.out.println("Binary representation: " + binaryString);

break;

case 2:

// Binary to Decimal

System.out.print("Enter a binary number: ");


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
String binaryInput = scanner.next();

int decimalValue = Integer.parseInt(binaryInput, 2);

System.out.println("Decimal representation: " + decimalValue);

break;

default:

System.out.println("Invalid choice. Please select 1 or 2.");

break;

// Close the scanner

scanner.close();

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

PRACTICAL 3 – JAVA DATA TYPES


Q.1 Write a java program to count the letters, space, numbers and other
characters of an input string.

PROGRAM
import java.util.Scanner;

public class CharacterCounter {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a string

System.out.print("Enter a string: ");

String inputString = scanner.nextLine();

// Initialize counters

int letterCount = 0;

int spaceCount = 0;

int digitCount = 0;

int otherCount = 0;

// Iterate through each character in the string

for (char ch : inputString.toCharArray()) {

if (Character.isLetter(ch)) {

letterCount++;

} else if (Character.isDigit(ch)) {

digitCount++;
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
} else if (Character.isWhitespace(ch)) {

spaceCount++;

} else {

otherCount++;

// Print the results

System.out.println("Letters: " + letterCount);

System.out.println("Digits: " + digitCount);

System.out.println("Spaces: " + spaceCount);

System.out.println("Other characters: " + otherCount);

// Close the scanner

scanner.close();

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
Q.2 Implement a java function that calculate the sum of digits for a given char
array consisting of the digits '0' to '9'. The function should return the digit
sum as a long value.

PROGRAM
public class DigitSumCalculator {

public static long calculateDigitSum(char[] digits) {

long sum = 0;

// Iterate through each character in the array

for (char digit : digits) {

// Check if the character is a digit

if (digit >= '0' && digit <= '9') {

// Convert the character to its integer value and add to sum

sum += (digit - '0'); // Subtracting '0' gives the integer value

} else {

// If the character is not a valid digit, you can handle it as needed

System.out.println("Invalid character: " + digit);

return sum;

public static void main(String[] args) {

// Example usage

char[] digitArray = {'1', '2', '3', '4', '5'};


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
long result = calculateDigitSum(digitArray);

System.out.println("The sum of digits is: " + result);

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.3 Find the smallest and largest element from the array.

PROGRAM
public class MinMaxFinder {

public static void main(String[] args) {

// Example array

int[] numbers = {34, 15, 88, 2, 7, 99, -5, 42};

// Call the method to find the smallest and largest elements

int[] minMax = findMinMax(numbers);

// Print the results

System.out.println("Smallest element: " + minMax[0]);

System.out.println("Largest element: " + minMax[1]);

public static int[] findMinMax(int[] array) {

// Initialize min and max with the first element of the array

int min = array[0];

int max = array[0];

// Iterate through the array to find min and max

for (int i = 1; i < array.length; i++) {

if (array[i] < min) {

min = array[i]; // Update min

if (array[i] > max) {

max = array[i]; // Update max


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
}

// Return the min and max as an array

return new int[]{min, max};

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

PRACTICAL 4 – INHERITANCE
Q.1 Write a java program to implement a single level inheritance.

PROGRAM
// Base class

class Animal {

// Method in the base class

void eat() {

System.out.println("This animal eats food.");

// Derived class

class Dog extends Animal {

// Method in the derived class

void bark() {

System.out.println("The dog barks.");

// Main class to test the inheritance

public class SingleLevelInheritance {

public static void main(String[] args) {

// Create an object of the derived class

Dog dog = new Dog();

// Call method from the base class


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
dog.eat();

// Call method from the derived class

dog.bark();

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.2 Write a java program to implement method overriding.

PROGRAM
// Base class

class Animal {

// Method to be overridden

void sound() {

System.out.println("Animal makes a sound");

// Derived class

class Dog extends Animal {

// Overriding the sound method

@Override

void sound() {

System.out.println("Dog barks");

// Another derived class

class Cat extends Animal {

// Overriding the sound method

@Override

void sound() {

System.out.println("Cat meows");

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

// Main class to test method overriding

public class MethodOverridingExample {

public static void main(String[] args) {

// Create objects of the derived classes

Animal myDog = new Dog();

Animal myCat = new Cat();

// Call the overridden methods

myDog.sound(); // Output: Dog barks

myCat.sound(); // Output: Cat meows

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.3 Write a java program to implement multiple inheritance.

PROGRAM
// First interface

interface Animal {

void eat();

// Second interface

interface Pet {

void play();

// Class that implements both interfaces

class Dog implements Animal, Pet {

// Implementing the methods from Animal interface

@Override

public void eat() {

System.out.println("Dog eats dog food.");

// Implementing the methods from Pet interface

@Override

public void play() {

System.out.println("Dog plays fetch.");

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
// Main class to test multiple inheritance

public class MultipleInheritanceExample {

public static void main(String[] args) {

Dog myDog = new Dog();

// Call methods from both interfaces

myDog.eat(); // Output: Dog eats dog food.

myDog.play(); // Output: Dog plays fetch.

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

PRACTICAL 5 – VECTORS AND MULTITHREADING


Q.1 Write a java program to implement the vectors.

PROGRAM
import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

// Create a Vector to hold Integer elements

Vector<Integer> vector = new Vector<>();

// Adding elements to the Vector

vector.add(10);

vector.add(20);

vector.add(30);

vector.add(40);

vector.add(50);

// Displaying the elements of the Vector

System.out.println("Elements in the Vector: " + vector);

// Accessing elements

System.out.println("First element: " + vector.get(0));

System.out.println("Second element: " + vector.get(1));

// Removing an element

vector.remove(2); // Removes the element at index 2 (30)


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
System.out.println("After removing element at index 2: " + vector);

// Checking the size of the Vector

System.out.println("Size of the Vector: " + vector.size());

// Iterating through the Vector

System.out.println("Iterating through the Vector:");

for (Integer element : vector) {

System.out.println(element);

// Clearing the Vector

vector.clear();

System.out.println("After clearing, size of the Vector: " + vector.size());

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.2 Write a java program to implement thread life cycle.

PROGRAM
class MyThread extends Thread {

@Override

public void run() {

System.out.println(Thread.currentThread().getName() + " is in RUNNABLE state.");

try {

// Simulating some work with sleep

Thread.sleep(2000); // Timed Waiting state

System.out.println(Thread.currentThread().getName() + " is back to RUNNABLE state


after sleep.");

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " was interrupted.");

synchronized (this) {

System.out.println(Thread.currentThread().getName() + " is in BLOCKED state.");

try {

// Simulating waiting for a lock

wait(); // Waiting state

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " was interrupted while


waiting.");

System.out.println(Thread.currentThread().getName() + " is in TERMINATED state.");


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
}

public class ThreadLifeCycleExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

// Starting the threads

thread1.start();

thread2.start();

try {

// Main thread sleeps for a while to let the other threads run

Thread.sleep(500);

synchronized (thread1) {

thread1.notify(); // Notify thread1 to continue

Thread.sleep(500);

synchronized (thread2) {

thread2.notify(); // Notify thread2 to continue

} catch (InterruptedException e) {

System.out.println("Main thread was interrupted.");

// Wait for threads to finish

try {
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
thread1.join();

thread2.join();

} catch (InterruptedException e) {

System.out.println("Main thread was interrupted while waiting for threads to


finish.");

System.out.println("Main thread is in TERMINATED state.");

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.3 Write a java program to implement multithreading.

PROGRAM
class MyThread extends Thread {

private String threadName;

MyThread(String name) {

this.threadName = name;

@Override

public void run() {

for (int i = 0; i < 5; i++) {

System.out.println(threadName + " - Count: " + i);

try {

// Sleep for a while to simulate work

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(threadName + " interrupted.");

System.out.println(threadName + " has finished execution.");

public class MultithreadingExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread("Thread 1");


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
MyThread thread2 = new MyThread("Thread 2");

// Start the threads

thread1.start();

thread2.start();

// Wait for threads to finish

try {

thread1.join();

thread2.join();

} catch (InterruptedException e) {

System.out.println("Main thread interrupted.");

System.out.println("Main thread has finished execution.");

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

PRACTICAL 5 – FILE HANDLING


Q.1 Write a java program to open a file and display the content in the console
windows.

PROGRAM
import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

public class FileReadExample {

public static void main(String[] args) {

// Specify the path to the file

String filePath = "example.txt"; // Change this to your file path

// Use try-with-resources to ensure the BufferedReader is closed automatically

try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {

String line;

// Read the file line by line

while ((line = br.readLine()) != null) {

System.out.println(line); // Print each line to the console

} catch (IOException e) {

System.err.println("An error occurred while reading the file: " + e.getMessage());

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.2 Write a java program to copy the content from one file to other file.

PROGRAM
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

public class FileCopyExample {

public static void main(String[] args) {

// Specify the source and destination file paths

String sourceFilePath = "source.txt"; // Change this to your source file path

String destinationFilePath = "destination.txt"; // Change this to your destination file path

// Use try-with-resources to ensure resources are closed automatically

try (BufferedReader br = new BufferedReader(new FileReader(sourceFilePath));

BufferedWriter bw = new BufferedWriter(new FileWriter(destinationFilePath))) {

String line;

// Read from the source file and write to the destination file

while ((line = br.readLine()) != null) {

bw.write(line);

bw.newLine(); // Write a new line to the destination file

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
System.out.println("File copied successfully!");

} catch (IOException e) {

System.err.println("An error occurred while copying the file: " + e.getMessage());

OUTPUT
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

Q.3 Write a java program to read the student data from user and store it in
the file.

PROGRAM
import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class StudentDataExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String filePath = "students.txt"; // Specify the file path to store student data

// Use try-with-resources to ensure the BufferedWriter is closed automatically

try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {

System.out.println("Enter student data (type 'exit' to stop):");

while (true) {

System.out.print("Enter student name: ");

String name = scanner.nextLine();

if (name.equalsIgnoreCase("exit")) {

break; // Exit the loop if the user types 'exit'

System.out.print("Enter student age: ");


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
int age = Integer.parseInt(scanner.nextLine());

System.out.print("Enter student grade: ");

String grade = scanner.nextLine();

// Write the student data to the file

writer.write("Name: " + name + ", Age: " + age + ", Grade: " + grade);

writer.newLine(); // Write a new line for the next entry

System.out.println("Student data saved.");

System.out.println("Data entry completed. All student data has been saved to " +
filePath);

} catch (IOException e) {

System.err.println("An error occurred while writing to the file: " + e.getMessage());

} catch (NumberFormatException e) {

System.err.println("Invalid input for age. Please enter a valid number.");

} finally {

scanner.close(); // Close the scanner

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT

You might also like