0% found this document useful (0 votes)
25 views19 pages

50 Kash Sharma Java

Uploaded by

Kash Sharma
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)
25 views19 pages

50 Kash Sharma Java

Uploaded by

Kash Sharma
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
You are on page 1/ 19

JOURNAL

IN THE MAJOR COURSE


JAVA
SUBMITTED BY
MR. KASH SHARMA
SYDS
Roll no : SDDS050A
SEMESTER III
UNDER THE GUIDANCE OF
ASST. PROF. SANJANA KHEMKA
ACADEMIC YEAR
2023 - 2024
CERTIFICATE

This is to certify that Mr. Kash Sharma of Second year


B.SC.DS Div.: A, Roll No. SDDS050A of Semester III (2023 -
2024) has successfully completed the Journal for the Major
course JAVA as per the guidelines of KES’ Shroff College of
Arts and Commerce, Kandivali(W), Mumbai-400067.

Teacher In-charge Principal


ASST. PROF. SANJANA KHEMKA Dr. L Bhushan.
INDEX

Sr. Practical Practical Name Page No.


No. No.
1. 1 Write a program to find the square and square root of a 4
number using built-in function and user defined
function.
2. 2 Write a program to find factorial of a number by using 5
user-defined function in a class.
3. 3 Write a program to find the sum of two numbers using 6
the concept of constructor in a class.
4. 4 Write a program to find the area of rectangle using 7
constructor in the class.
5. 5 Write a program to find the perimeter of a square and 8
rectangle by using the concept of method overloading in
a class.
6. 6 Write a program to find the sum of digits of a number 9
using static variable and static function in a class
7. 7 Program to show use of String methods (equals, length, 10
concat, toLowercase, toUppercase) in a java program.
8. 8 Write a program to sort 5 numbers in ascending and 11
descending order using Array.
9. 9 Write a program to find the sum of two matrices using 12
two-dimensional array.
10. 10 Program to implement single inheritance as shown in 13
the diagram.
11. 11 Write a java program to implement the following 14, 15
hierarchal structure.
12. 12 Program to find the sum of two numbers using 16
autoboxing and unboxing.
13. 13 Write a java program to create a file and write the text in 17
it and save the file.
14. 14 Write a java program to read a file and display the 18
content on screen.
15. 15 Write a program to connect to the database ‘mydata’ 19
and insert data in student table.
Practical No. 1:
Aim: Write a program to find the square and square root of a number using built-in function
and user defined function.
Built-in Function: A built-in function in Java is a function that is already defined in the Java
class libraries. These functions can be used in Java programs without having to be written by
the programmer. Built-in functions can be used to perform a variety of tasks, such as
mathematical calculations, string manipulation, and input/output.
User Define Function: A user-defined function in Java is a block of code that can be called
by other parts of the program. It is a way to modularize code and break down large tasks into
smaller, more manageable pieces.
Code:
import java.lang.Math;
class Square {
int a;
public void calculateSquare(int b) {
a = b;
System.out.println("Square of " + a + " = " + (a * a));
}
}
public class SquareRoot {
public static void main(String[] args) {
double d = 9;
Square squareObj = new Square();
System.out.println("Square root of " + d + " = " + Math.sqrt(d));
squareObj.calculateSquare(9);
}
}
Output:

4|Java Roll No.: SDDS050A


