Java Rec Faisal
Java Rec Faisal
1ST BIT:
1. Write a Java program to display Welcome message.
Solution:
public class WelcomeMessage {
}
}
Output:
1604-21-737-093
3a. Write a program to calculate factorial of a given number (both iterative
and recursive)
Solution:
// Using Iterative Method
import java.util.Scanner;
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
1604-21-737-093
System.out.println("Factorial of " + number + " using iterative
approach: " + factorial);
}
}
}
Output:
}
if (n == 0 || n == 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
1604-21-737-093
int factorial = factorialRecursive(number);
if (factorial != -1) {
System.out.println("Factorial of " + number + " using recursive
approach: " + factorial);
}
}
}
Output:
1604-21-737-093
// If no two elements were swapped in the inner loop, the array is
already sorted
if (!swapped) {
break;
}
}
}
System.out.println("Original array:");
printArray(arr);
bubbleSort(arr);
System.out.println("Sorted array:");
printArray(arr);
1604-21-737-093
System.out.println();
}
}
Output:
1604-21-737-093
int upperLimit = scanner.nextInt();
if (isPrime) {
System.out.print(i + " ");
}
}
System.out.println();
}
}
Output:
1604-21-737-093
6. Write a program to convert a decimal number into its equivalent binary
number.
Solution:
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int binaryNumber = 0;
int placeValue = 1;
}
}
Output:
1604-21-737-093
7. Write programs demonstrating Multidimensional Arrays.
Solution:
import java.util.Scanner;
public class TwoDimensionalArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
}
}
Output:
1604-21-737-093
1604-21-737-093
8. Write a program using Switch statement to know if an input month
number (1,2,…12) is in {Autumn, spring, winter or summer}
Solution:
import java.util.Scanner;
public class SeasonChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid month number";
break;
}
1604-21-737-093
System.out.println("The season for the given month number is: " +
season);
}
}
Output:
1604-21-737-093
2Nd BIT:
1. Write programs to demonstrate Constructor, Methods, Parameter
passing, and method overloading.
Solution:
1a.constructor
/* Here, Box uses a constructor to initialize the
dimensions of a box.
*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;}
// compute and return volume
double volume() {
return width * height * depth;
}}
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
1604-21-737-093
1b.method overloading
Solution:
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
1604-21-737-093
}
Output:
1604-21-737-093
double volume() {
return width * height * depth;
}
}
class OverloadCons {
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:
1604-21-737-093
3. Program to demonstrate all usages of this keyword
Solution:
class Person {
private String name;
private int age;
1604-21-737-093
// Method to set the age using the "this" keyword
public void setAge(int age) {
this.age = age; // "this" is used to refer to the instance variable
}
1604-21-737-093
Person person1 = new Person("Alice", 25);
person1.displayInfo();
person1.printSelf();
}
}
Output:
1604-21-737-093
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Output:
1604-21-737-093
class Stack {
/* Now, both stck and tos are private. This means
that they cannot be accidentally or maliciously
altered in a way that would be harmful to the stack.
*/
private int stck[] = new int[10];
private int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
1604-21-737-093
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
1604-21-737-093
6. Write a program to demonstrate Inner classes
Solution:
1604-21-737-093
7. Write a program to demonstrate Single level inheritance
Solution:
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
1604-21-737-093
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Output:
1604-21-737-093
8. Write a program to demonstrate Multilevel inheritance
Solution:
// Start with Box.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.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 = -1; // use -1 to indicate
height = -1; // an uninitialized
1604-21-737-093
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
// Add shipping costs.
class Shipment extends BoxWeight {
double cost;
1604-21-737-093
// construct clone of an object
Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}
// constructor when all parameters are specified
Shipment(double w, double h, double d,
double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
// default constructor
Shipment() {
super();
cost = -1;
}
// constructor used when cube is created
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
1604-21-737-093
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}
Output:
1604-21-737-093
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.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 = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
1604-21-737-093
BoxWeight(double w, double h, double d, double m) {
1604-21-737-093
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}
Output:
1604-21-737-093
B subOb = new B(1, 2);
subOb.show();
}
}
Output:
1604-21-737-093
10. Program to assign SubClass Object to SuperClass reference Variable
Solution:
class SuperClass {
public void m1 () {
System.out.println("m1");
}
}
class SuperSub {
public static void main(String args[]){
SuperClass ss = new SubClass();
ss.m1();
}
}
Output:
1604-21-737-093
11. Member Access in java in inheritance hierarchy.
Solution:
class Animal {
String name;
1604-21-737-093
dog.displayInfo();
Output :
1604-21-737-093
12. Program to demonstrate order of invocation of constructors in a
multilevel hierarchy
Solution:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
1604-21-737-093
C c = new C();
}
}
Output:
3rd BIT:
1. Write a program to demonstrate Method overriding
Solution:
// Using run-time polymorphism.
class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}
1604-21-737-093
Rectangle(double a, double b) {
super(a, b);
}
class FindAreas {
public static void main(String args[]) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref;
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
figref = f;
System.out.println("Area is " + figref.area());
}
}
1604-21-737-093
Output:
1604-21-737-093
2. Write a program to demonstrate Dynamic Polymorphism. (DMD)
Solution:
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Output:
1604-21-737-093
3. Write a Java program to demonstrate Abstract Classes.
Solution:
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
1604-21-737-093
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Output:
1604-21-737-093
4. Write a program to demonstrate all usages of final keyword with respect
to inheritance. (prevention of inheritance and method overriding)
Solution:
final class Parent {
final String name = "Parent";
class AnotherClass {
void nonFinalMethod() {
System.out.println("This is a non-final method in AnotherClass.");
}
}
Output:
1604-21-737-093
5. Write a program to demonstrate creation of a package, also write about
different ways to compile and run a package based program
Solution:
// MyClass.java
package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in mypackage!");
}
}
//PackageDemo.java
package mypackage;
public class PackageDemo {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.displayMessage();
}
}
Output:
1604-21-737-093
6. Write a program to illustrate about access protection with respect to
access specifiers and packages. (demonstrate all combinations of access
protection table)
Solution:
Package p1
// Demo package p1.
package p1;
package p1;
package p1;
1604-21-737-093
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
package p1;
class SamePackage {
SamePackage() {
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Package P2
// Demo package p2.
package p2;
class OtherPackage {
OtherPackage() {
1604-21-737-093
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
package p2;
Output:
1604-21-737-093
7. Write a program to show how to import a package into a program
Solution:
package mypack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
String name;
1604-21-737-093
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
import mypack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
Output:
1604-21-737-093
4Th BIT:
1. Write a program to define and implement an interface
Solution:
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
class CallBackDemo {
public static void main(String args[]) {
Client client = new Client();
client.callback(42);
}
}
Output:
1604-21-737-093
2. Write a program to demonstrate access of implementation of interface
methods through an interface reference variable.
Solution:
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}
Output:
1604-21-737-093
3. Write a program to demonstrate Partial Implementation of an interface.
Solution:
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
class PartialImplementationDemo {
public static void main(String args[]) {
Incomplete inc = new Incomplete();
inc.show();
}
}
Output:
1604-21-737-093
4. Write programs to demonstrate Nested Interfaces and Interface
extensions.
Solution:
class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
public boolean isNotNegative(int x) {
return x < 0 ? false : true;
}
}
class NestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIF nif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
Output:
1604-21-737-093
1604-21-737-093
5. Write Write a program to show how interfaces extend another interface.
Solution:
1604-21-737-093
6. Write a program to demonstrate Uncaught Exceptions.
Solution:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
try {
// Accessing an index out of bounds will throw an
ArrayIndexOutOfBoundsException
int result = numbers[5];
System.out.println("Result: " + result);
} catch (Exception e) {
// The default exception handler will handle the uncaught exception
System.err.println("Exception caught by the default handler:");
e.printStackTrace();
}
1604-21-737-093
8. Write a program to demonstrate Exception handling through a try and
catch block and also display description of exception object along with
stack trace.
Solution:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
1604-21-737-093
9. Write a program to demonstrate multiple catch clauses.
Solution:
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output:
1604-21-737-093
10. Program to demonstrate Unreachable Code Error
Solution:
class A2 {
public static void main(String[] args) {
try {
System.out.println("1");
throw new NumberFormatException();
}
catch (NullPointerException ne) {
System.out.println("Null Pointer Exception");
}
catch (RuntimeException re) {
System.out.println("Caught here");
}
catch (NumberFormatException ne) {
System.out.println("Number Format Exception");
}
System.out.println("5");
}
}
Output:
1604-21-737-093
11. Write a program to demonstrate nested try blocks.
Solution:
try {
// Inner try block
System.out.println("Inner Try Block: Start");
1604-21-737-093
12. Write a program to demonstrate nesting of try blocks using methods.
Solution:
1604-21-737-093
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Output:
import java.lang.*;
class ThrowDemo {
public static void demoproc() throws NullPointerException {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch (NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Output:
1604-21-737-093
1604-21-737-093
14. Program to demonstrate the usage of throws keyword
Solution:
1604-21-737-093
15. Write a program to demonstrate finally keyword.
Solution:
class finallyDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
Output:
1604-21-737-093
16. Write a program to create user defined exception classes
Solution:
Output:
1604-21-737-093
1604-21-737-093
5Th BIT:
1. Write a program to control the main thread using currentThread() method.
Solution:
class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName("My Thread");
System.out.println("After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Output:
1604-21-737-093
2. Write a program to create a new thread by implementing Runnable
interface
Solution:
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}System.out.println("Exiting child thread.");
}}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}System.out.println("Main thread exiting.");
}}
Output:
1604-21-737-093
3. Write a program to create a new thread by extending Thread class.
Solution:
1604-21-737-093
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Output:
1604-21-737-093
4. Write a program to demonstrate creation of multiple threads in a
program
Solution:
1604-21-737-093
Output:
1604-21-737-093
5. Write a program to ensure that the main thread terminates after the child
thread using isAlive() and join() methods.
Solution:
1604-21-737-093
try {
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "
+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "
+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Output:
1604-21-737-093
1604-21-737-093
6. Write a program to demonstrate changing thread priorities.
Solution:
1604-21-737-093
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
Output:
1604-21-737-093
7. Write a program to demonstrate call to a method of an object by several
threads without synchronization among threads. (without using
synchronized keyword)
Solution:
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
1604-21-737-093
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Output:
1604-21-737-093
8. Write a program to demonstrate call to a method of an object by several
threads with synchronization among threads. (using synchronized keyword)
Solution:
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
1604-21-737-093
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Output:
1604-21-737-093
9. Write a program to demonstrate Interthread Communication (Producer
and Consumer Problem)
Solution:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
1604-21-737-093
public void run() {
int i = 0;
while(i < 7) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Output:
1604-21-737-093
1604-21-737-093
10. Write a program to illustrate the concept of multithreading that creates
three threads; first thread displays Good Morning ever one second, second
thread displays “Hello” after every two seconds, and third thread displays
“Welcome” after every three seconds.
Solution:
1604-21-737-093
System.out.println("Welcome");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
thread3.start();
try {
Thread.sleep(10000); // Let the threads run for 10 seconds (adjust
as needed)
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Program terminated.");
}
}
Output:
1604-21-737-093
6Th BIT
1. Write a program to demonstrate file handling in java
Solution:
import java.io.*;
class FileHandling {
public static void main(String args[]) throws IOException {
FileInputStream fis = new FileInputStream("test.txt");
int c;
while ( (c = fis.read()) != -1)
System.out.print((char)c);
fis.close(); S
}
}
Output:
1604-21-737-093
2. Write a program that displays file attributes for a given filename.
Solution:
// Demonstrate File.
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("test.txt");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
Output:
1604-21-737-093
3. Write a program that reads a filename and displays its contents on
screen with a line number before each line
Solution:
import java.io.*;
class FileLineCount {
public static void main(String args[]) throws IOException {
FileInputStream fr = new FileInputStream("test.txt");
int c;
int lines = 1;
System.out.print(lines + ": ");
while ((c = fr.read()) != -1) {
System.out.print((char)c);
if (c == (int)'\n') {
lines++;
System.out.print(lines + ": ");
}
}
}
}
Output:
1604-21-737-093
4. Write a program that prints number of characters, words, lines in a given
file.
Solution:
1604-21-737-093
FileReader fr;
try {
if (args.length == 0) { // We're working with stdin
wc(new InputStreamReader(System.in));
}
else { // We're working with a list of files
for (int i = 0; i < args.length; i++) {
fr = new FileReader(args[i]);
wc(fr);
}
}
}
catch (IOException e) {
return;
}
System.out.println(lines + " " + words + " " + chars);
}
}
Output:
1604-21-737-093
7Th BIT:
1. Write a Java program to change a specific character in a file. Note that:
Filename, number of the byte in the file to be changed and the new
character are specified on the command line.
Solution:
import java.io.*;
class FileCopy {
public static void main(String args[]) throws IOException {
if (args.length == 0) {
System.err.println("No command line arguements specified!");
return;
}
FileInputStream fileInput = new FileInputStream("original.txt");
char val = args[0].charAt(0);
byte[] buffer = new byte[fileInput.available() + 1];
int c, index = 0;
while ((c = fileInput.read()) != -1) {
if (c == (int)' ') c = (int)val;
buffer[index++] = (byte)c;
}
fileInput.close();
FileOutputStream fileOutput = new FileOutputStream("original.txt", false);
fileOutput.write(buffer, 0, buffer.length - 1);
fileOutput.close();
}
}
Output:
1604-21-737-093
Text File After Execution:
1604-21-737-093
2a. Write a Java program to illustrate collection classes like Array List,
Iterator, Hashmap etc.
Solution:
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
al.add("C");
al.add("A");
al.add("E");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
System.out.println("Contents of al: " + al)
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output:
1604-21-737-093
2b.Program to demonstrate Iterator Class:
Solution:
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al.
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
1604-21-737-093
}
System.out.println();
}
}
Output:
1604-21-737-093
2c.Program to demonstrate HashMap:
Solution:
import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map.
HashMap<String, Double> hm = new HashMap<String, Double>();
hm.put("John Doe", Double.valueOf(3434.34));
hm.put("Tom Smith", Double.valueOf(123.22));
hm.put("Jane Baker", Double.valueOf(1378.00));
hm.put("Tod Hall", Double.valueOf(99.22));
hm.put("Ralph Smith", Double.valueOf(-19.08));
Set<Map.Entry<String, Double>> set = hm.entrySet();
for(Map.Entry<String, Double> me : set) {
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
double balance = hm.get("John Doe");
Output:
1604-21-737-093
3. Write a program to implement Serialization concept
Solution:
import java.io.*;
public class SerializationDemo {
public static void main(String args[]) {
// Object serialization
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
} catch (IOException e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass) ois.readObject();
ois.close();
System.out.println("object2: " + object2);
} catch (Exception e) {
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
1604-21-737-093
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}
}
Output:
1604-21-737-093
4a. Write programs to demonstrate legacy classes and interfaces.
Solution:
Output:
1604-21-737-093
1604-21-737-093
4b.Program to demonstrate HashTable(Dictionary)
Solution:
// Demonstrate a Hashtable.
import java.util.*;
class HTDemo {
public static void main(String args[]) {
Hashtable<String, Double> balance = new Hashtable<String, Double>();
Enumeration<String> names;
String str;
double bal;
names = balance.keys();
while(names.hasMoreElements()) {
str = names.nextElement();
System.out.println(str + ": " + balance.get(str));
}
System.out.println();
Output:
1604-21-737-093
1604-21-737-093
5. Write programs to demonstrate usage of Iterations over Collection using
Iterator interface and ListIterator interface.
Solution:
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
1604-21-737-093
System.out.println();
Output:
1604-21-737-093
8Th BIT:
1. Develop an applet that displays a simple message
Solution:
import java.applet.*;
import java.awt.*;
Output:
1604-21-737-093
1604-21-737-093
2. Develop an applet that displays lines, rectangles, ovals, square etc
Solution:
import java.applet.*;
import java.awt.*;
1604-21-737-093
3a. Write java programs using AWT controls.
Solution:
1604-21-737-093
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current selections.
public void paint(Graphics g)
{
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
Output:
1604-21-737-093
1604-21-737-093
3b.Program to Demonstrate Check Box
Solution:
1604-21-737-093
public void paint(Graphics g)
{
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
Output:
1604-21-737-093
1604-21-737-093
3c.Program to Demonstrate Label
Solution:
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width="300" height="200"> </applet>
*/
public class LabelDemo extends Applet
{
Font f=new Font("Arial",Font.BOLD, 20);
public void init()
{
setFont(f);
setBackground(Color.blue);
setForeground(Color.yellow);
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
Label four=new Label("Fourth Label");
// add labels to applet window
add(one);
add(two);
add(three);
add(four);
}
}
Output :
1604-21-737-093
1604-21-737-093
3d.Program to demonstrate Check Box Group
Solution:
1604-21-737-093
}
// Display current state of the check boxes.
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}
Output:
1604-21-737-093
3e.Program to demonstrate Button
Solution:
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener
{
String msg = "";
Button yes, no, maybe;
public void init()
{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
//close=new Button("Close");
add(yes);//addding buttons to the applet
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Yes"))
{
msg = "You pressed Yes.";
}
else if(str.equals("No"))
{
msg = "You pressed No.";
1604-21-737-093
}
else
{
msg = "You pressed Undecided.";
}
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 6, 100);
}
public void stop()
{
destroy();
}
}
Output:
1604-21-737-093
1604-21-737-093
9Th BIT:
1. Write a Java program for handling Key events
Solution:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/
1604-21-737-093
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Output:
AppletViewer Output:
1604-21-737-093
1604-21-737-093
2. Write a Java program for handling Mouse events
Solution:
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
{
String msg="";
int mouseX=0, mouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Clicked.";
repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Exited";
repaint();
}
1604-21-737-093
public void mousePressed(MouseEvent me)
{
mouseX=0;
mouseY=10;
msg="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent me)
{
mouseX=0;
mouseY=30;
msg="Mouse Released";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mouseX=me.getX();
mouseY=me.getY();
msg="*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Output:
1604-21-737-093
AppletViewer Output:
1604-21-737-093
10Th BIT:
1. Write a Java program that works as a simple calculator. Use a grid layout
to arrange buttons for the digits and for the +, -,*, % operations. Add a text
field to display the result.
Solution:
1604-21-737-093
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++) {
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++) {
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae) {
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+")){
num1=Integer.parseInt (T1.getText());
Operation='+';
1604-21-737-093
T1.setText ("");
}
if(str.equals("-")){
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*")){
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/")){
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%")){
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("=")) {
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e) {
result=num2;
1604-21-737-093
JOptionPane.showMessageDialog(this,"Divided
by zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear")) {
T1.setText("");
}
}
}
Output:
1604-21-737-093
2a. Demonstrate Servlets – write programs for simple Servlet, Servlet for
Get and Post Methods, Cookies, and Session Tracking.
Solution:
import java.io.*;
import javax.servlet.*;
Output:
1604-21-737-093
2b.Program to demonstrate Get and Post Methods
Solution:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Output:
Index.html Ouput :
1604-21-737-093
Get Method Output:
1604-21-737-093
2c.Program to demonstrate Servlet Cookies
Solution:
//AddCookieServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
//GetCookieServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
for (Cookie cookie: cookies) {
1604-21-737-093
pw.println("name = " + cookie.getName() + "; value = " +
cookie.getValue());
}
pw.close();
}
}
Output:
AddCookieServlet Output:
1604-21-737-093
2d.Program to demonstrate Session Tracking
Solution:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Output:
1604-21-737-093
3a. Write JDBC programs to do following: Connect to a data source, create
tables, insert data into tables, select data from tables, update tables, drop
tables, use where clause, login page, retrieve table records using AWT
controls and event hanlding.
Solution:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.sql.*;
public class ConnectDemo {
public static void main (String[] args) {
Connection conn = null;
try{
String userName = "root";
String password = "root12";
String url = "jdbc:mysql://localhost:3306/";
Class.forName ("com.mysql.cj.jdbc.Driver");// This is the newest
driver
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e) {
System.err.println ("Cannot connect to database server:"+e);
} finally {
if (conn != null) {
try {
conn.close ();
1604-21-737-093
System.out.println ("Database connection
terminated:");
} catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Output:
1604-21-737-093
3b.Program to Create Table in a Database
Solution:
import java.sql.*;
import java.sql.ResultSet;
public class CreateTable
{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String TableName;
try {
String userName = "root";
String password = "root12";
String url = "jdbc:mysql://localhost:3306/";
Class.forName ("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection (url, userName, password);
stmt = conn.createStatement();
//Selecting Database
stmt.execute("use mysql;");
//Creating table
stmt.execute("create table JavaCourse23(Roll Integer primary key,
Name Varchar(30), Marks Integer not null, Grade Varchar(2))");
System.out.println("table has been created successful");
} catch (SQLException ex){
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e){
System.err.println ("Cannot connect to database server");
}
finally {
if (rs != null) {
try {
rs.close();
1604-21-737-093
} catch (SQLException sqlEx) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) {}
stmt = null;
}
if (conn != null) {
try {
conn.close ();
} catch (Exception e) { /* Ignore code for closing
errors */ }
}
}
}
}
Output:
1604-21-737-093
3c.Program to Insert Data in a Record
Solution:
import java.sql.*;
public class InsertRecord{
public static void main (String[] args)
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String NameString, RollString, MarksString, GradeString;
try{
String userName = "root";
String password = "root12";
String url = "jdbc:mysql://localhost:3306/";
Class.forName ("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection (url, userName, password);
stmt = conn.createStatement();
stmt.execute("insert into JavaCourse23 values (01,'Abbas', 75,
'A')");
stmt.execute("insert into JavaCourse23 values(02,'Srinivas', 85,
'EX')");
stmt.execute("insert into JavaCourse23 values(03,'Deepika', 65,
'B')");
stmt.execute("insert into JavaCourse23 values(04,'Ilyas', 78,
'A')");
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e){
System.err.println ("Cannot connect to database server");
}
finally {
1604-21-737-093
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
if (conn != null) {
try {
conn.close ();// System.out.println ("Database
connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Output:
1604-21-737-093
3d.Program to Select a Record From a Database
Solution:
import java.sql.*;
import java.sql.ResultSet;
public class SelectRecord {
public static void main (String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
int TotalMarks=0, Num_Student=0;
float Avg_Marks;
String NameString, RollString, MarksString, GradeString;
try{
String userName = "root";
String password = "root12";
String url = "jdbc:mysql://localhost:3306/";
Class.forName ("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection (url, userName, password);
stmt = conn.createStatement();
stmt.execute("use mysql;");
stmt.execute("SELECT * FROM JavaCourse23");
rs = stmt.getResultSet();
System.out.println("\n\n ------- Results ---------\n");
while (rs.next()) {
NameString = rs.getString("Name");
RollString = rs.getString("Roll");
MarksString = rs.getString("Marks");
GradeString = rs.getString("Grade");
TotalMarks = TotalMarks + Integer.parseInt(MarksString);
System.out.println("Name: = "+NameString+"\t\t"+"Roll: =
"+RollString+"\t\t"+"Marks: = "+MarksString+"\t\t"+"Grade: = "+GradeString+"\n");
} //end while
rs.last();
Num_Student = rs.getRow();
Avg_Marks = TotalMarks / Num_Student;
System.out.println("\n\n ------- AVERAGE Marks =
"+Avg_Marks+"--------");
1604-21-737-093
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
catch (Exception e) {
System.err.println ("Cannot connect to database server");
}
finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (conn != null) {
try {
conn.close ();
// System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Output:
1604-21-737-093
1604-21-737-093
3e.Program to update a record
Solution:
import java.sql.*;
import java.sql.ResultSet;
public class UpdateRecord{
public static void main (String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String NameString, RollString, MarksString, GradeString;
try{
String userName = "root";
String password = "freeroam";
String url = "jdbc:mysql://localhost:3306/";
Class.forName ("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection (url, userName, password);
stmt = conn.createStatement();
stmt.execute("use mysql;");
stmt.execute("update JavaCourse23 set Name='Tanveer' where
Name='Abbas'");
stmt.execute("update JavaCourse23 set Marks=85, Grade='Ex'
where Name='Deepika'");
}
catch (SQLException ex){
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
catch (Exception e){
System.err.println ("Cannot connect to database server");
}
finally {
if (rs != null) {
try {
1604-21-737-093
rs.close();
} catch (SQLException sqlEx) { } // ignore
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
if (conn != null) {
try {
conn.close ();
// System.out.println ("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Output:
1604-21-737-093
3f.Program to use Where Clause
Solution:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
1604-21-737-093
}
con.close();
pt.close();
}
catch(Exception e)
{
System.out.println("Exception caught in main method");
}
}
}
Output:
1604-21-737-093
3g.Program to create Login Page
Solution:
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
1604-21-737-093
cancel=new Button("Cancel");
uname=new TextField("User Name");
pwd=new TextField("Enter Password");
pwd.setEchoChar('*');
setVisible(true);
setLayout(new FlowLayout(FlowLayout.CENTER));
setSize(500,500);
add(un); add(uname); add(pd); add(pwd); add(login);
add(cancel);add(result);
login.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
boolean found=false;
if(ae.getSource()==login)
{
try
{
while(res.next())
{
String name=res.getString("uname");
String password=res.getString("pwd");
if(name.equals(uname.getText()) &&
password.equals(pwd.getText()))
{
System.out.println("read and retrieved uname
"+uname.getText()+ " " + name);
result.setText("Login Successfull");
found=true;
break;
}
}
if(found==false)
{
result.setText("Login Unsuccessful..");
res=stmt.executeQuery("select * from udb");
}
}
1604-21-737-093
catch(Exception e){System.out.println("Exception caught in
listener"); }
}
}
public static void main(String arg[])
{
new LoginDemo();
}
}
Output:
1604-21-737-093
3h.Program to Retrieve Records using Java AWT controls and Event
Handling
Solution:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
1604-21-737-093
grade=new TextField("Grade");
setVisible(true);
setSize(500,500);
setLayout(new FlowLayout(FlowLayout.LEFT));
add(rno);
add(name);
add(marks);
add(grade);
add(next);
add(previous);
add(clear);
next.addActionListener(this);
previous.addActionListener(this);
clear.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
try {
if(ae.getSource()==next)
{
if(rs.next())
{
rno.setText(""+rs.getInt("Roll"));
name.setText(""+rs.getString("Name"));
marks.setText(""+rs.getInt("Marks"));
grade.setText(""+rs.getString("grade"));
}
else
{
rno.setText("NA");
name.setText("NA");
marks.setText("NA");
grade.setText("NA");
}
}
}catch(SQLException sqe){ System.out.println("Caught in actionPerformed
method");}
}
1604-21-737-093
public static void main(String arg[]) throws SQLException
{
new DBRetrieval();
}
}
Output:
1604-21-737-093
1604-21-737-093