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

JAVA EXPERIMENTS1-41

The document contains a series of Java programming experiments demonstrating various concepts such as class definition, control statements, matrix operations, command line arguments, constructor overloading, method overloading, static variables, string manipulation, final members, sorting, inheritance, and method overriding. Each experiment includes code snippets along with their expected outputs. The document serves as a comprehensive guide for practicing fundamental Java programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JAVA EXPERIMENTS1-41

The document contains a series of Java programming experiments demonstrating various concepts such as class definition, control statements, matrix operations, command line arguments, constructor overloading, method overloading, static variables, string manipulation, final members, sorting, inheritance, and method overriding. Each experiment includes code snippets along with their expected outputs. The document serves as a comprehensive guide for practicing fundamental Java programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

JAVA EXPERIMENTS:

1. Write a Java Program to define a class, define instance methods for setting
and retrieving values of instance variables , instantiate its object and
operators.
import java.lang.*;
class emp
{
String name;
int id;
String address;
void getdata(String name,int id,String address)
{
this.name=name;
this.id=id;
this.address=address;
}
void putdata()
{
System.out.println("Employee details are :");
System.out.println("Name :" +name);
System.out.println("ID :" +id);
System.out.println("Address :" +address);
}
}
class empdemo
{
public static void main(String arg[])
{
emp e=new emp();
e.getdata("Mukesh",768,"Delhi");
e.putdata();
}
}

Output:
Employee details are :
Name : Mukesh
ID : 768
Address : Delhi

EXP2:Write a Java Program on control and iterative


statements
/ Java program to illustrate
// if statement without curly block
import java.util.*;

class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)

// part of if block(immediate one statement


// after if condition)
System.out.println("Inside If block");

// always executes as it is outside of if block


System.out.println("10 is less than 15");

// This statement will be executed


// as if considers one statement by default again
// below statement is outside of if block
System.out.println("I am Not in if");
}
}
Output
Inside If block
10 is less than 15
I am Not in if
// Java program to demonstrate
// the working of if-else statement
import java.util.*;

class Geeks {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output
i is smaller than 15
// Java program to demonstrate the
// working of nested-if statement
import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i < 15) {

// First if statement
if (i < 15)
System.out.println("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println(
"i is smaller than 12 too");
}
else {
System.out.println("i is greater than 15");
}
}
}
Output
i is smaller than 15
i is smaller than 12 too
EXP:3

3. Write a java program to find the transpose, addition, subtraction and multiplication of a
two-dimensional matrix using loops.
//Multiply two matrices program in java

import java.io.*;

// Driver Class

