Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 88

DR. B.R.

AMBEDKAR NATIONAL INSTITUTE OF TECHNOLOGY


JALANDHAR

ADVANCED PROGRAMMING CONCEPTS USING JAVA


CSX-351

SESSION: JULY-DEC 2019

SUBMITTED TO: SUBMITTED BY:

Dr . Rajneesh Rani Gaurav Sachdeva


Asst. Professor 17103032
Dept of CSE G-2
17103032

Lab 1
1. Write to program to enter two numbers from the user and print the “Larger
Number”.

public class LargerNo{


public static void main(String[] args)
{
System.out.println("Entered numbers are: "+args[0]+" and "+args[1]);
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
if(a==b){
System.out.println("These numbers are equal");
}
else if(a>b)
{
System.out.println(args[0]+" is larger");
}
else
{
System.out.println(args[1]+" is larger");
}
}
}

2
17103032

2. WAP in which user passes arguments using command line, print number of
arguments.
public class CLA{
public static void main(String[] args)
{
int l=args.length;
System.out.println("Number of arguements: "+l);
System.out.println("Arguements: ");
for(int i=0;i<l;i++)
{
System.out.println(args[i]);
}
}
}

3. WAP to print Pascal Triangle


import java.util.*;
public class PascalTriangle {

public static void main(String[] args) {


Scanner input= new Scanner(System.in);
System.out.print("Enter a number: ");
int n=input.nextInt();
for(int i=0;i<n;i++) {
int val = 1;
for (int j=1;j<(n-i);j++)
System.out.print(" ");
for (int k = 0; k <= i; k++){
System.out.print(" "+val);
val=val*(i-k) /(k + 1);
}
System.out.print("\n");
}
System.out.print("\n");
}
}

3
17103032

4. WAP to print patterns: 1 box, 2 oval, 3 Arrow Diamond

public class patterns{


public static void main(String[] args){
int ch=Integer.parseInt(args[0]);
switch(ch){
case 1:
//Rectangle Pattern
for (int i = 0; i < 7; i++)
{
System.out.println();
for (int j = 0; j < 6; j++)
{
if (i == 0 || i == 6 || j== 0 || j == 5)
System.out.print("*");
else
System.out.print(" ");
}
}
break;
case 2:
//Circle pattern
double d;
int r=3;
for(int i=0;i<=r*2;i++)
{
for(int j=0;j<=r*2;j++)
{
d=Math.sqrt((i-r)*(i-r)+(j-r)*(j-r));
if(d>r-0.5 && d<r+0.5)
System.out.print("*");
else
System.out.print(" ");

}
System.out.println();

4
17103032

}
break;
case 3:
//arrow pattern
int n=3;
for (int i=0; i<n; i++)
{
for (int j=n-i; j>1; j--)
{
System.out.print(" ");
}
for (int j=0; j<=i; j++ )
{
System.out.print("* ");
}
System.out.println();
}
for(int i=0;i<4;i++)
System.out.println(" * ");
break;
case 4:
//Diamond pattern
for(int i=0;i<4;i++)
{
for(int j=0;j<4-i;j++)
{
System.out.print(" ");
}
for(int j=0;j<2*i+1;j++)
{
if(j==0 || j==(2*i))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
for(int i=3;i>0;i--)
{
for(int j=0;j<4-i+1;j++)
System.out.print(" ");
for(int j=0;j<2*i-1;j++)
{
if(j==0||j==(2*i-2))
System.out.print("*");
else

5
17103032

System.out.print(" ");
}
System.out.println();
}
break;
}
}
}

6
17103032

Lab 2
1. WAP to input three numbers and check whether they are Pythagorean triplets
or not.
import java.util.Scanner;
import java.lang.*;
class Pythagorean {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the three numbers to be checked: ");
int num1 = input.nextInt();
int num2=input.nextInt();
int num3=input.nextInt();
int maxi = Math.max(num1, Math.max(num2, num3));
if(num1*num1 + num2*num2 == maxi*maxi)
System.out.println("Yes! Pythagoren");
else if(num1*num1 + num3*num3 == maxi*maxi)
System.out.println("Yes! Pythagoren");
else if(num2*num2 + num3*num3 == maxi*maxi)
System.out.println("Yes! Pythagoren");
else
System.out.println("No! not Pythagoren");
}
}

7
17103032

2. WAP to input radius of the circle and print its diameter, circumference and area
using radius.
import java.util.Scanner;

class CircleCal{
double diameter,cir,area;
final double pi=3.14159;
void calculation(float r)
{
diameter=2*r;
System.out.println("Diameter is: "+diameter);
cir=2*pi*r;
System.out.println("Circumference is: "+cir);
area=pi*r*r;
System.out.println("Area is: "+area);
}
}
class Circle
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the radius of the circle: ");
float radius= in.nextFloat();
CircleCal c = new CircleCal();
c.calculation(radius);
}
}

8
17103032

3. WAP which contains account class that allows deposit and withdrawal of money.
import java.util.Scanner;

class AccountTest{
public static void main(String[] args)
{
System.out.println("Welcome to the Bank");
Scanner in = new Scanner(System.in);
System.out.print("\nEnter the initial balance of the account: ");
double bal= in.nextDouble();
Account obj = new Account(bal);
obj.debit();
}
}

class Account{
double balance;
Scanner in = new Scanner(System.in);
Account(double balance)
{
this.balance=balance;
}
void debit()
{
System.out.print("Enter the amount you wish to debit from your account: ");
double damt= in.nextDouble();
if(balance-damt<0)
System.out.print("Failed! Debit Amount Exceeded Account Balance");
else
{
balance-=damt;
System.out.print("Success! Available Balance: "+balance);
}
System.out.println();
}
}

9
17103032

4. WAP to determine the gross pay of 3 employees.


import java.util.Scanner;

