JAVA EXPERIMENTS1-41
JAVA EXPERIMENTS1-41
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
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
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 {
int colSize)
{
for (int i = 0; i < rowSize; i++) {
System.out.println();
// Function to multiply
int i, j, k;
System.out.println("\nMatrix A:");
System.out.println("\nMatrix B:");
if (row2 != col1) {
System.out.println(
return;
System.out.println("\nResultant Matrix:");
// Driver code
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 } };
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 {
// greater than 0
if (args.length > 0) {
// Print statements
else
+ "arguments found.");
Output:
// 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;
// overloading in Java
return (x + y + z);
// parameters
return (x + y);
}
// Driver code
System.out.println(s.sum(10, 20));
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
class Test {
// static variable
// static block
static
}
// static method
System.out.println("from m1");
return 20;
System.out.println("from main");
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
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
Output
Value of PI: 3.14159
// Java Program to demonstrate
// Main class
class GFG {
System.out.println(sb);
sb.append("ForGeeks");
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 {
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:
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
class RR {
// instance variable
int a = 10;
// static variable
void GFG()
// instance variable(i.e, a)
this.a = 100;
System.out.println(a);
// static variable(i.e, b)
this.b = 600;
System.out.println(b);
// 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
import java.io.*;
// Class
class GFG {
child.hello();
}
}
// Class 2
// Child class
// Overriding
// @Override
// Class 3
// Base class
class Base {
Out put:
// Interface Declared
interface testInterface {
class Geeks
{
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Output
Geek
10
interface Walkable {
void walk();
interface Swimmable {
void swim();
System.out.println("Duck is walking.");
}
public void swim()
System.out.println("Duck is swimming.");
class Main {
duck.walk();
duck.swim();
Output:
Duck is walking.
Duck is swimming.
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[]){
Output:
package example;
// Class
public class gfg {
obj.show();
Output:
obj.show();
}
Output:
package p1;
class Geek
void display()
System.out.println("Hello World!");
package p2;
class GeekNew {
o.display();
package p1;
// Class A
class A {
System.out.println("GeeksforGeeks");
}
// Class B
class B {
// of another class
obj.display();
package p1;
// Class A
public class A {
System.out.println("GeeksforGeeks");
Output
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!
// Class 1
// Helper class extending Applet class
public class AppletDemo extends Applet
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
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());
}
}
// 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 {
try {
int a = 30, b = 0;
} catch (ArithmeticException e) {
}
Output
Can't divide a number by 0
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
try {
// size 5
} catch (ArrayIndexOutOfBoundsException e) {
}
Output
Array Index is Out Of Bounds
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
int ans = n / m;
Output:
// Java program to demonstrates handling
import java.io.*;
class Geeks {
int n = 10;
int m = 0;
try {
int ans = n / m;
catch (ArithmeticException e) {
finally {
System.out.println(
}
Output
Error: Division by zero is not allowed!
Program continues after handling the exception.
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:
// main method
public static void main(String args[])
{
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
Output
ArrayIndexOutOfBoundsException
Element at such index does not exists
Output:
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
// 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
// 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();
}
}
}
}
};
Output:
/*
*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
// Establish connection
Connection con = DriverManager.getConnection(url, username,
password);
System.out.println("Connection Established successfully");
// Create a statement
Statement st = con.createStatement();
Output:
// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);
// Close resources
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
stmt = con.createStatement();
//execute create table query
stmt.executeUpdate("create table EMPLOYEE("
+ "ID number(4), NAME
varchar2(22))");
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 ServletLifeCycle()
{
System.out.println("Am from default constructor");
}
{
System.out.println("Am from Init method...!");
}
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close();
}
{
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
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;