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

Java Rec Faisal

The document contains solutions to various Java programming assignments, including: 1. A program that displays a welcome message. 2. A program that takes command line arguments as input and calculates the sum of two numbers. 3. Programs that calculate the factorial of a given number using both iterative and recursive methods. 4. A program that implements bubble sort on an integer array. 5. A program that generates prime numbers up to a given limit. 6. A program that converts a decimal number to its binary equivalent. 7. Programs demonstrating multidimensional arrays. 8. A program using a switch statement to determine the season based on a month number.

Uploaded by

dsds v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

Java Rec Faisal

The document contains solutions to various Java programming assignments, including: 1. A program that displays a welcome message. 2. A program that takes command line arguments as input and calculates the sum of two numbers. 3. Programs that calculate the factorial of a given number using both iterative and recursive methods. 4. A program that implements bubble sort on an integer array. 5. A program that generates prime numbers up to a given limit. 6. A program that converts a decimal number to its binary equivalent. 7. Programs demonstrating multidimensional arrays. 8. A program using a switch statement to determine the season based on a month number.

Uploaded by

dsds v
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

LAB ASSIGNMENT

1ST BIT:
1. Write a Java program to display Welcome message.
Solution:
public class WelcomeMessage {

public static void main(String[] args) {


System.out.println("Welcome to our program!");
}
}
Output:

2. Write a Java program to demonstrate Command line arguments