class Gross{
public static void main(String[] args){
Scanner input= new Scanner(System.in);
System.out.println("Welcome!");
GrossPay obj[] = {null,null,null};
for(int i=1;i<4;i++)
{
System.out.print("Enter the number of hours and salary for Employee: "+ i+" :");
int h= input.nextInt();
int s=input.nextInt();
obj[i-1] = new GrossPay(h,s);
}
int gp=0;
for(int i=1;i<4;i++)
{

int temp=obj[i-1].display();

System.out.println("Total Salary of Employee "+ i+": "+temp);

gp+=temp;
}

System.out.println("GrossPay: "+gp);
}
}

class GrossPay{

int hours,salary,ts;
GrossPay(int hours,int salary)
{
this.hours=hours;
this.salary=salary;
}
int display()
{
if(hours<=40)
{
ts=salary*hours;
}
else

10
17103032

{
ts=(hours-40)*(salary/2)+40*salary;
}
return ts;
}
}

11
17103032

Lab 3
1. WAP for addition of two dices as 2D array and display as the table given.
class twodices{
public static void main(String [] args)
{
int arr[][]= new int[7][7];
for(int i=0;i<7;i++)
{
arr[0][i]=i;
arr[i][0]=i;
}
for(int i=1;i<7;i++)
{
for(int j=1;j<7;j++)
{
arr[i][j]=arr[0][j]+arr[i][0];
}
}
for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}

12
17103032

2. WAP to perform all the functions of a string class.


import java.util.Scanner;
import java.lang.String;

class Strings{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String to perform operations: ");
String S=in.nextLine();
cal c=new cal();
c.fun(S);
}
}

class cal{
Scanner in=new Scanner(System.in);
void fun(String S)
{
System.out.println("Lower Case: "+S.toLowerCase());
System.out.println("Upper Case: "+S.toUpperCase());
System.out.println("Enter the character to be replaced: ");
char c=in.next().charAt(0);
System.out.println("Enter the new character: ");
char cn=in.next().charAt(0);
S=S.replace(c,cn);
System.out.println("New String: "+S);
System.out.println("Enter String to be checked: ");
String SN;
SN=in.nextLine();
SN=in.nextLine();
System.out.println("They are equal: "+S.equals(SN));
System.out.println("Length of the String is: "+S.length());
System.out.println("Enter the position to find character: ");
int p=0;
p=in.nextInt();
System.out.println("Character is: "+S.charAt(p-1));
System.out.println("Enter the string to add: ");
String PN;
PN=in.nextLine();
PN=in.nextLine();
System.out.println("Joined String is: "+S+PN);
System.out.println("Enter the starting and ending index to find substring: ");
int s=in.nextInt();
int e=in.nextInt();
System.out.println("SubString is: "+S.substring(s-1,e-1));

13
17103032

14
17103032

3. WAP to check whether a string is a double string or not.


import java.lang.String;
import java.util.Scanner;

class DoubleString
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the string to be checked: ");
String S=in.nextLine();
if(S.length()%2==0)
{
if(S.substring(S.length()/2).equals(S.substring(0,S.length()/2)))
System.out.println("Double String");
else
System.out.println("Not a double String");
}
else
{
System.out.println("Not a double String");
}
}
}

15
17103032

4. WAP to copy and paste a continuous subarray from a given array.


import java.util.Scanner;
class continoussubarray
{
public static void main(String [] args)
{
Scanner in= new Scanner(System.in);
System.out.println("Enter the size of the array: ");
int n=in.nextInt();
int arr[] = new int[100];
System.out.println("Enter the elements of array: ");
for(int i=0;i<n;i++)
{
arr[i]=in.nextInt();
}
calculation obj=new calculation();
obj.cs(arr,n);
}}
class calculation
{
Scanner in=new Scanner(System.in);
void cs(int arr[],int n)
{
System.out.println("Enter the starting and ending index: ");
int s=in.nextInt();
int e=in.nextInt();
System.out.println("Enter the index at which you want to place it: ");
int place=in.nextInt();
int size=(e-s)+n;
int k=size;
int temp=(e-s)+2;
int b[]=new int[temp];
int l=0;
for(int i=s-1;i<e;i++)
{
b[l]=arr[i];
l++;
}
for(int i=n;i>=e-1;i--)
{
arr[k]=arr[i];
k--;
}l=0;

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

16
17103032

if(i<place-1 || i>place+(e-s)+1)
{
arr[i]=arr[i];
}else
{
arr[i]=b[l];
l++;
}}

System.out.println("New Array is: ");


for(int i=0;i<size;i++)
{
System.out.println(arr[i]);
} }}

17
17103032

5. WAP to display the maximum number of time a given number n repeated


consecutively.
import java.util.Scanner;
import java.lang.Math;

class oned{
public static void main(String [] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n=in.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements of array: ");
for(int i=0;i<n;i++)
arr[i]=in.nextInt();

//int max=0;
int result=0;
int count=0;
for(int i=0;i<n;i++)
{
count=0;
for(int j=i;j<n;j++)
{
if(arr[j]==arr[i])
{
count++;
}
else
break;
}
result=Math.max(result,count);
}
System.out.println(result);
}
}

18
17103032

Lab 4
1. WAP to show the concept of Packages in Java

//Parent.java
package p1;

public class Parent{


private int priv=100;
public int pub;
protected int prot;

public void printPrivateThroughClass(){


System.out.println("\tPrivate: "+priv);
}
public void printPublicThroughClass(){
System.out.println("\tPublic: "+pub);
}
public void printProtectedThroughClass(){
System.out.println("\tProtected: "+prot);
}

public void setPrivate(int p){


priv = p;
}
}

//Child1.java
package p1;

public class Child1 extends Parent{


// public void printPrivateThroughSubClass(){
// System.out.println("\tPrivate: "+priv);
// }
public void printPublicThroughSubClass(){
System.out.println("\tPublic: "+pub);
}
public void printProtectedThroughSubClass(){
System.out.println("\tProtected: "+prot);
}

public void setProtected(int a){


prot = a;
}
}

19
17103032

