Java Record Lab 2
Java Record Lab 2
JAVA INTRODUCTION:
Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is intended to let
application developers write once, and run anywhere (WORA), meaning that compiled
Java code can run on all platforms that support Java without the need for
recompilation. Java was first released in 1995 and is widely used for developing
applications for desktop, web, and mobile devices. Java is known for its simplicity,
robustness, and security features, making it a popular choice for enterprise-level
applications. Java was developed by James Gosling at Sun Microsystems Inc in May
1995 and later acquired by Oracle Corporation. It is a simple programming language.
Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few implementation dependencies
as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support
Java. Java applications are compiled to byte code that can run on any Java Virtual
Machine. The syntax of Java is similar to C/C++.
HISTORY OF JAVA:
Java’s history is as interesting as it is impactful. The journey of this powerful
programming language began in 1991 when James Gosling, Mike Sheridan, and Patrick
Naughton, a team of engineers at Sun Microsystems known as the “Green Team,” set
out to create a new language initially called “Oak.” Oak was later renamed Java,
inspired by Java coffee, and was first publicly released in 1996 as Java 1.0. This initial
version provided a no-cost runtime environment across popular platforms, making it
accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0 compiler to
strictly comply with its specifications, ensuring its reliability and cross-platform
capabilities.
Features of Java:
1. Platform Independent
2. Object-Oriented Programming
3. Simplicity
4. Robustness
5. Security
6. Distributed
7. Multithreading
8. Portability
9. High Performance
JDK IN JAVA:
The Java Development Kit (JDK) is a cross-platformed software development
environment that offers a collection of tools and libraries necessary for developing
Java-based software applications and applets. It is a core package used in Java, along
with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment). Beginners
often get confused with JRE and JDK, if you are only interested in running Java programs
on your machine then you can easily do it using Java Runtime Environment. However, if
you would like to develop a Java-based software application then along with JRE you
may need some additional necessary tools, which is called JDK.
JDK=JRE+Development Tools
JAVA DATATYPES:
[Link] a JAVA program to display default value of all primitive data type of JAVA.
Aim: To write a program to display the default value of all primitive data type of JAVA.
Program code:
public class DataType
{
static byte b;
static short s;
static int i;
static long l;
static float f; static double d;
static char c;
static boolean bl;
public static void main(String[] args)
{
[Link]("The default values of primitive data types are:");
[Link]("Byte :"+b);
[Link]("Short :"+s);
[Link]("Int :"+i);
[Link]("Long :"+l);
[Link]("Float :"+f);
[Link]("Double :"+d);
[Link]("Char :"+c);
[Link]("Boolean :"+bl);
Output:
C:\23-532>javac [Link]
C:\23-532>java DataType
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0
Char :
Boolean :false
Result:
Hence, the program to display the default value of all primitive data type of JAVA
executed successfully.
[Link] a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.
Aim: To write a program to display the roots of a quadratic equation ax2+bx=0.
Program code:
package Week1;
import [Link].*;
public class quadraticformula
{
public static void main(String args[]){
int a,b,c,d,f=0;
Scanner scr=new Scanner([Link]);
[Link]("\nEnter the values of a ,b ,c : ");
a=[Link]();
b=[Link]();
c=[Link]();
d=(b*b)-(4*a*c);
if(d==0){
[Link]("Roots are real and Equal");
f=1;
}
else if(d>0){
[Link]("Roots are real and UnEqual");
f=1;
}
else
[Link]("Roots are imaginary");
if(f==1)
{
float r1=(float)(-b+[Link](d))/(2*a);
float r2=(float)(-[Link](d))/(2*a);
[Link]("Roots are : "+r1+" ,"+r2);
}
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java quadraticformula
[Link] a JAVA program to search for an element in a given list of elements using
binary search mechanism.
Aim: To search for an element in a given list of elements using binary search
mechanism.
Program Code:
import [Link].*;
class BinarySearch
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of elements in the array: ");
int size = [Link]();
int array[] = new int[size];
[Link]("Enter the elements of the array :");
for (int i = 0; i < size; i++)
{
array[i] = [Link]();
}
[Link]("Enter the value to search for: ");
int target = [Link]( );
int result = binarySearch(array, target);
if (result != -1)
{
[Link]("Element found at index: " + result);
}
else
{
[Link]("Element not found in the array.");
}
[Link]( );
}
public static int binarySearch(int[] array, int target)
{
int low = 0;
int high = [Link] - 1;
while (low <= high)
{
Output:
C:\23-532>javac [Link]
C:\23-532>java BinarySearch
Enter the number of elements in the array:4
Enter the elements of the array :
10
20
30
40
Enter the value to search for: 30
Element found at index: 2
Result:
Hence, the program to search for an element in a given list of elements using binary
search mechanism has been executed successfully.
4. Write a JAVA program to sort for an element in a given list of elements using
bubble sort.
Aim: To sort for an element in a given list of elements using bubble sort.
Program code:
import [Link].*;
public class BubbleSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]( );
int arr[] = new int[n];
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++)
{
arr[i] = [Link]( );
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]("Sorted Array:");
for (int i = 0; i < n; i++)
{
[Link]( " \n"+arr[i] );
}
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java BubbleSort
Enter the number of elements:
4
Enter 4 elements:
46
35
21
67
Sorted Array:
21
35
46
67
Result:
Hence, the program to sort for an element in a given list of elements using bubble sort
executed successfully.
Result:
Hence, the program to write a program to StringBuffer to delete, remove character
executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java Calculator1
Enter any Two values:
3
4
Addition of 3 and 4: 7
Subtraction of 3 and 4: -1
Multiplication of 3 and 4: 12
Division of 3 and 4: 0.75
Result:
Hence, the program to implement class mechanism. Create a class, methods and
invoke them inside main method executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java MethodOverloading1
Sum of two integers: 8
Sum of two doubles: 12.0
Sum of three integers: 18
Result:
Hence, the program to implement method overloading executed successfully.
[Link] = age;
[Link]("Parameterized constructor called");
}
public Person(Person p)
{
[Link] = [Link];
[Link] = [Link];
[Link]("Copy Constructor called");
}
public void display( )
{
[Link]("Name: " + name +" \t" +", Age: " + age);
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java Constructor
Default constructor called
Name: null, Age: 0
Parameterized constructor called
Name:thirumalesh, Age: 21
Copy Constructor called Name: thirumalesh, Age: 21
Result:
Hence, the program to implement constructor executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java ConstructorOverloading
Default Constructor called
Name: Unknown , Age: 0, Course: Not Enrolled
Constructor with two parameters called
Name:thiru , Age:12, Course: Not Enrolled
Constructor with three parameters called
Name: sai, Age: 21, Course: Computer Science
Result:
Hence, the program to implement constructor overloading executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java SingleInheritance
Value of a is 20
Result:
Hence, the program to implement single inheritance executed successfully.
Output:
C:\23-532>javac Multilevel [Link]
C:\23-532>java Multilevel Inheritance
Value of a is 50
Inside ChildChildClass!"
Result:
Hence, the program to implement multi-level inheritance executed successfully.
12. Write a JAVA program for abstract class to find areas of different shapes.
Aim: To write a program for abstract class to find areas of different shapes.
Program code:
abstract class Shape
{
abstract double calculateArea();
}
class Circle extends Shape
{
double radius;
public Circle(double radius)
{
[Link] = radius;
}
@Override
double calculateArea( )
{
return [Link] * radius * radius;
}
}
class Rectangle extends Shape
{
double length;
double width;
public Rectangle(double length, double width)
{
[Link] = length;
[Link] = width;
}
@Override
double calculateArea( )
{
return length * width;
}
}
class Triangle extends Shape
{ double base; double height;
public Triangle(double base, double height)
{
[Link] = base;
[Link] = height;
}
@Override
double calculateArea()
{
return 0.5 * base * height;
}
}
public class AbstractClass
{
public static void main(String[] args)
{
// Creating objects of different shapes
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(6,7);
Shape triangle = new Triangle(4,5);
[Link]("Area of Circle: " + [Link]());
[Link]("Area of Rectangle: " + [Link]());
[Link]("Area of Triangle: " + [Link]());
}
}
Output:
C:\23532>javac [Link]
C:\23-532>java AbstractClass
Area of Circle: 78.53981633974483
Area of Rectangle: 42.0
Area of Triangle: 10.0
Result:
Hence, the write a program for abstract class to find areas of different shapes executed
successfully.
class SuperDemo
{
public static void main(String[] args)
{
Student s = new Student( );
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java SuperDemo
Person class Constructor
Student class Constructor
Result:
Hence, the program to implement “super” keyword executed successfully.
14. Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?
Aim: To implement Interface.
Program code:
interface AnimalEat
{ void eat( );
} interface AnimalTravel
{ void travel( );
} class Animal implements AnimalEat, AnimalTravel
{ public void eat( )
{
[Link]("Animal is eating");
} public void travel( )
{
[Link]("Animal is travelling");
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java InterfaceDemo
Animal is eating
Animal is travelling
Result:
Hence, the program to implement interface executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java RuntimePolymorphism
Dog barks
Cat meows
Result:
Hence, the program to implement runtime polymorphism executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java Main
Enter weight: 15
You are ready to fly!
Enter weight: 45
Weight limit exceeded by 30 kg.
Result:
Hence, the program to implement exception handling mechanism has been executed
successfully.
try {
int num1 = [Link]();
int num2 = [Link]();
int result = num1 / num2;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
catch ([Link] e) {
[Link]("Error: Please enter valid integers.");
}
catch (Exception e) {
[Link]("Error: An unexpected error occurred: " + [Link]());
}
finally {
[Link]();
}
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java MultipleCatchExample
Result:
Hence, the program to illustrate multiple catch clauses has been executed
successfully.
try {
int[] arr = new int[5];
[Link](arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: Index is out of bounds.");
}
try {
[Link]("[Link]");
} catch (ClassNotFoundException e) {
[Link]("ClassNotFoundException: The specified class was not
found.");
}
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java BuiltInExceptionsExample
Result:
Hence, the program to create java built-in exceptions has been executed successfully.
try {
checkAge(200);
} catch (InvalidAgeException e) {
[Link]("Caught exception: " + [Link]());
}
}
}
Output:
C:\23-532>javac UserDefinedExceptionDemo
C:\23-532>java UserDefinedExceptionDemo
Age is valid: 25
Caught exception: Age must be between 0 and 150.
Caught exception: Age must be between 0 and 150.
Result:
Hence, the program to create user defined exception has been executed successfully.
20. Write a JAVA program that creates threads by extending Thread class. First
thread display “Good Morning “every 1 sec, the second thread displays “Hello
“every 2 seconds and the third display “Welcome” every 3 seconds, (Repeat the
same by implementing Runnable).
Aim: To write a program to create threads by extending thread class.
Program code:
package week7;
import [Link];
class MessageRunnable implements Runnable {
private String message;
private int interval;
private int count;
public MessageRunnable(String message, int interval, int count) {
[Link] = message;
[Link] = interval;
[Link] = count;
}
public void run() {
for (int i = 0; i < count; i++) {
try {
[Link](interval);
[Link](message);
} catch (InterruptedException e) {
[Link](message + " Thread interrupted");
}
}
}
}
[Link]();
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java RunnableExample
Enter the limit for how many times to print each message: 3
Good night
Hello
Good night
World
Good night
Hello
World
Hello
World
Result:
Hence, the program to create threads by extending thread class has been executed
successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java ThreadDemo
Enter the number of threads to create: 3 Thread-0 is starting.
Is Thread-0 alive? true
Is Thread-1 alive? true Is Thread-2 alive? true Thread-1 is starting.
Thread-2 is starting.
Thread-0 has finished.
Thread-0 has completed execution. Thread-1 has finished.
Thread-1 has completed execution. Thread-2 has finished.
Thread-2 has completed execution.
All threads have completed execution
Result:
Hence, the program to illustrate isAlive and join() has been executed successfully.
Output:
C:\23-532>javac [Link]
C:\23-532>java DaemonThreadExample
Enter the number of iterations for the main thread: 5
Enter the number of iterations for the main thread: 5
Daemon thread is running: 0
Main thread is running: 0
Daemon thread is running: 1
Main thread is running: 1
Daemon thread is running: 2
Main thread is running: 2
Daemon thread is running: 3
Main thread is running: 3
Daemon thread is running: 4
Main thread is running: 4
Main thread is exiting.
Result:
Hence, the program to illustrate Daemon threads has been executed successfully.
[Link](i);
[Link](100);
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
class Consumer extends Thread {
private final Buffer buffer;
private final int itemsToConsume;
public Consumer(Buffer buffer, int itemsToConsume) { [Link] = buffer;
[Link] = itemsToConsume;
}
@Override
public void run() {
for (int i = 0; i < itemsToConsume; i++) { try {
[Link](); [Link](150);
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of items to produce: ");
int itemsToProduce = [Link]();
[Link]("Enter the number of items to consume: ");
int itemsToConsume = [Link]();
Buffer buffer = new Buffer(5);
Producer producer = new Producer(buffer, itemsToProduce);
Consumer consumer = new Consumer(buffer, itemsToConsume);
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]().interrupt();
}
[Link]("Production and consumption completed.");
[Link]();
}
}
Output:
C:\23-532>javac ProducerConsumerDemo
C:\23-532>java ProducerConsumerDemo
Enter the number of items to produce: 10
Enter the number of items to consume: 10
Produced: 0
Consumed: 0
Produced: 1
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Produced: 5
Consumed: 3
Produced: 6
Consumed: 4
Produced: 7
Consumed: 5
Produced: 8
Consumed: 6
Produced: 9
Consumed: 7
Consumed: 8
Consumed: 9
Production and consumption completed.
Result:
Hence, the program to solve the producer consumer problem executed successfully.
24. Write a java program that connects to a MySql database and Display Table
Details using JDBC.
Aim: To connects to a MySql database and Display Table Details using JDBC.
Program code:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mysql1
{
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = " ";
try
{
[Link]("[Link]");
Connection con = [Link](url, user, password);
[Link]("Connected to the database!");
Statement stmt = [Link]();
String query = "SELECT * FROM cricket";
ResultSet rs = [Link](query);
while ([Link]())
{
[Link]([Link](1) + "\t" + [Link](2) + "\t" + [Link](3)+"\t"
+[Link](4) + "\t" + [Link](5));
}
[Link]();
[Link]();
[Link]();
}
catch (Exception e)
{
[Link]("Error: " + [Link]());
}
}
}
Output:
Result:
Hence, the program to implement Java Program for to connect to MYSQL and display
the Table has been executed successfully.
25. Problem Statement: To write a JDBC program to connect MS Access with Insert
values in to it with using IDE.
Aim: To connect MS Access with Insert values in to it with using IDE.
Program Code:
package JDBC;
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBC
{
public static void main(String[] args)
{
try {
[Link]("[Link]");
String url = "jdbc:ucanaccess://D:\\[Link]";
Connection con = [Link](url);
[Link]("Connected to the database Ms Access!");
Statement st = [Link]();
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('1', 'Naveen')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('2', 'Vijay')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('3', 'Rama')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('4', 'Mohith')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('5', 'Bhusan')");
String sql = "SELECT * FROM DBTest ";
ResultSet rs = [Link](sql);
[Link]("ID\tName");
while ([Link]())
{
String ID = [Link]("ID");
String Name = [Link]("Name");
[Link](ID + "\t" + Name);
}
[Link]();
[Link]();
[Link]();
} catch (Exception e)
{
[Link]("Error: " + [Link]());
[Link]();
}
}
}
Output:
Result:
Hence, the program to connect MS Access with Insert values in to it with using IDE has
been executed Successfully.
26. To write a JDBC program to connect Oracle with Delete values in to it without
using IDE.
Aim: To connect Oracle with Delete values in to it without using IDE.
Program Code:
import [Link].*;
public class OracleConnect
{
public static void main(String[] args)
{
String url = "jdbc:oracle:thin:@//localhost:1521/xe";
String user = "system";
String password = "root";
try {
[Link]("[Link]");
Connection con = [Link](url, user, password);
[Link]("Connection successful!");
Statement stmt = [Link]();
String deleteSQL = "DELETE FROM employees WHERE EMP_SALARY= 75000";
int rows = [Link](deleteSQL);
if (rows> 0)
{
[Link]("Successfully deleted " + rows + " record(s).");
}
else
{
[Link]("No records found to delete.");
}
ResultSet rs=[Link]("select * from employees");
while([Link]())
{
[Link]([Link](1)+" \t "+[Link](2)+"\t "+[Link](3)+" \t
"+[Link](4));
}
[Link]();
}
catch (ClassNotFoundException e)
{
[Link]("JDBC Driver not found!");
[Link]();
} catch (SQLException e)
{
[Link]("Connection failed!");
[Link]();
}
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java OracleConnect
Connection successful!
Successfully deleted 2 record(s).
3 Chary 65000 IT
2 Sunil 70000 CSE
Result:
Hence, the program to connect Oracle with Insert values in to it without using IDE has
been executed Successfully.