Solution:
public class CommandLineArgument {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


int num1 = scanner.nextInt();

System.out.print("Enter the second number: ");


int num2 = scanner.nextInt();

int sum = num1 + num2;


System.out.println("Sum of " + num1 + " and " + num2 + " is: " +
sum);

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

public class FactorialCalculatorIterative {


public static int factorialIterative(int n) {
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return -1;
}

int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to calculate its factorial: ");


int number = scanner.nextInt();

int factorial = factorialIterative(number);


if (factorial != -1) {

1604-21-737-093
System.out.println("Factorial of " + number + " using iterative
approach: " + factorial);
}

}
}
Output:

3b.Using Recursive Method


Solution:
import java.util.Scanner;

public class FactorialCalculatorRecursive {


public static int factorialRecursive(int n) {
if (n < 0) {
System.out.println("Factorial is not defined for negative numbers.");
return -1;

}
if (n == 0 || n == 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number to calculate its factorial: ");


int number = scanner.nextInt();

1604-21-737-093
int factorial = factorialRecursive(number);
if (factorial != -1) {
System.out.println("Factorial of " + number + " using recursive
approach: " + factorial);
}

}
}
Output:

4. Write a program to demonstrate bubble sort on an array of elements.


Solution:
import java.util.Scanner;
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;

for (int i = 0; i < n - 1; i++) {


swapped = false;

for (int j = 0; j < n - i - 1; j++) {


if (arr[j] > arr[j + 1]) {
// Swap the elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}

1604-21-737-093
// If no two elements were swapped in the inner loop, the array is
already sorted
if (!swapped) {
break;
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();

int[] arr = new int[n];

System.out.println("Enter " + n + " elements:");

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


arr[i] = scanner.nextInt();
}

System.out.println("Original array:");
printArray(arr);

bubbleSort(arr);

System.out.println("Sorted array:");
printArray(arr);

public static void printArray(int[] arr) {


for (int num : arr) {
System.out.print(num + " ");
}

1604-21-737-093
System.out.println();
}
}
Output:

5. Write a program to generate prime numbers from 1 up to a given number.


Solution:
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the upper limit to generate prime numbers: ");

1604-21-737-093
int upperLimit = scanner.nextInt();

System.out.println("Prime numbers from 1 to " + upperLimit + ":");

for (int i = 2; i <= upperLimit; i++) {


boolean isPrime = true;

for (int j = 2; j <= Math.sqrt(i); j++) {


if (i % j == 0) {
isPrime = false;
break;
}
}

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

System.out.print("Enter a decimal number: ");


int decimalNumber = scanner.nextInt();

int binaryNumber = 0;
int placeValue = 1;

while (decimalNumber > 0) {


int remainder = decimalNumber % 2;
binaryNumber += remainder * placeValue;
decimalNumber /= 2;
placeValue *= 10;
}

System.out.println("Equivalent binary number: " + binaryNumber);

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

System.out.print("Enter the number of rows: ");


int rows = scanner.nextInt();

System.out.print("Enter the number of columns: ");


int columns = scanner.nextInt();
int[][] matrix = new int[rows][columns];
System.out.println("Enter the elements of the array:");

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


for (int j = 0; j < columns; j++) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.println("The 2D array:");

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


for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

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

System.out.print("Enter the month number (1-12): ");


int month = scanner.nextInt();

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:

2. Write a program to demonstrate Constructor overloading.


Solution:
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.
*/
class Box {
double width;
double height;
double 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

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;

// Constructor with parameters having the same name as instance variables


public Person(String name, int age) {
this.name = name; // "this" is used to refer to the instance variable
this.age = age; // "this" is used to refer to the instance variable
}

// Method to set the name using the "this" keyword


public void setName(String name) {
this.name = name; // "this" is used to refer to the instance variable
}

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
}

// Method to display the information of the person


public void displayInfo() {
System.out.println("Name: " + this.name); // "this" is optional here
System.out.println("Age: " + this.age); // "this" is optional here
}

// Method to pass the current object as an argument to another method


public void printSelf() {
printPerson(this); // "this" is passed as an argument
}

// Method to demonstrate the usage of "this" in a static context


public static void staticMethod() {
// "this" cannot be used in a static context because it refers to an
instance of the class.
// You'll get a compilation error if you uncomment the following line:
// System.out.println(this.name);
}

// Method to demonstrate the usage of "this" in a constructor


public Person() {
this("John Doe", 30); // "this" is used to call another constructor of the
same class
}

private static void printPerson(Person person) {


System.out.println("Person: " + person.name + ", Age: " + person.age);
}
}

public class PersonDemo {


public static void main(String[] args) {

1604-21-737-093
Person person1 = new Person("Alice", 25);
person1.displayInfo();

Person person2 = new Person();


person2.displayInfo();

person1.printSelf();
}
}

Output:

4. Write a program to demonstrate passing of objects as arguments to a


method.
Solution:
// Objects may be passed to methods.
class Test {
int a, b;

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:

5. Write a program to implement Stacks using arrays


Solution:
// This class defines an integer stack that can hold 10 values.

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

for(int i=0; i<10; i++)


System.out.println(mystack2.pop());
// these statements are not legal
// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}
Output:

1604-21-737-093
6. Write a program to demonstrate Inner classes
Solution:

// Define an inner class within a for loop.


class Outer {
int outer_x = 100;
void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Output:

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:

9. Write a program to demonstrate different usages of super keyword


Solution:
Using super to Call Superclass Constructors
// A complete implementation of BoxWeight.
class Box {
private double width;

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) {

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;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);

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:

A Second Use for super


// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {

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 SubClass extends SuperClass {


public void m2() {
System.out.println("m2");
}
}

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;

public Animal(String name) {


this.name = name;
}

public void makeSound() {


System.out.println("Animal sound");
}
}

class Dog extends Animal {


int age;

public Dog(String name, int age) {


super(name);
this.age = age;
}

public void makeSound() {


System.out.println("Woof! Woof!");
}

public void displayInfo() {


System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

public class MemberDemo {


public static void main(String[] args) {
Dog = new Dog("Buddy", 3);

// Accessing members of the Dog class


dog.makeSound();

1604-21-737-093
dog.displayInfo();

// Accessing members of the Animal class (inherited members)


System.out.println("Animal name: " + dog.name);
dog.makeSound(); // Calls the overridden method in the Dog class

// Upcasting: Assigning a Dog object reference to an Animal reference


Animal animal = dog;

// Accessing members of the Animal class through the Animal reference


System.out.println("Animal name (using Animal reference): " +
animal.name);
animal.makeSound(); // Calls the overridden method in the Dog class
}
}

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

class Rectangle extends Figure {

1604-21-737-093
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.");
return dim1 * dim2 / 2;
}
}

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

final void printMessage() {


System.out.println("This is a final method in Parent class.");
}
}

class AnotherClass {
void nonFinalMethod() {
System.out.println("This is a non-final method in AnotherClass.");
}
}

// Subclass that extends AnotherClass


class Subclass extends AnotherClass {

public class FinalDemo {


public static void main(String[] args) {
Parent parent = new Parent();
System.out.println("Name: " + parent.name);
parent.printMessage();

Subclass subclass = new Subclass();


subclass.nonFinalMethod();
}
}

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;

// Instantiate the various classes in p1.


public class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}

package p1;

class Derived extends Protection {


Derived() {
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = "4 + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

package p1;

public class Protection {


int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;

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;

// Instantiate the various classes in p2.


public class Demo {
public static void main(String args[]) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
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;

class Protection2 extends p1.Protection {


Protection2() {
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

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

abstract class Incomplete implements Callback {


int a, b;
void show() {
System.out.println(a + " " + b);
}

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:

// One interface can extend another.


interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Output:

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

7. Write a program to illustrate exception handling done by Java’s default


handler.
Solution:

public class DefaultExceptionHandlerExample {


public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };

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

// This code won't execute due to the uncaught exception above


System.out.println("Program continues after the exception.");
}
}
Output:

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:

public class NestedTryBlocksExample {


public static void main(String[] args) {
try {
// Outer try block
int[] numbers = { 1, 2, 3 };
System.out.println("Outer Try Block: Start");

try {
// Inner try block
System.out.println("Inner Try Block: Start");

int result = numbers[5]; // Accessing an invalid index

System.out.println("Inner Try Block: End");


} catch (ArrayIndexOutOfBoundsException e) {
// Inner catch block
System.out.println("Inner Catch Block: Caught
ArrayIndexOutOfBoundsException");
System.out.println("Inner Catch Block: Exception Message: " +
e.getMessage());
}

System.out.println("Outer Try Block: End");


} catch (Exception e) {
// Outer catch block
System.out.println("Outer Catch Block: Caught Exception");
System.out.println("Outer Catch Block: Exception Message: " +
e.getMessage());
}
System.out.println("Program continues after nested try-catch blocks.");
}
}
Output:

1604-21-737-093
12. Write a program to demonstrate nesting of try blocks using methods.
Solution:

// An example of nested try statements.


class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/*
* If no command-line args are present,
* the following statement will generate
* a divide-by-zero exception.
*/
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/*
* If one command-line arg is used,
* then a divide-by-zero exception
* will be generated by the following code.
*/
if (a == 1)
a = a / (a - a); // division by zero
/*
* If two command-line args are used,
* then generate an out-of-bounds exception.
*/
if (a == 2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception

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:

13. Write a program to throw an exception manually. (using throw keyword)


Solution:

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:

// This program contains an error and will not compile.


class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}

public static void main(String args[]) {


throwOne();
}
}
Output:

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

public static void main(String args[]) {


try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}

Output:

1604-21-737-093
16. Write a program to create user defined exception classes
Solution:

// This program creates a custom exception type.


class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

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:

class NewThread extends Thread {


NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
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 ExtendThread {
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);
}

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:

class NewThread extends Thread {


NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
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 ExtendThread {
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.");
}
}

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:

class NewThread implements Runnable {


String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
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());
// wait for threads to finish

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:

class clicker implements Runnable {


long click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.

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:

public class MultithreadingExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new Runnable() {
public void run() {
while (true) {
System.out.println("Good Morning");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

Thread thread2 = new Thread(new Runnable() {


public void run() {
while (true) {
System.out.println("Hello");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

Thread thread3 = new Thread(new Runnable() {


public void run() {
while (true) {

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

// Terminate the threads after 10 seconds


thread1.interrupt();
thread2.interrupt();
thread3.interrupt();

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:

// A word counting utility.


import java.io.*;
class WordCount {
public static int words = 0;
public static int lines = 0;
public static int chars = 0;
public static void wc(InputStreamReader isr) throws IOException {
int c = 0;
boolean lastWhite = true;
String whiteSpace = " \t\n\r";
while ((c = isr.read()) != -1) {
// Count characters
chars++;
// Count lines
if (c == '\n') {
lines++;
}
// Count words by detecting the start of a word
int index = whiteSpace.indexOf(c);
if(index == -1) {
if(lastWhite == true) {
++words;
}
lastWhite = false;
}
else {
lastWhite = true;
}
}
if(chars != 0) {
++lines;
}
}
public static void main(String args[]) {

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:

Original Text File:

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

System.out.println("John Doe's new 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);
}
}
}

class MyClass implements Serializable {


String s;
int i;
double d;

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:

Program to demonstrate vector class


//Demonstrate Various Vector operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {

Vector<Integer> v = new Vector<Integer>(3, 2);


System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(1);
v.addElement(2);
v.addElement(3);
System.out.println("Capacity after three additions: " +
v.capacity());
v.addElement(4);
System.out.println("Current capacity: " +
v.capacity());
System.out.println("First element: " + v.firstElement());
System.out.println("Last element: " + v.lastElement());
if(v.contains(3))
System.out.println("Vector contains 3.");
// Enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}

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;

balance.put("John Doe", 3434.34);


balance.put("Tom Smith", 123.22);
balance.put("Jane Baker", 1378.00);

names = balance.keys();
while(names.hasMoreElements()) {
str = names.nextElement();
System.out.println(str + ": " + balance.get(str));
}
System.out.println();

bal = balance.get("John Doe");


balance.put("John Doe", bal+1000);
System.out.println("John Doe's new balance: " +
balance.get("John Doe"));
}
}

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

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

1604-21-737-093
System.out.println();

System.out.print("Modified list backwards: ");


while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
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.*;

/*<applet code="AppletDemo" width="200" height="200"></applet>*/


public class AppletDemo extends Applet {
public void paint(Graphics g) {
g.drawString("Welcome to Applets", 100, 100);
}
}

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.*;

/*<applet code="CircleLine" width="200" height="200"></applet>*/


public class CircleLine extends Applet {
int x=300,y=100,r=50;
public void paint(Graphics g)
{
g.drawLine(3,300,200,10);
g.drawString("Line",100,100);
g.drawOval(x-r,y-r,100,100);
g.drawString("Circle",275,100);
g.drawRect(400,50,200,100);
g.drawString("Rectangel",450,100);
}
}
Output:

1604-21-737-093
3a. Write java programs using AWT controls.
Solution:

// Demonstrate Choice lists.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=180> </applet>
*/
public class ChoiceDemo extends Applet implements ItemListener
{
Choice os, browser;
String msg = "";
Font f=new Font("BookmanOldStyle", Font.BOLD, 20);
public void init()
{
setFont(f);
setBackground(Color.blue);
setForeground(Color.red);
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
// add choice lists to window
add(os);
add(browser);
// register to receive item events

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:

// Demonstrate check boxes.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width="550" height="550"> </applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
Font f=new Font("BookmanOldStyle", Font.BOLD, 20);
Checkbox winXP, winVista, solaris, mac;
public void init()
{
setFont(f);
setBackground(Color.blue);
setForeground(Color.yellow);
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
// Display current state of the check boxes.

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:

// Demonstrate check box group.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200> </applet>
*/
public class CBGroup extends Applet implements ItemListener
{
Font f=new Font("Arial", Font.BOLD, 20);
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init()
{
setBackground(Color.blue);
setForeground(Color.yellow);
setFont(f);
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, true);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);
add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();

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>
*/

public class KeyEvents extends Applet implements KeyListener {


String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
int key = ke.getKeyCode();
switch(key) {
case KeyEvent.VK_F1:
msg += "<F1>";
break;
case KeyEvent.VK_F2:
msg += "<F2>";
break;
case KeyEvent.VK_F3:
msg += "<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += "<PgDn>";
break;
case KeyEvent.VK_PAGE_UP:
msg += "<PgUp>";

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:

/* Program to create a Simple Calculator */


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="MyCalculator" width=300 height=300>
</applet>
*/
public class MyCalculator extends Applet implements ActionListener {
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init() {
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++) {
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");

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:

Applet Viewer 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.*;

public class HelloServlet extends GenericServlet {


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> Welcome to the first servlet program");
pw.close();
}
}

Output:

1604-21-737-093
2b.Program to demonstrate Get and Post Methods
Solution:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class GetPost extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String Color = request.getParameter("color");


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> GET: The Selected Color is: ");
pw.println(Color);
pw.close();
}

public void doPost(HttpServletRequest request,HttpServletResponse response)


throws ServletException, IOException {

String color = request.getParameter("color");


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B> POST: The selected color is: ");
pw.println(color);
pw.close();
}
}

Output:
Index.html Ouput :

1604-21-737-093
Get Method Output:

Post Method Output:

1604-21-737-093
2c.Program to demonstrate Servlet Cookies
Solution:

//AddCookieServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AddCookieServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = request.getParameter("data");

Cookie cookie = new Cookie("MyCookie", data);

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.*;

public class GetCookieServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();

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:

Get CookieServlet 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.*;

public class DateServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

HttpSession hs = request.getSession(true);

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");

Date date = (Date) hs.getAttribute("date");


if (date != null) {
pw.print("Last access: " + date + "<br>");
}

date = new Date();


hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

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:

// Update data in MySQL database using JDBC

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.*;

public class PreparedStatementDemo


{

public static void main(String arg[])


{
Connection con;
Statement stmt;
ResultSet res;
PreparedStatement pt;
String uname="root";
String pwd="freeroam";
String url="jdbc:mysql://localhost:3306/";
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection(url, uname, pwd);
stmt = con.createStatement();
stmt.execute("use mysql;");
pt=con.prepareStatement("Select * from javacourse23 where
marks > ?");
pt.setInt(1,80);
res=pt.executeQuery();
while(res.next())
{
int rno=res.getInt("Roll");
String name=res.getString("Name");
int marks=res.getInt("Marks");
String grade=res.getString("Grade");
System.out.println("Roll: "+rno+"\t Name: "+name+"\t Marks:
"+marks+"\t Grade: "+grade);

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.*;

public class LoginDemo extends Frame implements ActionListener


{
Button login, cancel;
TextField uname, pwd;
Label un,pd,result;
Connection con;
Statement stmt;
ResultSet res;
String mysqluname="root";
String mysqlpwd="freeroam";
String url="jdbc:mysql://localhost:3306/";
public LoginDemo()
{
super("Login Frame");
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection(url, mysqluname, mysqlpwd);
stmt=con.createStatement();
stmt.execute("use mysql;");
res=stmt.executeQuery("Select * from udb");
}
catch(Exception e)
{
System.out.println("Exception caught in constructor");
}
un=new Label("User Name");
pd=new Label("Password");
result=new Label("Login Result");
login=new Button("Login");

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.*;

public class DBRetrieval extends Frame implements ActionListener


{
Button next, previous, clear;
TextField rno, name, marks, grade;
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String tableName;
String uname="root";
String pwd="freeroam";
String url="jdbc:mysql://localhost:3306/";
public DBRetrieval()
{
super("My JDBC Fram");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection(url, uname, pwd);
stmt=con.createStatement();
stmt.execute("use mysql;");
//stmt.execute("SELECT * FROM stud23");
rs=stmt.executeQuery("SELECT * FROM stud23");
}
catch(Exception sqe) { System.out.println("caught in constructor"); }
next=new Button("Next");
previous=new Button("Previous");
clear=new Button("Clear");
rno=new TextField("Rno");
name=new TextField("Name");
marks=new TextField("Marks");

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

You might also like