//Child 2.java
package p1;

public class Child2 extends Parent{


// public void printPrivateThroughSubClass(){
// System.out.println("\tPrivate: "+priv);
// }
public void printPublicThroughSubClass(){
System.out.println("\tPublic: "+pub);
}
public void printProtectedThroughSubClass(){
System.out.println("\tProtected: "+prot);
}

public void setProtected(int a){


prot = a;
}
}

//AccessP1.java

package p2;
import p1.Child1;

public class AccessP1{


Child1 ch;
public AccessP1(Child1 c){
ch = c;
}
public void printPublic(){
System.out.println("\tPublic: "+ch.pub);
}
}

//Problem1.java

import p1.Child1;
import p2.AccessP1;

public class Problem1{


public static void main(String args[]){
Child1 c = new Child1();
c.pub = 120;
c.setProtected(80);
c.setPrivate(20);
System.out.println("Accessing Variables through Same class");

20
17103032

c.printPrivateThroughClass();
c.printPublicThroughClass();
c.printProtectedThroughClass();

System.out.println("Accessing Variables through Sub class");


c.printPublicThroughSubClass();
c.printProtectedThroughSubClass();

System.out.println("Accessing Variables through another package P2");


AccessP1 a = new AccessP1(c);
a.printPublic();
}
}

21
17103032

2. WAP that contains class students and class Test. Implement Multiple inheritance
in java using these classes.
import java.util.*;
class Student{
int rollnumber;
Student(int r){
rollnumber =r;
}
}

class Test extends Student{


int total;
Test(int r, int m, int s){
super(r);
total=m+s;
}
}

interface Sports{
void putMarks(int a);
}

class Result extends Test implements Sports{


int sportsmarks;
Result(int r, int m, int sci){
super(r,m,sci);
}
@Override
public void putMarks(int sp){
sportsmarks = sp;
}
}

public class StudentMain{


public static void main(String args[]){
System.out.println("Enter the roll number");

Scanner sc = new Scanner(System.in);


int r = sc.nextInt();

System.out.print("Enter marks obtained in\n\tMaths: ");


int m = sc.nextInt();

System.out.print("\tScience: ");
int sci = sc.nextInt();

22
17103032

Result res = new Result(r,m,sci);

System.out.print("\tPut Sports Marks: ");

int sp = sc.nextInt();

res.putMarks(sp);

System.out.println("\nRoll Number: "+res.rollnumber);

System.out.println("\tTotal(Maths+Science): "+res.total);

System.out.println("\tSports Marks: "+res.sportsmarks);


}
}

23
17103032

3. WAP to display the maximum number of time a given number n repeated


consecutively.
import java.util.Scanner;
import java.lang.Math;

class oned{
public static void main(String [] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n=in.nextInt();
int arr[]=new int[n];
System.out.println("Enter the elements of array: ");
for(int i=0;i<n;i++)
arr[i]=in.nextInt();

//int max=0;
int result=0;
int count=0;
for(int i=0;i<n;i++)
{
count=0;
for(int j=i;j<n;j++)
{
if(arr[j]==arr[i])
{
count++;
}
else
break;
}
result=Math.max(result,count);
}
System.out.println(result);
}
}

24
17103032

4. WAP for addition of two dices as 2D array and display as the table given.
class twodices{
public static void main(String [] args)
{
int arr[][]= new int[7][7];
for(int i=0;i<7;i++)
{
arr[0][i]=i;
arr[i][0]=i;
}
for(int i=1;i<7;i++)
{
for(int j=1;j<7;j++)
{
arr[i][j]=arr[0][j]+arr[i][0];
}
}

for(int i=0;i<7;i++)
{
for(int j=0;j<7;j++)
{
System.out.print(arr[i][j]+"\t");
}
System.out.println();
}
}
}

25
17103032

5. WAP to perform all the functions of a string class.


import java.util.Scanner;
import java.lang.String;

class Strings{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter the String to perform operations: ");
String S=in.nextLine();
cal c=new cal();
c.fun(S);
}
}