Practical No. 2:
Aim: Write a program to find factorial of a number by using user-defined function in a class.
User Define Function: A user-defined function in Java is a block of code that can be called
by other parts of the program. It is a way to modularize code and break down large tasks into
smaller, more manageable pieces.
Code:
public class FactorialProgram {
public static void main(String[] args) {
int number = 5; // Replace with your desired number
long factorial = 1;
for (int i = 2; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial of " + number + " = " + factorial);
}
}
Output:

5|Java Roll No.: SDDS050A


Practical No. 3:
Aim: Write a program to find the sum of two numbers using the concept of constructor in a
class.
Constructor: A constructor in Java is a special method that is used to initialize objects. It is
called when an object of a class is created. The constructor can be used to set initial values
for object attributes.
Code:
class SumCalculator {
private int num1;
private int num2;
public SumCalculator(int a, int b) {
num1 = a;
num2 = b;
}
public int calculateSum() {
return num1 + num2;
}
}
public class SumProgram {
public static void main(String[] args) {
int firstNumber = 5;
int secondNumber = 7;
SumCalculator calculator = new SumCalculator(firstNumber, secondNumber);
int sum = calculator.calculateSum();
System.out.println("Sum of " + firstNumber + " and " + secondNumber + " = " +
sum);
}
}
Output:

6|Java Roll No.: SDDS050A


Practical No. 4:
Aim: Write a program to find the area of rectangle using constructor in the class.
Constructor: A constructor in Java is a special method that is used to initialize objects. It is
called when an object of a class is created. The constructor can be used to set initial values
for object attributes.
Code:
class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double calculateArea() {
return length * width;
}
}
public class RectangleProgram {
public static void main(String[] args) {
double length = 5.0, width = 3.0;
Rectangle rectangle = new Rectangle(length, width);
System.out.println("Area of the rectangle = " + rectangle.calculateArea());
}
}
Output:

7|Java Roll No.: SDDS050A


Practical No. 5:
Aim: Write a program to find the perimeter of a square and rectangle by using the concept of
method overloading in a class.
Method Overloading: Method overloading is a feature of Java that allows a class to have
more than one method with the same name, but with different parameters. The parameters
can differ in their number, type, or order. Method overloading is used to provide different
implementations of a method for different types or numbers of arguments.
Code:
class ShapeCalculator {
public double calculatePerimeter(double sideLength) {
return 4 * sideLength;
}
public double calculatePerimeter(double length, double width) {
return 2 * (length + width);
}
}
public class PerimeterCalculator {
public static void main(String[] args) {
ShapeCalculator calculator = new ShapeCalculator();
double squarePerimeter = calculator.calculatePerimeter(4.0);
System.out.println("Perimeter of the square: " + squarePerimeter);
double rectanglePerimeter = calculator.calculatePerimeter(5.0, 3.0);
System.out.println("Perimeter of the rectangle: " + rectanglePerimeter);
}
}
Output:

8|Java Roll No.: SDDS050A


Practical No. 6:
Aim: Write a program to find the sum of digits of a number using static variable and static
function in a class.
Static Variable: A static variable in Java is a variable that belongs to the class rather than to
an instance of the class. There is only one copy of a static variable, regardless of how many
instances of the class are created.
Static Function: A static function is a function that belongs to a class rather than an instance
of a class. This means that you can call a static function without creating an object of the
class. Static functions are sometimes called class functions.
Code:
class DigitSumCalculator {
private static int sum = 0;
public static int calculateDigitSum(int number) {
while (number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
}
public class DigitSumProgram {
public static void main(String[] args) {
int number = 12345;
int digitSum = DigitSumCalculator.calculateDigitSum(number);
System.out.println("Sum of digits in " + number + " = " + digitSum);
}
}
Output:

9|Java Roll No.: SDDS050A


Practical No. 7:
Aim: Program to show use of String methods (equals, length, concat, toLowercase,
toUppercase) in a java program.
String Methods: A string method in Java is a subroutine that can be applied to a string to
perform a specific operation. For example, the length() method returns the length of a string,
while the indexOf() method returns the index of a substring within a string. String methods
can be used to manipulate strings in a variety of ways, such as converting them to upper or
lower case, splitting them into tokens, and comparing them to other strings.
Code:
public class StringMethods {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2);
System.out.println("str1 equals str2: " + isEqual);
String text = "Java Programming";
int length = text.length();
System.out.println("Length of the string: " + length);
String part1 = "Hello, ";
String part2 = "World!";
String combined = part1.concat(part2);
System.out.println("Concatenated string: " + combined);
String uppercaseText = "HELLO";
String lowercaseText = uppercaseText.toLowerCase();
System.out.println("Lowercase string: " + lowercaseText);
String lowercaseText2 = "world";
String uppercaseText2 = lowercaseText2.toUpperCase();
System.out.println("Uppercase string: " + uppercaseText2);
}
}
Output:

