You are on page 1of 41

Page |1

1.WAP to add two numbers


import java.util.Scanner;

class Addition1
{
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
int a = s1.nextInt();
int b = s1.nextInt();
int add = a + b;
System.out.println("Addition of two numbers is " + add);
s1.close();
}
}

OUTPUT:
Page |2

2. WAP to calculate area of circle


import java.util.Scanner;
class Area {
double circle(int radius) {
final double pi = 3.14;
int r = radius;
return (pi * Math.pow(r, 2));
}
}

class circle
{
public static void main(String[] args)
{
Scanner S = new Scanner(System.in);
Area A = new Area();
System.out.println("Enter Radius of Circle");
int b = S.nextInt();
double AREA = A.circle(b);
System.out.print("Area Of The Circle Is : "+AREA+" sq units.");
S.close();

}
}

OUTPUT:
Page |3

3. WAP to implement the concept of operators


import java.util.Scanner;
class demo
{
void display(float a,float b)
{
System.out.print("a+b=" + (a+b));
System.out.print("\na-b=" + (a-b));
System.out.print("\na/b=" + (a/b));
System.out.print("\na*b=" + (a*b));
}
}
class operator
{
public static void main(String[] args)
{
Scanner S1 = new Scanner(System.in);
demo d = new demo();
float x = S1.nextInt();
float y = S1.nextInt();
System.out.println("Concept of operators----->");
d.display(x,y);
S1.close();
}
}

OUTPUT:
Page |4

4.WAP to show that number is +ve or -ve (concept of if-else )


import java.util.Scanner;
class ifelse
{
public static void main(String[] args)
{
Scanner S = new Scanner(System.in);
int num = S.nextInt();
if(num > 0)
{
System.out.println("Number is positive");
}
else
{
System.out.print("Number is negative");
}
S.close();
}
}

OUTPUT:
Page |5

5. WAP to find largest number from three(concept of nested if)


import java.util.Scanner;
class largest
{
int bigger(int num1,int num2,int num3)
{
int largest;
if(num1>=num2)
{
if(num1>=num3)
{
largest = num1;
}
else
{
largest = num3;
}
}
else
{
if (num2>=num3)
{
largest = num2;
}
else
{
largest = num3;
}
}
return largest ;
}
}
class biggest_3
{
public static void main(String[] args)
{
largest obj = new largest();
Scanner obj1 = new Scanner(System.in);
System.out.println("Enter number for comparison->");
int a = obj1.nextInt();
Page |6

int b = obj1.nextInt();
int c = obj1.nextInt();
int BIGGER = obj.bigger(a,b,c);
System.out.print("\nThe Largest Number is "+BIGGER);
obj1.close();
}
}

OUTPUT:
Page |7

6. WAP to make calculator using switch statement


import java.util.Scanner;
public class Calculator
{
public static void main(String[] args) {
Scanner = new Scanner(System.in);

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


double firstNumber = scanner.nextDouble();

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


double secondNumber = scanner.nextDouble();

System.out.println("Enter the operator (+, -, *, /): ");


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

double result = 0;

switch (operator) {
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
result = firstNumber / secondNumber;
break;
default:
System.out.println("Invalid operator.");
break;
}

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


}
}
Page |8

OUTPUT:
Page |9

7. WAP to print a table using for loop.


import java.util.Scanner;
class demo2
{
void printable(int num)
{
for(int i=1;i<=10;i++)
{
System.out.println(num + " X " + i + " = " + (num*i));
}
}
}
class table
{
public static void main(String[] args)
{
Scanner S = new Scanner(System.in);
demo2 obj = new demo2();
try {
System.out.println("Enter number to print table for :-> ");
int a = S.nextInt();
obj.printable(a);
} finally {
S.close();
}
}
}

OUTPUT:
P a g e | 10

8. WAP to calculate area of rectangle with objects


