You are on page 1of 104

CSX-331 17103081

DR. B.R. AMBEDKAR NATIONAL INSTITUTE OF


TECHNOLOGY , JALANDHAR

ADVANCED PROGRAMMING CONCEPTS IN JAVA LAB

Submitted To : Submitted by :

Dr. Rajneesh Rani Shubham Thind


17103081
CSE

1
CSX-331 17103081

Lab 1

1. Java Installation And Path Configuration:

Follow the below steps to install java jdk and jre, and to configure the path settings of
java compiler.

1. Download the desired jdk release from the official Oracle website.
2. Follow the installation steps given in the GUI java installer.
3. After finishing installation, type the command java –version in the cmd, it will return
a valid result if the installation is successful, otherwise not.
4. Now, right click on the This PC icon, open properties, go to advanced system settings.
5. There, edit the PATH environment variable and add the path of javac, which can be
copied from the installation directory, which is in Program Files.

Click apply and ok , and we are done with the installation and configuration of path.
Now , we can successfully compile and execute java programs in the system.

Follow the steps as given in following screenshots:

2
CSX-331 17103081

3
CSX-331 17103081

4
CSX-331 17103081

Copy the path here and then click OK.

5
CSX-331 17103081

Program 2: 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.*

6
CSX-331 17103081

public class TwoNos{

public static void main(String args[]){

Scanner scanner= new Scanner(System.in);


System.out.print("Enter the first number: ");
int firstNo= scanner.nextInt();
System.out.print("\nEnter the second number: ");
int secondNo= scanner.nextInt();

if(firstNo>secondNo)
System.out.print(firstNo +" is greater");
else if(secondNo>firstNo)
System.out.print(secondNo+ " is larger");
else
System.out.print("Both numbers are equal");
}
}
Output:

7
CSX-331 17103081

Program 3: 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.

import java.util.*;

class StringArgsDemo{
public static void main(String args[]){
System.out.println("No of command line arguments passed is "+args.length);
System.out.println("Following arguments were passed");
for(String arg:args){
System.out.println(arg);
}
}
}

8
CSX-331 17103081

Program 4: Write an application to implement Pascal Triangle.


1
11
121
1331

9
CSX-331 17103081

14641
.......
.......
import java.util.*;

