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

Java Practical Programs

Uploaded by

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

Java Practical Programs

Uploaded by

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

JAVA PRACTICALS CODE AND OUTPUT

Practical No.3 :

Write any program to check multiple Conditions using if statement.

public class MultipleConditionCheck {

public static void main(String[] args) {

int x = 10;

int y = 5;

// Checking multiple conditions

if (x > y) {

System.out.println("x is greater than y");

if (x < 15) {

System.out.println("x is less than 15");

if (y != 0) {
System.out.println("y is not equal to zero");

if (x % 2 == 0) {

System.out.println("x is even");

OUTPUT :

x is greater than y

x is less than 15

y is not equal to zero

x is even

Practical No.4 :

Write any program using switch case statement.


import java.util.Scanner;

public class DayOfWeek {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a day number (1-7): ");

int dayNumber = scanner.nextInt();

String dayName;

switch (dayNumber) {

case 1:

dayName = "Sunday";

break;

case 2:

dayName = "Monday";

break;

case 3:

dayName = "Tuesday";

break;

case 4:
dayName = "Wednesday";

break;

case 5:

dayName = "Thursday";

break;

case 6:

dayName = "Friday";

break;

case 7:

dayName = "Saturday";

break;

default:

dayName = "Invalid day number";

break;

System.out.println("The day is: " + dayName);

scanner.close();

}
OUTPUT :

Enter a day number (1-7): 3

The day is: Tuesday

Practical No.5 :

Develop a program to print command line argument using for loop.

public class CommandLineArguments {

public static void main(String[] args) {

System.out.println("Command Line Arguments:");

// Loop through each command-line argument

for (int i = 0; i < args.length; i++) {

System.out.println("Argument " + (i + 1) + ": " + args[i]);


}

OUTPUT :

java CommandLineArguments arg1 arg2 arg3

Command Line Arguments:

Argument 1: arg1

Argument 2: arg2

Argument 3: arg3

PRACTICAL NO.6 :

Develop a program to use logical operators in do-while loop.


import java.util.Scanner;

public class DoWhileWithLogicalOperators {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

char choice;

do {

System.out.println("Enter two numbers:");

int num1 = scanner.nextInt();

int num2 = scanner.nextInt();

System.out.println("Select operation (+, -, *, /):");

char operator = scanner.next().charAt(0);

double result;

// Perform calculation based on operator

switch (operator) {

case '+':

result = num1 + num2;


System.out.println("Result: " + result);

break;

case '-':

result = num1 - num2;

System.out.println("Result: " + result);

break;

case '*':

result = num1 * num2;

System.out.println("Result: " + result);

break;

case '/':

if (num2 != 0) {

result = (double) num1 / num2;

System.out.println("Result: " + result);

} else {

System.out.println("Cannot divide by zero!");

break;

default:

System.out.println("Invalid operator!");

break;

}
// Prompt the user to continue or not

System.out.println("Do you want to perform another operation? (y/n)");

choice = scanner.next().charAt(0);

} while (choice == 'y' || choice == 'Y');

scanner.close();

OUTPUT :

Enter two numbers:

Select operation (+, -, *, /):

Result: 8.0

Do you want to perform another operation? (y/n)


y

Enter two numbers:

10

Select operation (+, -, *, /):

Result: 5.0

Do you want to perform another operation? (y/n)

PRACTICAL NO. 7 & 8 :

Develop a program to show the use of implicit typecasting.

public class ImplicitTypeCasting {

public static void main(String[] args) {

// Implicit typecasting from int to double

int intValue = 10;


double doubleValue = intValue; // int promoted to double

System.out.println("int value: " + intValue);

System.out.println("double value: " + doubleValue);

// Implicit typecasting from float to double

float floatValue = 20.5f;

double doubleValue2 = floatValue; // float promoted to double

System.out.println("float value: " + floatValue);

System.out.println("double value: " + doubleValue2);

OUTPUT :

int value: 10

double value: 10.0

float value: 20.5

double value: 20.5


PRACTICAL NO.9 :

Develop a program to show the use of explicit type casting.

public class ExplicitTypeCasting {

public static void main(String[] args) {

// Explicit type casting from double to int

double doubleValue = 10.5;

int intValue = (int) doubleValue; // double explicitly casted to int

System.out.println("double value: " + doubleValue);

System.out.println("int value: " + intValue);

// Explicit type casting from double to float

double doubleValue2 = 20.7;

float floatValue = (float) doubleValue2; // double explicitly casted to float

System.out.println("double value: " + doubleValue2);

System.out.println("float value: " + floatValue);

}
OUTPUT :

double value: 10.5

int value: 10

double value: 20.7

float value: 20.7

PRACTICAL NO.10 :

Demonstrate the use of at least two types of constructors.

public class Car {

private String make;

private String model;

private int year;


// Default constructor

public Car() {

make = "Unknown";

model = "Unknown";

year = 0;

// Parameterized constructor

public Car(String make, String model, int year) {

this.make = make;

this.model = model;

this.year = year;

// Method to display car details

public void displayDetails() {

System.out.println("Make: " + make);

System.out.println("Model: " + model);

System.out.println("Year: " + year);

}
public static void main(String[] args) {

// Creating objects using both constructors

Car car1 = new Car(); // Using default constructor

Car car2 = new Car("Toyota", "Camry", 2022); // Using parameterized


constructor

// Displaying details of both cars

System.out.println("Details of Car 1:");

car1.displayDetails();

System.out.println();

System.out.println("Details of Car 2:");

car2.displayDetails();

OUTPUT :

Details of Car 1:

Make: Unknown
Model: Unknown

Year: 0

Details of Car 2:

Make: Toyota

Model: Camry

Year: 2022

PRACTICAL NO.11 & 12 :

Write a program to show the use of all methods of string class.

public class StringMethodsExample {

public static void main(String[] args) {

// Declaring a string

String str = "Hello, World!";

// 1. length(): returns the length of the string


System.out.println("Length of the string: " + str.length());

// Output: Length of the string: 13

// 2. charAt(int index): returns the character at the specified index

System.out.println("Character at index 7: " + str.charAt(7));

// Output: Character at index 7: W

// 3. substring(int beginIndex): returns a substring starting from the specified


index

System.out.println("Substring from index 7: " + str.substring(7));

// Output: Substring from index 7: World!

// 4. substring(int beginIndex, int endIndex): returns a substring within the


specified range

System.out.println("Substring from index 7 to 12: " + str.substring(7, 12));

// Output: Substring from index 7 to 12: World

// 5. contains(CharSequence s): checks if the string contains the specified


sequence

System.out.println("Does the string contain 'World'? " +


str.contains("World"));

// Output: Does the string contain 'World'? true


// 6. equals(Object another): checks if two strings are equal

String str2 = "Hello, World!";

System.out.println("Are the strings equal? " + str.equals(str2));

// Output: Are the strings equal? true

// 7. toLowerCase(): converts the string to lowercase

System.out.println("Lowercase string: " + str.toLowerCase());

// Output: Lowercase string: hello, world!

// 8. toUpperCase(): converts the string to uppercase

System.out.println("Uppercase string: " + str.toUpperCase());

// Output: Uppercase string: HELLO, WORLD!

// 9. trim(): removes leading and trailing whitespaces

String str3 = " Hello, World! ";

System.out.println("Trimmed string: '" + str3.trim() + "'");

// Output: Trimmed string: 'Hello, World!'

// 10. indexOf(int ch): returns the index of the first occurrence of the
specified character

System.out.println("Index of 'o': " + str.indexOf('o'));

// Output: Index of 'o': 4


// 11. lastIndexOf(int ch): returns the index of the last occurrence of the
specified character

System.out.println("Last index of 'o': " + str.lastIndexOf('o'));

// Output: Last index of 'o': 8

// 12. replace(CharSequence target, CharSequence replacement): replaces


occurrences of the target sequence with the replacement sequence

System.out.println("Replace 'World' with 'Java': " + str.replace("World",


"Java"));

// Output: Replace 'World' with 'Java': Hello, Java!

// 13. split(String regex): splits the string using the specified regular
expression

String[] parts = str.split(",");

System.out.println("Splitting the string: ");

for (String part : parts) {

System.out.println(part.trim());

/* Output:

Splitting the string:

Hello

World!
*/

// 14. startsWith(String prefix): checks if the string starts with the specified
prefix

System.out.println("Does the string start with 'Hello'? " +


str.startsWith("Hello"));

// Output: Does the string start with 'Hello'? true

// 15. endsWith(String suffix): checks if the string ends with the specified
suffix

System.out.println("Does the string end with 'World'? " +


str.endsWith("World"));

// Output: Does the string end with 'World'? false

// 16. isEmpty(): checks if the string is empty

System.out.println("Is the string empty? " + str.isEmpty());

// Output: Is the string empty? false

OUTPUT :
//Output is provided in the code itself in the form of comments.

PRACTICAL NO.13 :

Write a program to implement multidimensional array.

public class MultiDimensionalArrayExample {

public static void main(String[] args) {

// Declaring and initializing a 2D array

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Accessing elements of the 2D array using nested loops

System.out.println("Elements of the 2D array:");


for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println(); // Move to the next line after printing each row

OUTPUT :

Elements of the 2D array:

123

456

789

PRACTICAL NO.14 :
Write a program to insert different elements in the Vector and display
them.

import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

// Creating a Vector

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

// Inserting elements into the Vector

vector.add("Hello");

vector.add(123);

vector.add(3.14);

vector.add(true);

// Displaying elements of the Vector

System.out.println("Elements of the Vector:");

for (Object element : vector) {

System.out.println(element);

}
}

OUTPUT :

Elements of the Vector:

Hello

123

3.14

true

PRACTICAL NO.15 & 16 :

Write a Program to show the use of Integer Wrapper class Methods.

public class IntegerWrapperExample {


public static void main(String[] args) {

// Creating Integer objects

Integer num1 = 10;

Integer num2 = 20;

// intValue(): returns the value of the Integer object as an int

int value1 = num1.intValue();

System.out.println("Value of num1: " + value1);

// compareTo(Integer anotherInteger): compares two Integer objects


numerically

int comparison = num1.compareTo(num2);

System.out.println("Comparison result: " + comparison);

// max(Integer a, Integer b): returns the greater of two Integer objects

Integer max = Integer.max(num1, num2);

System.out.println("Max value: " + max);

// min(Integer a, Integer b): returns the smaller of two Integer objects

Integer min = Integer.min(num1, num2);

System.out.println("Min value: " + min);


// parseInt(String s): parses the string argument as a signed decimal integer

String str = "123";

int parsedValue = Integer.parseInt(str);

System.out.println("Parsed value: " + parsedValue);

// toString(int i): returns a String object representing the specified integer

String strValue = Integer.toString(parsedValue);

System.out.println("String representation: " + strValue);

// valueOf(int i): returns an Integer instance representing the specified int


value

Integer integerValue = Integer.valueOf(parsedValue);

System.out.println("Integer value: " + integerValue);

// hashCode(): returns the hash code value for this Integer object

int hashCode = integerValue.hashCode();

System.out.println("Hash code: " + hashCode);

// equals(Object obj): compares this Integer object to the specified object

boolean isEqual = num1.equals(num2);

System.out.println("Are num1 and num2 equal? " + isEqual);

}
}

OUTPUT :

Value of num1: 10

Comparison result: -1

Max value: 20

Min value: 10

Parsed value: 123

String representation: 123

Integer value: 123

Hash code: 123

Are num1 and num2 equal? false

PRACTICAL NO.17 :

Demonstrate the use of Overriding method display( ) using Super and


Sub classes.
// Superclass

class SuperClass {

// Method to display message

public void display() {

System.out.println("This is the display method of the superclass");

// Subclass extending SuperClass

class SubClass extends SuperClass {

// Overriding the display method

@Override

public void display() {

// Calling the superclass display method using super

super.display();

System.out.println("This is the display method of the subclass");

public class MethodOverrideExample {


public static void main(String[] args) {

// Creating an object of the subclass

SubClass subObj = new SubClass();

// Calling the display method of the subclass

subObj.display();

OUTPUT :

This is the display method of the superclass

This is the display method of the subclass

PRACTICAL NO.18 :

Write a program to implement single and multilevel inheritance.


// Superclass

class Animal {

// Method to print a message

public void eat() {

System.out.println("Animal is eating");

// Subclass inheriting from Animal (Single Inheritance)

class Dog extends Animal {

// Method to print a message

public void bark() {

System.out.println("Dog is barking");

// Subclass inheriting from Dog (Multilevel Inheritance)

class Labrador extends Dog {

// Method to print a message

public void color() {


System.out.println("Labrador is brown in color");

public class InheritanceExample {

public static void main(String[] args) {

// Single Inheritance

Dog dog = new Dog();

dog.eat(); // Accessing method from Animal class

dog.bark(); // Accessing method from Dog class

System.out.println();

// Multilevel Inheritance

Labrador labrador = new Labrador();

labrador.eat(); // Accessing method from Animal class

labrador.bark(); // Accessing method from Dog class

labrador.color(); // Accessing method from Labrador class

}
OUTPUT :

Animal is eating

Dog is barking

Animal is eating

Dog is barking

Labrador is brown in color

PRACTICAL NO.19 :

Demonstrate the use of interfaces to implemnet the concept of multiple


inheritance.

// First interface

interface Animal {

void eat(); // Abstract method


}

// Second interface

interface Vehicle {

void drive(); // Abstract method

// Class implementing both interfaces

class AnimalVehicle implements Animal, Vehicle {

// Implementation of eat() method from Animal interface

@Override

public void eat() {

System.out.println("AnimalVehicle is eating");

// Implementation of drive() method from Vehicle interface

@Override

public void drive() {

System.out.println("AnimalVehicle is driving");

}
public class MultipleInheritanceExample {

public static void main(String[] args) {

// Creating an object of class AnimalVehicle

AnimalVehicle animalVehicle = new AnimalVehicle();

// Calling methods from both interfaces

animalVehicle.eat();

animalVehicle.drive();

OUTPUT :

AnimalVehicle is eating

AnimalVehicle is driving

PRACTICAL NO.20 :
Write a program to implement user defined packages in terms of
creating a new package and importing the same.

package mypackage;

public class MyClass {

public void display() {

System.out.println("This is MyClass in mypackage");

/*Now, let's create another Java file outside the mypackage directory to
demonstrate how to use this package.*/

import mypackage.MyClass;

public class PackageDemo {

public static void main(String[] args) {

// Create an object of MyClass from the mypackage package

MyClass obj = new MyClass();


// Call the display method of MyClass

obj.display();

/*To compile and run these files:

Open terminal/command prompt.

Navigate to the directory containing both files.

Compile the files using the following commands:*/

javac mypackage/MyClass.java

javac PackageDemo.java

//Run the program using the command://

java PackageDemo

OUTPUT :
This is MyClass in mypackage

PRACTICAL NO.21 & 22 :

Develop a simple real-life application program to illustrate the use of


multithreads.

import java.util.concurrent.*;

// Class representing a cafe order

class Order {

private String itemName;

public Order(String itemName) {

this.itemName = itemName;

// Method to prepare the order


public void prepareOrder() {

System.out.println("Preparing order for: " + itemName);

try {

// Simulate order preparation time

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Order for: " + itemName + " is ready");

// Class representing a cafe staff member who processes orders

class CafeStaff implements Runnable {

private Order order;

public CafeStaff(Order order) {

this.order = order;

@Override

public void run() {


order.prepareOrder();

public class CafeSimulation {

public static void main(String[] args) {

// Create a thread pool with 3 threads

ExecutorService executor = Executors.newFixedThreadPool(3);

// Create some cafe orders

Order order1 = new Order("Coffee");

Order order2 = new Order("Sandwich");

Order order3 = new Order("Cake");

// Assign orders to cafe staff members

CafeStaff staff1 = new CafeStaff(order1);

CafeStaff staff2 = new CafeStaff(order2);

CafeStaff staff3 = new CafeStaff(order3);

// Submit orders to the thread pool

executor.submit(staff1);

executor.submit(staff2);
executor.submit(staff3);

// Shut down the executor after all tasks are completed

executor.shutdown();

OUTPUT :

Preparing order for: Coffee

Preparing order for: Sandwich

Preparing order for: Cake

Order for: Coffee is ready

Order for: Sandwich is ready

Order for: Cake is ready

PRACTICAL NO.23, 24 & 25 :


Demonstrates exception handling using try,catch and finally block.

import java.util.Scanner;

public class ExceptionHandlingExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

// Prompt the user to enter two numbers

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

int num1 = scanner.nextInt();

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

int num2 = scanner.nextInt();

// Perform division operation

int result = num1 / num2;

System.out.println("Result of division: " + result);

} catch (ArithmeticException e) {

// Catch block to handle ArithmeticException


System.out.println("Error: Division by zero is not allowed.");

} catch (Exception e) {

// Catch block to handle other exceptions

System.out.println("An error occurred: " + e.getMessage());

} finally {

// Finally block to close the scanner and perform cleanup

scanner.close();

System.out.println("Scanner closed.");

OUTPUT :

Enter the first number: 10

Enter the second number: 2

Result of division: 5

Scanner closed.
PRACTICAL NO.26 & 27 :

Demonstrate use of throw and throws clause.

USING THROW :

class AgeValidationException extends Exception {

public AgeValidationException(String message) {

super(message);

class Voter {

public void validateAge(int age) throws AgeValidationException {

if (age < 18) {

throw new AgeValidationException("Age must be 18 or above to vote.");

System.out.println("Age validated successfully. You are eligible to vote.");


}

public class ThrowAndThrowsExample {

public static void main(String[] args) {

Voter voter = new Voter();

try {

voter.validateAge(17);

} catch (AgeValidationException e) {

System.out.println("Error: " + e.getMessage());

OUTPUT :

Error: Age must be 18 or above to vote.

USING THROWS :
import java.io.FileNotFoundException;

import java.io.FileReader;

public class ThrowsExample {

public static void readFile(String filename) throws FileNotFoundException {

FileReader fileReader = new FileReader(filename);

System.out.println("File " + filename + " opened successfully.");

public static void main(String[] args) {

try {

readFile("example.txt");

} catch (FileNotFoundException e) {

System.out.println("Error: File not found.");

}
OUTPUT :

Error: File not found.

PRACTICAL NO.28 :

Create two applets by using different ways in java.

Approach 1: Extending the java.applet.Applet class

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello, World!", 20, 20);


}

OUTPUT :

typically need to embed them in an HTML file

Approach 2: Implementing the java.applet.Applet interface

import java.applet.Applet;

import java.awt.Graphics;

public class AnotherApplet implements Applet {

public void init() {

// Initialization code

public void start() {


// Start code

public void stop() {

// Stop code

public void destroy() {

// Cleanup code

public void paint(Graphics g) {

g.drawString("Hello from Another Applet!", 20, 20);

OUTPUT :

typically need to embed them in an HTML file


PRACTICAL NO.29 :

Write a program to implement an applet to draw basic animated


shapes.

import java.applet.Applet;

import java.awt.Color;

import java.awt.Graphics;

public class AnimatedShapesApplet extends Applet implements Runnable {

private int x = 0; // Initial x-coordinate of the circle

private int y = 50; // y-coordinate of the circle

public void init() {

setBackground(Color.white);

}
public void start() {

Thread t = new Thread(this);

t.start(); // Start the thread

public void run() {

try {

while (true) {

// Move the circle to the right

x += 5;

// Repaint the applet window

repaint();

// Pause for a moment

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}
public void paint(Graphics g) {

// Draw the circle at (x, y)

g.setColor(Color.blue);

g.fillOval(x, y, 30, 30);

OUTPUT :

need to embed it in an HTML file and open it in a browser.

PRACTICAL NO.30 :

Demonstrate the use of basic applet,which includes different shapes


like cone,cube,cylinders,etc.

import java.applet.Applet;
import java.awt.Color;

import java.awt.Graphics;

public class BasicShapesApplet extends Applet {

public void paint(Graphics g) {

// Draw cone

g.setColor(Color.red);

g.fillArc(50, 50, 100, 100, 0, 180);

g.drawLine(50, 100, 100, 200);

g.drawLine(150, 100, 100, 200);

// Draw cube

g.setColor(Color.green);

g.fillRect(200, 50, 100, 100);

g.fillRect(250, 100, 100, 100);

g.drawLine(200, 50, 250, 100);

g.drawLine(300, 50, 350, 100);

g.drawLine(200, 150, 250, 200);

g.drawLine(300, 150, 350, 200);

// Draw cylinder

g.setColor(Color.blue);
g.fillOval(400, 50, 100, 50);

g.fillOval(400, 150, 100, 50);

g.fillRect(400, 75, 100, 75);

g.fillRect(400, 50, 100, 50);

g.fillRect(400, 150, 100, 50);

g.setColor(Color.white);

g.drawLine(400, 75, 400, 150);

g.drawLine(500, 75, 500, 150);

OUTPUT :

embed this applet in an HTML file to view Output.

PRACTICAL NO.31 & 32 :


Demonstrate the use of stream classes for reading and writing
bytes/characters.

Reading and Writing Bytes:

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class ByteStreamExample {

public static void main(String[] args) {

try {

// Writing bytes to a file

FileOutputStream outputStream = new FileOutputStream("output.txt");

outputStream.write("Hello, World!".getBytes());

outputStream.close();

// Reading bytes from a file

FileInputStream inputStream = new FileInputStream("output.txt");

int data;
while ((data = inputStream.read()) != -1) {

System.out.print((char) data);

inputStream.close();

} catch (IOException e) {

e.printStackTrace();

OUTPUT :

Hello, World!

Reading and Writing Characters:

import java.io.FileReader;

import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample {

public static void main(String[] args) {

try {

// Writing characters to a file

FileWriter writer = new FileWriter("output.txt");

writer.write("Hello, World!");

writer.close();

// Reading characters from a file

FileReader reader = new FileReader("output.txt");

int data;

while ((data = reader.read()) != -1) {

System.out.print((char) data);

reader.close();

} catch (IOException e) {

e.printStackTrace();

}
OUTPUT :

Hello, World!

You might also like