import java.util.Scanner;
class rect
{
int area(int l,int b)
{
int x = l;
int y = b;
return (x*y);
}
}

class rect2
{
public static void main(String[] args)
{
Scanner S = new Scanner(System.in);
rect r1 = new rect();
int a,b;
a = S.nextInt();
b = S.nextInt();
int Area = r1.area(a,b);
System.out.println("The area of rectangle is");
System.out.println(Area);
S.close();
}
}

OUTPUT:
P a g e | 11

9. WAP to calculate area of rectangle without objects.


class rectangle
{
public static void main(String[] args)
{
int length = 15;
int breadth = 20;
int area = length*breadth;
System.out.println("The area of rectangle is "+area);
}
}

OUTPUT:
P a g e | 12

10. WAP to show concept of Method Overloading at least 3 functions.

public class Calculator1 {


// Method for adding two integers
public int add(int a, int b) {
return a + b;
}

// Method for adding three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Method for adding two double numbers


public double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator1 calculator = new Calculator1();

// Test the overloaded add methods


int result1 = calculator.add(10, 20);
int result2 = calculator.add(10, 20, 30);
double result3 = calculator.add(2.5, 3.5);

System.out.println("Result of int addition: " + result1);


System.out.println("Result of int addition with three arguments: " + result2);
System.out.println("Result of double addition: " + result3);
}
}
OUTPUT:
P a g e | 13

11. WAP to show concept of Method Overriding.


// Superclass
class Animal {
void makeSound() {
System.out.println("The animal makes a generic sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("The dog barks");
}
}
// Another Subclass
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("The cat meows");
}
}
public class Main1 {
public static void main(String[] args) {
Animal animal1 = new Dog(); // Create an instance of Dog
Animal animal2 = new Cat(); // Create an instance of Cat

animal1.makeSound(); // Calls Dog's makeSound() method


animal2.makeSound(); // Calls Cat's makeSound() method
}
}

OUTPUT:
P a g e | 14

12. WAP to show concept of single Inheritance .


// Superclass
class Animal01 {
void eat() {
System.out.println("The animal eats food.");
}
}

// Subclass
class Dog01 extends Animal01 {
void bark() {
System.out.println("The dog barks.");
}
}

public class single {


public static void main(String[] args) {
Dog01 myDog = new Dog01();
myDog.eat(); // Call the eat() method from the superclass
myDog.bark(); // Call the bark() method from the subclass
}
}

Output:
P a g e | 15

13. WAP to show concept of Multilevel Inheritance .


// Grandparent class
class Animal10 {
void eat() {
System.out.println("The animal eats food.");
}
}
// Parent class (inherits from Animal)
class Mammal10 extends Animal10 {
void run() {
System.out.println("The mammal runs.");
}
}
// Child class (inherits from Mammal)
class Dog10 extends Mammal10 {
void bark() {
System.out.println("The dog barks.");
}
}
public class multi {
public static void main(String[] args) {
Dog10 myDog = new Dog10();
myDog.eat(); // Call the eat() method from the Grandparent class (Animal)
myDog.run(); // Call the run() method from the Parent class (Mammal)
myDog.bark(); // Call the bark() method from the Child class (Dog)
}
}
OUTPUT:
P a g e | 16

14. WAP to show concept of Hierarchical Inheritance .


// Parent class
class Animal11 {
void eat() {
System.out.println("The animal eats food.");
}
}

// Child class 1
class Dog11 extends Animal11 {
void bark() {
System.out.println("The dog barks.");
}
}

// Child class 2
class Cat11 extends Animal11 {
void meow() {
System.out.println("The cat meows.");
}
}

public class heir {


public static void main(String[] args) {
Dog11 myDog = new Dog11();
Cat11 myCat = new Cat11();

myDog.eat(); // Call the eat() method from the Parent class (Animal) via
Dog
myDog.bark(); // Call the bark() method from the Dog class
System.out.println();

myCat.eat(); // Call the eat() method from the Parent class (Animal) via Cat
myCat.meow(); // Call the meow() method from the Cat class
}
}
P a g e | 17

