0% found this document useful (0 votes)
76 views41 pages

Java File Uday

The document provides 14 code examples demonstrating various Java programming concepts: 1. Adding two numbers 2. Calculating area of a circle 3. Implementing arithmetic operators 4. Checking if a number is positive or negative 5. Finding the largest of three numbers using nested if statements 6. Building a basic calculator using switch statement 7. Printing a multiplication table using for loop 8. Calculating area of rectangle with and without objects 9. Demonstrating method overloading with 3 functions 10. Demonstrating method overriding by overriding a method in subclasses 11. Demonstrating single inheritance 12. Demonstrating multilevel inheritance 13. Demonstrating hierarchical inheritance

Uploaded by

uday vaidya
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)
76 views41 pages

Java File Uday

The document provides 14 code examples demonstrating various Java programming concepts: 1. Adding two numbers 2. Calculating area of a circle 3. Implementing arithmetic operators 4. Checking if a number is positive or negative 5. Finding the largest of three numbers using nested if statements 6. Building a basic calculator using switch statement 7. Printing a multiplication table using for loop 8. Calculating area of rectangle with and without objects 9. Demonstrating method overloading with 3 functions 10. Demonstrating method overriding by overriding a method in subclasses 11. Demonstrating single inheritance 12. Demonstrating multilevel inheritance 13. Demonstrating hierarchical inheritance

Uploaded by

uday vaidya
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

Page |1

[Link] to add two numbers


import [Link];

class Addition1
{
public static void main(String[] args) {
Scanner s1 = new Scanner([Link]);
int a = [Link]();
int b = [Link]();
int add = a + b;
[Link]("Addition of two numbers is " + add);
[Link]();
}
}

OUTPUT:
Page |2

2. WAP to calculate area of circle


import [Link];
class Area {
double circle(int radius) {
final double pi = 3.14;
int r = radius;
return (pi * [Link](r, 2));
}
}

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

}
}

OUTPUT:
Page |3

3. WAP to implement the concept of operators


import [Link];
class demo
{
void display(float a,float b)
{
[Link]("a+b=" + (a+b));
[Link]("\na-b=" + (a-b));
[Link]("\na/b=" + (a/b));
[Link]("\na*b=" + (a*b));
}
}
class operator
{
public static void main(String[] args)
{
Scanner S1 = new Scanner([Link]);
demo d = new demo();
float x = [Link]();
float y = [Link]();
[Link]("Concept of operators----->");
[Link](x,y);
[Link]();
}
}

OUTPUT:
Page |4

[Link] to show that number is +ve or -ve (concept of if-else )


import [Link];
class ifelse
{
public static void main(String[] args)
{
Scanner S = new Scanner([Link]);
int num = [Link]();
if(num > 0)
{
[Link]("Number is positive");
}
else
{
[Link]("Number is negative");
}
[Link]();
}
}

OUTPUT:
Page |5

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


import [Link];
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([Link]);
[Link]("Enter number for comparison->");
int a = [Link]();
Page |6

int b = [Link]();
int c = [Link]();
int BIGGER = [Link](a,b,c);
[Link]("\nThe Largest Number is "+BIGGER);
[Link]();
}
}

OUTPUT:
Page |7

6. WAP to make calculator using switch statement


import [Link];
public class Calculator
{
public static void main(String[] args) {
Scanner = new Scanner([Link]);

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


double firstNumber = [Link]();

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


double secondNumber = [Link]();

[Link]("Enter the operator (+, -, *, /): ");


char operator = [Link]().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:
[Link]("Invalid operator.");
break;
}

[Link]("The result is: " + result);


}
}
Page |8

OUTPUT:
Page |9

7. WAP to print a table using for loop.


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

OUTPUT:
P a g e | 10

8. WAP to calculate area of rectangle with objects


import [Link];
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([Link]);
rect r1 = new rect();
int a,b;
a = [Link]();
b = [Link]();
int Area = [Link](a,b);
[Link]("The area of rectangle is");
[Link](Area);
[Link]();
}
}

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;
[Link]("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 = [Link](10, 20);
int result2 = [Link](10, 20, 30);
double result3 = [Link](2.5, 3.5);

[Link]("Result of int addition: " + result1);


[Link]("Result of int addition with three arguments: " + result2);
[Link]("Result of double addition: " + result3);
}
}
OUTPUT:
P a g e | 13

11. WAP to show concept of Method Overriding.


