Java Dip Lab2 25 Feb
Java Dip Lab2 25 Feb
a Java Program to define a class, define instance methods for setting and
retrieving values of instance variables , instantiate its object and operators.
public class Person {
// Instance
variables private
String name; private
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to set the name
public void setName(String name)
{ this.name = name;
}
// Method to get the name
public String getName() {
return name;
}
Name: Alice
Age: 30
Updated Name: Bob
Updated Age: 25
Age after 5 years: 30
Experiment-2
int[][] matrixB = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};
// Addition
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 3; j++)
{
resultAddition[i][j] = matrixA[i][j] + matrixB[i][j];
}
}
// Subtraction
// Multiplication
for (int i = 0; i < 3; i++)
{ for (int j = 0; j < 3; j++)
{
resultMultiplication[i][j] = 0;
for (int k = 0; k < 3; k++) {
resultMultiplication[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Display results
System.out.println("Addition of matrices:");
displayMatrix(resultAddition);
System.out.println("Subtraction of matrices:");
displayMatrix(resultSubtraction);
System.out.println("Multiplication of matrices:");
displayMatrix(resultMultiplication);
}
System.out.println();
}
}
}
Output:
Addition of matrices:
10 10 10
10 10 10
10 10 10
Subtraction of matrices:
-8 -6 -4
-2 0 2
468
Multiplication of matrices:
30 24 18
84 69 54
138 114 90
Experiment-3
class A{
sonoo
jaiswal
1
3
abc
Experiment-4
Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.
class Constructor
{
Constructor( )
{
System.out.println(“Default Constructor”);
}
Constructor(int a)
{
System.out.println(a);
}
Constructor(int a,int b)
{
System.out.println(a+b);
}
public static void main(String[] args)
{ Constructor c1=new Constructor();
Constructor c1=new Constructor(10);
Constructor c1=new Constructor(20,50);
}
}
Output:
Default Constructor
10
70
Experiment-5
class Main
{
}
Output:
10
show method
Experiment-7
Write a Java program to practice using String class and its methods.
public class StringMethodsDemo
{ public static void main(String[] args)
{
// Creating a string
String str = "Hello, World!";
// 4. Concatenation of strings
String str2 = " How are you?";
String concatenated = str.concat(str2);
System.out.println("Concatenated string: " + concatenated);
// 7. Convert to uppercase
String upperCaseString = str.toUpperCase();
System.out.println("Uppercase string: " + upperCaseString);
// 8. Convert to lowercase
String lowerCaseString = str.toLowerCase();
System.out.println("Lowercase string: " + lowerCaseString);
// Derived class
class Dog extends Animal {
// Method in the derived class
void bark() {
System.out.println("The dog barks.");
}
public static void main(String[] args) {
// Create an object of the derived class
Dog myDog = new Dog();
}
Output:
This animal eats food.
The dog barks.
Experiment-9
Write a Java program using ‘this’ and ‘super’ keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
}
Output:
111 ankit 5000.0
112 sumit 6000.0
Experiment-10
Write a java program to illustrate method overriding
class Super
{
void display()
{
System.out.println(“Super class method”);
}
}
class Sub extends Super
{
void display()
{
}
// Implement both interfaces in a single class
class Bat implements Animal, Bird {
// Implement the eat method from Animal interface
public void eat() {
System.out.println("Bat is eating.");
}
// Implement the fly method from Bird interface
public void fly() {
System.out.println("Bat is flying.");
}
}
}
Output:
Bat is eating.
Bat is flying.
Experiment-12
Write a Java program to implement the concept of importing classes from user
defined package and creating packages , creating sub packages.
//save by class1.java.
package pack1;
public class Class1{
public void display(){
System.out.println("Inside class1 method.")
}
//save by Class2.java
package pack2;
import pack1.*;
class Class2{
public static void main(String args[])
{ Class1 obj = new Class1();
obj.display();
}
}
Output:
Inside class1 method.
Experiment-13
Write a Java program using util package classes.
import java.util.ArrayList;
import java.util.Collections;
public class UtilPackageExample
{
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add some numbers to the list
numbers.add(5);
numbers.add(3);
numbers.add(8);
numbers.add(1);
numbers.add(6);
// Print the original list
System.out.println("Original list: " + numbers);
// Sort the list using Collections.sort()
Collections.sort(numbers);
// Print the sorted list
System.out.println("Sorted list: " + numbers);
}
}
Output:
Original list: [5, 3, 8, 1, 6]
Sorted list: [1, 3, 5, 6, 8]
Experiment-14
Write a Java program on applet life cycle
import java.applet.Applet;
import java.awt.Graphics;
public class AppletLifeCycle extends Applet {
// Called when the applet is first loaded
public void init() {
System.out.println("Applet initialized");
}
// Called when the applet is started or restarted
public void start() {
System.out.println("Applet started");
}
<html>
<body>
<applet code="AppletLifeCycle.class" width="300" height="200">
</applet>
</body>
</html>
Applet initialized
Applet started
Applet stopped
Applet destroyed
Experiment-15
Write a Java program on all AWT controls along with Events and its Listeners.
import java.awt.*;
import java.awt.event.*;
public class AWTControlsExample extends Frame {
public AWTControlsExample() {
// Initialize components
btnClick = new Button("Click Me");
textField = new TextField(20);
label = new Label("This is a label");
checkbox = new Checkbox("Accept Terms and Conditions");
radioGroup = new CheckboxGroup();
radio1 = new Checkbox("Option 1", radioGroup, false);
radio2 = new Checkbox("Option 2", radioGroup, false);
textArea = new TextArea("Type something here...");
}
}
});
radio2.addItemListener(new ItemListener()
{ public void itemStateChanged(ItemEvent e) {
if (radio2.getState()) {
label.setText("Radio Button 2 selected");
}
}
});
import java.awt.*;
import java.awt.event.*;
public class MouseKeyboardEventsExample extends Frame {
// Declare components
Label mouseLabel, keyboardLabel;
public MouseKeyboardEventsExample() {
// Set the frame layout
setLayout(new FlowLayout());
// Initialize components
mouseLabel = new Label("Mouse Event not yet triggered");
keyboardLabel = new Label("Keyboard Event not yet triggered");
});
class Main {
public static void main(String[] args)
{ try {
// code that generates exception
int divideByZero = 5 / 0;
}
catch (ArithmeticException e)
{ System.out.println("ArithmeticException => " + e.getMessage());
}
finally {
System.out.println("This is the finally block");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Experiment-18
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
}
System.out.println("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Experiment-19
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
Experiment-20
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
try {
threadFromRunnable.join();
myThread.join();
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
Output:
Experiment-23
}
}
class MyThread1 extends Thread
{ Table t;
// Constructor to initialize Table object
MyThread1(Table t) {
this.t = t;
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 5
t.printTable(5);
}
}
}
// Run method to execute thread
public void run() {
// Call synchronized method printTable with argument 100
t.printTable(100);
}
}
public class TestSynchronization2
{ public static void main(String args[])
{
// Create a Table object
Table obj = new Table();
// Create MyThread1 and MyThread2 objects with the same Table object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
// Start both threads
t1.start();
t2.start();
}
}
Output:
Experiment-24
class Customer{
int amount=10000;
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run()
{
c.withdraw(15000);
}
}.start();
new Thread()
{ public void
run()
{
c.deposit(10000);
}
}.start();
}
}
Output:
Experiment-25
}
};
t1.start();
t2.start();
}
}
Output:
Experiment-26
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Output:
Experiment-27
// Create a statement
Statement st = con.createStatement();
// Execute a query
String sql = "SELECT * FROM people";
ResultSet rs = st.executeQuery(sql);
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
// Java Program illustrating Prepared Statement in JDBC
import java.sql.*;
import
java.util.Scanner; class
Geeks {
public static void main(String[] args) {
// try block to check for exceptions
try {
// Loading drivers using forName() method
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println(
"What age do you want to search?? ");
// Create a statement
PreparedStatement ps =
con.prepareStatement( "select name from
world.people where age = ?");
// Execute the query
ps.setInt(1, age);
ResultSet res = ps.executeQuery();
}
// Catch block to handle database exceptions
catch (SQLException e) {
// Display the DB exception if any
System.out.println(e);
}
// Catch block to handle class exceptions
catch (ClassNotFoundException e) {
// Print the line number where exception occurred
// using printStackTrace() method if any
e.printStackTrace();
}
}
}
Output:
// Java Program illustrating
// Callable Statement in JDBC
import java.sql.*;
public class Geeks {
public static void main(String[] args) {
// Try block to check if any exceptions occur
try {
// Load and register the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish a connection
Connection con = DriverManager
.getConnection("jdbc:mysql:///world", "root", "12345");
// Create a CallableStatement
CallableStatement cs =
con.prepareCall("{call GetPeopleInfo()}");
}
}
}
Output:
Experiment-28
Write a Java program to perform DDL and DML statements using JDBC.
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully Registered
// Java program to illustrate
// updating the Database
import java.sql.*;
public class update1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String newPwd = "newpwd";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = con.createStatement();
// Updating database
if (x > 0)
{
System.out.println(e);
}
}
}
Output:
Password Successfully Updated
// Java program to illustrate
// deleting from Database
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" + id +
"' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURRED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
One User Successfully Deleted
// Java program to illustrate
// selecting from Database
import java.sql.*;
String id = "id1";
String pwd = "pwd1";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1"); Statement stmt = con.createStatement();
// SELECT query
System.out.println(e);
}
}
}
Output:
User-Id : id1
Full Name : Java Programming
E-mail : [email protected]