OUTPUT:
P a g e | 18

15. WAP to show the concept of constructor overloading.


class Student {
private String name;
private int age;
private String department;

// Constructor with no parameters


public Student() {
name = "Unknown";
age = 0;
department = "Unassigned";
}

// Constructor with name and age parameters


public Student(String name, int age) {
this.name = name;
this.age = age;
department = "Unassigned";
}

// Constructor with all three parameters


public Student(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {


return age;
}

public String getDepartment() {


return department;
}
}
P a g e | 19

public class over {


public static void main(String[] args) {
// Create objects using different constructors
Student student1 = new Student(); // Default constructor
Student student2 = new Student("Alice", 20); // Constructor with name and
age
Student student3 = new Student("Bob", 22, "Computer Science"); //
Constructor with all three parameters

// Display student information


System.out.println("Student 1: " + student1.getName() + ", " +
student1.getAge() + ", " + student1.getDepartment());
System.out.println("Student 2: " + student2.getName() + ", " +
student2.getAge() + ", " + student2.getDepartment());
System.out.println("Student 3: " + student3.getName() + ", " +
student3.getAge() + ", " + student3.getDepartment());
}
}

OUTPUT:
P a g e | 20

16. WAP to Implement abstract classes .


// Abstract class
abstract class Shape
{
// Abstract method
public abstract void calculateArea();

// Concrete method
public void display() {
System.out.println("This is a shape.");
}
}

// Concrete class inheriting from the abstract class


class Circle extends Shape
{
private double radius;

public Circle(double radius) {


this.radius = radius;
}

// Implementation of the abstract method


public void calculateArea() {
double area = Math.PI * radius * radius;
System.out.println("Area of the circle: " + area);
}
}

// Concrete class inheriting from the abstract class


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

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}
P a g e | 21

// Implementation of the abstract method


public void calculateArea() {
double area = length * width;
System.out.println("Area of the rectangle: " + area);
}
}

// Main class
class absclass
{
public static void main(String[] args) {
// Creating objects of concrete classes
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);

// Calling methods
circle.display();
circle.calculateArea();

rectangle.display();
rectangle.calculateArea();
}
}

OUTPUT:
P a g e | 22

17. WAP to Implement Interfaces .


// Define an interface
interface Animal {
void sound();
void eat();
}

// Implement the interface in a class


class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}

public void eat() {


System.out.println("Dog eats bones");
}
}

// Implement the interface in another class


class Cat implements Animal {
public void sound() {
System.out.println("Cat meows");
}

public void eat() {


System.out.println("Cat eats fish");
}
}

// Main class to test the implementation


class inter
{
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound();
dog.eat();

Animal cat = new Cat();


cat.sound();
cat.eat();
P a g e | 23

}
}

OUTPUT:
P a g e | 24

18. WAP to Implement Multiple Inheritance with Interfaces


interface Animal {
void sound();
}

interface Mammal {
void eat();
}

class Dog implements Animal, Mammal {


public void sound() {
System.out.println("Dog barks");
}

public void eat() {


System.out.println("Dog eats bones");
}
}

class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.eat();
}
}

OUTPUT:
P a g e | 25

19. WAP to Concatenate Strings in JAVA


class StringConcatenation {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";

// Using the + operator


String result1 = str1 + str2;
System.out.println("Using + operator: " + result1);

// Using the concat() method


String result2 = str1.concat(str2);
System.out.println("Using concat() method: " + result2);

// Using StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(str1);
sb.append(str2);
String result3 = sb.toString();
System.out.println("Using StringBuilder: " + result3);

// Using StringBuffer
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(str1);
stringBuffer.append(str2);
String result4 = stringBuffer.toString();
System.out.println("Using StringBuffer: " + result4);
}
}

