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

Java File Final

This document contains a table of contents for a Java practical file submitted by a student named Yuvraj Sachdeva. The table lists 25 programs covering Java concepts like method overloading, inheritance, interfaces, file I/O etc. An acknowledgement section thanks the instructor Miss Aditi for her guidance and support in completing the project.

Uploaded by

uday vaidya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java File Final

This document contains a table of contents for a Java practical file submitted by a student named Yuvraj Sachdeva. The table lists 25 programs covering Java concepts like method overloading, inheritance, interfaces, file I/O etc. An acknowledgement section thanks the instructor Miss Aditi for her guidance and support in completing the project.

Uploaded by

uday vaidya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Page |1

JAVA
(PRACTICAL FILE)

BCA SEMESTER-V

Submitted By: Submitted To:


Name - Yuvraj Sachdeva Miss. Aditi
Roll No. - 10722132933
Page |2

Index
s.n Title Pg no. Sign
o
1 Acknowledgment 4
2 WAP to add two numbers 5

3 WAP to calculate area of circle 6


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

5 WAP to find largest number from three(concept of 9-10


nested if)
6 WAP to make calculator using switch statement 11-12

7 WAP to print a table using for loop. 13


8 WAP to calculate area of rectangle with objects 14
9 WAP to show concept of Method Overloading at least 15
3 functions.
10 WAP to show concept of Method Overriding. 16
11 WAP to show concept of Method Overriding. 17
12 WAP to show concept of single Inheritance . 18-19
13 WAP to show concept of Multilevel Inheritance . 20-21
14 WAP to show concept of Hierarchical Inheritance 22-23
15 WAP to show the concept of constructor overloading 24-25
16 WAP to Implement abstract classes . 26-27
17 WAP to Implement Interfaces . 28
18 WAP to Implement Multiple Inheritance with 29
Interfaces
Page |3

19 WAP to Concatenate Strings in JAVA 30


20 WAP to Show String Comrison in JAVA 31
21 WAP to Find Substring from a String in JAVA 32
22 WAP to Create and Import User Defined Package 33-35
23 Write a Java Program to to perform various operations 33-35
in MySQL database

24 WAP to show file reader and writer stream 36


25 WAP to show buffered input and output stream 37-38
Page |4

Acknowledgment
I wish to extend my heartfelt gratitude and sincere
appreciation. Acknowledging one's feelings and
putting them into words are often two separate
challenges. In all honesty, I sometimes struggle to
find the right words when I truly want to express our
warmest thanks and profound indebtedness.

The successful completion of this project would not


have been possible without the unwavering support
and guidance provided by Miss Aditi. She not only
helped me navigate the intricacies of project
preparation but also stood by my side whenever I
encountered challenges.

I am deeply thankful to her for her invaluable


assistance, and for her exceptional patience and
perseverance in imparting knowledge and guidance
to us. Her dedication has been a source of
inspiration, and we are truly fortunate to have had
her support throughout this endeavor.
Page |5

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 |6

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:

3. WAP to implement the concept of operators


Page |7

import java.util.Scanner;
class demo
{
void display(float a,float b)
{
System.out.println("a+b=" + (a+b));
System.out.println("\na-b=" + (a-b));
System.out.println("\na/b=" + (a/b));
System.out.println("\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.print("Concept of operators----->");
d.display(x,y);
S1.close();
}
}

OUTPUT:

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


import java.util.Scanner;
Page |8

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:

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


import java.util.Scanner;
class largest
Page |9

{
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();
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();
}
P a g e | 10

OUTPUT:

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);
P a g e | 11

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);


}
}

OUTPUT:
P a g e | 12

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));
}
}
P a g e | 13

}
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:

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
{
P a g e | 14

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:

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 | 15

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;
}
P a g e | 16

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:

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() {
P a g e | 17

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:

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
P a g e | 18

myDog.bark(); // Call the bark() method from the subclass


}
}

Output:

12. 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) {
P a g e | 19

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:

13. 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 {


P a g e | 20

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
}
}

OUTPUT:
P a g e | 21

14. 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;
}
P a g e | 22

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

public int getAge() {


return age;
}

public String getDepartment() {


return department;
}
}

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 | 23

15. 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


P a g e | 24

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;
}

// 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 | 25

16. 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");
P a g e | 26

}
}

// 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();
}
}

OUTPUT:
P a g e | 27

17. 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 | 28

18. 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 | 29

19. WAP to Show String Comrison 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 | 30

20. 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 | 31

21. 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 | 32

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 | 33

23. 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, " +
"first_name VARCHAR(50), " +
P a g e | 34

"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 | 35

Output:
P a g e | 36

24. 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:

25. WAP to show buffered input and output stream


P a g e | 37

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 | 38

Output:

You might also like