class cal{
Scanner in=new Scanner(System.in);
void fun(String S)
{
System.out.println("Lower Case: "+S.toLowerCase());
System.out.println("Upper Case: "+S.toUpperCase());
System.out.println("Enter the character to be replaced: ");
char c=in.next().charAt(0);
System.out.println("Enter the new character: ");
char cn=in.next().charAt(0);
S=S.replace(c,cn);
System.out.println("New String: "+S);
System.out.println("Enter String to be checked: ");
String SN;
SN=in.nextLine();
SN=in.nextLine();
System.out.println("They are equal: "+S.equals(SN));
System.out.println("Length of the String is: "+S.length());
System.out.println("Enter the position to find character: ");
int p=0;
p=in.nextInt();
System.out.println("Character is: "+S.charAt(p-1));
System.out.println("Enter the string to add: ");
String PN;
PN=in.nextLine();
PN=in.nextLine();
System.out.println("Joined String is: "+S+PN);
System.out.println("Enter the starting and ending index to find substring: ");
int s=in.nextInt();
int e=in.nextInt();
System.out.println("SubString is: "+S.substring(s-1,e-1));

26
17103032

27
17103032

Lab 5
1. WAP to show access protection in user defined packages. Create a package p1
which has three class: Protection, Derived and Same Package.
import p1.Protection;
import p1.Derived;
import p1.SamePackage;
import p2.first;
import p2.second;

class Problem1 {

public static void main(String[] args) {


Protection p = new Protection();
System.out.println("Public Variable value : "+ p.publicVar);
System.out.println("\nThe variables and functions of Protection class are: ");
// System.out.println("Protected Varible: " + stringVariable);
System.out.println("\tCan't access Private and Protected variables\n");

Derived d = new Derived();


System.out.println("The variables and functions of Derived class are: ");
System.out.println("\tPublic variable value : " + d.stuffing);
d.print();
d.printProtected();
System.out.println();

SamePackage s = new SamePackage();


System.out.println("The variables and functions of SamePackage class are: ");
System.out.println("\tDefault variable of this class is not visible.");
System.out.println("\tProtected variable of this class is not visible.\n");

first f = new first();


System.out.println("The variables and functions of first class are: ");
System.out.println("\tThe default variable of the class is not accessible.");
System.out.println("\tPublic variable's value is : " + f.anyName + "\n");

second sec = new second();


System.out.println("The default variables of the class are not accessible.");
System.out.println("But there is a public function. Lets call that : ");
sec.print();
}}
//First Package Program
package p2;
import p1.*;
public class first extends Protection {
int anyNo = 741;
public String anyName = "Dragon";

28
17103032

}
//Second Package program
package p2;
public class second {
double doubleStuff = 2.444;
Integer integer = new Integer(23);
public void print() {
System.out.println("Function of second class.");
System.out.println("I have only two variable : " + doubleStuff + " and " +
integer);
}
}
//SamePackage Program
package p1;

public class SamePackage {


int variable = 23;
protected String is = "Hello World";
}
//Derived Package Program
package p1;
public class Derived extends Protection {
public int stuffing = 963;
public void print() {
System.out.println("\tDerived class Function");
}
public void printProtected() {
System.out.println("\tProtected variable of Protection class accessible,. Value: "
+ stringVar);
}}

29
17103032

2. Write an application showing multiple inheritance and Dynamic Polymorphism.


import java.util.*;
class Instruments {

public void type() {


System.out.println("I love to play musical instruments");
}
public void numberOfInst() {
System.out.println("I can play two imstruments");
}
}

class Guitar extends Instruments {


public void type() {
System.out.println("Guitar is my favourite instrument.");
}
public void numberOfInst() {
System.out.println("I have two guitars.");
}
}

class Keyboard extends Instruments {


public void type() {
System.out.println("Keyboard is my second favourite instrument.");
}
public void numberOfInst() {
System.out.println("I dont have any keyboard yet");
}
}

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

Instruments g = new Instruments();


System.out.println("Instruments class function : ");
g.type();
g.numberOfInst();
System.out.println("\n\n");

System.out.println("Guitar class functions : ");


g = new Guitar();
g.type();
g.numberOfInst();
System.out.println("\n\n");

System.out.println("Keyboard class functions : ");

30
17103032

g = new Keyboard();
g.type();
g.numberOfInst();
System.out.println("\n\n");
}
}

31
17103032

3. Write an application in which the main class, Find Area outside the package
area imports the package area and calculate the area of different shapes.
import area.Square;
import area.Rectangle;
import area.Circle;
import area.Ellipse;
import area.Triangle;

import java.util.*;

class Problem3 {

public static void main(String[] args) {


System.out.println("This application helps you find area");
Scanner input = new Scanner(System.in);

byte option;

do {

System.out.println("Enter the required shape name : ");


System.out.print("1. Square");
System.out.print("\t2. Rectangle");
System.out.print("\t3. Circle");
System.out.print("\t4. Ellipse");
System.out.print("\t5. Triangle");
System.out.println("\n0. Exit");
option = input.nextByte();
switch(option) {

case 1:
Square s = new Square();
System.out.println("The area is : " + s.getArea());
break;

case 2:
Rectangle r = new Rectangle();
System.out.println("The area is : " + r.getArea());
break;

case 3:
Circle c = new Circle();
System.out.println("The area is : " + c.getArea());
break;

case 4:

32
17103032

Ellipse e = new Ellipse();


System.out.println("The area is : " + e.getArea());
break;

case 5:
Triangle t = new Triangle();
System.out.println("The area is : " + t.getArea());
break;
}
}while(option != 0);
}
}

//Square Program
package area;
import java.util.Scanner;

public class Square {

private int side;


public Square() {
System.out.println("In Square. Please enter the length of a side of square : ");
Scanner input = new Scanner(System.in);
side = input.nextInt();
}

public double getArea() {


return side * side;
}
}

//Rectangle Program
package area;
import java.util.Scanner;

