Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
92 views

Java Internal

The document is a lab file submitted by Prabhat Chand Sharma that contains 10 programming assignments completed as part of an Advanced Programming Concepts using Java course. The assignments include programs to: 1) Compare two integers and output which is larger or if they are equal 2) Count command line arguments and print them 3) Implement Pascal's triangle 4) Print different patterns like a box, oval, arrow, and diamond based on user input

Uploaded by

Gaurav Sachdeva
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Java Internal

The document is a lab file submitted by Prabhat Chand Sharma that contains 10 programming assignments completed as part of an Advanced Programming Concepts using Java course. The assignments include programs to: 1) Compare two integers and output which is larger or if they are equal 2) Count command line arguments and print them 3) Implement Pascal's triangle 4) Print different patterns like a box, oval, arrow, and diamond based on user input

Uploaded by

Gaurav Sachdeva
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Java Lab File CSX-351 17103060

DR B R AMBEDKAR NATIONAL INSTITUE OF TECHNOLOGY


JALANDHAR

LAB FILE

ADVANCED PROGRAMMING CONCEPTS USING JAVA


CSX-351

SESSION: JULY-DEC 2019

SUBMITTED TO
SUBMITTED BY
Dr Rajneesh Rani
PRABHAT CHAND SHARMA
Asst Professor
17103060
Dept OF CSE, NITJ
G3, BTech CSE, 3rd year

1
Java Lab File CSX-351 17103060
Index
S.No. Practical Date Page Remarks
No.
1. Lab1 3-8
2. Lab2 9-12
3. Lab3 13-16
4. Lab4 17-21
5. Lab5 22-34
6. Lab6 35-42
7. Lab7 43-55
8. Lab8 56-59
9. Lab9 60-65
10. Lab10 66-68

2
Java Lab File CSX-351 17103060
Assignment 01
1. Write an application that ask the user to enter 2 integers, obtain them from user
and displays a large number followed by the work “is larger”. If the number are
equal, print the message “These numbers are equal”.
import java.util.Scanner;
public class Q1{
public static void main(String[] args) {
System.out.println("Enter two numbers: ");
Scanner in = new Scanner(System.in);
int num1 = in.nextInt();
int num2 = in.nextInt();
if(num1>num2)
System.out.println(num1 + " is larger");
else if(num2>num1)
System.out.println(num2 + " is larger");
else
System.out.println("These numbers are equal");
}
}