// Superclass
class Animal {
void makeSound() {
[Link]("The animal makes a generic sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void makeSound() {
[Link]("The dog barks");
}
}
// Another Subclass
class Cat extends Animal {
@Override
void makeSound() {
[Link]("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

[Link](); // Calls Dog's makeSound() method


[Link](); // Calls Cat's makeSound() method
}
}

OUTPUT:
P a g e | 14

12. WAP to show concept of single Inheritance .


// Superclass
class Animal01 {
void eat() {
[Link]("The animal eats food.");
}
}

// Subclass
class Dog01 extends Animal01 {
void bark() {
[Link]("The dog barks.");
}
}

public class single {


public static void main(String[] args) {
Dog01 myDog = new Dog01();
[Link](); // Call the eat() method from the superclass
[Link](); // 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() {
[Link]("The animal eats food.");
}
}
// Parent class (inherits from Animal)
class Mammal10 extends Animal10 {
void run() {
[Link]("The mammal runs.");
}
}
// Child class (inherits from Mammal)
class Dog10 extends Mammal10 {
void bark() {
[Link]("The dog barks.");
}
}
public class multi {
public static void main(String[] args) {
Dog10 myDog = new Dog10();
[Link](); // Call the eat() method from the Grandparent class (Animal)
[Link](); // Call the run() method from the Parent class (Mammal)
[Link](); // 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() {
[Link]("The animal eats food.");
}
}

// Child class 1
class Dog11 extends Animal11 {
void bark() {
[Link]("The dog barks.");
}
}

// Child class 2
class Cat11 extends Animal11 {
void meow() {
[Link]("The cat meows.");
}
}

public class heir {


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

[Link](); // Call the eat() method from the Parent class (Animal) via
Dog
[Link](); // Call the bark() method from the Dog class
[Link]();

[Link](); // Call the eat() method from the Parent class (Animal) via Cat
[Link](); // 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) {
[Link] = name;
[Link] = age;
department = "Unassigned";
}

// Constructor with all three parameters


public Student(String name, int age, String department) {
[Link] = name;
[Link] = age;
[Link] = 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


[Link]("Student 1: " + [Link]() + ", " +
[Link]() + ", " + [Link]());
[Link]("Student 2: " + [Link]() + ", " +
[Link]() + ", " + [Link]());
[Link]("Student 3: " + [Link]() + ", " +
[Link]() + ", " + [Link]());
}
}

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() {
[Link]("This is a shape.");
}
}

// Concrete class inheriting from the abstract class


class Circle extends Shape
{
private double radius;

public Circle(double radius) {


[Link] = radius;
}

// Implementation of the abstract method


public void calculateArea() {
double area = [Link] * radius * radius;
[Link]("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) {


[Link] = length;
[Link] = width;
}
P a g e | 21

// Implementation of the abstract method


public void calculateArea() {
double area = length * width;
[Link]("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
[Link]();
[Link]();

[Link]();
[Link]();
}
}

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

public void eat() {


[Link]("Dog eats bones");
}
}

// Implement the interface in another class


class Cat implements Animal {
public void sound() {
[Link]("Cat meows");
}

public void eat() {


[Link]("Cat eats fish");
}
}

// Main class to test the implementation


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

Animal cat = new Cat();


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

public void eat() {


[Link]("Dog eats bones");
}
}

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

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;
[Link]("Using + operator: " + result1);

// Using the concat() method


String result2 = [Link](str2);
[Link]("Using concat() method: " + result2);

// Using StringBuilder
StringBuilder sb = new StringBuilder();
[Link](str1);
[Link](str2);
String result3 = [Link]();
[Link]("Using StringBuilder: " + result3);

// Using StringBuffer
StringBuffer stringBuffer = new StringBuffer();
[Link](str1);
[Link](str2);
String result4 = [Link]();
[Link]("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 = [Link](str2);
[Link]("Using equals() method: " + isEqual1);

boolean isEqual2 = [Link](str3);


[Link]("Using equals() method: " + isEqual2);

// Using equalsIgnoreCase() method


String str4 = "hello";
boolean isEqualIgnoreCase = [Link](str4);
[Link]("Using equalsIgnoreCase() method: " +
isEqualIgnoreCase);

// Using compareTo() method


int compareResult = [Link](str2);
[Link]("Using compareTo() method: " + compareResult);

// Using compareToIgnoreCase() method


int compareResultIgnoreCase = [Link](str4);
[Link]("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 = [Link](7);
[Link]("Substring using substring(int beginIndex): " +
substring1);

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


String substring2 = [Link](7, 12);
[Link]("Substring using substring(int beginIndex, int endIndex):
" + substring2);

// Using indexOf() method


int startIndex = [Link]("World");
String substring3 = [Link](startIndex);
[Link]("Substring using indexOf(): " + substring3);
}
}

OUTPUT:
P a g e | 28

22. WAP to Create and Import User Defined Package


Create a package named “[Link]”

package myPackage;

public class MyClass {


public void displayMessage() {
[Link]("This is a message from the user-defined package!");
}
}

Now Import package using this command

import [Link];

public class Main {


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

OUTPUT:
P a g e | 29

23. WAP to handle Arithmetic Exception


import [Link];

public class ArithmeticExceptionExample {


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

[Link]("Enter the dividend: ");


int dividend = [Link]();

[Link]("Enter the divisor: ");


int divisor = [Link]();

try {
int result = dividend / divisor;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: " + [Link]());
}

[Link]();
}
}

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];
[Link]("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index out of bounds");
} catch (ArithmeticException e) {
[Link]("Error: Arithmetic exception occurred");
} catch (Exception e) {
[Link]("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);
[Link]("Age is valid");
} catch (IllegalArgumentException e) {
[Link]("Error: " + [Link]());
}
}

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) {
[Link] = name;
}