public class Rectangle {

private int length, breadth;


public Rectangle() {
System.out.println("In Rectangle. Please enter the length and breadth of the
rectangle : ");
Scanner input = new Scanner(System.in);
length = input.nextInt();
breadth = input.nextInt();
}

33
17103032

public double getArea() {


return length * breadth;
}
}
//Area Program
package area;
import java.util.Scanner;

public class Triangle {

private int height, base;


public Triangle() {
System.out.println("In Triangle. Please enter the length of height and base of the
Triangle : ");
Scanner input = new Scanner(System.in);
height = input.nextInt();
base = input.nextInt();
}

public double getArea() {


return 0.5 * base * height;
}
}
//Volume Program
package volume;

public interface Volume {

final double pi = 3.14;


public double volume();
}
//Eclipse Program
package area;
import java.util.Scanner;

public class Ellipse {

private int majorAxesLength, minorAxesLength;


public Ellipse() {
System.out.println("In Elipse. Please enter the length of major and minor axes of
ellipse : ");
Scanner input = new Scanner(System.in);
majorAxesLength = input.nextInt();
minorAxesLength = input.nextInt();
}

34
17103032

public double getArea() {


return 3.14 * majorAxesLength * minorAxesLength;
}
}
//Circle Program
package area;
import java.util.Scanner;

public class Circle {


private int radius;
public Circle() {
System.out.println("In Circle. Please enter the length of radius of circle : ");
Scanner input = new Scanner(System.in);
radius = input.nextInt();
}
public double getArea() {
return 3.14 * radius * radius;
}
}

35
17103032

Lab 6
1. WAP to determine that the catch block for type Exception A catches exceptions
of types Exception B and Exception C.

public class Exception1{


public static void main(String args[]){
try{
System.out.println("Throwing Exception of type ExceptionB");
throw new ExceptionB();
}catch(ExceptionA ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: ExceptionA");

try{
System.out.println("Throwing Exception of type ExceptionC");
throw new ExceptionC();
}catch(ExceptionA ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: ExceptionA");
}
}
}
class ExceptionA extends Exception{
}
class ExceptionB extends ExceptionA{

}
class ExceptionC extends ExceptionB{

36
17103032

2. WAP that demonstrates how various exceptions are caught with catch.
import java.io.*;

public class Exception2{

public static void main(String args[]){

try{
System.out.println("\nThrowing Exception of type ExceptionA");
throw new ExceptionA();

}catch(Exception ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: Exception");
}

try{
System.out.println("\nThrowing Exception of type ExceptionB");
throw new ExceptionB();

}catch(Exception ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: Exception");
}

try{
System.out.println("\nThrowing Exception of type NullPointerException");
throw new NullPointerException();

}catch(Exception ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: Exception");
}

try{

System.out.println("\nThrowing Exception of type IOException");

throw new IOException();

}catch(Exception ex){
System.out.println("Exception Caught");
System.out.println("\tException type: "+ex);
System.out.println("\tCaught in: Exception");

37
17103032

}
}
}

class ExceptionA extends Exception{}

class ExceptionB extends ExceptionA{}

3. WAP that shows that the order of catch blocks is important. If you try to catch a
superclass exception type before subclass type.

38
17103032

public class Exception3{


public static void main(String args[]){
try{
throw new NullPointerException();
}catch (Exception ex){
System.out.println("\nException Caught.\n\tException type: "+ex);
}catch (NullPointerException ex){
System.out.println("\nException Caught.\n\tException type: "+ex);
}
}
}

public class Exception3{


public static void main(String args[]){
try{
throw new NullPointerException();
}catch (NullPointerException ex){
System.out.println("\nException Caught.\n\tException type: "+ex);
}catch (Exception ex){
System.out.println("\nException Caught.\n\tException type: "+ex);
}
}
}

4. WAP that illustrates rethrowing an exception.

39
17103032

public class Exception4{


static void someMethod2() throws Exception{
System.out.println("Throwing Exception from someMethod2() method.");
throw new Exception();
}
static void someMethod() throws Throwable{
try{
someMethod2();
}catch(Exception e){
System.out.println("Caught Exception in someMethod()
method!\n\tRethrowing caught exception.");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try{
someMethod();
}catch(Exception e){
System.out.println("Caught Exception in Main method!");
e.printStackTrace();
}
}
}

40
17103032

5. WAP an application to define your own exceptions as following instructions:


issue_data and return_date.
import java.util.Scanner;

public class Exception5{


public static void main(String[] args) {
String date;
String[] intDates = new String[3];
int[] idate = new int[3];
int[] rdate = new int[3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the issue date (DD-MM-YY): ");
date=sc.next();
intDates=date.split("-");
for(int i=0;i<3;i++){
idate[i]=Integer.parseInt(intDates[i]);
}
System.out.println("Enter the return date (DD-MM-YY): ");
date=sc.next();
intDates=date.split("-");
for(int i=0;i<3;i++){
rdate[i]=Integer.parseInt(intDates[i]);
}

if(rdate[0]>idate[0]+15){
try{
throw new ExceptionA();
}catch(ExceptionA ex){
System.out.println(ex.getMessage()+" Total Fine:
"+ex.getTotalFine(rdate[0]-(idate[0]+15)));
}
}
if(rdate[0]<idate[0]){
try{
throw new ExceptionB();
}catch(ExceptionB ex){
System.out.println(ex.getMessage());
}
}
}
}

class ExceptionA extends Exception{


ExceptionA(){
super("Fine @50/day");
}

41
17103032

int getTotalFine(int days){


return 50*days;
}}
class ExceptionB extends Exception{
ExceptionB(){
super("Return date < Issue date");
}
}

42
17103032

Lab 7
1. Write an application of multithreading. Create three different classes (threads)
that inherit Thread class. Each class consist a for loop that prints identify of the
class with a number series in increasing order. Start all three threads together.
Now run the application 2 or 3 times and show the outputs.
class one extends Thread {
public void run()
{
for(int i=1;i<=5;i++)
System.out.println("Thread One count: "+i);

System.out.println("Thread one completed");


}
}
class two extends Thread {
public void run(){
for(int i=1;i<6;i++)
System.out.println("Thread two count: "+i);

System.out.println("Thread two completed");


}
}
class three extends Thread{
public void run()
{
for(int i=1;i<=5;i++)
System.out.println("Thread Three Count: "+i);

System.out.println("Thread three completed");


}
}
class threadprogram{
public static void main(String[] args){
new one().start();
new two().start();
new three().start();
}
}

43
17103032

44
17103032

2. Write an application of multithreading with priority. Create three threads


namely one,two,three. Create the threads implementing runnable interface. Start
all three threads together and print the identity of thread with increasing
number till the thread exit.

class myclass implements Runnable{


String s;
Thread t;
myclass(String n)
{ s=n;
t =new Thread(this,s);
t.start(); }

public void run()


{

try{
for(int i=1;i<5;i++)
{
System.out.println(s+":"+i);
Thread.sleep(100);
}
}

catch(InterruptedException e)
{
System.out.println("Child Interrupted");
}
System.out.println(s+" Thread Completed");
}
}

class threadrunnable{

public static void main(String[] args) {

new myclass("One");
new myclass("Two");
new myclass("Three");

try{
Thread.sleep(1000);
}

catch(InterruptedException e)

45
17103032

System.out.println("Main Interrupted"); }

System.out.println("Main Thread Completed");

46
17103032

3. Write an application of multithreading with priority. Create three different


threads of min,max and norm priority. Now run each thread together for 10
seconds. Each thread should consist a variable count that increases itself. Stop all
three threads and print the value of click for each and show the use priority in
multithreading.
class ThreadPriority{
public static void main(String args[])
{
Pattern P = new Pattern();

ThreadA thread1=new ThreadA(P);


ThreadB thread2=new ThreadB(P);
ThreadC thread3=new ThreadC(P);

thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);
thread3.setPriority(Thread.MIN_PRIORITY);

thread1.start();
thread2.start();
thread3.start();

try{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}

P.stop();
P.show();
}
}

class Pattern
{
long A=0;
long B=0;
long C=0;

boolean running=true;

public void countA()


{
while(running)

47
17103032

{
A++;
}
}
public void countB()
{
while(running)
{
B++;
}
}
public void countC()
{
while(running)
{
C++;
}
}
public void stop()
{
running=false;
}
public void show()
{
System.out.println("Thread A: "+A);
System.out.println("Thread B: "+B);
System.out.println("Thread C: "+C);
}
}
class ThreadA extends Thread
{
Pattern P;
ThreadA(Pattern P)
{
this.P=P;
}
public void run()
{
P.countA();
}
}
class ThreadB extends Thread
{
Pattern P;
ThreadB(Pattern P)
{

48
17103032

this.P=P;
}
public void run()
{
P.countB();
}
}
class ThreadC extends Thread
{
Pattern P;
ThreadC(Pattern P)
{
this.P=P;
}
public void run()
{
P.countC();
}
}

49
17103032

4. Inherit a class from Thread and override the run() method. Inside run(), print a
message and then call sleep(). Repeat this three times, then return fro run(). Put
a start-up message in the constructor and override finalize() to print a shut-down
message. Make a separate thread class that class system.get() and
system.run.finalization() inside run(). Make several thread objects of both types
and run them to see what happens.

class Th extends Thread{


Th(){
System.out.println("New Thread of Th class created");
}
@Override
public void run(){
for(int i=0;i<3;i++){
System.out.println("I am Thread "+Thread.currentThread().getId()+" of Th
class");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
return;
}
protected void finalize() throws Throwable{
System.out.println("Shutting down thread of Th class");
}
}

class Th2 extends Thread{


Th2(){
System.out.println("New Thread of Th2 class created");
}
@Override
public void run(){
for(int i=0;i<3;i++){
System.out.println("I am Thread "+Thread.currentThread().getId()+" of Th2
class");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e);
}
}
System.out.println("Calling System.gc()");
System.gc();

50
17103032

System.out.println("Calling System.runFinalization()");
System.runFinalization();
return;
}
protected void finalize() throws Throwable{
System.out.println("Shutting down thread of Th2 class");
}
}

public class Thread4{


public static void main(String args[]){
Th t1 = new Th();
// Th t2 = new Th();
Th2 th1 = new Th2();
Th2 th2 = new Th2();
t1.start();
// t2.start();
th1.start();
th2.start();
}
}

51
17103032

5. Create two thread subclasses, one with a run() that starts up, captures the
reference of the second thread object and then calls wait(). The other class run()
should call notifyAll() for the first thread after some number of seconds have
passed, so the first thread can print a message.

class AnotherTh extends Thread{


AnotherTh(){
System.out.println("New thread of AnotherTh class created!");
}
@Override
public synchronized void run(){
System.out.println("Waiting for 1 second...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//TODO: handle exception
System.out.println(e);
}
notifyAll();
}

class Th extends Thread{


Th(){
System.out.println("New Thread of Th class created!");
}

@Override
public void run(){
AnotherTh ath = new AnotherTh();
ath.start();

synchronized(ath){
try {
ath.wait();
}
catch (InterruptedException e) {
//TODO: handle exception
System.out.println(e);
}
}
System.out.println("Received notification from another thread!");
}
}

52
17103032

public class Thread5{


public static void main(String args[]){
Th t = new Th();
t.start();
}
}

53
17103032

6. Implement producer consumer problem using Java.


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();
}
public void run()
{
int i = 0;
while(true)
{
q.put(i++);
}
}
}

54
17103032

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 producer_consumer{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}}

55
17103032

56
17103032

Lab 8
1. Write an applet program to draw a string, “This is my first Applet” on given
coordinates and run the applet in both the browser and applet viewer.
import java.applet.Applet;
import java.awt.Graphics;
public class myFirstApplet extends Applet
{
private static final long serialVersionUID = 1L;
@Override
public void paint(Graphics g)
{
g.drawString("This is my first Applet", 20, 20);
} }

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My First applet</title>
</head>
<body>
<applet code="myFirstApplet.class" width="300" height="300"></applet>
</body></html>

57
17103032

2. Write an applet that draws a checkerboard pattern as follows:


****
****
****
****

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

public class Checkerboard extends Applet {

public void paint(Graphics g) {


int row;
int col;
int x,y;
for ( row = 0; row < 8; row++ ) {
for ( col = 0; col < 8; col++) {
x = col * 20;
y = row * 20;
if ( (row % 2) == (col % 2) )
g.setColor(Color.yellow);
else
g.setColor(Color.black);
g.fillRect(x, y, 20, 20);

}
}
}
}

//Checkboard.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Applet</title>

58
17103032

</head>
<body>
<applet code="Applet3.class" width="300" height="300"></applet>
</body>
</html>

59
17103032

3. Write an applet program that asks the user to enter two floaing point numbers
obtains the two numbers from the user and draws their sum, product, difference
and division. Note: Use PARAM tag for user input.

import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JOptionPane;

public class AdditionApplet extends JApplet{

double sum;
double product;
double difference;
double quotient;
double number1;
double number2;

public void init(){

double number1 = Double.parseDouble( getParameter("firstNumber"));


double number2 = Double.parseDouble( getParameter("secondNumber"));

// calculate sum of all numbers entered by user


sum = number1 + number2;

//calculate difference of all numbers entered by user


difference = number1 -number2;

//calculate product of all numbers entered by user


product = number1 * number2 ;

quotient= number1 / number2 ;


}

public void paint( Graphics g ){


super.paint( g );

g.drawString( "The sum is " + sum, 25, 25 );


g.drawString( "The difference is " + difference, 25, 45 );
g.drawString( "The product is " + product, 25, 65 );
g.drawString( "The quotient is " + quotient, 25, 85 );
}
}

60
17103032

//ArthmaticOperation.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Applet</title>
</head>
<body>
<applet code="AdditionApplet.class" width="300" height="300">
<param name="firstNumber" value="30.4">
<param name="secondNumber" value="64.9">
</applet>

</body>
</html>

61
17103032

4. Write an applet in which background is Red and foreground (text color) is Blue.
Also show the message “Background is Red and Foreground is Blue” in the
status window.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Label;

public class Appletcolor extends Applet{

public Appletcolor()
{
setBackground(Color.red);
setForeground(Color.blue);
add(new Label("Background is Red and foreground is Blue"));
}
}

//Appletcolor.html

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Applet</title>
</head>
<body>
<applet code="Appletcolor.class" width="300" height="300"></applet>
</body>
</html>

62
17103032

63
17103032

5. Write an applet program showing URL of code base and document vase in the
applet window. NOTE: Use getCodeBase() and getDocumentBase().

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

public class Applet5 extends Applet{


public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}

//Applet5.html

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Applet</title>
</head>
<body>
<applet code="Applet5.class" width="300" height="300"></applet>
</body>
</html>

64
17103032

65
17103032

Lab 9
1. Write an applet to print the message click, enter, exit, press and release messages
when respective. Mouse event happens in the applet and print dragged and
moved when respective mouse motion event happens in the event.
Note: Implement Mouse Listener and Mouse Motion Listener Interface

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

public class Mouse extends Applet

implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.yellow);
setForeground(Color.blue);
}

public void mouseEntered(MouseEvent m)


{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}

public void mouseExited(MouseEvent m)


{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}

public void mousePressed(MouseEvent m)


{
X=10;
Y=20;
msg="Mouse Pressed";
setBackground(Color.green);
repaint();

66
17103032

public void mouseReleased(MouseEvent m)


{
X=10;
Y=20;
msg="Released";
setBackground(Color.blue);
repaint();
}

public void mouseMoved(MouseEvent m)


{
X=m.getX();
Y=m.getY();
msg="Gaurav";
setBackground(Color.white);
showStatus("Mouse Moved");
repaint();
}

public void mouseDragged(MouseEvent m)


{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}

public void mouseClicked(MouseEvent m)


{
msg="Student";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,X,Y);
}
}

/*
<html>

67
17103032

<body>
<applet code="Mouse.class" width=500 height=500>
</applet>
</body>
</html>
*/

68
17103032

2. Write an applet to print the message of click, enter, exit, press and release
messages when respective. Note: Extend Mouse Adapter and Mouse Motion
Adapter class

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/

public class AdapterDemo extends Applet {

public void init() {


addMouseListener(new MyMouseAdapter(this));

addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter {


AdapterDemo adapterDemo;

public MyMouseAdapter(AdapterDemo adapterDemo) {

this.adapterDemo = adapterDemo;
}

// Handle mouse clicked.


public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
public void mouseExited(MouseEvent e){
adapterDemo.showStatus("Mouse Exited");
}
public void mouseEntered(MouseEvent e){
adapterDemo.showStatus("Mouse Entered");
}
public void mousepressed(MouseEvent e){
adapterDemo.showStatus("Mouse Pressed");

}
public void mouseReleased(MouseEvent e) {
adapterDemo.showStatus("Mouse Released");
}

69
17103032

}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
public void mouseMoved(MouseEvent e){
adapterDemo.showStatus("Mouse Moved");
}
}
/*
<html>
<body>
<applet code="AdapterDemo.class" width=300 height=100>
</applet>
</body>
</html>
*/

70
17103032

3. Write an applet to print the message implementing Key Listener Interface. Also
show the status of key press and release in status window.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Keyboarddeal3 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 Pressed Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Released Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

71
17103032

4. Write an applet to print the message extending Key Adapter class in inner class
and Anonymous Inner class.

//Inner class
import java.applet.*;
import java.awt.Graphics;
import java.awt.event.*;
public class InnerClassDemo extends Applet {
String msg = "";
int X = 10, Y = 20;
public void init() {
addKeyListener(new MyMouseAdapter());
}
class MyMouseAdapter extends KeyAdapter {
public void keyPressed(KeyEvent me) {
showStatus("key Pressed");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
//Display keystrokes.
}
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

//Anonymous Inner Class Demo


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

72
17103032

import java.awt.event.*;
public class AnonymousInnerClassDemo extends Applet {
String msg = "";
int X = 10, Y = 20;
public void init() {
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent me) {
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}});}
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}}

73
17103032

5. Write an applet demonstrating some virtual keys codes i.e. Function Keys, Page
Up, Page down and arrow keys.
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>";
break;
case KeyEvent.VK_LEFT:
msg += "<Left Arrow>";
break;
case KeyEvent.VK_RIGHT:
msg += "<Right Arrow>";
break;
case KeyEvent.VK_UP:
msg += "<Up Arrow>";
break;
case KeyEvent.VK_DOWN:
msg += "<Down Arrow>";

74
17103032

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

/*
<html>
<body>
<applet code="KeyEvents.class" width="300" height="300">
</applet>
</body>
</html>
*/

75
17103032

Lab 10
1. Write an applet to design calculator
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class calculator implements ActionListener
{
int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
public calculator()
{
f = new Frame("My calculator");
p = new Panel();
f.setLayout(new FlowLayout());
b1 = new Button("0");
b1.addActionListener(this);
b2 = new Button("1");
b2.addActionListener(this);
b3 = new Button("2");
b3.addActionListener(this);
b4 = new Button("3");
b4.addActionListener(this);
b5 = new Button("4");
b5.addActionListener(this);
b6 = new Button("5");
b6.addActionListener(this);
b7 = new Button("6");
b7.addActionListener(this);
b8 = new Button("7");
b8.addActionListener(this);
b9 = new Button("8");
b9.addActionListener(this);
b10 = new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
76
17103032

b14.addActionListener(this);

b16 = new Button("=");


b16.addActionListener(this);

tf = new TextField(20);
f.add(tf);
g = new GridLayout(4,4,10,20);
p.setLayout(g);

p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.add(b7);p.add(b8);
p.add(b9);
p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(b16);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}

77
17103032

if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");

78
17103032

c=1;}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;

}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}

79
17103032

if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText(""); }
}
public static void main(String[] abc)
{
calculator v = new calculator();
}
}