2. Write an application in which user passes Command Line arguments and the
output shows the count of the arguments passed on command line and also print
them all.
public class Q2 {
public static void main(String[] args){
int cnt=args.length;
System.out.println("no. of arguments is " + cnt + "\n");
for(int i=0;i<cnt;i++){
System.out.println(args[i] + " ");
}
}

3
Java Lab File CSX-351 17103060

C: \Users\Gyanesh\Desktop\Java\Lab1> java Q2 5 7 8 3

3. Write an application to implement Pascal Triangle.


1
11
121
1331
14641
.......
import java.util.Scanner;
public class Q3 {
public static int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
public static int ncr(int n, int r)
{
int res;
res=fact(n)/(fact(r)*fact(n-r));
return res;
}
public static void main(String args[])
{
System.out.print("enter no. of rows: ");
Scanner in=new Scanner(System.in);
int row=in.nextInt();
for(int i=0;i<row;i++)
{
for(int j=0;j<row-i-1;j++)
System.out.print(" ");
for(int j=0;j<=i;j++)
{
4
Java Lab File CSX-351 17103060
System.out.print(ncr(i,j)+ " ");
}
System.out.println();
}
}
}

C: \Users\Gyanesh\Desktop\Java\Lab1> java Q3

4. Write a menu driven application using switch-case statements in which case 1 : print a
box, case 2 : an oval, case 3 : an arrow and case 4 : a diamond using loop and control
statements.
1. ******* 2. *** 3. * 4. *
* * * * *** * *
* * * * ***** * *
* * * * * * *
* * * * * * *
* * * * * * *
******* *** * *

import java.util.Scanner;
public class Pattern1 {
public static void printBox(int n){
for(int i=1;i<=n;i++)
{
if(i==1 || i==n)
for(int j=1;j<=n;j++)
System.out.print("*");
else{
System.out.print("*");
for(int j=1;j<=n-2;j++)
System.out.print(" ");
System.out.print("*");
}
5
Java Lab File CSX-351 17103060
System.out.println();
}
}
public static void printOval(int n){
int t=(n-3)/4;
for(int i=1;i<=n;i++){
if(i==1 || i==n){
for(int j=1;j<=t+1;j++)
System.out.print(" ");
for(int j=1;j<=2*t+1;j++)
System.out.print("*");
}
else if(i>1 && i<=t+1){
for(int j=1;j<=t-i+2;j++)
System.out.print(" ");
System.out.print("*");
for(int j=1;j<=2*t+1+2*(i-2);j++)
System.out.print(" ");
System.out.print("*");
}
else if(i>t+1 && i<(3*t+3)){
System.out.print("*");
for(int j=1;j<=4*t+1;j++)
System.out.print(" ");
System.out.print("*");
}
Else{
int k=n-i+1;
for(int j=1;j<=t-k+2;j++)
System.out.print(" ");
System.out.print("*");
for(int j=1;j<=2*t+1+2*(k-2);j++)
System.out.print(" ");
System.out.print("*");
}
System.out.println();
}
}
public static void printArrow(int n)
{
for(int i=0;i<n/2+1;i++){
for(int j=0;j<n/2-i;j++)
System.out.print(" ");

for(int j=0;j<2*i+1;j++)
System.out.print("*");
System.out.print("\n");
}
for(int i=0;i<n/2+2;i++){
for(int j=0;j<n/2;j++)
System.out.print(" ");
System.out.print("*\n");
}

6
Java Lab File CSX-351 17103060
}
static void printDiamond(int n){
for(int i=0;i<n/2+1;i++){
for(int j=0;j<n/2-i;j++)
System.out.print(" ");
System.out.print("*");
for(int j=0;j<2*i-1;j++)
System.out.print(" ");
if(i>0)
System.out.print("*");
System.out.print("\n");
}
for(int i=n/2-1;i>=0;i--){
for(int j=0;j<n/2-i;j++){
System.out.print(" ");
System.out.print("*");
for(int j=0;j<2*i-1;j++){
System.out.print(" ");
if(i>0)
System.out.print("*");
System.out.print("\n");
}
}
public static void main(String args[]){
System.out.println("1.print a box");
System.out.println("2.print a oval");
System.out.println("3.print a arrow");
System.out.println("4.print a diamond");
System.out.println("5.exit");
int t=1;
while(t==1){
System.out.print("enter your choice");
Scanner in = new Scanner(System.in);
int ch=in.nextInt();
switch(ch){
case 1:
System.out.print("enter no .of rows");
int n=in.nextInt();
printBox(n);
break;
case 2:
System.out.print("enter no .of rows in 4n+3");
int m=in.nextInt();
printOval(m);
break;
case 3:
System.out.print("enter no .of rows in 2n+1");
int r=in.nextInt();
printArrow(r);
break;
case 4:
System.out.print("enter no .of rows in 2n+1");
int d=in.nextInt();

7
Java Lab File CSX-351 17103060
printDiamond(d);
break;
case 5:
t=0;
break;
}
}}}

C: \Users\Gyanesh\Desktop\Java\Lab1> java Q4

8
Java Lab File CSX-351 17103060

Assignment 02
1. Write an application to that asks the user to enter three integer values(2 < n < 100) ,
and then displays that these values are Pythagorean triplets or not. The application
should try all the combinations of the values.
import java.util.*;
public class Q2{

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int a , b , c;
System.out.println("Enter the sides of triangle");
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
a =a*a;
b =b*b;
c = c*c;
if(((a == b+c) || (b == a+c) ) || (c ==a+b) )
System.out.println("The given numbers are phythagorous
triplets");
else System.out.println("The given numbrs are not phytagorous
triplets");

C: \Users\Gyanesh\Desktop\Java\Lab2> java Q1

2. Write an application that inputs from the user the radius of the circle as a floating point
and prints the diameter, circumference and area. Use the following formulas :
Diameter = 2r
Circumferece = 2 * PI * r
Area = PI * r2
Take PI = 3.14159, should be declared as final
import java.util.*;
public class circle {
9
Java Lab File CSX-351 17103060

static final double pi = 3.14;


public static void main(String[] args)
{
double r;
System.out.print("enter radius of circle");
Scanner in = new Scanner(System.in);
r = in.nextFloat();
in.close();
System.out.println("The diameter of the circle is "+ (2*r));
System.out.println("The circum. of the circle is"+ (2*pi*r));
System.out.println("The Area of the circle is" + (pi * r*
r ));

}
}

C: \Users\Gyanesh\Desktop\Java\Lab2> java Q2

3. Write an application which contains a class named “Account” that maintains the
balance of a bank account. The Account class has method debit() that withdraws money
from the account. Ensure that the debit amount does not exceed the account’s balance. If
it does, the balance should remain unchanged with a message indicating “Debit amount
exceeded account balance”.
import java.util.Scanner;

class Account
{
public int balance;
Account(int a)
{
this.balance = a;
}
}
public class AccountTest {

public static void main(String[] args) {


Scanner in = new Scanner(System.in);
int amt;
System.out.print("enter amount: ");
amt = in.nextInt();
Account obj = new Account(amt);
int debit ;
System.out.print("enter amount u want to debit: ");
debit = in.nextInt();
10
Java Lab File CSX-351 17103060
if(debit > obj.balance)
{
System.out.println("Debit balance exceeded from the
current balance");
System.out.println("new balance is " + obj.balance);

}
else
{
obj.balance = obj.balance - debit;
System.out.println("Account debited successfully");
System.out.println("new balance is "+ obj.balance);
}
in.close();
}
}

C: \Users\Gyanesh\Desktop\Java\Lab2> java Q3

4. Write an application to determine the gross pay for 3 employees. The company pays
straight for first 40 hours and half after that for overtime. Salary per hour and number of
hours of each employee should be input by user.
import java.util.Scanner;

class Employee
{
public int whour;
public int salary;
Employee()
{
this.whour =0;
this.salary =0;
}
}
public class Grosspay {

public static void main(String[] args) {


Employee[] arr = new Employee[3];
Scanner in = new Scanner(System.in);

11
Java Lab File CSX-351 17103060
System.out.println("Enter the salary per hour and working
hours for the three employees");
for(int i=0;i<3;i++)
{
arr[i] = new Employee();
arr[i].salary = in.nextInt();
arr[i].whour = in.nextInt();
}
System.out.println("The amount paid to each employee at the
end of the month is ");
for(int i=0; i<3;i++)
{
if(arr[i].whour>40)
{
System.out.println("the amount paid to "+ i + "th
employee is " +( (40*arr[i].salary) +( (arr[i].whour - 40 )*
( arr[i].salary / 2))) );
}
else
System.out.println("the amount paid to "+ i + "th
employee is " + arr[i].whour *arr[i].salary);
}
in.close();
}
}

C: \Users\Gyanesh\Desktop\Java\Lab2> java Q2

12
Java Lab File CSX-351 17103060

Assignment 03
1. Write an application to store all the addition combination of the two dices in 2D
array and display as follows :
class Q1
{
public static void main(String[] args)
{
int max_value=7;
int[][] sums=new int[7][7];
for(int i=0;i<max_value;++i)
{
for(int j=0;j<max_value;++j)
sums[i][j]=i+j;
}
for(int i=0;i<max_value;++i)
{
for(int j=0;j<max_value;++j)
System.out.print(sums[i][j] + " ");
System.out.print("\n");
}}}

2. To perform string operations

import java.util.Scanner;
class Q2{
public static void main(String[] args){
String s1,s2;
Scanner input=new Scanner(System.in);
System.out.println("Enter the two strings : ");
s1=input.nextLine();
13
Java Lab File CSX-351 17103060
s2=input.nextLine();
int a=0;
do{
System.out.println("Enter your choice :
1.Concatenate two strings\n2.Compare two
strings\n3.Find the lenght of strings");

int c=input.nextInt();
if(c==1){
System.out.println("The concatenated strings is
: " + s1+s2);
}
else if(c==2){
if(s1==s2)
System.out.println("Strings are equal");
else if(s1.equals(s2)==false)
System.out.println("String 1 is greater
than string 2");
else
System.out.println("String 2 is greater
than string 1");
}
else if(c==3){
System.out.println("The lenghts of string s1
and s2, respectively, are : "
+ s1.length()+" "+s2.length());
}
else
System.out.println("Wrong input!");
System.out.println("Want to continue?(0 or 1)");
a=input.nextInt();
}while(a>=1);
}}

14
Java Lab File CSX-351 17103060

3. To find if a given string is a double string

import java.util.Scanner;
class DoubleString
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
String s;
System.out.println("Enter the string : ");
s=input.nextLine();
int a=0;
if(s.length()==0)
System.out.println("Empty String! ");
else if(s.length()%2!=0)
a=1;
else{
int j=s.length()/2;
for(int i=0;i<s.length()/2;++i){
char x=s.charAt(i);
char b=s.charAt(j);
if(x!=b){
a=2;
break;
}
++j;
}
}
if(a==1)
System.out.println("String of odd length!");
15
Java Lab File CSX-351 17103060
else if(a==2)
System.out.println("Not a double string! ");
else
System.out.println("String is a double string!");
}
}

4. To copy a range of array and paste it at some other position


import java.util.Scanner;
import java.util.Vector;
import java.util.ArrayList;
class Q4
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter the size of the array :");
int n=input.nextInt();
int[] a=new int[n];
System.out.println("Enter the Array elements : ");
for(int i=0;i<n;++i)
a[i]=input.nextInt();
int x,y;
System.out.println("Enter the range to be copied : ");
x=input.nextInt();
y=input.nextInt();
int n2=y-x+1;
System.out.println("Enter the index to be copied at : ");
int z=input.nextInt();
int[] b=new int[n2];
for(int i=x;i<=y;++i)
b[i-x]=a[i];
System.out.println("The copied array is : ");
for(int i=0;i<z;++i)
System.out.print(a[i] + " ");
for(int i=0;i<n2;++i)
System.out.print(b[i]+ " ");
16
Java Lab File CSX-351 17103060
for(int i=z;i<n;++i)
System.out.print(a[i]+ " ");

}
}

Assignment 04
1.Create a package package1 which contains three classes, one is super class and others
are subclasses. Make some of the components private, some of them protected and some
public, show access control using the above description. Then, create another package p2
in which the class can access public components of package package1. Now import the
classes of package package1 and package2 for the class of the main() method.

package lab_4.p1;

import java.util.*;

class Q1 {

public static void main(String[] args) {


problem1b p1b = new problem1b();
System.out.println("\nWow! I can access my public members
here: " + p1b.stuff);
System.out.println("\nAlso, I can use my parents function :
");
p1b.CallMe();
}
}

package lab_4.p1;

17
Java Lab File CSX-351 17103060
public class problem1 {

public int variable1 = 1234;

protected String variable2 = " Java is Beautiful";

private float variable3 = 2.345f;

static public int variable4 = 4321;

void CallMe() {
System.out.println("Calling a function of the problem1
class\n");
System.out.println("We have called you. And you answered, so
nice of you! I think you are default or public(may be protected if I am
your child:)");
}
}
package lab_4.p1;

class problem1a extends problem1 {

private int variable = 1234;

package lab_4.p1;

class problem1b extends problem1 {

public int stuff = 1000000;

private float a = 0.00023495320f;


}

package lab_4.p2;

import lab_4.p1.*;
class anotherClass {

public String variable = "This is my public Variable";


void Public() {
System.out.println("\nThe called function is my public.\n\n");
}

void CallingProblem1() {
System.out.println("\nThis is the public member of the
problem1 class of package1 : " + lab_4.p1.problem1.variable4);
}
}

18
Java Lab File CSX-351 17103060
package lab_4;

import lab_4.p1.*;

class checkingPackage {

public static void main(String[] args) {

problem1 p = new problem1();


p.variable1 = 2;
System.out.println(p.variable1);
}
}

2. Create a class student which takes the roll number of the students, another class Test
extends Student and add up marks of two tests. Now an interface Sports declares the
sports marks and has method putMarks. Implement multiple inheritance in Class Result
using above classes and interface.

import java.util.*;

class Student {

int rollNumber;

void SetRollNumber(int rollNumber) {


this.rollNumber = rollNumber;
}

int GetRollNumber() {
return this.rollNumber;
}
}

class Test extends Student {

int marks1, marks2;


// int sportsMarks = 0;
public void setMarks(int marks1, int marks2) {
this.marks1 = marks1;
this.marks2 = marks2;
}

19
Java Lab File CSX-351 17103060

int AddMarksUp() {
return this.marks1 + this.marks2;
}
}

interface Sports {

public void setSportsMarks(int sM);


public int putMarks();
}

class Result extends Test implements Sports {

int sportsMarks;

public void setSportsMarks(int sM) {


sportsMarks = sM;
}

public int putMarks() {


int totalMarks = sportsMarks + marks1 + marks2;
return totalMarks;
}
}

class MarksCalculation {

public static void main(String[] args) {

Result R = new Result();

Test T = new Test();


Scanner input = new Scanner(System.in);
System.out.println("Enter the marks in the two tests: ");
int marks1 = input.nextInt();
int marks2 = input.nextInt();
T.setMarks(marks1, marks2);

System.out.println("Enter the marks in the sports test: ");


int sportsMarks = input.nextInt();
R.setSportsMarks(sportsMarks);
R.marks1 = T.marks1;
R.marks2 = T.marks2;
System.out.println("\nThe result is finally out : " +
R.putMarks());
}
}

20
Java Lab File CSX-351 17103060

3. To find the maximum frequency of an element in an array


import java.util.Scanner;
class Freq
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter the length of array : ");
int n=input.nextInt();
int[] a=new int[n];
System.out.println("Enter the array elements : ");
for(int i=0;i<n;++i)
a[i]=input.nextInt();
int[] cnt=new int[10];
for(int i=0;i<10;++i)
cnt[i]=0;
for(int i=0;i<n;++i)
cnt[a[i]]+=1;
int m=1;
int ans=m;
for(int i=0;i<n-1;++i)
{
if(a[i]==a[i+1])
{
m+=1;
if(m>ans)
ans=m;
}
else
m=1;
}
System.out.println("Maximum frequency is : " + m);
}
}

21
Java Lab File CSX-351 17103060

Assignment 05
1.Write an application to show access protection in user defined packages. Create a
package p1 which has three classes: Protection, Derived and SamePackage. First class
contains variables of all the access types. Derived is subclass of Protection but
SamePackage is not. Other package p2 consisting of two class: one deriving p1.Protection
and other not. Import the package considering all the cases of access protection.
package lab_5.p1;

public class Protection {

public int publicVariable = 2323;


private float floatVariable = 23.223f;
protected String stringVariable = "Protected";
}

package lab_5.p1;

public class Derived extends Protection {

22
Java Lab File CSX-351 17103060
public int stuff = 23421;

public void print() {


System.out.println("I am a function of Derived class");
}

public void printProtected() {


System.out.println("I can access the protected variable of
Protection class. Its value is: " + stringVariable);
}

package lab_5.p1;

public class SamePackage {


int variable = 23;
protected String is = "Hello";

package lab_5.p2;

import lab_5.p1.*;

public class first extends Protection {

int anyNumber = 23422;


public String anyName = "Henry Ford";
}

package lab_5.p2;

public class second {

double doubleStuff = 2.3324;


Integer integer = new Integer(23);

public void print() {


System.out.println("I am a function of second class.");
System.out.println("I have only two variable : " + doubleStuff +
"and " + integer);
}
}

package lab_5;

import lab_5.p1.*;
import lab_5.p2.*;

class Problem1 {

23
Java Lab File CSX-351 17103060

public static void main(String[] args) {


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

Derived d = new Derived();


System.out.println("The variables and functions of Derived class
are: ");
System.out.println("Public variable's value : " + d.stuff);
d.print();
d.printProtected();
System.out.println("\n\n");

SamePackage s = new SamePackage();


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

first f = new first();


System.out.println("The variables and functions of first class
are: ");
System.out.println("The default variable of the class is not
accessible.");
System.out.println("Public variable's value is : " + f.anyName +
"\n\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();
System.out.println("\n\n");
}
}

24
Java Lab File CSX-351 17103060

2. Multiple Inheritance in java is when a class implements more than one interface. Write
an application showing Multiple Inheritance and Dynamic Polymorphism (Method
Overriding) using Interface.
class Game {
public void type() {
System.out.println("We are talking about Indoor and Outdoor
games.");
}
public void numberOfPlayers() {
System.out.println("Number of player is a relative term, depends
on the game.");
}
}
class Football extends Game {

public void type() {


System.out.println("Football is an outdoor game.");

25
Java Lab File CSX-351 17103060
}
public void numberOfPlayers() {
System.out.println("In Football, we have 11 players in each
team.");
}
}
class Kabaddi extends Game {

public void type() {


System.out.println("Kabaddi is an outdoor game.");
}
public void numberOfPlayers() {
System.out.println("In Kabaddi, we have 12 players in each
team.");
}
}
import java.util.*;
class Problem2 {
public static void main(String[] args) {
System.out.println("\n\n");
Game g = new Game();

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


g.type();
g.numberOfPlayers();
System.out.println("\n\n");
System.out.println("Football class functions : ");
g = new Football();
g.type();
g.numberOfPlayers();
System.out.println("\n\n");
System.out.println("Kabaddi class functions : ");
g = new Kabaddi();
26
Java Lab File CSX-351 17103060
g.type();
g.numberOfPlayers();
System.out.println("\n\n");
}
}

3. Define a package named area which contains classes : Square, Rectangle, Circle, Elipse
and Triangle. Write an application in which the main class, FindArea outside the package
area imports the package area and calculate the area of different shapes. Output of your
application should be menu driven.
package lab_5.area;

public class Circle {


double radius;
public void putrad(double radius){
this.radius=radius;
}
public double get_area()
{
return 3.14*radius*radius;
}

}
package lab_5.area;

public class Rectangle {


double length, breadth;
public void putsides(double length, double breadth){
this.length=length;

27
Java Lab File CSX-351 17103060
this.breadth=breadth;
}
public double get_area()
{
return length*breadth;
}

}
package lab_5.area;

public class Elipse {


double major, minor;
public void putaxes(double major, double minor){
this.major=major;
this.minor=minor;
}
public double get_area()
{
return 3.14*major*minor;
}

}
package lab_5.area;

public class Square {


double side;
public void putside(double side){
this.side=side;
}
public double get_area()
{
return side*side;
}

}
package lab_5.area;

public class Triangle {


double base, height;
public void putdims(double base, double height){
this.base=base;
this.height=height;
}
public double get_area()
{
return 0.5*base*height;
}

}
package lab_5;
import java.util.Scanner;

28
Java Lab File CSX-351 17103060
import lab_5.area.*;
public class FindArea {
public static void main(String []args){
System.out.println("You can find the area for ");
System.out.println("1. square");
System.out.println("2. rectangle");
System.out.println("3. circle");
System.out.println("4. elipse");
System.out.println("5. triangle");
while(true){
System.out.println("enter choice");
int choice ;
Scanner in = new Scanner(System.in);
choice = in.nextInt();
switch(choice){
case 1 :{
Square s = new Square();
System.out.println("enter side");
double side = in.nextDouble();
s.putside(side);
System.out.println("area of square = " + s.get_area());
break;
}
case 2 :{
Rectangle r = new Rectangle();
System.out.println("enter length and breadth");
double length = in.nextDouble();
double breadth = in.nextDouble();
r.putsides(length,breadth);
System.out.println("area of rectangle = " +
r.get_area());
break;
}
29
Java Lab File CSX-351 17103060
case 3 :{
Circle c = new Circle();
System.out.println("enter radius");
double rad = in.nextDouble();
c.putrad(rad);
System.out.println("area of circle = " + c.get_area());

break;
}
case 4 :{
Elipse e = new Elipse();
System.out.println("enter major and minor axes");
double major = in.nextDouble();
double minor = in.nextDouble();
e.putaxes(major,minor);
System.out.println("area of rectangle = " +
e.get_area());
break;
}
case 5 :{
Triangle t = new Triangle();
System.out.println("enter base and height");
double base = in.nextDouble();
double height = in.nextDouble();
t.putdims(base, height);;
System.out.println("area of rectangle = " +
t.get_area());
break;
}
default :{
System.out.println("enter a valid choice");
in.close();
return ;
30
Java Lab File CSX-351 17103060
}}}

4.Define an interface Volume having a final variable P1 and a method to calculate


volumes of different shapes. Implement the interface Volume in class Cube, Cylinder,
Cone and Sphere to calculate the volume of these different shapes. Calculate the volume
using the main class FindVolume. Output of your application should be menu driven.
public interface Volume {

final double pi = 3.14;


public double volume();
}

package lab_5.Volume;

public class Sphere implements Volume{

31
Java Lab File CSX-351 17103060
public int radius;

public Sphere(int radius){


this.radius = radius;
}
public double volume(){
double v = (4 * pi * radius * radius * radius ) / 3;
return v;
}
}

package lab_5.Volume;

public class Cone implements Volume{


public int radius,height;

public Cone(int radius,int height){


this.radius=radius;
this.height=height;
}
public double volume(){
return (pi*radius*radius*height)/3;
}
}
package lab_5.Volume;
public class Cube implements Volume{
public int side;
public Cube(int side){
this.side=side;
}
public double volume(){
return side*side*side;

32
Java Lab File CSX-351 17103060
}
}
package lab_5.Volume;
public class Cylinder implements Volume {
public int radius,h;
public Cylinder(int radius, int h){
this.radius=radius;
this.h=h;
}
public double volume(){
return pi*radius*h;
}
}
import java.util.Scanner;
import volume.Sphere;
import volume.Cube;
import volume.Cylinder;
import volume.Cone;
public class Problem4 {

public static void main(String[] args) {


int option;
Scanner input = new Scanner(System.in);
do {
System.out.println("Choose the solid you want the volume
for: ");
System.out.println("1. Sphere");
System.out.println("2. Cylinder");
System.out.println("3. Cube");
System.out.println("4. Cone");
System.out.println("0. Exit");
option = input.nextInt();
switch(option) {
33
Java Lab File CSX-351 17103060
case 1:
System.out.println("Enter radius : ");
int r = input.nextInt();
Sphere s = new Sphere(r);
System.out.println("Volume of the sphere is : " +
s.volume()+ "\n");
break;
case 2:
System.out.println("Enter radius and height of the
cylinder : ");
int radius = input.nextInt();
int height = input.nextInt();
Cylinder c = new Cylinder(radius, height);
System.out.println("Volume of the cylinder : " +
c.volume() + "\n");
break;
case 3:
System.out.println("Enter the side of the cube : ");
int side = input.nextInt();
Cube cB = new Cube(side);
System.out.println("Volume of cone is : " +
cB.volume() + "\n");
break;
case 4:
System.out.println("Enter the side of the Cone : ");
radius = input.nextInt();
height = input.nextInt();
Cone cN = new Cone(radius, height);
System.out.println("Volume of cone is : " +
cN.volume() + "\n");
break;
}
}while(option != 0);
}

34
Java Lab File CSX-351 17103060
}

Assignment 06
1. Use inheritance to create an exception superclass (called ExceptionA) and
exception subclasses ExceptionB and ExceptionC, where ExceptionB inherits from
ExceptionA and ExceptionC inherits from ExceptionB. Write a program to
demonstrate that the catch block for type ExceptionA catches exceptions of type
ExceptionB and ExceptionC.
import java.util.Scanner;
class ExceptionA extends Exception
{
public String toString() {
return "Exception A";
}
}
class ExceptionB extends ExceptionA{

35
Java Lab File CSX-351 17103060
public String toString() {
return "Exception B";
}
}

class ExceptionC extends ExceptionB{


public String toString() {
return "Exception C";
}
}
public class Q1 {
static int val;
public static void main(String args[]){
System.out.println("Enter 1 to throw ExceptionA, 2 for
ExcpetionB, 3 for ExceptionC");
Scanner in = new Scanner(System.in);
val = in.nextInt();
try{
switch(val){
case 1:
throw new ExceptionA();

case 2:
throw new ExceptionB();
case 3:
}
}
catch(ExceptionA e){
System.out.println("Caught Exception is "+ e+" and is
caught in ExceptionA catch.");
}
}
}
36
Java Lab File CSX-351 17103060

2. Write a program that demonstrates how various exceptions are caught with
catch(Exception exception).
This time, define classes ExceptionA (which inherits from class Exception) and
ExceptionB (which inherits from class ExceptionA). In your program, create try
blocks that throw exceptions of types ExceptionA, ExceptionB,
NullPointerException and IOException. All exceptions should be caught with catch
blocks specifying type Exception.
import java.io.IOException;
import java.util.Scanner;
class ExceptionA extends Exception{
public String toString() {
return "Exception A";
}
}
class ExceptionB extends ExceptionA{
public String toString() {
return "Exception B";
}
}
public class Q2 {
static int val;
public static void main(String args[]){
System.out.println("Enter 1 to throw ExceptionA, 2 for
ExcpetionB, 3 for NullPointerException, 4 for IOException");
Scanner in = new Scanner(System.in);
val = in.nextInt();
try{
switch(val){
case 1:
37
Java Lab File CSX-351 17103060
throw new ExceptionA();
case 2:
throw new ExceptionB();
case 3:
throw new NullPointerException();
case 4:
throw new IOException();
}
}
catch(Exception e){
System.out.println("Caught Exception is "+ e);
}
}
}

3.Write a program that shows that the order of catch blocks is important. If you try a
catch a superclass exception type before a subclass type, the compiler should generate
errors.
import java.io.IOException;
import java.util.Scanner;
public class Q3{
static int val;
public static void main(String args[]){
System.out.println("Enter 1 to throw ExceptionA, 2 for
ExcpetionB, 3 for NullPointerException, 4 for IOException");
Scanner in = new Scanner(System.in);
val = in.nextInt();
try{
switch(val){
case 1:
38
Java Lab File CSX-351 17103060
throw new ExceptionA();{
case 2:
throw new ExceptionB();{
case 3:
throw new NullPointerException();
case 4:
throw new IOException();
}
}
catch(Exception e){
System.out.println("Caught Exception is "+ e);
}
catch(ExceptionA e){
System.out.println("Caught Subclass Exception is "+ e);
}
}
}

4.Write a program that illustrates rethrowing an exception. Define methods someMethod


and someMethod2. Method someMethod2 should initially throw an exception. Method
someMethod should call someMethod2, catch the exception and rethrow it. Call
someMethod from method main(), and catch the rethrow exception. Print the stack trace
of this exception.
import java.io.IOException;
public class ExceptionInMethod {
public static void methodB()
{
System.out.println("Hello You are in method B");
Try{
39
Java Lab File CSX-351 17103060
throw new IOException();
}
catch(Exception e){
e.printStackTrace();
throw new NullPointerException();
}}
public static void methodA(){
System.out.println("Hello You are in method A");
Try{
methodB();
}
catch(Exception e){
e.printStackTrace();
throw new ArithmeticException();
}
}
public static void main(String args[]){
System.out.println("you are in Main");
Try{
methodA();
}
catch(Exception e){
e.printStackTrace();
}}}

40
Java Lab File CSX-351 17103060

5.Write an application to define two different Exceptions. Enter an issue_date and a


return_date and define two different exceptions. First, if difference of issue-date and
return_date is more than 15 days, throw an exception displayking calculated fine(Rs. 50
per day) after 15 days. Second, if return date is before issue_date, throw an excpetion
displaying “Return date < Issue date”.
import java.util.Date;
import java.util.Scanner;

class FineException extends Exception{


int fine ;
public FineException(int fine){
this.fine = fine;
}
public String toString(){
return "Fine for 15 days :" + fine;
}
}
class InvalidDateException extends Exception{
public String toString(){
return "Return Date < Issue Date" ;
}
}
public class DateException {

41
Java Lab File CSX-351 17103060
static Date issue_date,return_date;
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("\nEnter the Year/Month/Date for the
issuing date: ");
int year, month, date;
year = input.nextInt();
month = input.nextInt();
date = input.nextInt();
issue_date = new Date(year,month,date);
System.out.println("\nEnter the Year/Month/Date for the
returning date: ");
year = input.nextInt();
month = input.nextInt();
date = input.nextInt();
return_date = new Date(year,month,date);

try
{
if(return_date.before(issue_date))
{
throw new InvalidDateException();
}

if(return_date.getTime()-
issue_date.getTime()>15*24*60*60*1000)
{
int fine = (int)(return_date.getTime()-
issue_date.getTime())/(24*60*60*1000)*50;
throw new FineException(fine);
}
}
catch(InvalidDateException e){
42
Java Lab File CSX-351 17103060
System.out.print(e);
}
catch(FineException e){
System.out.print(e);
}
}
}

Assignment 07
1. Write an application of multithreading. Create three different classes(threads) that
inherit Thread class. Each class consists of a for loop that prints identity 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 output.
class NewThread1 extends Thread
{
NewThread1(){

43
Java Lab File CSX-351 17103060
// Create a new thread
super("Thread class one ");
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 NewThread2 extends Thread{
NewThread2(){
super("Thread class two ");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
public void run() {
try{
for(int i = 5; i > 0; i--){
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
}

44
Java Lab File CSX-351 17103060
catch (InterruptedException e){
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class NewThread3 extends Thread{
NewThread3(){
// Create a new thread
super("Thread class three ");
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 Q1{
public static void main(String args[]){
new NewThread1();
new NewThread2();
new NewThread3();
try{
for(int i = 5; i > 0; i--){

45
Java Lab File CSX-351 17103060
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting");
}}

2. Write an application of multithreading to create three different threads namely: One,


Two and Three. Crete the threads implementing Runnable Interace. Start all three threads
together and print the thread with increasing number till the thread exit. Make sure that
main thread exits at last.
NOTE : Use Thread.sleep().

class NewThread implements Runnable


{
String name; // name of thread
Thread t;
46
Java Lab File CSX-351 17103060
NewThread(String n)
{
name = n;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run()
{
try
{
for(int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class Q2
{
public static void main(String args[]) {
new NewThread("One"); // Create the 3 threads
new NewThread("Two");
new NewThread("Three");
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}

47
Java Lab File CSX-351 17103060

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


min, max and norm priority each. Now run each thread together for 10 seconds. Each
thread should consist of a variable count that increases itself with time(click++). Stop all
threads after 10 seconds and print the value of click for each and show the use priority in
multithreading.
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++;
}

48
Java Lab File CSX-351 17103060
}
public void stop()
{
running = false;
}
public void start()
{
t.start();
}
}
class Q3{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker h = new clicker(Thread.NORM_PRIORITY + 2);
clicker l = new clicker(Thread.NORM_PRIORITY - 2);
l.start();
h.start();

try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
l.stop();
h.stop();
try
{
h.t.join();
l.t.join();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + l.click);
System.out.println("High-priority thread: " + h.click);
}
}

49
Java Lab File CSX-351 17103060

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 from run(). Put a
start-up message in the constructor and override finalize() to print a shut down message.
Make a separate thread class that calls System.gc() and System.runFinalization() inside
run(), printing a message as it does so. Make several thread objects of both types and run
them to see what happens.
import java.lang.*;
class NewThread2 extends Thread{
NewThread2(){
start();
}
public void run(){
System.out.println("Starting garbage collector");
System.gc();

System.out.println("Runing finalization method");


System.runFinalization();
}

}
class NewThread extends Thread{
NewThread(){
System.out.println("New thread starting");
start();
}
public void run(){
for(int i=0;i<3;i++){
System.out.println("Iteration "+i);
try {
Thread.sleep(1000);
}
catch (InterruptedException e){
System.out.println("Error");
}
}
// finalize();
}
public void finalize(){
System.out.println("Thread is completed and destroyed");

50
Java Lab File CSX-351 17103060
}
}
public class Q1 {
public static void main(String[] args){
NewThread t =new NewThread();
new NewThread();
new NewThread2();
new NewThread();
new NewThread2();
new NewThread();
}
}

4.Inter thread communication by using notify() and wait() methods


class thread1 extends Thread {
public void run()
{
synchronized(this)
{
System.out.println
(Thread.currentThread().getName() +
"...starts");
try {
this.wait();
}
catch (InterruptedException e) {
e.printStackTrace();

51
Java Lab File CSX-351 17103060
}
System.out.println
(Thread.currentThread().getName() +
"...notified");
}
}
} class thread2 extends Thread {
thread1 t;
thread2(thread1 t)
{
this.t = t;
}
public void run()
{
synchronized(this.t)
{
System.out.println
(Thread.currentThread().getName() +
"...starts");

try {
this.t.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println
(Thread.currentThread().getName() +
"...notified");
}
}
} class thread3 extends Thread {
thread1 t;
thread3(thread1 t){
this.t = t;
}
public void run(){
synchronized(this.t)
{
System.out.println
(Thread.currentThread().getName() + "...starts");

this.t.notifyAll();
System.out.println
(Thread.currentThread().getName() + "...notified");
}
}
} class Q2 {
public static void main(String[] args) throws InterruptedException
{

52
Java Lab File CSX-351 17103060
thread1 t = new thread1();
thread2 t2 = new thread2(t);
thread3 t3 = new thread3(t);
Thread T1 = new Thread(t, "Thread-1");
Thread T2 = new Thread(t2, "Thread-2");
Thread T3 = new Thread(t3, "Thread-3");
T1.start();
T2.start();
Thread.sleep(100);
T3.start();
}
}

5.There are two processes, a producer and a consumer, that share a common buffer
with a limited size. The producer “produces” data and stores it in the buffer, and
the consumer “consumes” the data, removing it from the buffer. Having two
processes that run in parallel, we need to make sure that the producer won’t put
new data in the buffer when the buffer is full nad the consumer won’t try to
remove data from the buffer if the buffer is empty.

import java.util.LinkedList;

public class Q3
{
public static void main(String[] args) throws
InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
53
Java Lab File CSX-351 17103060
}
}
});
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC
{
LinkedList<Integer> list = new LinkedList<>();
int capacity = 5;
public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
while (list.size()==capacity)
wait();
System.out.println("Producer produced-" +
value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
while (list.size()==0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-" +
val);

54
Java Lab File CSX-351 17103060
notify();
Thread.sleep(1000);
}
}
}
}

55
Java Lab File CSX-351 17103060
Assignment 08

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;
import java.awt.Color;

public class Q4 extends Applet{

public void paint(Graphics g) //to draw something in the


applet window
{
g.drawString("Hey There, I am an Applet ! ",150,150);
g.drawString("By Prabhat Chand Sharma",500,200);
}
}

2.Wrte an applet program that asks the user to enter two floating point numbers and
draws their sum, difference, product and division.
Note : Use PARAM tag for user input.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class Q2 extends Applet{

public void paint(Graphics g)


{
float x, y;
x = 0;
56
Java Lab File CSX-351 17103060
y = 0;
x = Float.valueOf(getParameter("xvalue"));
y = Float.valueOf(getParameter("yvalue"));
float sum = x + y;
String msg = "The sum of the given numbers is: " + sum;
g.drawString(msg,10,30);
msg = "";
float mult = x * y;
msg = "The multiplication of given numbers is: " + mult;
g.drawString(msg,10,50);
msg = "";
float diff = x - y;
msg = "The difference of given numbers is: " + diff;
g.drawString(msg,10,70);
}
}

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

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

public class Q3 extends Applet{


public void paint(Graphics g) //to draw something in the
applet window
{
g.drawString(" ****************** ",160,150);
g.drawString(" ****************** ",180,170);
g.drawString(" ****************** ",160,190);

57
Java Lab File CSX-351 17103060
g.drawString(" ****************** ",180,310);
}
}

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.Graphics;
import java.awt.Color;

public class Q4 extends Applet{

public void init()


{
setBackground(Color.RED);
setForeground(Color.BLUE);
showStatus("Colors and colors ");
}

public void paint(Graphics g) //to draw something in the


applet window
{
g.drawString(" Applet program to set foreground and background
colors ! ",150,150);
}
}

58
Java Lab File CSX-351 17103060

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

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class Q5 extends Applet{
public void paint(Graphics g) //to draw something in the
applet window
{
g.drawString(" getCodeBase() and getDocumentBase() functions!
",150,150);
String code = getCodeBase().toString();
String doc = getDocumentBase().toString();
g.drawString(" Code url: " + code , 150,180);
g.drawString(" Document Base: " + doc, 150,210);
}
}

59
Java Lab File CSX-351 17103060
Assignment 09
1. Write an applet to print the message of click , enter, exit , press and release messages
when respective Mouse event happens in the applet and print dragged and moved when
respective moue motion event happens int the applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Q1 extends Applet implements MouseListener,


MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
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();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{
60
Java Lab File CSX-351 17103060
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
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)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}

2.Write an applet to print the message implementing KeyListener 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 Q2 extends Applet implements KeyListener


{
String msg = " ";
int mouseX = 100, mouseY = 100;
public void init()
{
setBackground(Color.pink);
addKeyListener(this);
61
Java Lab File CSX-351 17103060
requestFocus();
}
public void keyTyped(KeyEvent ke)
{
char c = ke.getKeyChar();
msg += "Char Typed: ";
msg += c;
repaint();
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key pressed ");
}
public void keyReleased(KeyEvent ke)
{
showStatus(" Key Released ");
}

public void paint(Graphics g)


{
g.drawString(msg, mouseX, mouseY);
}
}
/*
<html>
<body>
<applet code ="Q2" width = 900 height = 640>
</applet>
</body>
</html>
*/

3.Write an applet to print the message extending KeyAdapter class in Inner class and
Anonymous Inner class. Also show the status of key press and release in status window.
import java.awt.*;

62
Java Lab File CSX-351 17103060
import java.awt.event.*;
import java.applet.*;

public class Q4 extends Applet


{
public void init()
{
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent ke)
{
showStatus("Key Pressed");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
});
requestFocus();
}
public void paint(Graphics g)
{
g.drawString(msg,100,200);
}
}

4.Write an applet demonstrating some virtual key codes i.e. Function keys, Page Up, Page
Down and arrow keys. To demonstrate only print the message of the key pressed. Also
show the status of key press and release .
import java.awt.*;
import java.awt.event.*;
63
Java Lab File CSX-351 17103060
import java.applet.*;

public class Q5 extends Applet implements KeyListener


{
String msg = " ";
int mouseX = 100, mouseY = 100;
public void init()
{
setBackground(Color.pink);
addKeyListener(this);
requestFocus();
}
public void keyTyped(KeyEvent ke)
{
char c = ke.getKeyChar();
msg += "Char Typed: ";
msg += c;
repaint();
}
public void keyPressed(KeyEvent ke)
{
int k = ke.getKeyCode();
switch(k)
{
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;
}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus(" Key Released ");
}

public void paint(Graphics g)


64
Java Lab File CSX-351 17103060
{
g.drawString(msg, mouseX, mouseY);
}
}
/*
<html>
<body>
<applet code ="Q5" width = 900 height = 640>
</applet>
</body>
</html>
*/

Assignment 10
65
Java Lab File CSX-351 17103060
1. Using AWT controls and event handling, implement a basic calculator
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="Q1" width=500 height=300>
</applet>
*/

public class Q1 extends Applet


implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init(){
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++){
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
add(b[i]);
add(add);
add(sub); add(mul); add(div);
add(mod); add(clear); add(EQ);
for(int i=0;i<10;i++)
b[i].addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
String str =a e.getActionCommand();
char ch = str.charAt(0);
if ( Character.isDigit(ch)){
66
Java Lab File CSX-351 17103060
t1.setText(t1.getText()+str);
else
if(str.equals("add")){
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub")){
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul")){
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div")){
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod")){
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ")){
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
t1.setText("");
}
}

67
Java Lab File CSX-351 17103060

68

You might also like