public class Pascal{


public static void main(String args[]){
Scanner scanner= new Scanner(System.in);
System.out.print("Enter number of rows you want to print: ");
int n= scanner.nextInt();
int i,j, value;
Factorial fact= new Factorial();
for(i=0;i<n;i++){

for(j=0;j<n-i;j++){
System.out.print(' ');
}

for(j=0;j<=i;j++){
value = fact.factorial(i)/(fact.factorial(j)*fact.factorial(i-j));
System.out.print(value+" ");
}
System.out.print("\n");
}
}

}
class Factorial{

10
CSX-331 17103081

public int factorial(int n){


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

Program 5: 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.*;
import java.lang.Math;

public class Patterns{

11
CSX-331 17103081

public static void main(String[] args){


int shape,s;
Scanner scanner= new Scanner(System.in);
int choice=1;
while(choice==1){
System.out.println("Enter shape to be printed:
\n1.Square\n2.Diamond\n3.Arrow\n4.Circle ");

shape= scanner.nextInt();
switch(shape){
case 1:
Square square= new Square();
System.out.print("Enter length of side of square: ");
s= scanner.nextInt();
square.printSquare(s);
break;

case 2:
Diamond diamond= new Diamond();
System.out.print("Enter length of side of diamond: ");
s= scanner.nextInt();
diamond.printDiamond(s);
break;

case 3:
Arrow arrow= new Arrow();
System.out.print("Enter size of arrow: ");
s= scanner.nextInt();
arrow.printArrow(s);
break;

12
CSX-331 17103081

case 4:
Circle circle= new Circle();
System.out.print("Enter radius of circle: ");
s= scanner.nextInt();
circle.printCircle(s);
break;
default:
System.out.print("Invalid choice!");
}

System.out.print("Want to continue? (y=1 / n=0)");


choice= scanner.nextInt();

}
}
}
class Square{
public void printSquare(int n){
int i,j;

for(i=0;i<n;i++){
if(i==0||i==n-1)
for(j=0;j<n;j++){
System.out.print('*');
}
else{
for(j=0;j<n;j++){
if(j==0||j==n-1)
System.out.print('*');

13
CSX-331 17103081

else
System.out.print(' ');
}
}
System.out.print('\n');
}
}
}
class Diamond{
public void printDiamond(int n){
if(n%2==0){
System.out.println("Please enter an odd number");
return;
}

int mid=n/2;
int i,j;
int cnt=mid;
int cnt2=0;
for(i=0;i<n;i++){
if(i<=mid){
for(j=0;j<n;j++){
if(j==cnt||j==n-1-cnt)
System.out.print('*');
else
System.out.print(' ');
}
cnt--;
}
else{

14
CSX-331 17103081

cnt2++;;
for(j=0;j<n;j++){
if(j==cnt2||j==n-1-cnt2)
System.out.print('*');
else
System.out.print(' ');
}

System.out.print('\n');
}
}
}
class Arrow{
public void printArrow(int n){
int mid=n/2;
int i,j;
for(i=0;i<n;i++){
if(i<mid){
for(j=0;j<mid-i-1;j++){
System.out.print(" ");
}
for(j=0;j<2*i+1;j++){
System.out.print("*");
}
}else{
for(j=0;j<n-2;j++){
if(j==mid-1)

15
CSX-331 17103081

System.out.print("*");
else
System.out.print(" ");
}
}
System.out.print("\n");
}
}
}

class Circle{
public void printCircle(int r){
double dist;
int i,j;

for(i=0;i<=2*r;i++){
for(j=0;j<=2*r;j++){
dist= Math.sqrt((i-r)*(i-r)+(j-r)*(j-r)); //distance of point from
center
if(dist>r-0.5 && dist<r+0.5)
System.out.print("*");
else
System.out.print(" ");
}
System.out.print("\n");
}
}

16
CSX-331 17103081

17
CSX-331 17103081

18
CSX-331 17103081

Lab 2
Program 1: Write an application to that asks the user to enter three integer values(2 <
n < 100) , tand 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 Pythagorean {

public static void main(String[] args){


Scanner in= new Scanner(System.in);
int a,b,c;
for(int i=0;i<2;i++){
System.out.println("Enter three numbers a,b and c: ");
a=in.nextInt();
b=in.nextInt();
c=in.nextInt();

if(a*a+b*b==c*c||a*a+c*c==b*b||b*b+c*c==a*a){
System.out.println("Yes it's a pythagorean triplet! ");
}else{
System.out.println("No it's not a pythagorean triplet ");

}
}

}
}

19
CSX-331 17103081

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

public static void main(String[] args) {

final float pi=(float) 3.14;


System.out.println("\nEnter the radius of the circle");
Scanner in = new Scanner(System.in);
int r = in.nextInt();

20
CSX-331 17103081

System.out.println("Diameter is " +2*r);


System.out.println("Circumference is " +2*pi*r);
System.out.println("Area is " +pi*r*r);
}
}

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

public class EmployeeDetails{


public static void main(String args[]){
int regNo,i;
ArrayList<Employee>emps= new ArrayList<Employee>();
Scanner sc= new Scanner(System.in);
int option;
int choice=1;
while(choice==1){
System.out.print("Enter option: \n1.Get employee Details\n2.Create new
employee\n3.Search employee\n4.Display all employees");
option=sc.nextInt();
switch(option){

21
CSX-331 17103081

case 1:
if(emps.size()==0){
System.out.println("No employees yet");
break;
}
System.out.println("Enter registration number of employee: ");
int reg= sc.nextInt();
for(i=0;i<emps.size();i++){
if(emps.get(i).getRegNo()==reg)
emps.get(i).getData();
}
break;
case 2:
System.out.print("Enter name, registration no and salary: ");
String name = sc.next();
regNo= sc.nextInt();
int salary =sc.nextInt();
Employee e=new Employee();
e.setData(name,regNo,salary);
emps.add(e);
break;
case 3:
System.out.print("Enter registration no of employee: ");
regNo= sc.nextInt();
Employee e1;
for(i=0;i<emps.size();i++){
if(emps.get(i).getRegNo()==regNo){
{
emps.get(i).getData();
break;

22
CSX-331 17103081

}
}
}
if(i==emps.size()){
System.out.println("Employee with given id doesn't exist");
}
break;

case 4:
for(i=0;i<emps.size();i++){
emps.get(i).getData();
}
break;
default:
System.out.println("Please enter a valid option!");
}

System.out.println("Do you want to continue? (1=yes, 0=no)");


choice=sc.nextInt();
}
}
}
class Employee{

private String name;


private int regNo;
private int salary;

23
CSX-331 17103081

void setData(String name, int regNo,int salary){


this.name=name;
this.regNo= regNo;
this.salary=salary;
}
void getData(){
System.out.println("Name: "+name +" Registration no: "+regNo+" Salary: "+salary);
}
int getRegNo(){
return regNo;
}
}

24
CSX-331 17103081

25
CSX-331 17103081

Program 4: Write an application to determine the gross pay for 3 employees. The
company pays strainght 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.

Gross pay class


import java.util.*;

class GrossPay{

public static void main(String[] args) {

Emp[] E = new Emp[3];

for(int i=1; i<=3; i++) {


int salaryPerHour;
Scanner in = new Scanner(System.in);

26
CSX-331 17103081

System.out.println("Enter the salary of the employee: ");


salaryPerHour = in.nextInt();

System.out.println("Enter the number of hours the employee worked:


");
int numberOfHours = in.nextInt();

Emp E1 = new Emp(numberOfHours, salaryPerHour);

System.out.println("Salary Got : " + E1.getSalary());


}

}
}

Employee class
import java.util.*;

class Emp {

private int numberOfHours;


private int salaryPerHour;

Emp(int n, int s) {
numberOfHours = n;
salaryPerHour = s;
}

int extraHours() {

27
CSX-331 17103081

if(numberOfHours <= 40) {


return 0;
}
return numberOfHours - 40;
}

int getSalary() {
return ((numberOfHours * salaryPerHour) + (extraHours() *
(salaryPerHour/2)));
}
}

Lab 3
Program 1: Write a program to find an element taken as the input by the user in a 2D
array.
import java.util.*;

public class Search2D{


public static void main(String[] args){

28
CSX-331 17103081

Scanner sc= new Scanner(System.in);


System.out.print("Enter number of rows and columns of 2D array: ");
int rows= sc.nextInt();
int cols=sc.nextInt();
int[][] arr=new int[rows][cols];
System.out.println("Enter elements of array: ");
int i,j;
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
arr[i][j]=sc.nextInt();
}
}
int choice=1;
while(choice==1){
System.out.println("Enter the element you want to search in the 2D
array: ");
int emt=sc.nextInt();
boolean present = false;
for(i=0;i<rows;i++){
for(j=0;j<cols;j++){
if(arr[i][j]==emt){
present=true;
break;
}
}
}
if(present==true)
System.out.println("Element found");
else
System.out.println("Element not found");

29
CSX-331 17103081

System.out.println("Want to search another element? (1=yes,0=no)");


choice=sc.nextInt();
}
}
}

Output

Program 2: 2. Write a program to implement all the functions of the String class.

i. To conver the string to lowercase letters


ii. To convert the string to uppercase letters
iii. Replace the character at the given index
iv. Check if two strings are equal
v. To find the length of the string
vi. Find the character at the given position
vii. Concatenate two strings
viii. Check if the given string is a substring of a another given string

import java.util.*;

30
CSX-331 17103081

public class StringFuncs{

public static void main(String[] args) {

Scanner in = new Scanner(System.in);


System.out.println("Enter a string: ");
String str = in.nextLine();

System.out.println("\nEnter a choice from the options below: ");


System.out.println("1. Convert to Lower case");
System.out.println("2. Convert to Upper case");
System.out.println("3. Replace a character");
System.out.println("4. Check equality");
System.out.println("5. Find length");
System.out.println("6. Find character at given index");
System.out.println("7. Concatenatation");
System.out.println("8. Check substring\n");
int option = in.nextInt();

do {

switch(option) {

case 1:
System.out.println(str.toLowerCase());
break;

case 2:
System.out.println(str.toUpperCase());

31
CSX-331 17103081

break;

case 3:
System.out.println("Enter index ");
int x = in.nextInt();
System.out.println("Enter new character ");
char ch = in.next().charAt(0);
String replace = str.substring(0, x) + ch + str.substring(x+1);
System.out.println(replace);
break;

case 4:
System.out.println("Enter another string: ");
String string = in.next();
if(str.equals(string))
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");

break;

case 5:
System.out.println("The length of string is : " + str.length());
break;

case 6:
System.out.println("Enter the index position of the character(indexing starts from 0):
");
int index = in.nextInt();
System.out.println(str.charAt(index));
break;

32
CSX-331 17103081

case 7:
System.out.println("Enter the other string to concatenate: ");
string = in.next();
String string3 = str.concat(string);
System.out.println("The final string is: "+ string3);
break;

case 8:
System.out.println("Enter the string to check as a substring: ");
String substring = in.next();
System.out.println("The given string is " );
if(str.contains(substring)) {
System.out.println("contains the substring.");
}
else {
System.out.println("doesn't contain the substring. ");
}
break;
}

System.out.println("Do you want to continue?(yes=1, no=0)");


option = in.nextInt();

}while(option != 0);
}

33
CSX-331 17103081

34
CSX-331 17103081

Program 3: A string is a double string if it has even length and half of the string is
equal to the next half of the string. Write a program to check if the given string is a
double string.

import java.util.*;

public class DoubleString{


public static void main(String[] args){
Scanner sc= new Scanner(System.in);
System.out.println("Enter a string: ");
String s=sc.next();
if(s.length()%2==0){
int mid=(0+s.length())/2;
int i,j;
boolean isDouble=true;
for(i=0,j=mid;i<mid;i++,j++){
if(s.charAt(i)!=s.charAt(j)){
isDouble=false;
break;
}
}
if(isDouble==true){
System.out.println("Double string");
}else{
System.out.println("Not a double string");
}
}else{
System.out.println("Not a double string");
}

35
CSX-331 17103081

Output

Program 4: Write a program in which you have an array of integers. Implement copy
paste which allows you to copy any continuous subsequences of array and paste it int
any position of the array.

import java.util.*;

class CopyAndPaste{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter size of array: ");
int size=sc.nextInt();
int[] arr= new int[size];
int i,j,length;
System.out.println("Enter elements of array: ");

36
CSX-331 17103081

for(i=0;i<size;i++){
arr[i]=sc.nextInt();
}
int sCopy,eCopy,sPaste;
int choice=1;
while(choice==1){
System.out.println("Enter starting and ending index for copying");
sCopy=sc.nextInt();
eCopy=sc.nextInt();
if(sCopy<0 || eCopy>=size){
System.out.println("Error: Indices out of bound ");
}else{
length=eCopy-sCopy+1;
int[] copiedArray= new int[length];
for(i=sCopy,j=0;i<=eCopy;i++,j++){
copiedArray[j]=arr[i];
}

System.out.println("Enter starting index for pasting");


sPaste=sc.nextInt();
sPaste++;
if(sPaste+length<size){
for(i=sPaste-1,j=0;i<sPaste+length-1;i++,j++){
arr[i]=copiedArray[j];
}
for(i=0;i<size;i++){
System.out.print(arr[i]+" ");
}
}
}

37
CSX-331 17103081

}
}
}
Output

38
CSX-331 17103081

Lab 4
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 package1;

public class problem1 {

public int variable1 = 1234; // accessible to other classes and other packages also

protected String variable2 = " Java is Beautiful"; // only accessible to the base
classes of class Problem1

private float variable3 = 2.345f; // not accessible outside this class

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:)");
}
// this function acts as public within this package and private outside.
}

package package1;

class problem1a extends problem1 {

39
CSX-331 17103081

private int variable = 1234;

package package1;

class problem1b extends problem1 {

public int stuff = 1000000;

private float a = 0.00023495320f;


}

package p2;

import package1.*;
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 : " + package1.problem1.variable4);
}
}

import package1.*;

40
CSX-331 17103081

class checkingPackage {

public static void main(String[] args) {

problem1 p = new problem1();


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

package package1;
import java.util.*;

class mainClass {

public static void main(String[] args) {

System.out.println("\nAccessing the problem1b(which extends the problem1)


variables and functions.");
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();
}
}

Program 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.

41
CSX-331 17103081

Student.java
Scanner sc= new Scanner(System.in);

public class Student{


public int rollNo;

public void setRollNo(){


System.out.println("Enter Roll No: ");
rollNo=sc.nextInt();
}
public int getRollNo(){
return rollNo;
}

Test.java
public class Test extends Student{
public int marks1, marks2;

public void setMarks(){


System.out.println("Enter marks in subject 1 and subject 2: ");
marks1= sc.nextInt();
marks2= sc.nextInt();
}
public int getTotalMarks(){
return marks1+marks2;
}
}

42
CSX-331 17103081

Sports.java
interface Sports{
int sportsMarks=50;
void getSportsMarks();
}
Result.java
public class Result extends Test implements Sports{

public void getSportsMarks(){


System.out.println(" ");
}

int totalResult= sportsMarks+ getTotalMarks();

public void showResult(){


System.out.println("Roll no: "+ getRollNo());
System.out.println("Marks in sports: "+ sportsMarks);
System.out.println("Marks in tests: "+ testMarks);
System.out.println("Total marks: "+totalResult);
}
}

43
CSX-331 17103081

Program 3: Write an application which takes a 1D array of the numbers 0<=n<=9 only
as input and displays the number of times n repeated most consecutively. For example :
Input : 1 2 1 1 1 5 5 2 2 3 3 5 5 5 5 4 6
Output : 4

import java.util.*;
public class Problem3 {

public static void main(String[] args){


Scanner sc= new Scanner(System.in);

System.out.println("Enter the size of array: ");


int n=sc.nextInt();

int arr[]= new int[n];

System.out.println("Enter elements of array: ");


for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}

int count=0;
int max=0;
int number=arr[0];
for(int i=0;i<n-1;i++){
if(arr[i]==arr[i+1]){
count++;
if(count>max){
max=count;

44
CSX-331 17103081

number=arr[i];
}
}
}

System.out.println("Number occuring max number of times consecutively is: "+ number);

Program 4: Write an application to store all the addition combination of the two dices
in 2D array and display as follows :

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11

45
CSX-331 17103081

6 7 8 9 10 11 12

import java.util.*;

public class TwoDicesSum{


public static void main(String[] args){
int[][] arr= new int[7][7];
int i,j;
for(i=0;i<7;i++){
for(j=0;j<7;j++){
if(i==0 && j!=0){
arr[i][j]=j;
}else if(j==0 && i!=0){
arr[i][j]=i;
}
else{
arr[i][j]=i+j;
}

if(i+j==0){
System.out.print(" ");
}
else{
System.out.print(arr[i][j]+ " ");
}

}
System.out.println('\n');
}
}

46
CSX-331 17103081

47
CSX-331 17103081

Lab 5
Program 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 p1;

public class Protection {

public int publicVariable = 2323;


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

package p1;

public class Derived extends Protection {


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

48
CSX-331 17103081

public class SamePackage {


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

package p2;
import p1.*;

public class first extends Protection {


int anyNumber = 23422;
public String anyName = "Henry Ford";
}

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

import p1.Protection;
import p1.Derived;
import p1.SamePackage;

49
CSX-331 17103081

import p2.first;
import p2.second;

class Problem1 {

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

50
CSX-331 17103081

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

Problem 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.

public class MyClass implements Interface1, Interface2{


public void show(){
System.out.println("I am the show() method!");

51
CSX-331 17103081

System.out.println("I can implement the show() methods of both interfaces alone!");


}
}

public interface Interface1 {


public void show();
}

public interface Interface2 {


public void show();
}

public class Problem2{


public static void main(String[] args){
MyClass myObject= new MyClass();

myObject.show();
}
}

52
CSX-331 17103081

Problem 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.

import area.*;
import java.util.*;

public class Problem3 {


public static void main(String[] args){
int choice=1,option;
Scanner sc= new Scanner(System.in);
while(choice==1){
System.out.println("Choose the shape to find area");
System.out.println("1.Square\n2.Circle\n3.Rectangle\n4.Ellipse ");
option= sc.nextInt();

switch(option){

case 1:
System.out.println("Enter side of square");
int side= sc.nextInt();
Square square=new Square(side);
System.out.println("Area: "+ square.squareArea());
break;

case 2:
System.out.println("Enter radius of circle ");

53
CSX-331 17103081

int r= sc.nextInt();
Circle circle= new Circle(r);
System.out.println("Area: "+circle.circleArea());
break;

case 3:
System.out.println("Enter sides of rectangle: ");
int a=sc.nextInt();
int b=sc.nextInt();

Rectangle rect= new Rectangle(a,b);


System.out.println("Area: "+rect.rectangleArea());
break;

case 4:
System.out.println("Enter length of major and minor axes of ellipse: ");
int mj=sc.nextInt();
int mn=sc.nextInt();
mj=mj/2;
mn=mn/2;
Ellipse e= new Ellipse(mj,mn);
System.out.println("Area: "+e.ellipseArea());
break;

default:
System.out.println("Enter a valid option! ");

}
System.out.println("Press 1 to continue, 0 to exit ");
choice=sc.nextInt();

54
CSX-331 17103081

}
}

package area;

public class Circle {


public double r;

public Circle(double r){


this.r=r;
}
public double circleArea(){
return 3.14*r*r;
}
}

package area;

public class Ellipse {

public double a,b;

public Ellipse(double a,double b){


this.a=a;
this.b=b;

55
CSX-331 17103081

public double ellipseArea(){


return 3.14*a*b;
}
}

package area;

public class Rectangle {


public int a,b;

public Rectangle(int a,int b){


this.a=a;
this.b=b;
}
public int rectangleArea(){
return a*b;
}
}

package area;

public class Square {


public int a;
public Square(int a){
this.a=a;
}
public int squareArea(){

56
CSX-331 17103081

return a*a;
}
}

57
CSX-331 17103081

Problem 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.

import java.util.Scanner;

import vol.*;

public class Problem4 {


public static void main(String[] args){
int choice=1,option;
Scanner sc= new Scanner(System.in);
while(choice==1){
System.out.println("Choose the shape to find volume");
System.out.println("1.Sphere\n2.Cylinder\n3.Cube\n4.Cone ");
option= sc.nextInt();

switch(option){

case 1:
System.out.println("Enter radius: ");
int r= sc.nextInt();
Sphere sphere=new Sphere(r);

58
CSX-331 17103081

System.out.println("Volume of sphere is: " + sphere.volume());


break;

case 2:
System.out.println("Enter radius and height of cylinder ");
int rs= sc.nextInt();
int ht= sc.nextInt();
Cylinder c= new Cylinder(rs,ht);
System.out.println("Volume of cylinder is "+ c.volume());
break;

case 3:
System.out.println("Enter side of cube: ");
int a=sc.nextInt();
Cube cube= new Cube(a);
System.out.println("Volume of cube is "+cube.volume());
break;

case 4:
System.out.println("Enter radius and height of cone ");
int ra=sc.nextInt();
int he=sc.nextInt();
Cone cone = new Cone(ra,he);
System.out.println("Volume of cone is "+ cone.volume());
break;

default:
System.out.println("Enter a valid option! ");

59
CSX-331 17103081

}
System.out.println("Press 1 to continue, 0 to exit ");
choice=sc.nextInt();
}
}
}

package vol;

public interface Volume {


final double pi= 3.14;
public double volume();
}

package vol;

public class Sphere implements Volume{


public int r;

public Sphere(int r){


this.r=r;
}
public double volume(){

60
CSX-331 17103081

double v= (4*pi*r*r*r)/3;
return v;
}
}

package vol;

public class Cylinder implements Volume {


public int r,h;

public Cylinder(int r, int h){


this.r=r;
this.h=h;
}
public double volume(){
return pi*r*h;
}
}

package vol;

public class Cube implements Volume{


public int a;
public Cube(int a){
this.a=a;

61
CSX-331 17103081

}
public double volume(){
return a*a*a;
}
}

package vol;

public class Cone implements Volume{


public int r,h;

public Cone(int r,int h){


this.r=r;
this.h=h;
}
public double volume(){
return (pi*r*r*h)/3;
}
}

62
CSX-331 17103081

63
CSX-331 17103081

Lab 6

Problem 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.*;
import package1.ExceptionA;
import package1.ExceptionB;
import package1.ExceptionC;

class Problem1 {

public static void main(String[] args) throws ExceptionB {

int a;
Scanner in = new Scanner(System.in);

int choice=1;
while(choice==1){
System.out.println("Enter a number: ");
a = in.nextInt();

try {

if(a == 1) {
throw new ExceptionA(a);

64
CSX-331 17103081

}
if(a == 2) {
throw new ExceptionB(a);
}
if(a == 3) {
throw new ExceptionC(a);
}

}
catch(ExceptionA eA) {
System.out.println("Caught in A");
}

System.out.println("Press 1 to continue, 0 to exit: ");


choice=in.nextInt();
}

}
}
package package1;

public class ExceptionA extends Exception {


protected int detailA;

public ExceptionA(int a) {
detailA = a;
}

public String toString() {


return "The Number is equal to " + detailA + "\n";

65
CSX-331 17103081

}
}

package package1;

public class ExceptionB extends ExceptionA {


protected int detailB;

public ExceptionB(int a) {
super(a);
detailB = a;
}

public String toString() {


return "The number is equal to " + detailB + "\n";
}
}

package package1;

public class ExceptionC extends ExceptionB {

protected int detailC;

public ExceptionC(int a) {
super(a);
detailC = a;

66
CSX-331 17103081

public String toString() {


return "the number is equal to " + detailC + "\n";
}
}

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

import package1.ExceptionA;
import package1.ExceptionB;
import package1.ExceptionC;

67
CSX-331 17103081

class Problem2 {

public static void main(String[] args) throws ExceptionB {

int a;
Scanner in = new Scanner(System.in);

int choice=1;
while(choice==1){
System.out.println("Enter a number: ");
a = in.nextInt();

try {

if(a == 1) {
throw new ExceptionA(a);
}
else if(a == 2) {
throw new ExceptionB(a);
}
else if(a == 3) {
throw new IOException("IO Exception");
}
else{
throw new NullPointerException("Null pointer");
}

}
catch(Exception e) {
System.out.println("Caught by Exception, " + e);

68
CSX-331 17103081

System.out.println("Press 1 to continue, 0 to exit: ");


choice=in.nextInt();
}

}
}

Program 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.util.*;
import package1.ExceptionA;
import package1.ExceptionB;
import package1.ExceptionC;

69
CSX-331 17103081

class Problem3 {

public static void main(String[] args) {

int a;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");

a = in.nextInt();

try {

if(a == 1) {
throw new ExceptionA(a);
}
if(a == 3) {
throw new ExceptionB(a);
}
if(a == 5) {
throw new ExceptionC(a);
}

} catch(ExceptionA eC) {
System.out.println("Caught " + eC);
}

70
CSX-331 17103081

catch(ExceptionB eB) {
System.out.println("Caught " + eB);

catch(ExceptionC eA) {
System.out.println("Caught " + eA);
}
}
}

Program 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.util.*;
class Problem4 {
static void someMethod2(int m, int n) throws ArithmeticException {
int a;
try {

71
CSX-331 17103081

a = (m-n)/(m+n);
}
finally {}
}

static void someMethod(int n, int m) throws ArithmeticException {


try {
someMethod2(n, m);
}
finally {}
}

public static void main(String[] args) {

try {
someMethod(1, -1);
} catch(ArithmeticException mE) {
System.out.println("\nException raised by : " + mE);
System.out.println("\nStack trace is shown below : \n");
mE.printStackTrace();
}
}
}

72
CSX-331 17103081

Problem 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.*;
import package5.DatePassedException;
import package5.InvalidDatesException;

class Problem5 {

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

Date issueDate = new Date(year, month, date);

System.out.println("\nEnter the Year/Month/Date for the returning date: ");

73
CSX-331 17103081

year = input.nextInt();
month = input.nextInt();
date = input.nextInt();

Date returnDate = new Date(year, month, date);

long difference = returnDate.getTime() - issueDate.getTime();

// long differenceSeconds = (difference / 1000) % 60;


// long differenceMinutes = (difference / (60 * 1000)) % 60;
// long differenceHours = (difference / (60 * 60 * 1000)) % 24;
long differenceDays = (difference / (24 * 60 * 60 * 1000));
int duration = 15;

try {
if(differenceDays < 0) {
throw new InvalidDatesException();
}

if(differenceDays > duration) {


throw new DatePassedException(differenceDays);
}

System.out.println("You can keep the book for " + (15 - differenceDays) + " more
days.\n");
}

catch(InvalidDatesException eID) {
System.out.println(eID);
}
catch(DatePassedException eDP) {

74
CSX-331 17103081

eDP.generateAndDisplayFine();
}
}
}

package package5;

public class DatePassedException extends Exception{

long differenceDays;
int finePerDay = 50;
int duration = 15;
public DatePassedException(long differenceDays) {
this.differenceDays = differenceDays;
}

public void generateAndDisplayFine() {


System.out.println("\nYou haven't returned on time.");
System.out.println("\nYou have to pay(according to Rs. " + finePerDay + "/day from
expected date of return: Rs. " );
System.out.print((differenceDays-duration) * finePerDay + "\n\n");
}
}

package package5;

public class InvalidDatesException extends Exception {

public String toString() {


return "The dates you have entered are inconsistent.\n";

75
CSX-331 17103081

}
}

76
CSX-331 17103081

Lab 7
Program 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 timese and show the output.

class NewThread extends Thread{


NewThread(String name){
super(name);
System.out.println("Thread: "+ this);
start();
}
public void run(){
try {
for(int i=0;i<5;i++) {
System.out.println(this.getName() +" :" + i);
Thread.sleep(1000);
}
}catch(InterruptedException e) {
System.out.println(this.getName() + " interrupted");
}
System.out.println(this.getName() +" finished");
}
}

public class Multithreading1{

public static void main(String[] args) {


new NewThread("First Thread");
new NewThread("Second Thread");

77
CSX-331 17103081

new NewThread("Third Thread");


}
}

Program 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().

import java.util.*;

78
CSX-331 17103081

class NewThread implements Runnable{


String name;
Thread t;

NewThread(String tname){
name=tname;
t= new Thread(this,name);
System.out.println(t.getName());
t.start();
}
public void run(){
try {
for(int i=0;i<5;i++) {
System.out.println(t.getName() +" :" + i);
Thread.sleep(1000);
}
}catch(InterruptedException e) {
System.out.println(t.getName() + " interrupted");
}
System.out.println(name +" finished");
}

public class Multithreading2 {


public static void main(String[] args) {
new NewThread("First Thread");
new NewThread("Second Thread");

79
CSX-331 17103081

new NewThread("Third Thread");

try {
Thread.sleep(10000);
}catch(Exception e) {
System.out.println("Main thread interrupted");
}
System.out.println("Main thread finished");
}
}
Output

Program 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.

80
CSX-331 17103081

class PriorityThread implements Runnable{


Thread t;
long click=0;
public volatile boolean running = true;

PriorityThread(String name,int p){


t=new Thread(this,name);
t.setPriority(p);
t.start();

public void run() {


while(running) {
click++;
}
}
public void stop() {
running=false;
}
}

public class Multithreading3 {

public static void main(String args[]) {


PriorityThread minP=new PriorityThread("Min priority",Thread.MIN_PRIORITY);
PriorityThread maxP=new PriorityThread("Max priority",Thread.MAX_PRIORITY);
PriorityThread normP=new PriorityThread("Normal
priority",Thread.NORM_PRIORITY);;

81
CSX-331 17103081

try {
Thread.sleep(10000);
}catch(InterruptedException e) {
System.out.println("Main thread interrupted");
}
minP.stop();
maxP.stop();
normP.stop();

System.out.println("Clicks count of minP: "+ minP.click);


System.out.println("Clicks count of maxP: "+ maxP.click);
System.out.println("Clicks count of normP: "+ normP.click);

System.out.println("Main thread exited");


}
}
Output

Program 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().

82
CSX-331 17103081

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.

Program 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.

Program 6. 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.

83
CSX-331 17103081

Lab 8

Program 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.

package appletdemo;

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

public class Applet1 extends Applet{


String msg;

public void init(){


msg="This is my first Applet";
setBackground(Color.green);
setForeground(Color.blue);
}
public void start(){

}
public void stop(){

}
public void destroy(){

}
public void paint(Graphics g){
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));

84
CSX-331 17103081

g.drawString(msg,10,30);
}

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

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

package appletdemo;

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

public class Applet2 extends Applet{

85
CSX-331 17103081

String msg1="**** ";


String msg2=" ****";

public void init(){


setBackground(Color.green);
setForeground(Color.black);
}
public void start(){

}
public void stop(){

}
public void destroy(){

}
public void paint(Graphics g){
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString(msg1, 10, 20);
g.drawString(msg2, 10, 40);
g.drawString(msg1, 10, 60);
g.drawString(msg2, 10, 80);
}
}

86
CSX-331 17103081

Program 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.

package appletdemo;

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

public class Applet3 extends Applet implements ActionListener{

87
CSX-331 17103081

int n1,n2,ans;

TextField t1= new TextField(10);


TextField t2= new TextField(10);
TextField plus= new TextField(5);
TextField minus= new TextField(5);
TextField mult= new TextField(5);
TextField divide= new TextField(5);

public void init(){

t2.addActionListener(this);
add(new Label("First number")); add(t1);
add(new Label("Second number")); add(t2);
add(new Label("Sum :")); add(plus);
add(new Label("Difference :")); add(minus);
add(new Label("Product :")); add(mult);
add(new Label("Difference :")); add(divide);

public void actionPerformed(ActionEvent e){


double n1= Double.parseDouble(t1.getText());
double n2= Double.parseDouble(t2.getText());

double sum= n1+n2;


double diff= n1-n2;
double prod= n1*n2;

88
CSX-331 17103081

double div= n1/n2;

plus.setText(""+sum);
minus.setText(""+ diff);
mult.setText(""+prod);
divide.setText(""+div);

public void paint(Graphics g){

Program 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.

package appletdemo;

89
CSX-331 17103081

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

public class Applet5 extends Applet{


String msg;

public void init(){


msg="Background is red and foreground is blue";
setBackground(Color.red);
setForeground(Color.blue);
}
public void start(){

}
public void stop(){

}
public void destroy(){

}
public void paint(Graphics g){
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString(msg,10,30);
}

90
CSX-331 17103081

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

package appletdemo;

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

public class Applet4 extends Applet {

public void paint(Graphics g){

g.setFont(new Font("TimesRoman", Font.PLAIN, 15));


String msg;
URL url= getCodeBase();
msg= "Code Base: "+ url.toString();
g.drawString(msg, 10, 20);

91
CSX-331 17103081

url= getDocumentBase();
msg= "Document Base: "+url.toString();
g.drawString(msg, 10, 60);

92
CSX-331 17103081

Lab 9
Program 1 : Write an applet to print the message of click, enter , exit, press, and release
when respective mouse event happens in the applet and print dragged and moved when
respective mouse motion event happens in the applet.
Note: Implement MouseListener and MouseMotionListener

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

public class Problem1 extends Applet implements MouseListener, MouseMotionListener {


String msg = "";
int mouseX = 0, mouseY = 0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) {
mouseX = 10;
mouseY = 10;
msg = "Mouse clicked inside applet";
repaint();
}

public void mouseEntered(MouseEvent me) {


mouseX = 10;
mouseY = 10;
msg = "Mouse entered applet";
repaint();
}

93
CSX-331 17103081

public void mouseExited(MouseEvent me) {


mouseX = 10;
mouseY = 10;
msg = "Mouse exited applet";
repaint();
}
public void mousePressed(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Pressed";
repaint();
}
public void mouseReleased(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Released";
repaint();
}
public void mouseDragged(MouseEvent me) {
mouseX = me.getX();
mouseY = me.getY();
msg = "Dragging";
showStatus("Dragging mouse at (x,y)= (" + mouseX + ", " + mouseY+")");
repaint();
}

public void mouseMoved(MouseEvent me) {

showStatus("Moving mouse at (x,y) = (" + me.getX() + ", " + me.getY()+")");

94
CSX-331 17103081

public void paint(Graphics g) {


g.drawString(msg, mouseX, mouseY);

}
}

Program 2 : Write an applet to print the message of click, enter , exit, press, and release
when respective mouse event happens in the applet and print dragged and moved when
respective mouse motion event happens in the applet.
Note: Implement MouseAdapter and MouseMotionAdapter
package myAdapters;

import java.applet.*;

public class AdapterDemo extends Applet{


public void init(){
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}

95
CSX-331 17103081

package myAdapters;

import java.awt.event.*;

public class MyMouseAdapter extends MouseAdapter{


AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo){
this.adapterDemo= adapterDemo;
}

public void mouseClicked(MouseEvent me){


adapterDemo.showStatus("Mouse clicked");
}
public void mouseReleased(MouseEvent me){
adapterDemo.showStatus("Mouse released");
}

public void mouseEntered(MouseEvent me){


adapterDemo.showStatus("Mouse entered");
}
public void mouseExited(MouseEvent me){
adapterDemo.showStatus("Mouse exited");
}
}

96
CSX-331 17103081

package myAdapters;

import java.awt.event.*;

public class MyMouseMotionAdapter extends MouseAdapter{


AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo){
this.adapterDemo= adapterDemo;
}

public void mouseDragged(MouseEvent me){


adapterDemo.showStatus("Mouse dragged");
}
}

Program 3: Write an applet to print the message implementing KeyListener Interface.


Also show the status of key press and release in status window.

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

97
CSX-331 17103081

public class Problem3 extends Applet implements KeyListener{


String msg="";

public void init(){


addKeyListener(this);
}

public void keyTyped(KeyEvent e) {


msg+=e.getKeyChar();
repaint();
}

public void keyPressed(KeyEvent e) {


showStatus("Key pressed");
}

public void keyReleased(KeyEvent e) {


showStatus("Key released");
}

public void paint(Graphics g){


g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString(msg,10,20);
}

98
CSX-331 17103081

Program 4: Write an applet printing 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.applet.*;
import java.awt.event.*;
import java.awt.*;

public class AnonymousInnerClassDemo extends Applet{


String msg="";
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();

99
CSX-331 17103081

}
});
}
public void paint(Graphics g){
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString(msg,10,40);
}
}

import java.applet.*;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import myAdapters.*;

public class InnerClassDemo extends Applet{


String msg="";

public void init(){


addKeyListener(new MyKeyAdapter());
}
public class MyKeyAdapter extends KeyAdapter{
public void keyPressed(KeyEvent ke){
showStatus("Key pressed");
}

public void keyReleased(KeyEvent ke){

100
CSX-331 17103081

showStatus("Key released");
}
public void keyTyped(KeyEvent ke){
msg+= ke.getKeyChar();
repaint();
}
}

public void paint(Graphics g){


g.setFont(new Font("TimesRoman", Font.PLAIN, 25));
g.drawString(msg,10,40);
}
}

101
CSX-331 17103081

Problem 5: Write an applet demonstrating some virtual key codes i.e. Function keys.
Page Up and Page Down and arrow keys. To demonstrate only print the message of the
pressed. Also show the status of key press and release.

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

public class Problem5 extends Applet implements KeyListener {


String msg = "";

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;

102
CSX-331 17103081

case KeyEvent.VK_F2:
msg += " F2 ";
break;
case KeyEvent.VK_F3:
msg += " F3 ";
break;
case KeyEvent.VK_PAGE_DOWN:
msg += " PageDown ";
break;
case KeyEvent.VK_PAGE_UP:
msg += " PageUp";
break;
case KeyEvent.VK_LEFT:
msg += " LeftArrow ";
break;
case KeyEvent.VK_RIGHT:
msg += " RightArrow";
break;
}
repaint();
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
public void paint(Graphics g) {
g.setFont(new Font("TimesRoman", Font.PLAIN, 25));

103
CSX-331 17103081

g.drawString(msg,10,40);
}
}

104

You might also like