JAVA PROGRAMMING LAB
B.Tech - CSE (Data Science) - HITS
II-B.Tech II-Semester LTPC
Course Code: A1DS406PC 0021
LIST OF EXPERIMENTS :
1) JAVA BASICS
2) ARRAYS
3) STRINGS
4) OVERLOADING & OVERRIDING
5) INHERITANCES
6) INTERFACES
7) EXCEPTION HANDLING
8) I/O STREAMS
9) MULTI THREADING
10) GENERICS
11) COLLECTIONS
12) CONNECTING TO DATABASE
WEEK – 1 : JAVA BASICS
a. Write a java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use
the quadratic formula.
b. The Fibonacci sequence is defined by the following rule. The first two values
in the sequence are 1 and 1. Every
subsequent value is the sum of the two values preceding it. Write a java
program that uses both recursive and
non-recursive functions.
WEEK – 2 : ARRAYS
a. Write a java program to sort given list of integers in ascending order.
b. Write a java program to multiply two given matrices.
WEEK – 3: STRINGS
a. Write a java program to check whether a given string is palindrome.
b. Write a java program for sorting a given list of names in ascending order.
WEEK – 4: OVERLOADING & OVERRIDING
a. Write a java program to implement method overloading and constructors
overloading.
b. Write a java program to implement method overriding.
WEEK – 5: INHERITANCES
Write a java program to create an abstract class named Shape that contains
two integers and an empty method named
print Area (). Provide three classes named Rectangle, Triangle and Circle such
that each one of the classes extends
the class Shape. Each one of the classes contains only the method print Area ()
that prints the area of the given shape.
WEEK – 6 INTERFACES
a. Write a program to create interface A in this interface we have two method
meth1 and meth2. Implements this
interface in another class named My Class.
b. Write a program to give example for multiple inheritances in Java.
WEEK – 7 EXCEPTION HANDLING
Write a program that reads two numbers Num1 and Num2. If Num1 and Num2
were not integers, theprogram
would throw a Number Format Exception. If Num2 were zero, the program
would throw an Arithmetic Exception
Display the exception.
WEEK – 8 I/O STREAM
a. Write a java program that reads a file name from the user, and then displays
information about whether the file
exists, whether the file is readable, whether the file is writable, the type of file
and the length of the file in
bytes.
b. Write a java program that displays the number of characters, lines and words
in a text file.
WEEK – 9 MULTI THREADING
Write a java program that implements a multi-thread application that has three
threads. First thread generates
random integer every 1 second and if the value is even, second thread
computes the square of the number and
prints. If the value is odd, the third thread will print the value of cube of the
number.
WEEK – 10 GENERICS
a. Write a Java program to swap two different types of data using Generics.
b. Write a Java program to find maximum and minimum of two different types
of data usingGenerics.
WEEK – 11 COLLECTIONS
Create a linked list of elements.
a. Delete a given element from the above list.
b. Display the contents of the list after deletion.
WEEK – 12 CONNECTING TO DATABASE
Write a java program that connects to a database using JDBC and does add,
delete, modify and retrieve
operations.
JAVA PROGRAMMING LAB
WEEK – 1 JAVA BASICS
a. Write a java program that prints all real solutions to the quadratic equation
ax2+bx+c=0. Read in a, b, c and use the quadratic formula.
b. The Fibonacci sequence is defined by the following rule. The first two values
in the sequence are 1 and 1. Every subsequent value is the sum of the two
values preceding it. Write a java program that uses both recursive and
non-recursive functions.
a. QuadraticEquation
1. import java.util.Scanner;
2. public class QuadraticEquationExample1
3. {
4. public static void main(String[] Strings)
5. {
6. Scanner input = new Scanner(System.in);
7. System.out.print("Enter the value of a: ");
8. double a = input.nextDouble();
9. System.out.print("Enter the value of b: ");
10.double b = input.nextDouble();
11.System.out.print("Enter the value of c: ");
12.double c = input.nextDouble();
13.double d= b * b - 4.0 * a * c;
14.if (d> 0.0)
15.{
16.double r1 = (-b + Math.pow(d, 0.5)) / (2.0 * a);
17.double r2 = (-b - Math.pow(d, 0.5)) / (2.0 * a);
18.System.out.println("The roots are " + r1 + " and " + r2);
19.}
20.else if (d == 0.0)
21.{
22.double r1 = -b / (2.0 * a);
23.System.out.println("The root is " + r1);
24.}
25.else
26.{
27.System.out.println("Roots are not real.");
28.}
29.}
30.}
Output 1:
Output 2:
b. non recursive
import java.util.Scanner;
class Fib {
public static void main(String args[ ]) {
Scanner input=new Scanner(System.in);
int i,a=1,b=1,c=0,n;
System.out.print("Enter value of n: ");
n=input.nextInt();
System.out.print(a);
System.out.print(" "+b);
for(i=0;i<n-2;i++) {
c=a+b;
a=b;
b=c;
System.out.print(" "+c);
System.out.println();
System.out.print(n+"th number of the series is: "+c);
Output
Recursive Solution
import java.io.*;
import java.lang.*;
class Fib1 {
int fib(int n) {
if(n==1)
return (1);
else if(n==2)
return (1);
else
return (fib(n-1)+fib(n-2));
}
class FibR {
public static void main(String args[])throws IOException {
InputStreamReader obj=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(obj);
System.out.print("Enter value of n: ");
int n=Integer.parseInt(br.readLine());
Fib1 ob=new Fib1();
System.out.print("Fibonaccie Series is:");
int res=0;
for(int i=1;i<=n;i++) {
res=ob.fib(i);
System.out.print(" "+res);
System.out.println();
System.out.println(n+"th number of the series is: "+res);
Output
WEEK – 2 ARRAYS
a. Write a java program to sort given list of integers in ascending order.
b. Write a java program to multiply two given matrice
a.
sorting of arrays
1. public class SortAsc {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {5, 2, 8, 7, 1};
5. int temp = 0;
//Displaying elements of original array
6. System.out.println("Elements of original array: ");
7. for (int i = 0; i < arr.length; i++) {
8. System.out.print(arr[i] + " ");
9. }
10. //Sort the array in ascending order
11. for (int i = 0; i < arr.length; i++) {
12. for (int j = i+1; j < arr.length; j++) {
13. if(arr[i] > arr[j]) {
14. temp = arr[i];
15. arr[i] = arr[j];
16. arr[j] = temp;
17. }
18. }
19. }
20.
21. System.out.println();
22. //Displaying elements of array after sorting
23. System.out.println("Elements of array sorted in ascending order: ");
24. for (int i = 0; i < arr.length; i++) {
25. System.out.print(arr[i] + " ");
26. }
27. }
28.}
Output:
Elements of original array:
52871
Elements of array sorted in ascending order:
12578
c. Multiply matrix
public class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3]; //3 rows and 3 columns
//multiplying and printing multiplication of 2 matrices
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=0;
for(int k=0;k<3;k++)
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}}
Output:
666
12 12 12
18818
WEEK – 3 STRINGS
a. Write a java program to check whether a given string is palindrome.
b. Write a java program for sorting a given list of names in ascending order.
a. Palindrome Program in Java
1. import java.util.*;
2. class PalindromeExample2
3. {
4. public static void main(String args[])
5. {
6. String original, reverse = ""; // Objects of String class
7. Scanner in = new Scanner(System.in);
8. System.out.println("Enter a string/number to check if it is a palindro
me");
9. original = in.nextLine();
10. int length = original.length();
11. for ( int i = length - 1; i >= 0; i-- )
12. reverse = reverse + original.charAt(i);
13. if (original.equals(reverse))
14. System.out.println("Entered string/number is a palindrome.");
15. else
16. System.out.println("Entered string/number isn't a palindrome.");
17. }
18.}
Output :
Enter a string/number to check if it is a palindrome lol
Entered string/number is a palindrome
b.sorting names
// Java Program to Sort Names in an Alphabetical
Order import java.io.*;
class GFG {
public static void main(String[] args)
// storing input in
variable int n = 4;
// create string array called
names String names[]
= { "Rahul", "Ajay", "Gourav",
"Riya" }; String temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// to compare one string with other
strings if (names[i].compareTo(names[j]) >
0) {
// swapping
temp = names[i];
names[i] = names[j];
names[j] = temp;
// print output
array
System.out.println(
"The names in alphabetical order are: ");
for (int i = 0; i < n; i++) {
System.out.println(names[i]);
}
Output :The names in alphabetical order are :
The names in alphabetical order are :Ajay
Gourav
Rahul
Riya
WEEK – 4 OVERLOADING & OVERRIDING
a. Write a java program to implement method overloading and constructors
overloading.
b. Write a java program to implement method overriding.
a.
method overloading
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
Output:
Arguments: 1
Arguments: 1 and 4
Constructor overloading
1. public class Student {
2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13.}
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name :
"+stu dent.name);
24.}
25.}
Output:
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : David
b.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16.}
Output:
17. Bike is running safely
WEEK – 5 INHERITANCES
Write a java program to create an abstract class named Shape that contains
two integers and an empty method named print Area (). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes extends
the class Shape. Each one of the classes contains only the method print Area ()
that prints the area of the given shape.
import java.util.*;
abstract class shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle is :"+(x*y));
}
}
class Circle extends shape
{
void area(double x,double y)
{
System.out.println("Area of circle is :"+(3.14*x*x));
}
}
class Triangle extends shape
{
void area(double x,double y)
{
System.out.println("Area of triangle is :"+(0.5*x*y));
}
}
public class AbstactDDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(2,5);
}
Output:
Area of rectangle is :10.0
Area of circle is :78.5
Area of triangle is :5.0
WEEK – 6 INTERFACES
a. Write a program to create interface A in this interface we have two method
meth1 and meth2. Implements this interface in another class named My Class.
b. Write a program to give example for multiple inheritances in Java.
a.
// One interface an extend another.
interface A
void meth1();
void meth2();
}
// B now includes meth1() and meth2()–it adds
meth3(). interface B extends A
{
void meth3();
}
// This class must implement all of A and B
class MyClass implements B
public void meth1 ( )
System.out.println(“Implement meth1().”);
public void meth2()
System.out.println (“Implement meth2().”);
public void meth3()
System.out.println (“Implement meth().” );
class IFExtend
public static void main(String arg[])
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
output:
method 1
method 2
method 3
b.
interface AnimalEat {
void eat();
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
public void travel() {
System.out.println("Animal is travelling");
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
Output
Animal is eating
Animal is travelling
WEEK – 7 EXCEPTION HANDLING
Write a program that reads two numbers Num1 and Num2. If Num1 and Num2
were not integers, the program would throw a Number Format Exception. If
Num2 were zero, the program would throw an Arithmetic Exception Display
the exception.
import java.util.Scanner;
public class Main {
public static void main(String[] args) { Scanner
scanner = new Scanner(System.in);
System.out.print("Enter num1: ");
String num1 = scanner.next();
System.out.print("Enter num2: ");
String num2 = scanner.next();
try {
int result = Integer.parseInt(num1) / Integer.parseInt(num2);
System.out.println("Result: " + result);
} catch (NumberFormatException e) {
System.out.println("Both arguments must be integers");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
Output :
Eneter num1: 10
Enter num2:5
Result:2
Eneter num1:1
Eneter num 2:0
Cannot divide by zero
Enter num1 :1
Enter num 2:a
Both arguments must be integers
WEEK – 8 I/O STREAMS
a. Write a java program that reads a file name from the user, and then displays
information about whether the file exists, whether the file is readable,
whether the file is writable, the type of file and the length of the file in bytes.
b. Write a java program that displays the number of characters, lines and
words in a text file.
a.
import java.io.*;
import java.util.*;
class AboutFile{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the file:");
String file_name = input.nextLine();
File f = new File(file_name);
if(f.exists())
System.out.println("The file " +file_name+ " exists");
else
System.out.println("The file " +file_name+ " does not exist");
if(f.exists()){
if(f.canRead())
System.out.println("The file " +file_name+ " is readable");
else
System.out.println("The file " +file_name+ " is not readable");
if(f.canWrite())
System.out.println("The file " +file_name+ " is
writeable"); else
System.out.println("The file " +file_name+ " is not writeable");
System.out.println("The file type is: "
+file_name.substring(file_name.indexOf('.')+1));
System.out.println("The Length of the file:" +f.length());
Output:
WEEK – 9 MULTI THREADING
Write a java program that implements a multi-thread application that has three
threads. First thread generates
random integer every 1 second and if the value is even, second thread
computes the square of the number and
prints. If the value is odd, the third thread will print the value of cube of the
number.
import java.util.*;
class NewNumber extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(10);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread st = new SquareThread(randomInteger);
st.start();
}
else {
CubeThread ct = new CubeThread(randomInteger);
ct.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
class SquareThread extends Thread {
int number;
SquareThread(int randomNumber) {
number = randomNumber;
}
public void run() {
System.out.println("Square of " + number + " = " + (number * number));
}
}
class CubeThread extends Thread {
int number;
CubeThread(int randomNumber) {
number = randomNumber;
}
public void run() {
System.out.println("Cube of " + number + " = " + number * number * number);
}
}
public class MultiThr {
public static void main(String args[]) {
NewNumber nm= new NewNumber();
nm.start();
}
}
#output:
Random Integer generated : 7
Cube of 7 = 343
Random Integer generated : 4
Square of 4 = 16
Random Integer generated : 7
Cube of 7 = 343
Random Integer generated : 3
Cube of 3 = 27
Random Integer generated : 3
Cube of 3 = 27
Random Integer generated : 4
Square of 4 = 16
Random Integer generated : 1
Cube of 1 = 1
Random Integer generated : 6
Square of 6 = 36
Random Integer generated : 3
Cube of 3 = 27
Random Integer generated : 4
Square of 4 = 16
WEEK – 10 GENERICS
a. Write a Java program to swap two different types of data using Generics.
b. Write a Java program to find maximum and minimum of two different types
of data usingGenerics.
a.#program:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class Generics {
static final <T> void swap (T[] a, int i, int j) {
T t = a[i];
a[i] = a[j];
a[j] = t;
}
static final <T> void swap (List<T> l, int i, int j) {
Collections.<T>swap(l, i, j);
}
static void test() {
String [] a = {"Hits ", "Cse"};
swap(a, 0, 1);
System.out.println("a:"+Arrays.toString(a));
List<String> l = new ArrayList<String>(Arrays.asList(a));
swap(l, 0, 1);
System.out.println("l:"+l);
}
public static void main(String args[])
{
test();
}
}
#output:
a:[Cse, Hits ]
l:[Hits , Cse]
b.#program:
import java.util.ArrayList;
import java.util.Collections;
class NewList {
public static void main(String args[]) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(35);
System.out.println("List: " + list);
System.out.println("Minimum value of list is: "+Collections.min(list));
System.out.println("Maximum value of list is" +Collections.max(list));
}
}
#output:
List: [10, 20, 30, 35]
Minimum value of list is: 10
Maximum value of list is35
WEEK – 11 COLLECTIONS
Create a linked list of elements.
a. Delete a given element from the above list.
b. Display the contents of the list after deletion.
a&b.#program:
import java.io.*;
import java.util.LinkedList;
class List{
public static void main(String args[]){
LinkedList<Integer> list=new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
System.out.println(list);
list.remove(2);
System.out.println(list);
}
}
#Output:
[1, 2, 3, 4]
[1, 2, 4]
WEEK – 12 CONNECTING TO DATABASE
Write a java program that connects to a database using JDBC and does add,
delete, modify and retrieve operations.
#data insert program:
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Statement;
public class JdbcInsert
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/pk","root","m
ysql");
System.out.println("Connection Created");
String query="insert into student values(701,'bhanu')";
Statement st=con.createStatement();
System.out.println("Statement created");
st.execute(query);
System.out.println("data inserted");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#output:
Connection Created
Statement created
data inserted
+--------+----------+
| rollno | name |
+--------+----------+
| 701 | bhanu |
| 702 | Priyanka |
+--------+----------+
#data delete program:
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Statement;
public class JdbcDelete
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/pk","root","m
ysql");
System.out.println("Connection Created");
String query="delete from student where rollno=702";
Statement st=con.createStatement();
System.out.println("Statement created");
st.execute(query);
System.out.println("data deleted");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#output:
Connection Created
Statement created
data deleted
+--------+-------+
| rollno | name |
+--------+-------+
| 701 | bhanu |
+--------+-------+
#data update program:
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Statement;
public class JdbcUpdate
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/pk","root","m
ysql");
System.out.println("Connection Created");
String query="update student set name='BhanuPrasad'
where rollno=701";
Statement st=con.createStatement();
System.out.println("Statement created");
st.execute(query);
System.out.println("data Updated");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
#output:
Connection Created
Statement created
data Updated
+--------+-------------------+
| rollno | name |
+--------+-------------------+
| 701 | BhanuPrasad |
+--------+-------------------+
#data retrieve program:
import java.sql.*;
class Dbconnect
{
public static void main(String args[])
{
try
{
// class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
Connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/labman","ro
ot","mysql");
System.out.println("connected");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from employee");
while(rs.next())
{
System.out.println("empno="+rs.getString(1)+"
ename="+rs.getString(2)+"job="+rs.getString(3)+"mgr="+rs.getString(4)+"sal="
+rs.getString(5));
}
}
catch(SQLException s)
{
System.out.println(s);
}
}
}
#output:
connected
empno=101 ename=abhi job=manager mgr=1234 sal=10060
empno=102 ename=rohith job=analyst mgr=2345 sal=10060
empno=103 ename=david job=trainee mgr=3456 sal=9000
empno=104 ename=sruthi job=HRmgr=5678 sal=35000