void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


String breed;

Dog(String name, String breed) {


super(name);
[Link] = breed;
}

void sound() {
[Link](); // calling the sound() method of the parent class
[Link]("Dog barks");
}

void display() {
[Link]("Name: " + [Link]); // accessing the name variable
of the parent class
[Link]("Breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy", "Labrador");
[Link]();
[Link]();
}
}
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++) {
[Link]("Task 1 - Count: " + i);
}
}
}

class Task2 implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task 2 - Count: " + i);
}
}
}

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

[Link]();
[Link]();
}
}

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++) {
[Link]("Task 1 - Count: " + i);
}
}
}

class Task2 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task 2 - Count: " + i);
}
}
}

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

[Link]();
[Link]();
}
}

OUTPUT:
P a g e | 36

29. Write a Java Program to to perform various


operations in MySQL database
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MySQLDatabaseOperations {


static final String JDBC_DRIVER = "[Link]";
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
[Link](JDBC_DRIVER);

// Open a connection
[Link]("Connecting to the database...");
conn = [Link](DB_URL, USER, PASSWORD);

// Create a new database


String createDatabaseSQL = "CREATE DATABASE IF NOT EXISTS mydb";
stmt = [Link]();
[Link](createDatabaseSQL);
[Link]("Database 'mydb' created successfully.");

// Switch to the newly created database


[Link]("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))";
[Link](createTableSQL);
[Link]("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')";
[Link](insertSQL1);
[Link](insertSQL2);
[Link]("Records inserted successfully.");

// Fetch and display records


String selectSQL = "SELECT * FROM employees";
ResultSet resultSet = [Link](selectSQL);

[Link]("Fetching records from 'employees' table:");


while ([Link]()) {
int id = [Link]("id");
String firstName = [Link]("first_name");
String lastName = [Link]("last_name");
[Link]("ID: " + id + ", First Name: " + firstName + ", Last
Name: " + lastName);
}

// Clean up
[Link]();
[Link]();
[Link]();
} catch (SQLException se) {
[Link]();
} catch (Exception e) {
[Link]();
} finally {
try {
if (stmt != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException se) {
[Link]();
P a g e | 38

}
}
}
}

Output:
P a g e | 39

30. WAP to show file reader and writer stream

import [Link].*;

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("[Link]");
[Link](str); // write the string to the file
[Link]();
} catch (IOException e) {
[Link]();
}

try {
// Create an instance of FileReader
FileReader fileRead = new FileReader("[Link]");

// Reading data from a file


while ((ch = [Link]()) != -1) {
[Link]((char) ch); // type cast to char to print characters
}

[Link](); // close the reader stream


} catch (IOException e) {
[Link]();
}
}
}

Output:
P a g e | 40

31. WAP to show buffered input and output stream

import [Link].*;

public class BufferIOStreamDemo {


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

// Create a buffered output stream


BufferedOutputStream bout = new BufferedOutputStream(fout);

// Write data to the stream


for (int i = 1; i <= 10; i++) {
[Link](i); // Write individual bytes, not integer values
}

[Link](); // Close buffered output stream


} catch (IOException e) {
[Link]();
}

try {
// Create a file input stream
FileInputStream fin = new FileInputStream("[Link]");

// Create a buffered input stream


BufferedInputStream bin = new BufferedInputStream(fin);

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


while ((ch = [Link]()) != -1) {
[Link](ch);
}

[Link](); // Close buffered input stream


} catch (IOException e) {
[Link]();
}
P a g e | 41

}
}

Output:

You might also like