0% found this document useful (0 votes)
22 views

Java Lab Manuals

Example programs for java which is useful for students study purpose
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Lab Manuals

Example programs for java which is useful for students study purpose
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

KARPAGAM ACADEMY OF HIGHER EDUCATION

(Deemed to be University Established Under Section 3 Of UGC Act 1956)


Pollachi Main Road, Eachanari Post, Coimbatore – 641 021, INDIA

Faculty of Engineering
Department of Artificial Intelligence and Data Science

Course / Semester : B.Tech. AI&DS / III Semester


Subject Code / Name: 23BTAD343 / JAVA PROGRAMMING

LAB MANUAL

Prepared by

Dr .Laxmi Raja

AP/ Cyber

Approved by

HOD / Cyber DEAN-FOE


LIST OF EXPERIMENTS:

1. Programs using flow control statements and arrays.


2. Programs using classes and objects.
3. Programs using inheritance and polymorphism.
4. Programs using String, String Buffer and StringBuilder class.
5. Programs using package, abstract class and interface.
6. Programs using exception handling mechanism.
7. Programs using user defined exception.
8. Programs using Collection API.
9. Programs using Multithreading.
10. Programs using thread synchronization.
11. Programs using JDBC.
12. Programs using Lambda Expression.
JAVA
DEFINITION:
Java is an object-oriented programming language that produces software for multiple
platforms. When a programmer writes a Java application, the compiled code (known as
bytecode) runs on most operating systems (OS), including Windows, Linux and Mac OS.
Java derives much of its syntax from the C and C++ programming languages.
Common Applications of Java
Java produces Applets (browser-run programs), which facilitate graphical user
interface (GUI) and object interaction by internet users. Prior to Java applets, web pages were
typically static and non-interactive. Java applets have diminished in popularity with the
release of competing products, such as Adobe Flash and Microsoft Silverlight.

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.

Development time may be accelerated through the use of Integrated Development


Environments (IDE) – such as JBuilder, Netbeans, Eclipse or JCreator. IDEs facilitate the
development of GUIs, which include buttons, text boxes, panels, frames, scrollbars and other
objects via drag-and-drop and point-and-click actions.
Ex.No: 1
Date : Programs using flow control statements and arrays

Aim:
To create a JAVA program to using Control Structure and Array

Algorithm:

Step 1: Start the program


Step 2: Define class
Step 3: Declare variables of specific type
Step 4: Using Control Structure if and if else statements
Step 5: Check the Conditions
Step 6: Need to just print the variables.

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:

Enter the any Number: 19


19 is a Prime Number

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:

Step 1: Start the program


Step 2: Create a Main class
Step 3: Create a method
Step 4: Create a method do operations
Step 5: Inside main, call the methods on the object
Step 6: Call the method
Step 8: Display the result

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Crate Public class and objects
Step 4: Define variable to get inputs
Step 6: Display the result

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

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}

1.OUTPUT:

2.OUTPUT:

The animal makes a sound


The pig says:wee wee
The dog says: bow bow

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create method and assign value
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

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

//creating strings using new keyword


String s3 = new String("BeginnersBook");
String s4 = new String("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");

// Appending more strings


stringBuffer.append(" World");
stringBuffer.append("!");

// Printing the content of the StringBuffer


System.out.println("Content of StringBuffer: " + stringBuffer);

// Inserting a string at a specific position


stringBuffer.insert(6, "beautiful ");
System.out.println("After insertion: " + stringBuffer);

// Deleting characters from the StringBuffer


stringBuffer.delete(6, 16);
System.out.println("After deletion: " + stringBuffer);

// Reversing the content of the StringBuffer


stringBuffer.reverse();
System.out.println("After reversing: " + stringBuffer);
}
}

3.StringBuilder

public class StringBuilderExample {


public static void main(String[] args) {
// Creating a StringBuilder object
StringBuilder stringBuilder = new StringBuilder("Hello");

// Appending more strings


stringBuilder.append(" World");
stringBuilder.append("!");

// Printing the content of the StringBuilder


System.out.println("Content of StringBuilder: " + stringBuilder);

// Inserting a string at a specific position


stringBuilder.insert(6, "beautiful ");
System.out.println("After insertion: " + stringBuilder);

// Deleting characters from the StringBuilder


stringBuilder.delete(6, 16);
System.out.println("After deletion: " + stringBuilder);

// Reversing the content of the StringBuilder


stringBuilder.reverse();
System.out.println("After reversing: " + stringBuilder);
}
}