OUTPUT:
P a g e | 26

20. WAP to Show String Comparison in JAVA


public class StringComparison {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "Hello";

// Using equals() method


boolean isEqual1 = str1.equals(str2);
System.out.println("Using equals() method: " + isEqual1);

boolean isEqual2 = str1.equals(str3);


System.out.println("Using equals() method: " + isEqual2);

// Using equalsIgnoreCase() method


String str4 = "hello";
boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str4);
System.out.println("Using equalsIgnoreCase() method: " +
isEqualIgnoreCase);

// Using compareTo() method


int compareResult = str1.compareTo(str2);
System.out.println("Using compareTo() method: " + compareResult);

// Using compareToIgnoreCase() method


int compareResultIgnoreCase = str1.compareToIgnoreCase(str4);
System.out.println("Using compareToIgnoreCase() method: " +
compareResultIgnoreCase);
}
}

OUTPUT:
P a g e | 27

21. WAP to Find Substring from a String in JAVA


public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";

// Using substring(int beginIndex) method


String substring1 = str.substring(7);
System.out.println("Substring using substring(int beginIndex): " +
substring1);

// Using substring(int beginIndex, int endIndex) method


String substring2 = str.substring(7, 12);
System.out.println("Substring using substring(int beginIndex, int endIndex):
" + substring2);

// Using indexOf() method


int startIndex = str.indexOf("World");
String substring3 = str.substring(startIndex);
System.out.println("Substring using indexOf(): " + substring3);
}
}

OUTPUT:
P a g e | 28

22. WAP to Create and Import User Defined Package


Create a package named “MyClass.java”

package myPackage;

public class MyClass {


public void displayMessage() {
System.out.println("This is a message from the user-defined package!");
}
}

Now Import package using this command

import myPackage.MyClass;

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}

OUTPUT:
P a g e | 29

23. WAP to handle Arithmetic Exception


import java.util.Scanner;

public class ArithmeticExceptionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the dividend: ");


int dividend = scanner.nextInt();

System.out.print("Enter the divisor: ");


int divisor = scanner.nextInt();

try {
int result = dividend / divisor;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}

scanner.close();
}
}

OUTPUT:
P a g e | 30

24. WAP to Handle Multiple Exception using Multiple


Catch Block
public class MultipleCatchBlocksExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int index = 4;
int result = numbers[index];
System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds");
} catch (ArithmeticException e) {
System.out.println("Error: Arithmetic exception occurred");
} catch (Exception e) {
System.out.println("Error: An exception occurred");
}
}
}

OUTPUT:
P a g e | 31

25. WAP to Handle Multiple Exception using Throw


Keyword
public class ThrowKeywordExample {
public static void main(String[] args) {
try {
int age = -5;
validateAge(age);
System.out.println("Age is valid");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void validateAge(int age) {


if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}

OUTPUT:
P a g e | 32

26. WAP to Implement Super Keyword


class Animal {
String name;

Animal(String name) {
this.name = name;
}

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

class Dog extends Animal {


String breed;

Dog(String name, String breed) {


super(name);
this.breed = breed;
}

void sound() {
super.sound(); // calling the sound() method of the parent class
System.out.println("Dog barks");
}

void display() {
System.out.println("Name: " + super.name); // accessing the name variable
of the parent class
System.out.println("Breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Labrador");
myDog.sound();
myDog.display();
}
}
P a g e | 33

OUTPUT:
P a g e | 34

27. WAP to show Multitasking using single thread


class Task1 implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 1 - Count: " + i);
}
}
}

class Task2 implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 2 - Count: " + i);
}
}
}

class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new Task1());
Thread t2 = new Thread(new Task2());

t1.start();
t2.start();
}
}

OUTPUT:
P a g e | 35

28. WAP to show Multitasking using Multiple Threads


class Task1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 1 - Count: " + i);
}
}
}