10 | J a v a Roll No.: SDDS050A


Practical No.8:
Aim: Write a program to sort 5 numbers in ascending and descending order using Array.
Array: An array is an object that contains a fixed number of elements. Each element in an
array has a unique index that is used to access it. The first element in an array is at index 0,
the second element is at index 1, and so on. The last element in an array is at index one less
than the length of the array.
Code:
import java.util.Arrays;
public class NumberSorter {
public static void main(String[] args) {
int[] numbers = {5, 2, 9, 1, 8};
Arrays.sort(numbers);
System.out.println("Ascending Order: " + Arrays.toString(numbers));
int[] descendingOrder = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
descendingOrder[i] = numbers[numbers.length - 1 - i];
}
System.out.println("Descending Order: " + Arrays.toString(descendingOrder));
}
}
Output:

11 | J a v a Roll No.: SDDS050A


Practical No. 9:
Aim: Write a program to find the sum of two matrices using two-dimensional array.
Array: An array is an object that contains a fixed number of elements. Each element in an
array has a unique index that is used to access it. The first element in an array is at index 0,
the second element is at index 1, and so on. The last element in an array is at index one less
than the length of the array.
Code:
public class MatrixSum {
public static void main(String[] args) {
int rows = 3;
int columns = 3;
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
int[][] sumMatrix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Sum of the matrices:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(sumMatrix[i][j] + " ");
}
System.out.println();
}
}
}
Ouput:

12 | J a v a Roll No.: SDDS050A


Practical No.: 10:
Aim: Program to implement single inheritance as shown in the diagram
Inheritance: Inheritance in Java is a mechanism that allows you to
create new classes based on existing classes. the new classes, called
subclasses, inherit the properties and methods of the existing classes,
called superclasses.
Code:
class Employee {
float salary;
Employee(float salary) {
this.salary = salary;
}
void displaySalary() {
System.out.println("Employee Salary: " + salary);
}
}
class Programmer extends Employee {
int bonus;
Programmer(float salary, int bonus) {
super(salary);
this.bonus = bonus;
}
void displayBonus() {
System.out.println("Programmer Bonus: " + bonus);
}
}
public class Inheritance1 {
public static void main(String[] args) {
float employeeSalary = 50000.0f;
int programmerBonus = 10000;
Programmer programmer = new Programmer(employeeSalary,
programmerBonus);
programmer.displaySalary();
programmer.displayBonus();
}
}
Output:

13 | J a v a Roll No.: SDDS050A