1.OUTPUT:

String s1 and s2 are equal


String s3 and s4 are NOT equal

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create method,package ,interface and assign value
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create Exception Handling methods and assign value
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create Package by using Wrapper Classes and assign value
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

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

public class Main {


public static void main(String[] args) {
MathOperation mathOperation = new MathOperation();
double number = -25.0;

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

=== Code Execution Successful ===

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create List,ArrayList and assign values
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

Code:

import java.util.*;

public class CollectionExample {


public static void main(String[] args) {
// Creating and populating a list
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

// Iterating over the list using enhanced for loop


System.out.println("Elements in the list:");
for (String fruit : list) {
System.out.println(fruit);
}

// Creating and populating a set


Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(30);

// Iterating over the set using an iterator


System.out.println("\nElements in the set:");
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Creating and populating a map
Map<String, Integer> map = new HashMap<>();
map.put("John", 25);
map.put("Alice", 30);
map.put("Bob", 28);

// Iterating over the map using a for-each loop


System.out.println("\nElements in the map:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}

OUTPUT

Elements in the list:


Apple
Banana
Orange

Elements in the set:


20
10
30

Elements in the map:


Bob: 28
Alice: 30
John: 25

=== Code Execution Successful ===

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:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create and assign values
Step 5: Define Public class and objects
Step 6: Get the input and Display the result

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

public class MultithreadingExample {


public static void main(String[] args) {
MyThread thread1 = new MyThread();
thread1.setName("Thread 1");
MyThread thread2 = new MyThread();
thread2.setName("Thread 2");

// Start the threads


thread1.start();
thread2.start();

// Main thread continues its execution


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

=== Code Execution Successful ===


Result:
Thus the java program to perform multithreading has been executed
successfully.
Ex.No: 10
Programs using thread synchronization
Date :

Aim:
To write a JAVA program using thread synchronization.

Algorithm:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create and assign values
Step 5: Define Public class and objects
Step 6: Get the input and display the result

Code:

class Counter {
private int count = 0;

// Method to increment the counter in a thread-safe manner


public synchronized void increment() {
count++;
}

// Method to decrement the counter in a thread-safe manner


public synchronized void decrement() {
count--;
}

// Method to retrieve the current value of the counter


public synchronized int getCount() {
return count;
}
}

class IncrementThread extends Thread {


private Counter counter;

public IncrementThread(Counter counter) {


this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

class DecrementThread extends Thread {


private Counter counter;

public DecrementThread(Counter counter) {


this.counter = counter;
}

public void run() {


for (int i = 0; i < 1000; i++) {
counter.decrement();
}
}
}

public class ThreadSynchronizationExample {


public static void main(String[] args) {
Counter counter = new Counter();

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

// Wait for all threads to finish


try {
incrementThread1.join();
incrementThread2.join();
decrementThread1.join();
decrementThread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Print the final value of the counter


System.out.println("Final counter value: " + counter.getCount());
}
}
Output:
Final counter value: 0

=== Code Execution Successful ===


Result:
Thus the java program to perform thread synchronization has been executed
successfully.

Ex.No: 11
Date : Programs using JDBC

Aim:
To write a JAVA program using JDBC.

Algorithm:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create and assign values
Step 5: Define Public class and objects
Step 6: Get the input and display the result

Code:

import java.sql.*;

public class JdbcExample {


public static void main(String[] args) {
// JDBC URL, username, and password
String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";

// Connection, Statement, and ResultSet objects


Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Establishing a connection to the database
connection = DriverManager.getConnection(jdbcUrl, username,
password);

// Creating a statement object


statement = connection.createStatement();
// Executing a query
String sqlQuery = "SELECT * FROM students";
resultSet = statement.executeQuery(sqlQuery);

// Iterating over the result set and printing the data


while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " +
age);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Closing the resources
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

OUTPUT

ID: 22
NAME: Ram
AGE: 22
Result:
Thus the java program to perform JDBC has been executed successfully.

Ex.No: 12 Programs using Lambda Expression


Date :

Aim:
To write a JAVA program using Lambda Expression

Algorithm:

Step 1: Start the program


Step 2: Create main class
Step 3: Define instance variables of the class
Step 4: Create and assign values
Step 5: Define Public class and objects
Step 6: Get the input and display the result

Code:
import java.util.ArrayList;
import java.util.List;

public class LambdaExpressionExample {


public static void main(String[] args) {
// Creating a list of integers
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);

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

// Using lambda expression with multiple statements


System.out.println("\nUsing lambda expression with multiple statements:");
numbers.forEach(number -> {
int squared = number * number;
System.out.println(number + " squared is " + squared);
});

// Using lambda expression with method reference


System.out.println("\nUsing lambda expression with method reference:");
numbers.forEach(System.out::println);
}
}

OUTPUT

Using lambda expression:


1
2
3
4
5

Using lambda expression with multiple statements:


1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

Using lambda expression with method reference:


1
2
3
4
5

=== Code Execution Successful ===

Result:
Thus the java program using Lambda expression has been executed successfully.
VIVA QUESTIONS

1.Programs using flow control statement and array.

1. What is the purpose of the if-else statement in Java?


The if-else statement executes a block of code if a condition is true, otherwise, it
executes an alternative block.
2. How do you declare and initialize an array in Java?
You declare an array by specifying the type and name, then initialize it with values
enclosed in curly braces.
3. What is the syntax for a for loop in Java?
The syntax is for (initialization; condition; iteration) { }.

4. How do you access elements in an array?


You access elements by referring to the index within square brackets, starting from 0.
5. What happens if an array index is out of bounds?
It results in an ArrayIndexOutOfBoundsException at runtime.
6. Name a type of loop in Java that executes its body at least once.
The do-while loop.
7. How do you iterate over elements of an array using a for-each loop?
for (type variable : array) { }
8. What is the purpose of the switch statement?
It evaluates an expression and executes code blocks based on matching case labels.
9. Can you nest control statements in Java?
Yes, you can nest if statements, loops, and switch statements within each other.
10. What is the length of an array?
The length of an array is the number of elements it contains, accessed via the
length property.
2. Programs using classes and objects

1. What is a class in Java?


A class is a blueprint for creating objects that defines attributes and behaviors.
2. How do you define a class in Java?
By using the class keyword followed by the class name and class body containing
attributes and methods.
3. What is an object in Java?
An object is an instance of a class that represents a real-world entity.
4. How do you create an object in Java?
By using the new keyword followed by the class name and optional constructor
arguments.
5. What is a constructor in Java?
A constructor is a special method that initializes objects when they are created.
6. How do you invoke methods on an object in Java?
By using the dot (.) operator followed by the method name and optional arguments.
7. Can a class have multiple constructors?
Yes, a class can have multiple constructors with different parameters (method
overloading).
8. What is the purpose of the this keyword in Java?
It refers to the current object and is used to differentiate between instance variables
and parameters with the same name.
9. How do you access class variables and methods without creating an object?
By using the class name followed by the dot (.) operator.
10. What is encapsulation in Java?
Encapsulation is the mechanism of bundling data (attributes) and methods that operate
on the data within a single unit (class), hiding the internal implementation details.
3. Programs using inheritance and polymorphism
1. What is inheritance in Java?
Inheritance allows a class (subclass) to inherit attributes and methods from another class
(superclass).
2. How do you implement inheritance in Java?
By using the extends keyword followed by the superclass name in the subclass
declaration.
3. What is a superclass and a subclass?
A superclass is the class being inherited from, while a subclass is the class that inherits
from a superclass.
4. Can a Java class inherit from multiple classes?
No, Java does not support multiple inheritance for classes, but it supports multiple
inheritance for interfaces.
5. What is polymorphism in Java?
Polymorphism allows objects of different classes to be treated as objects of a common
superclass through method overriding and method overloading.
6. How do you achieve method overriding in Java?
By providing a method in the subclass with the same signature (name and parameters) as
a method in the superclass.
7. What is dynamic method dispatch in Java?
It is the mechanism by which the correct version of an overridden method is invoked at
runtime based on the object's actual type.
8. How do you achieve method overloading in Java?
By defining multiple methods in a class with the same name but different parameter lists.
9. Can you use polymorphism with variables of superclass type?
Yes, you can assign objects of subclasses to variables of superclass type and invoke
overridden methods using those variables.
10. What is the difference between static and dynamic binding?
Static binding (early binding) occurs at compile-time, while dynamic binding (late
binding) occurs at runtime.
4. Programs using string, stringbuffer, and string builder
class

1. What is the difference between String, StringBuffer, and StringBuilder classes?


String is immutable, StringBuffer is mutable and synchronized, StringBuilder is mutable
but not synchronized.
2. How do you create a String object in Java?
By using double quotes: String str = "Hello";.
3. What is immutability in the context of String objects?
Once created, the content of a String object cannot be changed.
4. How do you concatenate Strings in Java?
By using the + operator or the concat() method.
5. What is the advantage of using StringBuffer over String for concatenation?
StringBuffer is mutable, so concatenating Strings using StringBuffer is more efficient
than using immutable Strings.
6. How do you create a StringBuffer object in Java?
By using the new keyword: StringBuffer sb = new StringBuffer();.
7. What is the difference between StringBuffer and StringBuilder?
StringBuffer is synchronized (thread-safe), while StringBuilder is not synchronized (not
thread-safe).
8. How do you append or modify a StringBuffer object?
By using the append() method to add characters or strings to the end of the buffer.
9. Can you convert a StringBuffer or StringBuilder object to a String?
Yes, by using the toString() method.
10. When would you choose StringBuffer over StringBuilder?
When thread safety is required, StringBuffer is preferred; otherwise, StringBuilder is
more efficient.
5. Programs using package, abstract class and interface

1. What is a package in Java?


A package is a grouping mechanism that organizes related classes and interfaces.
2. How do you declare a package in Java?
By using the package keyword followed by the package name at the beginning of the
source file.
3. What is the purpose of using packages?
Packages help organize code, prevent naming conflicts, and facilitate reusability.
4. What is an abstract class in Java?
An abstract class is a class that cannot be instantiated and may contain abstract methods.
5. How do you declare an abstract class in Java?
By using the abstract keyword before the class declaration.
6. Can abstract classes have constructors?
Yes, abstract classes can have constructors for initializing common properties.
7. What is the difference between an abstract class and an interface?
Abstract classes can have both abstract and concrete methods, while interfaces can only
have abstract methods (prior to Java 8).
8. How do you declare an interface in Java?
By using the interface keyword before the interface name.
9. Can interfaces have variables?
Yes, interfaces can have constants (public, static, final variables).
10. How do you implement an interface in a class?
By using the implements keyword followed by the interface name in the class
declaration, and implementing all the methods defined in the interface.
6. Programs using exceptional handling and mechanism

1. What is an exception in Java?


An exception is an event that disrupts the normal flow of program execution.
2. How do you handle exceptions in Java?
By using try-catch blocks to catch and handle exceptions gracefully.
3. What is the purpose of the try block?
The try block contains code that may throw exceptions.
4. What is the purpose of the catch block?
The catch block handles exceptions thrown by the code in the try block.
5. Can you have multiple catch blocks in a try-catch statement?
Yes, you can have multiple catch blocks to handle different types of exceptions.
6. What is the purpose of the finally block?
The finally block contains code that is always executed, regardless of whether an
exception is thrown or caught.
7. How do you throw custom exceptions in Java?
By using the throw keyword followed by an instance of an exception class.
8. What is the difference between checked and unchecked exceptions? Checked exceptions
are checked at compile-time, while unchecked exceptions are not.
9. How do you define your own exception class in Java?
By extending the Exception class or one of its subclasses.
10. What is the purpose of exception chaining in Java?
Exception chaining allows one exception to be associated with another, providing more
context about the error.
7. Programs using user defined exception
1. What is a user-defined exception in Java?
A user-defined exception is an exception created by the programmer to handle specific
error conditions.
2. How do you create a user-defined exception class in Java?
By extending the Exception class or one of its subclasses.
3. Why would you create a user-defined exception in Java?
To handle application-specific error conditions that are not covered by built-in
exception classes.
4. What is the naming convention for user-defined exception classes?
Typically, user-defined exception class names end with "Exception" (e.g.,
CustomException).
5. How do you throw a user-defined exception in Java?
By creating an instance of the custom exception class and throwing it using the throw
keyword.
6. How do you handle a user-defined exception in Java?
By catching the custom exception using try-catch blocks and handling it appropriately.
7. Can user-defined exceptions have custom constructors?
Yes, user-defined exception classes can have custom constructors to provide additional
information about the error.
8. When would you use a user-defined exception instead of a built-in exception?
When you need to handle application-specific error scenarios with specific error
messages or actions.
9. Can a user-defined exception be a checked exception or an unchecked exception?
It can be either, depending on whether it extends Exception (checked) or
RuntimeException (unchecked).
10. How can user-defined exceptions improve code readability and maintainability?
They can provide descriptive error messages and encapsulate error-handling logic,
making code more understandable and maintainable
8. Program using collection API

1. What is the Collection API in Java?


The Collection API is a framework that provides interfaces and classes to represent
and manipulate collections of objects.
2. Name some core interfaces in the Collection API.
Some core interfaces include List, Set, Queue, and Map.
3. What is the difference between a List and a Set?
A List allows duplicate elements and maintains insertion order, while a Set does not
allow duplicates and does not guarantee order.
4. How do you create an ArrayList in Java?
By using the ArrayList class and its constructor: List<String> list = new
ArrayList<>();.
5. What is the purpose of the Map interface?
The Map interface represents a collection of key-value pairs.
6. How do you iterate over elements in a collection using a for-each loop?
for (Type var : collection) { }.
7. What is the purpose of the Iterator interface?
The Iterator interface provides a way to iterate over elements in a collection
sequentially.
8. How do you add elements to a collection?
By using the add() method for lists and sets, and the put() method for maps.
9. Can you remove elements from a collection?
Yes, by using the remove() method.
10. What are some concrete implementations of the Collection interface?
Some concrete implementations include ArrayList, LinkedList, HashSet, TreeSet,
HashMap, and TreeMap.
9. Programs using Multithreading
1. What is multithreading in Java?
Multithreading is the simultaneous execution of multiple threads within a single Java
program.
2. How do you create a thread in Java?
By extending the Thread class or implementing the Runnable interface and then
instantiating a Thread object.
3. What is the difference between extending the Thread class and implementing the
Runnable interface?
Extending Thread class binds the code and the execution thread, while implementing
Runnable allows code to be executed by any thread.
4. How do you start a thread in Java?
By calling the start() method on a Thread object.
5. What is the purpose of the run() method in a Thread?
The run() method contains the code to be executed by the thread.
6. What is a race condition in multithreading?
A race condition occurs when multiple threads access shared resources concurrently,
leading to unexpected behavior.
7. How do you synchronize access to shared resources in Java?
By using synchronized blocks or methods to ensure that only one thread can access
the shared resource at a time.
8. What is the purpose of the wait() and notify() methods in Java?
The wait() method pauses the current thread until another thread calls notify() or
notifyAll() to wake it up.

9. How do you implement thread synchronization using locks in Java?


By using explicit lock objects from the java.util.concurrent.locks package,
such as ReentrantLock.
10. What are daemon threads in Java?
Daemon threads are background threads that run intermittently to perform tasks such
as garbage collection or monitoring.
10.Programs using thread synchronization
1. What is thread synchronization in Java?
Thread synchronization is the coordination of multiple threads to ensure they access
shared resources in a predictable manner.

2. How do you achieve thread synchronization in Java?


By using synchronized blocks or methods, or by using explicit locks from the
java.util.concurrent.locks package.

3. What is a synchronized block in Java?


A synchronized block is a code block that is synchronized on a specified object to
ensure exclusive access by only one thread at a time.

4. Can synchronized blocks synchronize on any object?


Yes, synchronized blocks can synchronize on any object, including this or a specific
lock object.

5. What is the purpose of the synchronized keyword in Java?


The synchronized keyword is used to define synchronized methods or blocks to
achieve thread safety.

6. What is the difference between synchronized methods and synchronized blocks?


Synchronized methods synchronize on the object instance (this), while synchronized
blocks can synchronize on any object.

7. How do you implement thread-safe data structures in Java?


By using synchronized methods or blocks to ensure atomicity and consistency of
operations on shared data.

8. What is the purpose of the wait() and notify() methods in Java?


The wait() method pauses the current thread until another thread calls notify() or
notifyAll() to wake it up.

9. How do you handle deadlock situations in Java?


By carefully designing synchronization logic and avoiding nested locks, or using
timeouts and thread interruption.

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.

You might also like