class Task2 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Task 2 - Count: " + i);
}
}
}

class Main {
public static void main(String[] args) {
Task1 t1 = new Task1();
Task2 t2 = new Task2();

t1.start();
t2.start();
}
}

OUTPUT:
P a g e | 36

29. Write a Java Program to to perform various


operations in MySQL database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MySQLDatabaseOperations {


static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";

static final String USER = "yourUsername";


static final String PASSWORD = "yourPassword";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;

try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);

// Open a connection
System.out.println("Connecting to the database...");
conn = DriverManager.getConnection(DB_URL, USER, PASSWORD);

// Create a new database


String createDatabaseSQL = "CREATE DATABASE IF NOT EXISTS mydb";
stmt = conn.createStatement();
stmt.executeUpdate(createDatabaseSQL);
System.out.println("Database 'mydb' created successfully.");

// Switch to the newly created database


conn.setCatalog("mydb");

// Create a table
String createTableSQL = "CREATE TABLE IF NOT EXISTS employees (" +
"id INT AUTO_INCREMENT PRIMARY KEY, " +
P a g e | 37

"first_name VARCHAR(50), " +


"last_name VARCHAR(50))";
stmt.executeUpdate(createTableSQL);
System.out.println("Table 'employees' created successfully.");

// Insert records into the table


String insertSQL1 = "INSERT INTO employees (first_name, last_name)
VALUES ('John', 'Doe')";
String insertSQL2 = "INSERT INTO employees (first_name, last_name)
VALUES ('Jane', 'Smith')";
stmt.executeUpdate(insertSQL1);
stmt.executeUpdate(insertSQL2);
System.out.println("Records inserted successfully.");

// Fetch and display records


String selectSQL = "SELECT * FROM employees";
ResultSet resultSet = stmt.executeQuery(selectSQL);

System.out.println("Fetching records from 'employees' table:");


while (resultSet.next()) {
int id = resultSet.getInt("id");
String firstName = resultSet.getString("first_name");
String lastName = resultSet.getString("last_name");
System.out.println("ID: " + id + ", First Name: " + firstName + ", Last
Name: " + lastName);
}

// Clean up
resultSet.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
P a g e | 38

}
}
}
}

Output:
P a g e | 39

30. WAP to show file reader and writer stream

import java.io.*;

public class FileRWDemo {


public static void main(String[] args) {
int ch;
String str = "Welcome to the world of character streams";

try {
// Create an instance of FileWriter
FileWriter fileWrite = new FileWriter("charfile.txt");
fileWrite.write(str); // write the string to the file
fileWrite.close();
} catch (IOException e) {
e.printStackTrace();
}

try {
// Create an instance of FileReader
FileReader fileRead = new FileReader("charfile.txt");

// Reading data from a file


while ((ch = fileRead.read()) != -1) {
System.out.print((char) ch); // type cast to char to print characters
}

fileRead.close(); // close the reader stream


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

Output:
P a g e | 40

31. WAP to show buffered input and output stream

import java.io.*;

public class BufferIOStreamDemo {


public static void main(String[] args) {
int ch;
try {
// Create a file output stream
FileOutputStream fout = new FileOutputStream("mydata.dat");

// Create a buffered output stream


BufferedOutputStream bout = new BufferedOutputStream(fout);

// Write data to the stream


for (int i = 1; i <= 10; i++) {
bout.write(i); // Write individual bytes, not integer values
}

bout.close(); // Close buffered output stream


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

try {
// Create a file input stream
FileInputStream fin = new FileInputStream("mydata.dat");

// Create a buffered input stream


BufferedInputStream bin = new BufferedInputStream(fin);

// Reading data from a file, until EOF is reached


while ((ch = bin.read()) != -1) {
System.out.println(ch);
}

bin.close(); // Close buffered input stream


} catch (IOException e) {
e.printStackTrace();
}
P a g e | 41

}
}

Output:

You might also like