80
17103032

2. Write an applet displaying three buttons and three check boxes labelled
Rectangle, Oval, Line, Red, Green and Blue Respectively.

import java.util.*;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javafx.scene.control.CheckBox;

public class ShapesAndColors extends Applet implements


ItemListener,ActionListener {
Button Rectangle,Oval,Line;
Checkbox Red,Green,Blue;
public String shape;
public int color;
public void init() {

Red=new Checkbox("Red",null,false);
Blue=new Checkbox("Blue",null,false);
Green=new Checkbox("Green",null,false);
Rectangle=new Button("Rectangle");
Oval=new Button("Oval");
Line=new Button("Line");

add(Red);
add(Green);
add(Blue);
add(Rectangle);
add(Oval);
add(Line);
Red.addItemListener(this);
Green.addItemListener(this);
Blue.addItemListener(this);
Rectangle.addActionListener((ActionListener) this);
Oval.addActionListener((ActionListener) this);
Line.addActionListener((ActionListener) this);

81
17103032

}
@Override
public void itemStateChanged(ItemEvent e) {
int numberOfCheckboxes=0;
if(Red.getState())
{
color=1;
numberOfCheckboxes++;
}
if(Green.getState()){
color=2;
numberOfCheckboxes++;
}
if(Blue.getState()){
color=3;
numberOfCheckboxes++;
}
if(numberOfCheckboxes!=1){
color=0;
}
}
@Override
public void actionPerformed(ActionEvent e) {
shape=e.getActionCommand();
repaint();
}
public void paint(Graphics g){
if(shape.equals("Line")){
g.drawLine(100,100,50, 80);
}
else if(shape.equals("Rectangle")){
g.drawRect(100, 100,80, 60);
if(color==0)
showStatus("Check only one check box");
else if(color==1)
g.setColor(Color.red);
else if(color==2)
g.setColor(Color.green);
else
g.setColor(Color.blue);

g.fillRect(100, 100, 80, 60);

}
else{
g.drawOval(100, 100,60, 40);

82
17103032

if(color==0)
showStatus("Check only one check box");
else if(color==1)
g.setColor(Color.red);
else if(color==2)
g.setColor(Color.green);
else
g.setColor(Color.blue);

g.fillOval(100, 100, 60, 40);

}
}
}