class GFG {

// Function to print Matrix

static void printMatrix(int M[][], int rowSize,

int colSize)

{
for (int i = 0; i < rowSize; i++) {

for (int j = 0; j < colSize; j++)

System.out.print(M[i][j] + " ");

System.out.println();

// Function to multiply

// two matrices A[][] and B[][]

static void multiplyMatrix(int row1, int col1,

int A[][], int row2,

int col2, int B[][])

int i, j, k;

// Print the matrices A and B

System.out.println("\nMatrix A:");

printMatrix(A, row1, col1);

System.out.println("\nMatrix B:");

printMatrix(B, row2, col2);

// Check if multiplication is Possible

if (row2 != col1) {
System.out.println(

"\nMultiplication Not Possible");

return;

// Matrix to store the result

// The product matrix will

// be of size row1 x col2

int C[][] = new int[row1][col2];

// Multiply the two matrices

for (i = 0; i < row1; i++) {

for (j = 0; j < col2; j++) {

for (k = 0; k < row2; k++)

C[i][j] += A[i][k] * B[k][j];

// Print the result

System.out.println("\nResultant Matrix:");

printMatrix(C, row1, col2);

// Driver code

public static void main(String[] args)


{

int row1 = 4, col1 = 3, row2 = 3, col2 = 4;

int A[][] = { { 1, 1, 1 },

{ 2, 2, 2 },

{ 3, 3, 3 },

{ 4, 4, 4 } };

int B[][] = { { 1, 1, 1, 1 },

{ 2, 2, 2, 2 },

{ 3, 3, 3, 3 } };

multiplyMatrix(row1, col1, A, row2, col2, B);

Matrix A:
1 1 1
2 2 2
3 3 3
4 4 4

Matrix B:
1 1 1 1
2 2 2 2
3 3 3 3

Resultant Matrix:
6 6 6 6
12 12 12 12
18 18 18 18
24 24 24 24
Output
Matrix A:
1 1 1
2 2 2
3 3 3
4 4 4

Matrix B:
1 1 1 1
2 2 2 2
3 3 3 3

Resultant Matrix:
6 6 6 6
12 12 12 12
18 18 18 18
24 24 24 24
EXP:4
// Java Program to Check for Command Line Arguments
class Hello {

// Main driver method

public static void main(String[] args)

// Checking if length of args array is

// greater than 0

if (args.length > 0) {

// Print statements

System.out.println("The command line"

+ " arguments are:");

// Iterating the args array

// using for each loop

for (String val : args)


System.out.println(val);

else

System.out.println("No command line "

+ "arguments found.");

Output:

EXP:5. Write a Java Program to define a class, describe its


constructor, overload the Constructors and instantiate its object.
// Java program to illustrate
// Constructor Overloading
class Box {
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box() { width = height = depth = 0; }

// constructor used when cube is created


Box(double len) { width = height = depth = len; }

// compute and return volume


double volume() { return width * height * depth; }
}

// Driver code
public class Test {
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

EXP:6. Write a Java Program to illustrate method overloading

// Java program to demonstrate working of method

// overloading in Java

public class Sum {

// Overloaded sum(). This sum takes two int parameters

public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters

public int sum(int x, int y, int z)

return (x + y + z);

// Overloaded sum(). This sum takes two double

// parameters

public double sum(double x, double y)

return (x + y);

}
// Driver code

public static void main(String args[])

Sum s = new Sum();

System.out.println(s.sum(10, 20));

System.out.println(s.sum(10, 20, 30));

System.out.println(s.sum(10.5, 20.5));

Output
30
60
31.0

EXP:7. Write a java program to demonstrate static variables and static methods

// Java program to demonstrate execution

// of static blocks and variables

class Test {

// static variable

static int a = m1();

// static block

static

System.out.println(&quot;Inside static block&quot;);

}
// static method

static int m1()

System.out.println(&quot;from m1&quot;);

return 20;

// static method(main !!)

public static void main(String[] args)

System.out.println(&quot;Value of a : &quot; + a);

System.out.println(&quot;from main&quot;);

Output
from m1
Inside static block
Value of a : 20
from main
EXP:8
8. Write a Java program to practice using String class and its
methods.
// Java Program to Create a String
import java.io.*;
class GFG {
public static void main (String[] args) {

// String literal
String s="Geeks for Geeks String in Java";

System.out.println(s);
}
}
Output
Geeks for Geeks String in Java

// Java Program to Create a String


import java.io.*;

class GFG {
public static void main (String[] args) {

// String literal
String s1="String1";
System.out.println(s1);
// Using new Keyword
String s2= new String("String2");
System.out.println(s2);
}
}
Output
String1
String2

EXP:9

9. Write a Java program using final members


public class ConstantExample {
public static void main(String[] args) {
// Define a constant variable PI
final double PI = 3.14159;

// Print the value of PI


System.out.println("Value of PI: " + PI);
}
}

Output
Value of PI: 3.14159
// Java Program to demonstrate

// Reference of Final Variable

// Main class

class GFG {

// Main driver method


public static void main(String[] args)

// Creating an object of StringBuilder class

// Final reference variable

final StringBuilder sb = new StringBuilder("Geeks");

// Printing the element in StringBuilder object

System.out.println(sb);

// changing internal state of object reference by

// final reference variable sb

sb.append("ForGeeks");

// Again printing the element in StringBuilder

// object after appending above element in it

System.out.println(sb);

}
Output
Geeks
GeeksForGeeks
EXP10. Write a Java Program to sort a list of names in lexicographical order.
// Java Program to Sort Elements in
// Lexicographical Order (Dictionary Order)
import java.io.*;
import java.util.Arrays;

class GFG {

// this function prints the array passed as argument


public static void print(String arr[]) {

for (String s : arr)


System.out.print(s + " ");
System.out.println();
}

public static void main(String[] args)


{
// Initializing String array
String arr2[]
= { "Rat", "Dog", "Cat" };

// sorting String array in Lexicographical Order


// Ingonring case case while sorting using CASE_INSENSITIVE_ORDER
Arrays.sort(arr2,
String.CASE_INSENSITIVE_ORDER);

print(arr2);
}
}
Output
Cat Dog Rat
EXP11:
11. Write a Java Program to implement single inheritance.
class Student{
void Fee() {
System.out.println("Student Fee= 20000");
}
}
class Student_Name extends Student{
void Name() {
System.out.println("Student Name=Jayanti");
}
}
class College {
public static void main(String args[]) {
Student_Name p = new Student_Name();
p.Fee();
p.Name();
}
}

Output:

Student Fee= 20000


Student Name=Jayanti

Exp:12. Write a Java Program to implement multilevel inheritance by applying various


access controls to its data members and methods.
class Car{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{

public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:

Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

Exp:13. Write a Java program using ‘this’ and ‘super’ keyword.

// Program to illustrate this keyword

// is used to refer current class

class RR {

// instance variable

int a = 10;

// static variable

static int b = 20;

void GFG()

// referring current class(i.e, class RR)

// instance variable(i.e, a)

this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)

// static variable(i.e, b)
this.b = 600;

System.out.println(b);

public static void main(String[] args)

// Uncomment this and see here you get

// Compile Time Error since cannot use

// 'this' in static context.

// this.a = 700;

new RR().GFG();

Output
100
600
Exp14:
Write a java program to illustrate method overriding
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

Output:

Boy is eating

exp15. Write java program to explain the use of final keyword in avoiding
method overriding.
// Java Program to Prevent Method Overriding

// using a final keyword method

// Importing input output classes

import java.io.*;

// Class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating object of Child class

Child child = new Child();

// Calling hello() method using Child class object

child.hello();

}
}

// Class 2

// Child class

class Child extends Base {

// Overriding

// @Override

// Method of child class

public void hello()

// Print statement for Child class

System.out.println("Hello from child class");

// Class 3

// Base class

class Base {

// Method of parent class


public final void hello()

// Print statement for Base(parent) class

System.out.println("Hello from base class");

Out put:

exp16. Write a program to demonstrate the use of interface.


import java.io.*;

// Interface Declared
interface testInterface {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// Class implementing interface


class TestClass implements testInterface {

// Implementing the capabilities of


// Interface
public void display(){
System.out.println("Geek");
}
}

class Geeks
{
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}

}
Output
Geek
10

exp17. Write a java program to implement multiple inheritance using the


concept of interface
// Declare the interfaces

interface Walkable {

void walk();

interface Swimmable {

void swim();

// Implement the interfaces in a class

class Duck implements Walkable, Swimmable {

public void walk()

System.out.println("Duck is walking.");

}
public void swim()

System.out.println("Duck is swimming.");

// Use the class to call the methods from the interfaces

class Main {

public static void main(String[] args)

Duck duck = new Duck();

duck.walk();

duck.swim();

Output:

Duck is walking.
Duck is swimming.

exp18. Write a Java program on hybrid and hierarchical inheritance


class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}

Output:

exp19. Write a Java program to implement the concept of importing classes


from user defined package and creating packages , creating sub packages

// Java program to create a user-defined

// package and function to print

// a message for the users

package example;

// Class
public class gfg {

public void show()

System.out.println("Hello geeks!! How are you?");

public static void main(String args[])

gfg obj = new gfg();

obj.show();

Output:

Hello geeks!! How are you?


import example.gfg;

public class GFG {

public static void main(String args[])

gfg obj = new gfg();

obj.show();
}

Output:

Hello geeks!! How are you?

exp20. Write a Java program on access modifiers.


// default access modifier

package p1;

// Class Geek is having

// Default access modifier

class Geek

void display()

System.out.println("Hello World!");

// error while using class from different

// package with default modifier

package p2;

import p1.*; // importing package p1


// This class is having

// default access modifier

class GeekNew {

public static void main(String args[]) {

// Accessing class Geek from package p1

Geek o = new Geek();

o.display();

// error while using class from different package with

// private access modifier

package p1;

// Class A

class A {

private void display() {

System.out.println("GeeksforGeeks");

}
// Class B

class B {

public static void main(String args[]) {

A obj = new A();

// Trying to access private method

// of another class

obj.display();

// protected access modifier

package p1;

// Class A

public class A {

protected void display() {

System.out.println("GeeksforGeeks");

Out put :geeksfor geeks

21. Write a Java program using util package classes.


package com.tutorialspoint;
import java.util.ArrayList;

public class ArrayListDemo {

public static void main(String args[]) {


// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());

// display the array list


System.out.println("Contents of al: " + al);

// Remove elements from the array list


al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}

Output

Initial size of al: 0


Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

exp22. Write a Java program using io package classes .


// Java code to illustrate print()
import java.io.*;

class Demo_print {
public static void main(String[] args)
{

// using print()
// all are printed in the
// same line
System.out.print("GfG! ");
System.out.print("GfG! ");
System.out.print("GfG! ");
}
}
Output
GfG! GfG! GfG!
// Java code to illustrate println()
import java.io.*;

class Demo_print {
public static void main(String[] args)
{

// using println()
// all are printed in the
// different line
System.out.println("GfG! ");
System.out.println("GfG! ");
System.out.println("GfG! ");
}
}
Output
GfG!
GfG!
GfG!

exp23. Write a Java program using stream classes.


import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamIntermediateOperationsExample {


public static void main(String[] args) {
// List of lists of names
List<List<String>> listOfLists = Arrays.asList(
Arrays.asList("Reflection", "Collection", "Stream"),
Arrays.asList("Structure", "State", "Flow"),
Arrays.asList("Sorting", "Mapping", "Reduction", "Stream")
);

// Create a set to hold intermediate results


Set<String> intermediateResults = new HashSet<>();

// Stream pipeline demonstrating various intermediate operations


List<String> result = listOfLists.stream()
.flatMap(List::stream) // Flatten the list of lists into a single
stream
.filter(s -> s.startsWith("S")) // Filter elements starting with "S"
.map(String::toUpperCase) // Transform each element to
uppercase
.distinct() // Remove duplicate elements
.sorted() // Sort elements
.peek(s -> intermediateResults.add(s)) // Perform an action (add to set)
on each element
.collect(Collectors.toList()); // Collect the final result into a list

// Print the intermediate results


System.out.println("Intermediate Results:");
intermediateResults.forEach(System.out::println);

// Print the final result


System.out.println("Final Result:");
result.forEach(System.out::println);
}
}
Output
Intermediate Results:
STRUCTURE
STREAM
STATE
SORTING
Final Result:
SORTING
STATE
STREAM
STRUCTURE

Exp24. Write a Java program on applet life cycle


Class AppletLifeCycle extends Applet
{
public void init()
{
// Initializes objects
}
public void start()
{
// Starts the applet code
}
public void paint(Graphics graphics)
{
// Any shape's code
}
public void stop()
{
// Stops the applet code
}
public void destroy()
{
// Destroys the applet code
}
}
// Java Program to Make An Applet

// Importing required classes from packages


import java.awt.*;
import java.awt.applet.*;

// Class 1
// Helper class extending Applet class
public class AppletDemo extends Applet

// Note: Every class used here is a derived class of applet,


// Hence we use extends keyword Every applet is public
{
public void init()
{
setBackground(Color.black);
setForeground(Color.yellow);
}
public void paint(Graphics g)
{
g.drawString("Welcome", 100, 100);
}
}

// Save file as AppletDemo.java in


<html>
<applet code = AppletDemo
width = 400
height = 500>
</applet>
</html>
<!-- Save as Applet.html -->
exp25. Write a Java program on all AWT controls along with Events and its
Listeners.
/// import necessary packages
import java.awt.event.*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
gfgObj.textField.setText("Using Different Classes");
}
Out put:
exp26. Write a Java program on mouse and keyboard events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100></applet>*/

public class MouseEvents extends Applet implements MouseListener,


MouseMotionListener,MouseWheelListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";

repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();

mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}

// Handle mouse wheel moved.


public void mouseWheelMoved(MouseWheelEvent me) {
// show status
showStatus("Mouse Wheel Moving at " + me.getX() + ", " + me.getY());

}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

Output:
exp27. Write a Java program on inbuilt Exceptions
// Java program to demonstrate

// ArithmeticException

class ArithmeticException_Demo {

public static void main(String[] args) {

try {

int a = 30, b = 0;

int c = a / b; // cannot divide by zero

System.out.println("Result = " + c);

} catch (ArithmeticException e) {

System.out.println("Can't divide a number by 0");

}
Output
Can't divide a number by 0
// Java program to demonstrate
// ArrayIndexOutOfBoundException

class ArrayIndexOutOfBound_Demo {

public static void main(String[] args) {

try {

int[] a = new int[5];

a[5] = 9; // accessing 6th element in an array of

// size 5

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Array Index is Out Of Bounds");

}
Output
Array Index is Out Of Bounds

exp28. Write a Java program on Exception handling


import java.io.*;

class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;

int ans = n / m;

System.out.println("Answer: " + ans);


}
}

Output:
// Java program to demonstrates handling

// the exception using try-catch block

import java.io.*;

class Geeks {

public static void main(String[] args)

int n = 10;

int m = 0;

try {

// Code that may throw an exception

int ans = n / m;

System.out.println("Answer: " + ans);

catch (ArithmeticException e) {

// Handling the exception


System.out.println(

"Error: Division by zero is not allowed!");

finally {

System.out.println(

"Program continues after handling the exception.");

}
Output
Error: Division by zero is not allowed!
Program continues after handling the exception.

exp29. Write a program to implement multi-catch statements


// A Java program to demonstrate that we needed
// multiple catch blocks for multiple exceptions
// prior to Java 7

import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());

if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
catch (ArithmeticException ex)
{
System.out.println("Arithmetic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Number Format Exception " + ex);
}
}
}

Input 1:

GeeksforGeeks

Output 1:

Number Format Exception java.lang.NumberFormatException

For input string: "GeeksforGeeks"

exp30. Write a java program on nested try statements.


class NestedTry {

// main method
public static void main(String args[])
{
// Main try block
try {

// initializing array
int a[] = { 1, 2, 3, 4, 5 };

// trying to print element at index 5


System.out.println(a[5]);

// try-block2 inside another try block


try {

// performing division by zero


int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not exists");
}
}
}

Output
ArrayIndexOutOfBoundsException
Element at such index does not exists

exp31. Write a java program to create user-defined exceptions


// Custom Checked Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String m) {
super(m); //message
}
}

// Using the Custom Exception


public class Geeks {
public static void validate(int age)
throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above.");
}
System.out.println("Valid age: " + age);
}

public static void main(String[] args) {


try {
validate(12);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}
Output
Caught
This is a custom exception

exp32. Write a program to create thread (i)extending Thread class (ii)


implementing Runnable interface
/ Java program to illustrate defining Thread
// by extending Thread class

// Here we cant extends any other class


class Test extends Thread
{
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
Test t = new Test();
t.start();
System.out.println("Main method executed by main thread");
}
}

Output:

Main method executed by main thread


Run method executed by child Thread
// Java program to illustrate defining Thread
// by implements Runnable interface
class Geeks {
public static void m1()
{
System.out.println("Hello Visitors");
}
}

// Here we can extends any other class


class Test extends Geeks implements Runnable {
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
Test t = new Test();
t.m1();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}
}

Output:

Hello Visitors
Main method executed by main thread
Run method executed by child Threa
exp33. Write a java program to create multiple threads and thread priorities,
ThreadGroup

// Java Program to Illustrate Priorities in Multithreading


// via help of getPriority() and setPriority() method
import java.lang.*;

class Thread1 extends Thread {

// run() method for the thread that is called


// as soon as start() is invoked for thread in main()
public void run()
{
System.out.println(Thread.currentThread().getName()
+ " is running with priority "
+ Thread.currentThread().getPriority());
}

// Main driver method


public static void main(String[] args)
{
// Creating random threads
// with the help of above class
Thread1 t1 = new Thread1();
Thread1 t2 = new Thread1();
Thread1 t3 = new Thread1();

// Display the priority of above threads


// using getPriority() method
System.out.println("t1 thread priority: " + t1.getPriority());
System.out.println("t2 thread priority: " + t2.getPriority());
System.out.println("t3 thread priority: " + t3.getPriority());

// Setting priorities of above threads by


// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// Error will be thrown in this case


// t3.setPriority(21);

// Last Execution as the Priority is low


System.out.println("t1 thread priority: " + t1.getPriority());

// Will be executed before t1 and after t3


System.out.println("t2 thread priority: " + t2.getPriority());

// First Execution as the Priority is High


System.out.println("t3 thread priority: " + t3.getPriority());

// Now Let us Demonstrate how it will work


// According to it's Priority
t1.start();
t2.start();
t3.start();

// Thread - 0, 1 , 2 signify 1 , 2 , 3
// respectively
}
}

Output:

t1 thread priority: 5
t2 thread priority: 5
t3 thread priority: 5
t1 thread priority: 2
t2 thread priority: 5
t3 thread priority: 8
Thread-1 is running with priority 5
Thread-2 is running with priority 8
Thread-0 is running with priority 2

exp34. Write a java program to implement thread synchronization


// Java Program to demonstrate synchronization in Java
class Counter {
private int c = 0; // Shared variable

// Synchronized method to increment counter


public synchronized void inc() {
c++;
}

// Synchronized method to get counter value


public synchronized int get() {
return c;
}
}

public class Geeks {


public static void main(String[] args) {
Counter cnt = new Counter(); // Shared resource

// Thread 1 to increment counter


Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
cnt.inc();
}
});

// Thread 2 to increment counter


Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
cnt.inc();
}
});

// Start both threads


t1.start();
t2.start();

// Wait for threads to finish


try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// Print final counter value


System.out.println("Counter: " + cnt.get());
}
}
Output
Counter: 2000

exp35. Write a java program on Inter Thread Communication


import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {


// Shared queue used by both producer and consumer
private static final Queue<Integer> queue = new LinkedList<>();
// Maximum capacity of the queue
private static final int CAPACITY = 10;

// Producer task
private static final Runnable producer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is full
while (queue.size() == CAPACITY) {
try {
System.out.println("Queue is at max capacity");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Add item to the queue
queue.add(10);
System.out.println("Added 10 to the queue");
queue.notifyAll(); // Notify all waiting consumers
try {
Thread.sleep(2000); // Simulate some delay in production
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};

// Consumer task
private static final Runnable consumer = new Runnable() {
public void run() {
while (true) {
synchronized (queue) {
// Wait if the queue is empty
while (queue.isEmpty()) {
try {
System.out.println("Queue is empty, waiting");
queue.wait(); // Release the lock and wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Remove item from the queue
System.out.println("Removed " + queue.remove() + " from the
queue");
queue.notifyAll(); // Notify all waiting producers
try {
Thread.sleep(2000); // Simulate some delay in consumption
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};

public static void main(String[] args) {


System.out.println("Main thread started");
// Create and start the producer thread
Thread producerThread = new Thread(producer, "Producer");
// Create and start the consumer thread
Thread consumerThread = new Thread(consumer, "Consumer");
producerThread.start();
consumerThread.start();
System.out.println("Main thread exiting");
}
}

Output:

The program will produce output similar to this:

Main thread started


Main thread exiting
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue
Queue is empty, waiting
Added 10 to the queue
Removed 10 from the queue
...

exp36. Write a java program on deadlock


// Utility class to pause thread execution
class Util {
static void sleep(long millis)
{
try {
Thread.sleep(millis);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// this class is shared by both threads
class Shared {

// first synchronized method


synchronized void test1(Shared s2)
{
System.out.println(Thread.currentThread().getName()
+ " enters test1 of " + this);
Util.sleep(1000);

// Trying to call test2


// on another object
s2.test2();
System.out.println(Thread.currentThread().getName()
+ " exits test1 of " + this);
}

// Second synchronized method


synchronized void test2()
{
System.out.println(Thread.currentThread().getName()
+ " enters test2 of " + this);
Util.sleep(1000);

// taking object lock of s1 enters


// into test1 method
System.out.println(Thread.currentThread().getName()
+ " exits test2 of " + this);
}
}

class Thread1 extends Thread {


private Shared s1;
private Shared s2;

// constructor to initialize fields


public Thread1(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}

// run method to start a thread


@Override public void run() { s1.test1(s2); }
}

class Thread2 extends Thread {


private Shared s1;
private Shared s2;

// constructor to initialize fields


public Thread2(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}

// run method to start a thread


@Override public void run() { s2.test1(s1); }
}
public class Geeks {

// In this class deadlock occurs


public static void main(String[] args)
{
// creating one object
Shared s1 = new Shared();
Shared s2 = new Shared();

// creating first thread and starting it


Thread1 t1 = new Thread1(s1, s2);
t1.setName("Thread1");
t1.start();

// creating second thread and starting it


Thread2 t2 = new Thread2(s1, s2);
t2.setName("Thread2");
t2.start();
Util.sleep(2000);
}
}
Output:

exp37. Write a Java program to establish connection with database.


// This code is for establishing connection with MySQL
// database and retrieving data
// from db Java Database connectivity

/*
*1. import --->java.sql
*2. load and register the driver ---> com.jdbc.
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/

import java.sql.*;

class Geeks {
public static void main(String[] args) throws Exception {
String url = "jdbc:mysql://localhost:3306/database_name"; // Database
details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query = "select * from students"; // Query to be run

// Load and register the driver


Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
Connection con = DriverManager.getConnection(url, username,
password);
System.out.println("Connection Established successfully");

// Create a statement
Statement st = con.createStatement();

// Execute the query


ResultSet rs = st.executeQuery(query);

// Process the results


while (rs.next()) {
String name = rs.getString("name"); // Retrieve name from db
System.out.println(name); // Print result on console
}

// Close the statement and connection


st.close();
con.close();
System.out.println("Connection Closed....");
}
}

Output:

exp38. Write a Java program on different types of statements


// Java Program illustrating Create Statement in JDBC
import java.sql.*;

public class Geeks {


public static void main(String[] args) {
try {

// Load the driver


Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/world", "root", "12345");
// Create a statement
Statement st = con.createStatement();

// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);

// Process the results


while (rs.next()) {
System.out.println("Name: " + rs.getString("name") +
", Age: " + rs.getInt("age"));
}

// Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output: Name and age are as shown for random inputs.


exp39. Write a Java program to perform DDL and DML statements using
JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class StatementCreateExample {
public static void main(String... arg) {
Connection con = null;
Statement stmt = null;
try {
// registering Oracle driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
// getting connection
con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"ankit", "Oracle123");
System.out.println("Connection established successfully!");

stmt = con.createStatement();
//execute create table query
stmt.executeUpdate("create table EMPLOYEE("
+ "ID number(4), NAME
varchar2(22))");

System.out.println("EMPLOYEE Table created");


} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(stmt!=null) stmt.close(); //close Statement
if(con!=null) con.close(); // close connection
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*OUTPUT
Connection established successfully!
EMPLOYEE Table created
*/

exp40. Write a Java program on Servlet life cycle.


ackage java4s;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletLifeCycle extends HttpServlet


{

public ServletLifeCycle()
{
System.out.println("Am from default constructor");
}

public void init(ServletConfig config)

{
System.out.println("Am from Init method...!");
}

public void doGet(HttpServletRequest req,HttpServletResponse


res)throws ServletException,IOException

{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close();
}

public void destroy()

{
System.out.println("Am from Destroy methods");
}

web.xml
123456789101112<web-app>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>java4s.ServletLifeCycle</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/lifecycle1</url-pattern>

</servlet-mapping>
</web-app>

Output
https://www.java4s.com/wp-content/uploads/2013/01/life-cycle-browser.png

exp41. Write a Java program to handle HTTP requests and


responses using doGet() and doPost() methods
package com.LearnServlets;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddServlet extends HttpServlet {

public void doGet(HttpServletRequest req,


HttpServletResponse res)
throws IOException
{
int num1
= Integer.parseInt(req.getParameter("num1"));
int num2
= Integer.parseInt(req.getParameter("num2"));

int result = num1 + num2;


PrintWriter out = res.getWriter();
out.println("The result is = " + result);
}
}
<web-app>
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.LearnServlets.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
Output:

You might also like