Java Lab Manuals
Java Lab Manuals
Faculty of Engineering
Department of Artificial Intelligence and Data Science
LAB MANUAL
Prepared by
Dr .Laxmi Raja
AP/ Cyber
Approved by
Java applets run in a web browser with Java Virtual Machine (JVM), which translates Java
bytecode into native processor instructions and allows indirect OS or platform program
execution. JVM provides the majority of components needed to run bytecode, which is
usually smaller than executable programs written through other programming languages.
Bytecode cannot run if a system lacks the required JVM.
Java program development requires a Java software development kit (SDK), which
typically includes a compiler, interpreter, documentation generator and other tools used to
produce a complete application.
Aim:
To create a JAVA program to using Control Structure and Array
Algorithm:
1.CODE:
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int num, i, count=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number: ");
num = s.nextInt();
for(i=2; i<num; i++)
{
if(num%i == 0)
{
count++;
break;
}
}
if(count==0)
System.out.println("\nIt is a Prime Number.");
else
System.out.println("\nIt is not a Prime Number.");
}
}
2.CODE(Array)
import java.util.Scanner;
public class CodesCracker
{
public static void main(String[] args)
{
int num, i, count=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number: ");
num = s.nextInt();
for(i=2; i<num; i++)
{
if(num%i == 0)
{
count++;
break;
}
}
if(count==0)
System.out.println("\nIt is a Prime Number.");
else
System.out.println("\nIt is not a Prime Number.");
}
}
1.OUTPUT:
2.OUTPUT:
10
20
70
40
50
Result:
Thus the java program to implement multi-level Inheritance has been executed
successfully
Ex.No: 2
Programs using classes and objects
Date :
Aim:
To create a JAVA program to using Classes and objects
Algorithm:
1.CODE(Array)
import java. util.Scanner;
class Lamp
{
Boolean ison;
Void turnon()
{
ison=true;
System.out.println(“Light on?”+ison);
}
public static void main(String[] args)
{
Lamp led=new Lamp();
Led.turnon();
}
}
Output:
Light on? True
Result:
Thus the java program to Classes and Objects has been executed successfully.
Ex.No:3
Date : Programs using inheritance and polymorphism
Aim:
To write a JAVA program to implement multi-level Inheritance
.
Algorithm:
Code:
import java.io.*;
class Student
{
int rno,age;
String name,gender;
public void get() throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("\n Enter roll no:");
rno=Integer.parseInt(d.readLine());
System.out.println("\n Enter age:");
age=Integer.parseInt(d.readLine());
System.out.println("\n Enter name:");
name=d.readLine();
System.out.println("\n Enter gender:");
gender=d.readLine();
}
public void put()
{
System.out.println("R NO:"+rno);
System.out.println("AGE:"+age);
System.out.println("NAME:"+name);
System.out.println("GENDER:"+gender);
}
}
class marks extends Student
{
int m1,m2,m3;
public void get1() throws IOException
{
DataInputStream d=new DataInputStream(System.in);
System.out.println("enter the M1:");
m1=Integer.parseInt(d.readLine());
System.out.println("enter the M2:");
m2=Integer.parseInt(d.readLine());
System.out.println("enter the M3:");
m3=Integer.parseInt(d.readLine());
}
public void put1()
{
System.out.println("the result is:");
System.out.println("M1:"+m1);
System.out.println("M2:"+m2);
System.out.println("M3:"+m3);
}
}
class total extends marks
{
int total;
float avg;
void showdata()
{
total=m1+m2+m3;
avg=total/3;
put();
put1();
System.out.println("TOTAL:"+total);
System.out.println("AVG:"+avg);
}
}
class Students9
{
public static void main(String args[])throws IOException
{
total t=new total();
t.get();
t.get1();
t.showdata();
}
}
2.Code(polymorph):
import java.io.*;
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}
1.OUTPUT:
2.OUTPUT:
Result:
Thus the java program to implement multi-level Inheritance and polymorphism
has been executed successfully.
Ex.No: 4
Date : Programs using String, String Buffer and StringBuilder class
Aim:
To write a JAVA program implement String Class, StringBuffer and StringBuilder
Algorithm:
1.Code(String ):
import java.io.*;
class JavaExample
{
public static void main(String args[])
{
//creating string using string literal
String s1 = "BeginnersBook";
String s2 = "BeginnersBook";
if(s1 == s2){
System.out.println("String s1 and s2 are equal");
}else{
System.out.println("String s1 and s2 are NOT equal");
}
if(s3 == s4){
System.out.println("String s3 and s4 are equal");
}else{
System.out.println("String s3 and s4 are NOT equal");
}
}
}
2.StringBuffer
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer object
StringBuffer stringBuffer = new StringBuffer("Hello");
3.StringBuilder
1.OUTPUT:
Result:
Thus the java program to implement string classes has been executed
successfully.
Ex.No: 5
Date : Programs using package, abstract class and interface
Aim:
To write a JAVA program implement Interface and Package
Algorithm:
1.Code(Interface):
import java.io.*;
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawa
ble()
d.draw();
}}
2.Code(Package):
MyMath.java:
package arithmetic;
public class MyMath
{
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
}
}
Test.java:
import arithmetic.*;
class Test
{
public static void main(String as[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));
System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
1.OUTPUT:
Drawing Circle
2.OUTPUT:
13
40
1.6
Result:
Thus the java program to perform Interface and Package has been executed
successfully.
Ex.No: 6
Programs using exception handling mechanism
Date :
Aim:
To write a JAVA program using Exception Handling Mechanism.
Algorithm:
Code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CheckedExceptionDemo
{
public static void main(String[] args) {
String filename="test.txt";
try
{
String fileContent = new CheckedExceptionDemo().readFile(filename);
System.out.println(fileContent);
}
catch (FileNotFoundException e)
{
System.out.println("File:"+ filename+" is missing, Please check file name");
}
catch (IOException e)
{
System.out.println("File is not having permission to read, please check the
permission");
}
}
public String readFile(String filename)throws FileNotFoundException, IOException{
FileInputStream fin;
int i;
String s="";
fin = new FileInputStream(filename);
do
{
i = fin.read();
if(i != -1) s =s+(char) i+"";
}
while(i != -1);
fin.close();
return s;
}
}
OUTPUT:
Result:
Thus the java program to perform Exception Handling methods has been
executed successfully.
Ex.No: 7
Date : Programs using user defined exception
Aim:
To write a JAVA program using user defined exception
Algorithm:
Code:
// Define a custom exception class
class NegativeNumberException extends Exception {
public NegativeNumberException(String message) {
super(message);
}
}
// Create a class that performs some operation (e.g., square root) and throws the
custom exception
class MathOperation {
double squareRoot(double number) throws NegativeNumberException {
if (number < 0) {
throw new NegativeNumberException("Cannot calculate square root of a
negative number");
}
return Math.sqrt(number);
}
}
try {
double result = mathOperation.squareRoot(number);
System.out.println("Square root of " + number + " is: " + result);
} catch (NegativeNumberException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
OUTPUT:
ERROR!
Error: Cannot calculate square root of a negative number
Result:
Thus the java program to perform Wrapper Classes has been executed
successfully
Ex.No: 8
Date : Programs using Collection API
Aim:
To write a JAVA program using Collection API.
Algorithm:
Code:
import java.util.*;
OUTPUT
Result:
Thus the java program to perform for collection API has been executed
successfully.
Ex.No: 9
Date : Programs using Multithreading
Aim:
To write a JAVA program using Multithreading.
Algorithm:
Code:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
Output:
main: 1
Thread 1: 1
Thread 2: 1
main: 2
Thread 2: 2
Thread 1: 2
main: 3
Thread 1: 3
Thread 2: 3
main: 4
Thread 2: 4
Thread 1: 4
main: 5
Thread 1: 5
Thread 2: 5
Aim:
To write a JAVA program using thread synchronization.
Algorithm:
Code:
class Counter {
private int count = 0;
// Create and start multiple threads to increment and decrement the counter
IncrementThread incrementThread1 = new IncrementThread(counter);
IncrementThread incrementThread2 = new IncrementThread(counter);
DecrementThread decrementThread1 = new DecrementThread(counter);
DecrementThread decrementThread2 = new DecrementThread(counter);
incrementThread1.start();
incrementThread2.start();
decrementThread1.start();
decrementThread2.start();
Ex.No: 11
Date : Programs using JDBC
Aim:
To write a JAVA program using JDBC.
Algorithm:
Code:
import java.sql.*;
try {
// Establishing a connection to the database
connection = DriverManager.getConnection(jdbcUrl, username,
password);
OUTPUT
ID: 22
NAME: Ram
AGE: 22
Result:
Thus the java program to perform JDBC has been executed successfully.
Aim:
To write a JAVA program using Lambda Expression
Algorithm:
Code:
import java.util.ArrayList;
import java.util.List;
// Using lambda expression to iterate over the list and print each element
System.out.println("Using lambda expression:");
numbers.forEach(number -> System.out.println(number));
OUTPUT
Result:
Thus the java program using Lambda expression has been executed successfully.
VIVA QUESTIONS
10. Can you achieve thread synchronization without using the synchronized keyword?
Yes, by using concurrent data structures from the java.util.concurrent package or
explicit locks from the java.util.concurrent.locks package.
11.Programs using JDBC
1. What is JDBC in Java?
JDBC (Java Database Connectivity) is an API for connecting Java applications to
databases and executing SQL queries.
2. How do you establish a connection to a database using JDBC?
By loading the JDBC driver, creating a connection object using DriverManager, and
specifying the database URL, username, and password.
3. What is a JDBC driver?
A JDBC driver is a software component that allows Java applications to interact with a
specific database management system.
4. What are the types of JDBC drivers?
Type 1: JDBC-ODBC Bridge, Type 2: Native-API driver, Type 3: Network Protocol
driver, Type 4: Thin driver (direct-to-database)
5. How do you execute SQL queries using JDBC?
By creating a Statement or PreparedStatement object, setting parameters if necessary,
and then executing the query using the executeQuery() or executeUpdate() method.
6. How do you retrieve data from a ResultSet object in JDBC?
By using methods like getString(), getInt(), getDouble(), etc., to retrieve column
values from the current row of the ResultSet.
7. What is the purpose of PreparedStatement in JDBC?
PreparedStatement is used to execute parameterized SQL queries, providing better
performance and protection against SQL injection attacks.
8. How do you handle transactions in JDBC?
By setting the auto-commit mode to false, executing multiple SQL statements within a
transaction, and then committing or rolling back the transaction as needed.
9. How do you handle exceptions in JDBC?
By using try-catch blocks to catch SQLExceptions and handling them appropriately,
such as rolling back transactions or closing resources.
10. What is the purpose of the ResultSetMetaData interface in JDBC?
ResultSetMetaData provides methods to retrieve metadata (such as column names,
types, and sizes) about the columns in a ResultSet.
12.Programs using Lambda Expressions
1. What is a lambda expression in Java?
A lambda expression is a concise way to represent anonymous functions or method
implementations.
2. What is the syntax for a lambda expression in Java?
(parameters) -> expression or (parameters) -> { statements; }.
3. What is the purpose of lambda expressions in Java?
Lambda expressions enable functional programming constructs such as passing
behavior as arguments to methods.
4. How do you use lambda expressions with functional interfaces?
By implementing the single abstract method of a functional interface with a lambda
expression.
5. Can lambda expressions capture variables from their surrounding scope?
Yes, lambda expressions can access effectively final local variables and instance or
static variables.
6. What are the types of lambda expressions in Java?
There are two types: one with parameters and a single expression, and another with
parameters and a block of statements.
7. How do you use lambda expressions to iterate over a collection?
By using the forEach() method of the Iterable or Stream interface.
8. How do you sort a collection using lambda expressions?
By using the sort() method of the Collections class or the sorted() method of the
Stream interface.
9. How do you filter elements in a collection using lambda expressions?
By using the filter() method of the Stream interface.
10. What are method references in Java?
Method references provide a way to refer to methods or constructors without invoking
them, often used as lambda expression shortcuts for simple method calls.