83
17103032

3. Write an applet to draw a square and two buttons labelled Enlarge and
Shrink respectively.

import java.util.*;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ShapeSize extends Applet implements ActionListener{

Button Enlarge,Shrink;

int length=30;

public void init() {

Enlarge=new Button("Enlarge");
Shrink=new Button("Shrink");
add(Enlarge);
add(Shrink);
Enlarge.addActionListener(this);
Shrink.addActionListener(this);
}

public void paint(Graphics g){


g.drawRect(100, 100, length, length);
g.setColor(Color.blue);
g.fillRect(100, 100, length, length);
}

@Override

public void actionPerformed(ActionEvent e) {

String function=e.getActionCommand();

if(function.equals("Enlarge")){
length+=5;
repaint();
}

84
17103032

else{
length-=5;
repaint();
}
}
}

85
17103032

4. Write an applet that gives the following output:

import java.util.*;
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class ChoiceList extends Applet implements ItemListener{


Label l1,l2;
String fn,fs;
int size=40;
Choice fontName,fontSize;
String msg="EVENT HANDLING IN JAVA";
Checkbox Centered,Left,Right,Bold,Italics;
CheckboxGroup cbg;
int px=50;
public void init() {

l1=new Label("Font Name");


l2=new Label("Font Size");
GraphicsEnvironment
ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts=ge.getAvailableFontFamilyNames();
fontName=new Choice();
fontSize=new Choice();
for(String i:fonts){
fontName.add(i);
}
for(int i=12;i<=50;++i){
fontSize.add(""+i);
}
add(l1);add(fontName);
add(l2);add(fontSize);

fontName.addItemListener(this);
fontSize.addItemListener(this);
cbg=new CheckboxGroup();

86
17103032

Centered=new Checkbox("Centered",cbg,false);
Left=new Checkbox("Left",cbg,false);
Right=new Checkbox("Right",cbg,false);
Bold=new Checkbox("Bold",null,false);
Italics=new Checkbox("Italics",null,false);
add(Centered);
add(Left);
add(Right);
add(Bold);
add(Italics);
Bold.addItemListener(this);
Italics.addItemListener(this);
Centered.addItemListener(this);
Left.addItemListener(this);;
Right.addItemListener(this);

}
public void paint(Graphics g){
fs=fontName.getSelectedItem();
fn=fontSize.getSelectedItem();
size=Integer.parseInt(fn);
int x=0,y=0;
if(Bold.getState())
x=Font.BOLD;
if(Italics.getState())
y=Font.ITALIC;
Font f=new Font(fs,x+y,size);
g.setFont(f);
this.l1.setLocation(0,0);
this.fontName.setLocation(80,0);
this.l2.setLocation(320,0);
this.fontSize.setLocation(400,0);
g.drawString(msg,px,80);
this.Centered.setLocation(0,120);
this.Left.setLocation(90,120);
this.Right.setLocation(150,120);
this.Bold.setLocation(0,140);
this.Italics.setLocation(60,140);
}

@Override
public void itemStateChanged(ItemEvent e) {

String s=cbg.getSelectedCheckbox().getLabel();
87
17103032

if(s.equals("Centered"))
px=50;
else if(s.equals("Left"))
px=0;
else
px=100;

repaint();
}
}

88

You might also like