Practical No. 11:
Aim: Write a java program to implement the following
hierarchal structure.
Hierarchical Inheritance: Hierarchical inheritance is a
type of inheritance in Java where a single parent class
can have multiple child classes. This allows for code
reuse, as the child classes can inherit the methods and
properties of the parent class. Hierarchical inheritance
can be used to model relationships between different
types of objects.
Code:
class Employee {
String name;
String department;
Employee(String name, String department) {
this.name = name;
this.department = department;
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Department: " + department);
}
}
class FullTimeEmployee extends Employee {
float monthlySalary;
FullTimeEmployee(String name, String department, float monthlySalary) {
super(name, department);
this.monthlySalary = monthlySalary;
}
void displayEarnings() {
System.out.println("Monthly Salary: Rs. " + monthlySalary);
}
}
class PartTimeEmployee extends Employee {
int hoursWorked;
float salaryPerHour;
PartTimeEmployee(String name, String department, int hoursWorked, float
salaryPerHour) {
super(name, department);
this.hoursWorked = hoursWorked;
this.salaryPerHour = salaryPerHour;
}
void displayEarnings() {

14 | J a v a Roll No.: SDDS050A


System.out.println("Hours Worked: " + hoursWorked);
System.out.println("Salary Per Hour: Rs. " + salaryPerHour);
System.out.println("Total Earnings: Rs." + (hoursWorked * salaryPerHour));
}
}
public class Employee123 {
public static void main(String[] args) {
FullTimeEmployee fullTimeEmployee = new FullTimeEmployee("John", "HR",
5000.0f);
PartTimeEmployee partTimeEmployee = new PartTimeEmployee("Alice", "IT",
20, 15.0f);
System.out.println("Full-Time Employee Details:");
fullTimeEmployee.displayDetails();
fullTimeEmployee.displayEarnings();
System.out.println("\nPart-Time Employee Details:");
partTimeEmployee.displayDetails();
partTimeEmployee.displayEarnings();
}
}
Output:

15 | J a v a Roll No.: SDDS050A


Practical No. 12:
Aim: Program to find the sum of two numbers using autoboxing and unboxing.
Autoboxing: Autoboxing is the conversion of a primitive data type into an object of the
corresponding wrapper class. For example, converting an int into an Integer object.
Unboxing: Unboxing is the conversion of an object of a wrapper class into its corresponding
primitive type. For example, converting an Integer object into an int value.
Code:
class Practical
{
public static void main (String args[])
{
int a = 50;
Integer a2=new Integer (a);
Integer a3=5;
System.out.println ("Value of object a2 is: " +a2);
System.out.println ("Value of object a3 is: " +a3);
int j=a2;
System.out.println ("Value of integer variable: " +j);
}
}
Output:

16 | J a v a Roll No.: SDDS050A


Practical No. 13:
Aim: Write a java program to create a file and write the text in it and save the file.
File Handling: File handling in Java is the process of reading from and writing data to files.
The File class from the java.io package provides methods for creating, opening, reading,
writing, and closing files.
Code:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class CreateAndWriteToFile {
public static void main(String[] args) {
String fileName = "example.txt";
String textToWrite = "This is a sample text that will be written to the file.";
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(textToWrite);
bufferedWriter.close();
System.out.println("Text has been written to the file successfully.");
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Output:

17 | J a v a Roll No.: SDDS050A


Practical No. 14:
Aim: Write a java program to read a file and display the content on screen.
File Handling: File handling in Java is the process of reading from and writing data to files.
The File class from the java.io package provides methods for creating, opening, reading,
writing, and closing files.
Code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReadAndDisplayFile {
public static void main(String[] args) {
String fileName = "example.txt";
try {
String content = new String(Files.readAllBytes(Paths.get(fileName)));
System.out.println(content);
} catch (IOException e) {
System.err.println("An error occurred: " + e.getMessage());
}
}
}
Output:

18 | J a v a Roll No.: SDDS050A


Practical No. 15:
Aim: Write a program to connect to the database ‘mydata’ and insert data in student table.
JDBC: JDBC, or Java Database Connectivity, is an Application Programming Interface
(API) that allows Java applications to connect to and interact with databases. JDBC is a set of
classes and interfaces that provide a standard way for Java programs to access data sources.
Code:

package project1;
import java.sql.*;
public class Project1 {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost/mydata";
String username = "root";
String password = "root";
try {
Connection connection=DriverManager.getConnection(jdbcUrl, username,
password);
String insertQuery = "INSERT INTO student (id, name, age) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "John Doe");
preparedStatement.setInt(3, 20);
preparedStatement.executeUpdate();
System.out.println("Data inserted successfully!");
preparedStatement.close();
connection.close();
} catch (SQLException e) {
System.err.println("Database connection error: " + e.getMessage());
}
}
}
Output:

19 | J a v a Roll No.: SDDS050A

You might also like