0% found this document useful (0 votes)
17 views37 pages

Java Programs for Beginners: Basics to Data Types

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views37 pages

Java Programs for Beginners: Basics to Data Types

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
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link];

public class MultiplicationTable {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter a number

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

int number = [Link]();

// Print the multiplication table for the given number

[Link]("Multiplication Table for " + number + ":");

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

[Link](number + " x " + i + " = " + (number * i));

// Close the scanner

[Link]();

}
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++) {

[Link]("*");

// Move to the next line after each row

[Link]();

}
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 [Link];

public class CircleCalculator {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter the radius

[Link]("Enter the radius of the circle: ");

double radius = [Link]();

// Calculate the area and perimeter

double area = [Link] * [Link](radius, 2);

double perimeter = 2 * [Link] * radius;

// Print the results

[Link]("Area of the circle: %.2f\n", area);

[Link]("Perimeter (Circumference) of the circle: %.2f\n", perimeter);

// Close the scanner

[Link]();

}
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 [Link];

public class BinaryAddition {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter two binary numbers

[Link]("Enter the first binary number: ");

String binary1 = [Link]();

[Link]("Enter the second binary number: ");

String binary2 = [Link]();

// Convert binary strings to decimal integers

int num1 = [Link](binary1, 2);

int num2 = [Link](binary2, 2);

// Add the two decimal numbers

int sum = num1 + num2;

// Convert the sum back to binary

String binarySum = [Link](sum);


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

// Print the result

[Link]("Sum of " + binary1 + " and " + binary2 + " is: " + binarySum);

// Close the scanner

[Link]();

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 [Link];

public class NumberConverter {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Choose conversion type:");

[Link]("1. Decimal to Binary");

[Link]("2. Binary to Decimal");

[Link]("Enter your choice (1 or 2): ");

int choice = [Link]();

switch (choice) {

case 1:

// Decimal to Binary

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

int decimalNumber = [Link]();

String binaryString = [Link](decimalNumber);

[Link]("Binary representation: " + binaryString);

break;

case 2:

// Binary to Decimal

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


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
String binaryInput = [Link]();

int decimalValue = [Link](binaryInput, 2);

[Link]("Decimal representation: " + decimalValue);

break;

default:

[Link]("Invalid choice. Please select 1 or 2.");

break;

// Close the scanner

[Link]();

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 [Link];

public class CharacterCounter {

public static void main(String[] args) {

// Create a Scanner object to read input

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter a string

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

String inputString = [Link]();

// Initialize counters

int letterCount = 0;

int spaceCount = 0;

int digitCount = 0;

int otherCount = 0;

// Iterate through each character in the string

for (char ch : [Link]()) {

if ([Link](ch)) {

letterCount++;

} else if ([Link](ch)) {

digitCount++;
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
} else if ([Link](ch)) {

spaceCount++;

} else {

otherCount++;

// Print the results

[Link]("Letters: " + letterCount);

[Link]("Digits: " + digitCount);

[Link]("Spaces: " + spaceCount);

[Link]("Other characters: " + otherCount);

// Close the scanner

[Link]();

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

[Link]("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);

[Link]("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

[Link]("Smallest element: " + minMax[0]);

[Link]("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 < [Link]; 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() {

[Link]("This animal eats food.");

// Derived class

class Dog extends Animal {

// Method in the derived class

void bark() {

[Link]("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
[Link]();

// Call method from the derived class

[Link]();

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() {

[Link]("Animal makes a sound");

// Derived class

class Dog extends Animal {

// Overriding the sound method

@Override

void sound() {

[Link]("Dog barks");

// Another derived class

class Cat extends Animal {

// Overriding the sound method

@Override

void sound() {

[Link]("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

[Link](); // Output: Dog barks

[Link](); // 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() {

[Link]("Dog eats dog food.");

// Implementing the methods from Pet interface

@Override

public void play() {

[Link]("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

[Link](); // Output: Dog eats dog food.

[Link](); // 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 [Link];

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

[Link](10);

[Link](20);

[Link](30);

[Link](40);

[Link](50);

// Displaying the elements of the Vector

[Link]("Elements in the Vector: " + vector);

// Accessing elements

[Link]("First element: " + [Link](0));

[Link]("Second element: " + [Link](1));

// Removing an element

[Link](2); // Removes the element at index 2 (30)


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
[Link]("After removing element at index 2: " + vector);

// Checking the size of the Vector

[Link]("Size of the Vector: " + [Link]());

// Iterating through the Vector

[Link]("Iterating through the Vector:");

for (Integer element : vector) {

[Link](element);

// Clearing the Vector

[Link]();

[Link]("After clearing, size of the Vector: " + [Link]());

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() {

[Link]([Link]().getName() + " is in RUNNABLE state.");

try {

// Simulating some work with sleep

[Link](2000); // Timed Waiting state

[Link]([Link]().getName() + " is back to RUNNABLE state


after sleep.");

} catch (InterruptedException e) {

[Link]([Link]().getName() + " was interrupted.");

synchronized (this) {

[Link]([Link]().getName() + " is in BLOCKED state.");

try {

// Simulating waiting for a lock

wait(); // Waiting state

} catch (InterruptedException e) {

[Link]([Link]().getName() + " was interrupted while


waiting.");

[Link]([Link]().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

[Link]();

[Link]();

try {

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

[Link](500);

synchronized (thread1) {

[Link](); // Notify thread1 to continue

[Link](500);

synchronized (thread2) {

[Link](); // Notify thread2 to continue

} catch (InterruptedException e) {

[Link]("Main thread was interrupted.");

// Wait for threads to finish

try {
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
[Link]();

[Link]();

} catch (InterruptedException e) {

[Link]("Main thread was interrupted while waiting for threads to


finish.");

[Link]("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) {

[Link] = name;

@Override

public void run() {

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

[Link](threadName + " - Count: " + i);

try {

// Sleep for a while to simulate work

[Link](500);

} catch (InterruptedException e) {

[Link](threadName + " interrupted.");

[Link](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

[Link]();

[Link]();

// Wait for threads to finish

try {

[Link]();

[Link]();

} catch (InterruptedException e) {

[Link]("Main thread interrupted.");

[Link]("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 [Link];

import [Link];

import [Link];

public class FileReadExample {

public static void main(String[] args) {

// Specify the path to the file

String filePath = "[Link]"; // 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 = [Link]()) != null) {

[Link](line); // Print each line to the console

} catch (IOException e) {

[Link]("An error occurred while reading the file: " + [Link]());

}
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 [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class FileCopyExample {

public static void main(String[] args) {

// Specify the source and destination file paths

String sourceFilePath = "[Link]"; // Change this to your source file path

String destinationFilePath = "[Link]"; // 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 = [Link]()) != null) {

[Link](line);

[Link](); // Write a new line to the destination file

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
[Link]("File copied successfully!");

} catch (IOException e) {

[Link]("An error occurred while copying the file: " + [Link]());

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 [Link];

import [Link];

import [Link];

import [Link];

public class StudentDataExample {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

String filePath = "[Link]"; // 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))) {

[Link]("Enter student data (type 'exit' to stop):");

while (true) {

[Link]("Enter student name: ");

String name = [Link]();

if ([Link]("exit")) {

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

[Link]("Enter student age: ");


NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021
int age = [Link]([Link]());

[Link]("Enter student grade: ");

String grade = [Link]();

// Write the student data to the file

[Link]("Name: " + name + ", Age: " + age + ", Grade: " + grade);

[Link](); // Write a new line for the next entry

[Link]("Student data saved.");

[Link]("Data entry completed. All student data has been saved to " +
filePath);

} catch (IOException e) {

[Link]("An error occurred while writing to the file: " + [Link]());

} catch (NumberFormatException e) {

[Link]("Invalid input for age. Please enter a valid number.");

} finally {

[Link](); // Close the scanner

}
NAME – SAHIL SATISH GUPTA
ROLL NO – BS242021

OUTPUT

You might also like