0% found this document useful (0 votes)
11 views55 pages

Object Oriented Programming Lab Record

This document is a lab record book submitted by Gulshan Kumar to Dr. Madhuri R. Kagale for the course Object Oriented Programming - LAB. The record book contains 40 programs completed by the student over the course of the semester, with brief 1-3 sentence descriptions of each program. The programs cover topics like odd-even checks, arithmetic operations, string manipulation, pattern printing, prime number checks, object-oriented concepts like classes, interfaces, inheritance and polymorphism, exceptions, threads, applets and more.

Uploaded by

rr3870044
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views55 pages

Object Oriented Programming Lab Record

This document is a lab record book submitted by Gulshan Kumar to Dr. Madhuri R. Kagale for the course Object Oriented Programming - LAB. The record book contains 40 programs completed by the student over the course of the semester, with brief 1-3 sentence descriptions of each program. The programs cover topics like odd-even checks, arithmetic operations, string manipulation, pattern printing, prime number checks, object-oriented concepts like classes, interfaces, inheritance and polymorphism, exceptions, threads, applets and more.

Uploaded by

rr3870044
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LAB RECORD BOOK 2022-2023

Submitted To: Dr. Madhuri R. Kagale

Department of Computer Science


School of Computer Science

CENTRAL UNIVERSITY OF KARNATAKA

GULSHAN KUMAR
REG. NO.: 22PGMCA15
Object Oriented Programming - LAB
Course Code: PCATC20007
MCA 2nd Semester
Object Oriented Programming

Sl. No Content Page No Remarks


1 (To check ODD-EVEN using Scanner object and
4
if-else)
2 (Arithmetic operation on floating point Numbers) 5
3 (Printing the Strings, input by command
6
line argument)
4 (To read the integer and float through Console) 7
5 Printing Pattern 8
6 (To check number is prime or not) 9
7 (To print the grade based on the given condition) 10
8 (To calculate the area of the rectangle) 11
9 (To print the user choice by Switch case) 12-14
10 (To calculate the volume of cuboid) 14
11 (To print the multiplication table using do-while) 15
12 (To print “2 to the power -n || n || 2 to power n”
16
using for and if-else)
13 (To print largest of two number using nested classes)18
14 (To print the total even and total odd numbers
18
from an array)
15 (To demonstrate the use of length(), equals() and
19
charAt() methods)
16 (To demonstrate the user defined mul() and
20
divide() methods)
17 (To read the string char by char and appending these
21
chars to StringBuffer obj through while loop)
18
19 (To sort the array using Bubble sort) 22
20 To demonstrate the various String methods like
toLowerCase(), toUpperCase(), replace('A','Q'), 23
trim() and equals() methods)
21 (To assign the values in Vector list through
Command line argument and then inserting element 24
to this list using insertElementAt("Cobol",2))
22 (To calculate the Simple interest when Principal
25
amt, Interest Rate and no of year is given)

Central University Of Karnataka


1
Object Oriented Programming

23 (To implement the interface ‘Polygon’ and calculate


the area of Rectangle using getArea() {user defined} 26
method)
24 (To implement the interface ‘Language’ and concate
the other string using getName() {user defined} 27
method)
25 (To implement the interface ‘Polygon’ having
getArea() and getSides() and also to override the
27-28
getSides() of Polygon in Rectangle class which is
implementing the Polygon )
26 (To calculate the Area and Perimeter of a triangle
28
implement the Polygon interface to Triangle class)
27 (To demonstrate the use of super keyword to invoke
30
super class method)
28 (To peform the basic arithmetic operations) 30-32
29 (To access the classes and their methods of different
32
program under same Package)
30 (To create an array of objects of class Balance,
initializing these objects through constructor and
33
Balance class is defined in another program under
same Package)
31 (To demonstrate the ArithmeticException in java) 34
32 (To demonstrate the use of multiple catch block
{with ArithmeticException 35
anArrayIndexOutOfBoundsException})
33 (To demonstrate the use of nested try blocks) 35-37
34 (To demonstrate the use of finally keyword) 37
35 (Creating Thread extending Thread class and using
38-40
its methods like yield(), sleep() and stop())
36 (Creating Thread implementing Runnable Interface) 40
37 (To draw the rectangle on applet using drawRect()
41
method)
38 (To display the string on applet using drawstring()
42
by extending Applet class )
39 (To creating a fillColor class extending Applet using
43
setColor())
40 (To display the image in applet window using
45
getImage() and drawImage() methods)
2
Central University of Karnataka
Object Oriented Programming
41 (To draw the different shapes like line, Oval and
rectangle on Applet using darwLine(), drawOval(), 46-48
drawRect() methods)
42
43 (To display the animation/image position shifting) 48-50
44 (To demonstrate the KeyListener interface for
Showing which key pressed.e.g. Key pressed or Key 50
Released)
45 (To demonstrate the MouseMotionListener interface
to 52
paint the screen by mouse dragging)
46 (For showing the string in TextField on button click
in 54-55
applet by implementing ActionListener interface)

Central University Of Karnataka


3
Object Oriented Programming

1. Check_even.java
(To check ODD-EVEN using Scanner object and if-else)
import [Link].*;
public class Check_Even {
public static void main(String[] args) {

Scanner sc=new Scanner([Link]);


[Link]("Enter a Number : ");
int n=[Link]();
if(n%2==0) {
[Link]("Even Number");
}
else {
[Link]("Odd Numeber");
}

Output:

4
Central University of Karnataka
Object Oriented Programming

2. [Link]
(Arithmetic operation on floating point Numbers)
import [Link];
public class FloatPoint {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
[Link]("Enter 1st Number : ");
double a=[Link]();
[Link]("Enter (+,-,*,/,%) Symbol : ");
char operator=[Link]().charAt(0);
[Link]("Enter 2nd Number : ");
double b=[Link]();
double result;
switch(operator) {
case '+':
result= a+b;
[Link]("Sum : "+result);
break;
case '-':
result= a-b;
[Link]("Sub : "+result);
break;
case '*':
result= a*b;
[Link]("Multi : "+result);
break;
case '/':
result= a/b;
[Link]("Div : "+result);
break;
case '%':
result= a%b;
[Link]("Rem : "+result);
break;
default:
[Link]("Please Enter Valid Input");
}
[Link]("Do you want to Continue(1/0)? : ");
con=[Link]();
}
}

Central University Of Karnataka


5
Object Oriented Programming

Output:

3. [Link]
(Printing the Strings, input by command line argument)
public class ComLineTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i=0;i<[Link];i++) {
[Link](args[i]);
}

Output:

6
Central University of Karnataka
Object Oriented Programming

4. [Link]
(To read the integer and float through Console)
import [Link];
public class Reading {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Integer Value : ");
int a=[Link]();
[Link]("You entered Integer Value : "+a);
[Link]("Enter Float Value : ");
float b=[Link]();
[Link]("You entered Float Value : "+b);

Central University Of Karnataka


7
Object Oriented Programming

Output:

5. [Link]
(To print the pattern like):
1
22
333
4444
55555
666666
7777777
88888888
999999999
import [Link];
public class Displaying {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Number of Rows : ");
8
Central University of Karnataka
Object Oriented Programming
int n=[Link]();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
[Link](i+" ");
}
[Link]();
}

Output:

6. [Link]
(To check number is prime or not)
import [Link];
public class Prime {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Number : ");
int n=[Link]();
boolean isPrime=true;
if(n==1 || n<1) {
isPrime=false;
}
else {
for(int i=2;i<=(n/2);i++) {
if(n%i==0) {
isPrime=false;
break;
}
}
}
if(isPrime==true) {
Central University Of Karnataka
9
Object Oriented Programming

[Link](n+ " is Prime Number");


}
else {
[Link](n+ " is Not Prime Number");
}

Output:

7. [Link]
(To print the grade based on the given condition)
import [Link].*;
public class Grade {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Student Name : ");
String name=[Link]();
[Link]("Enter Roll Number : ");
String roll=[Link]();
[Link]("Enter Number of Subject for Calculate Grade : ");
int nsub=[Link]();
double marks[]=new double[nsub];
double total=0.0;
for(int i=0;i<nsub;i++) {
10
Central University of Karnataka
Object Oriented Programming
[Link]("Enter %d Subject Marks : ",(i+1));
marks[i]=[Link]();
total+=marks[i];
}
double per=(total/nsub);
[Link]("Student Name : "+name);
[Link]("Student's Roll No : "+roll);
[Link]("Total Marks Scored : "+total);
[Link]("Percentage : "+per);
if(per>=80 && per<=100) {
[Link]("A++ Grade");

}
else if(per>=60 && per<80) {
[Link]("A Grade");
}
else if(per>=50 && per<60) {
[Link]("B++ Grade");
}
else if(per>=45 && per<50) {
[Link]("B Grade");
}
else if(per>=40 && per<45) {
[Link]("C++ Grade");
}
else if(per>=33 && per<40) {
[Link]("C Grade");
}
else {
[Link]("Fail");
}
}

Output:

Central University Of Karnataka


11
Object Oriented Programming

8. [Link]
(To calculate the area of the rectangle)
import [Link];
public class RectangleArea {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Length of Rectangle : ");
double l=[Link]();
[Link]("Enter Breadth of Rectangle : ");
double b=[Link]();
double area=(l*b);
[Link]("Area of Rectagle : "+area);
}

Output:

9. [Link]
(To print the user choice by Switch case)
import [Link].*;
public class ExSwitch {

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


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
[Link]("Enter 1st Value : ");
double a=[Link]();
[Link]("Enter 2nd Value : ");
double b=[Link]();

[Link]("[Link]\[Link]\[Link]\n4.D ivisi
on\[Link]\[Link]\nEnter Choice : ");
int choice=[Link]();
double result;
switch(choice) {
case 1:
12
Central University of Karnataka
Object Oriented Programming
result=a+b;
[Link]("Addition : "+result);
break;
case 2:
result=a-b;
[Link]("Subtraction : "+result);
break;
case 3:
result=a*b;
[Link]("Multiplication : "+result);
break;
case 4: {
try {
result=a/b;
[Link]("Division : "+result);
} catch(Exception e) {
[Link]("Can't be divide by zero");
}
break;
}
case 5:
result=a%b;
[Link]("Remainder : "+result);
break;
case 6:{
[Link]("Exit...");
[Link](0);
}

}
[Link]("\nDo you want to continue(1/0)? : ");
con=[Link]();
}

Output:

Central University Of Karnataka


13
Object Oriented Programming

10. [Link]
(To calculate the volume of cuboid)
import [Link];
public class VolCuboid {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Length of Cuboid : ");
double l=[Link]();
[Link]("Enter Breadth of Cuboid : ");
double b=[Link]();
[Link]("Enter Height of Cuboid : ");
double h=[Link]();
double area=2*(l*b + b*h + h*l);
14
Central University of Karnataka
Object Oriented Programming
[Link]("Area of Cuboid : "+area);
}

Output:

11. [Link]
(To print the multiplication table using do-while)
import [Link];
public class DowhileTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter a Number : ");
int n=[Link]();
int i=1;
do {
[Link](n+" * "+i+" = "+n*i);
i++;
}while(i<=10);

}
}

Output:

Central University Of Karnataka


15
Object Oriented Programming

12. [Link]
(To print “2 to the power -n || n || 2 to power n” using for and if-else)
import [Link].*;
public class ForTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
[Link]("Enter Number N : ");
int n=[Link]();
[Link]("1. 2 to the power of N \n2. 2 to the power of - N\n3. N to the power of
2\n4. N to the power of -2\[Link]\nPress Any Option : ");
int choice=[Link]();
if(choice==1) {
[Link]([Link](2, n));
}
else if(choice==2) {
[Link]([Link](2, (-n)));
}
else if(choice==3) {
[Link]([Link](n, 2));
}
else if(choice==4) {
[Link]([Link](n, -2));
}
else if(choice==5) {
[Link](0);
}
else {
[Link]("Please Press Valid Key!!!");
}
[Link]("\nDo you want to continue(1/0 )");
con=[Link]();
}
}

Output:
16
Central University of Karnataka
Object Oriented Programming

13. [Link]
(To print largest of two number using nested classes)
import [Link];

class CheckGreter {
class Check {
Scanner sc = new Scanner([Link]);
int a;
int b;

Central University Of Karnataka


17
Object Oriented Programming

public Check() {
[Link]("Enter 1st Value : ");
a = [Link]();
[Link]("Enter 2nd Value : ");
b = [Link]();
if (a > b) {
[Link]("1st Value is Greater");
} else {
[Link]("2nd Value is Greater");
}
}
}
}

public class NestingJava {


public static void main(String[] args) {
[Link] check = new CheckGreter().new Check();
}
}

Output:

14. [Link]
(To print the total even and total odd numbers from an array)
import [Link].*;
public class TotalEvenOdd {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Value of N : ");
int n=[Link]();
[Link]("Even\t\tOdd\n----------------------");
for(int i=1;i<=n;i++) {
if(i%2==0) {
[Link](i+"\t|");
}
else {
[Link]("\t|\t"+i);
}
}
18
Central University of Karnataka
Object Oriented Programming
[Link]("--------------------------------");
}

Output:

15. [Link]
(To demonstrate the use of length(), equals() and charAt() methods)
import [Link].*;
public class StringDemo {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
// (To demonstrate the use of length(), equals() and charAt() methods)
[Link]("Enter 1st String : ");
String str1=[Link]();
int len=[Link]();
[Link]("Length : "+len);
[Link]("\nEnter 2nd String : ");
String str2=[Link]();
//check str1 is equals or not
boolean check=[Link](str2);
[Link]("Equals : "+check);
[Link]("\nEnter Index to find Character in 1st String : ");
int index=[Link]();

Central University Of Karnataka


19
Object Oriented Programming

char find=[Link](index);
[Link]("Character at %d in %s : %c",index,str1,find);

Output:

16. [Link]
(To demonstrate the user defined mul() and divide() methods)
import [Link].*;

class Operation {
Scanner sc = new Scanner([Link]);
int a;
int b;

public Operation() {
[Link]("Enter 1st Value : ");
a = [Link]();
[Link]("Enter 2nd Value : ");
b = [Link]();
}

void mul() {
[Link]("Multiplication : "+a * b);
}

void div() {
[Link]("Division : "+a / b);
}
}

public class MathOperation {

public static void main(String[] args) {


20
Central University of Karnataka
Object Oriented Programming
// TODO Auto-generated method stub
Operation obj = new Operation();
[Link]();
[Link]();
}

}
Output:

17. [Link]
(To read the string char by char and appending these chars to StringBuffer obj
through while loop)
import [Link];

public class {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter a string: ");
String str = [Link]();

StringBuffer sb = new StringBuffer();

int i = 0;
while (i < [Link]()) {
char c = [Link](i);
[Link](c);
i++;
}

[Link]("The string is: " + [Link]());


}

}
Output:

Central University Of Karnataka


21
Object Oriented Programming

19. [Link]
(To sort the array using Bubble sort)
import [Link].*;
public class Sort {
public static void Sorting(int a[],int n) {
for(int i=0;i<n;i++) {
for(int j=0;j<n-i-1;j++) {
if(a[j]>a[j+1]) {
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
public static void arrayPrint(int a[],int n) {
for(int i=0;i<n;i++) {
[Link](a[i]+" ");
}
}

public static void main(String[] args) {

// TODO Auto-generated method stub


Scanner sc=new Scanner([Link]);
[Link]("Enter Lenght of Array : ");
int n=[Link]();
int a[]=new int[n];
[Link]("Enter Array Elements : ");
for(int i=0;i<n;i++) {
a[i]=[Link]();
}
[Link]("Array Element Before Sorting : \n");
arrayPrint(a,n);
Sorting(a,n);
[Link]("\nArray Element After Sorting : \n");
arrayPrint(a,n);

}
}

Output:

22
Central University of Karnataka
Object Oriented Programming

20. [Link]
(To demonstrate the various String methods like toLowerCase(), toUpperCase(),
replace('A','Q'), trim() and equals() methods)
import [Link].*;
public class StringMethods {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("Enter String to Convert Lower Case : ");
String str=[Link]();
[Link]("Lower Case : "+[Link]());
[Link]("Enter String to Convert Upper Case : ");
str=[Link]();
[Link]("Upper Case : "+[Link]());
[Link]("Enter String to To Replace 'A' to 'Q' : ");
str=[Link]();
[Link]("To Replace 'A' to 'Q': " + [Link]('A', 'Q'));
[Link]("Enter String to To trim() : ");
str = [Link]();
[Link]("Trim : " + [Link]());
[Link]("Enter 1st String : ");
str=[Link]();
[Link]("Enter 2nd String to check equals or not : ");
String str2=[Link]();
[Link]("To check equals : "+[Link](str2));
}

Output:

Central University Of Karnataka


23
Object Oriented Programming

21. [Link]
(To assign the values in Vector list through Command line argument and then
inserting element to this list using insertElementAt("Cobol",2))
import [Link];

public class LanguageVector {


public static void main(String[] args) {
// Create a new Vector
Vector<String> languages = new Vector<>();

// Assign values to the Vector using command line arguments


for (int i = 0; i < [Link]; i++) {
[Link](args[i]);
}

// Insert a new element at index 2


[Link]("Cobol", 2);

// Print the contents of the Vector


[Link]("Languages:");
for (String language : languages) {
[Link](language);
}
}
}
Output:

24
Central University of Karnataka
Object Oriented Programming

22. [Link]
(To calculate the Simple interest when Principal amt, Interest Rate and no of year
is given)

import [Link].*;
public class SimpleInterest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Principle : ");
double p=[Link]();
[Link]("Enter Rate : ");
double r=[Link]();
[Link]("Enter Time : ");
double t=[Link]();
double interest=(p*r*t)/100;
[Link]("Simple Interest : "+interest);
[Link]("\nAmmount(Principle + Interest) : "+(p+interest));
}
}

Output:

Central University Of Karnataka


25
Object Oriented Programming

23. [Link]
(To implement the interface ‘Polygon’ and calculate the area of Rectangle using
getArea() {user defined} method)
import [Link].*;
interface polygon{
Scanner sc=new Scanner([Link]);
void getInput();
}
class Area implements polygon{
double l,b,area;
public void getInput() {
[Link]("Enter Length of Rectangle : ");
l=[Link]();
[Link]("Enter Breadth of Rectangle : ");
b=[Link]();
}
void getArea() {
getInput();
[Link]("Area of Rectangle : "+(l*b));
}
}
public class Interface1 {

public static void main(String[] args) {


Area obj=new Area();
[Link]();
}
}
Output:

24. [Link] (To implement the interface ‘Language’ and concate the other
string using getName() {user defined} method)
import [Link].*;
interface Language{
Scanner sc=new Scanner([Link]);
void getName();
}
class Concate implements Language{
String s1,s2;
public void getName() {
26
Central University of Karnataka
Object Oriented Programming
[Link]("Enter 1st String : ");
s1=[Link]();
[Link]("Enter 2nd String : ");
s2=[Link]();
}
void getConcate() {
getName();
String s3=s1+" "+s2;
[Link]("String Concatanation : "+s3);
}
}
public class Interface2 {

public static void main(String[] args) {


Concate obj=new Concate();
[Link]();
}
}

Output:

25. [Link]
(To implement the interface ‘Polygon’ having getArea() and getSides() and also to
override the getSides() of Polygon in Rectangle class which is implementing the
Polygon )
import [Link];
interface Polygon {
double getArea();
int getSides();
}

class Rectangle implements Polygon {


private double length;
private double width;

public Rectangle(double length, double width) {


[Link] = length;
[Link] = width;
}

@Override
public double getArea() {

Central University Of Karnataka


27
Object Oriented Programming

return length * width;


}

@Override
public int getSides() {
return 4;
}
}

public class Interface3 {


public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("Enter Length : ");
double l=[Link]();
[Link]("Enter Breadth : ");
double b=[Link]();
Rectangle rectangle = new Rectangle(l, b);
[Link]("Area of rectangle: " + [Link]());
[Link]("Number of sides of rectangle: " + r [Link]());
}
}

Output:

26. [Link]
(To calculate the Area and Perimeter of a triangle implement the Polygon
interface to Triangle class)
import [Link].*;
interface Polygon1{
Scanner sc=new Scanner([Link]);
void getInput();
}
class Find implements Polygon1{
double s1,s2,s3;
public void getInput() {
[Link]("Enter Value of Side-1 : ");
s2=[Link]();
[Link]("Enter Value of Side-2 : ");
s1=[Link]();
[Link]("Enter Value of Side-3 : ");
s3=[Link]();
}
void getPerimeter() {
getInput();
28
Central University of Karnataka
Object Oriented Programming
double per=(s1+s2+s3);
[Link]("Perimeter of Triangle : "+per);
}
void getArea() {

double sp=(s1+s2+s3)/2;//SemiPerimeter
double area = ([Link]((sp * ((sp - s1) * (sp - s2) * (sp - s3)))));
[Link]("Area of Triangle : "+area);
}
}
public class Interface4 {
public static void main(String[] args) {
Find obj=new Find();
[Link]();
[Link]();
}

Output:

27. [Link]
(To demonstrate the use of super keyword to invoke super class method)
import [Link].*;
class T{
void m() {
[Link]("m method from Class T");
}
}
class D extends T{
void m() {
super.m();//Super Keyword is used to call super class,method,variable
[Link]("m method from Class D");
}

}
public class UseOfSuper {

public static void main(String[] args) {


D obj=new D();
obj.m();

Central University Of Karnataka


29
Object Oriented Programming

Output:

28. [Link]
(To peform the basic arithmetic operations)
import [Link].*;
public class BasicCalculator {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
[Link]("Enter 1st Value : ");
double a=[Link]();
[Link]("Enter (+,-,*,/,%) Operator : ");
char operator=[Link]().charAt(0);
[Link]("Enter 2nd Value : ");
double b=[Link]();
double result;
switch(operator) {
case '+':
result=(a+b);
[Link]("Sum : "+result);
break;
case '-':
result=(a-b);
[Link]("Sub : "+result);
break;
case '*':
result=(a*b);
[Link]("Multi : "+result);
break;
30
Central University of Karnataka
Object Oriented Programming
case '/':
result=(a/b);
[Link]("Div : "+result);
break;
case '%':
result=(a%b);
[Link]("Rem : "+result);
break;
default:
[Link]("Please Enter Valid Input");
}//end switch
[Link]("\nDo you want to continue(1/0)? : ");
con=[Link]();
}
}

Output:

29. [Link]
(To access the classes and their methods of different program under same
Package)
package [Link];

public class PackageInto {

public void info() {


[Link]("Name : Manish Kumar");
[Link]("Package : [Link]");
[Link]("Class : PackageInto");
[Link]("File Name : [Link]");
Central University Of Karnataka
31
Object Oriented Programming

package [Link];
public class PackageCall {

public static void main(String[] args) {

PackageInto obj=new PackageInto();


[Link]();

Output :

30. [Link] (To create an array of objects of class Balance, initializing


these objects through constructor and Balance class is defined in another program
under same Package)
Save : [Link]
package BalancePackage;

public class Balance {


private double amount;

public Balance(double amount) {


[Link] = amount;
}

public double getAmount() {


return amount;
}
}

Save : [Link]
32
Central University of Karnataka
Object Oriented Programming
package BalancePackage;
public class PackageProgram2 {
public static void main(String[] args) {
int arraySize = 5;
Balance[] balances = new Balance[arraySize];
balances[0] = new Balance(100.0);
balances[1] = new Balance(200.0);
balances[2] = new Balance(300.0);
balances[3] = new Balance(400.0);
balances[4] = new Balance(500.0);
for (int i = 0; i < arraySize; i++) {
[Link]("Balance " + (i + 1) + ": " + balances[i].getAmount());
}

}
}

Output :

31. [Link]
(To demonstrate the ArithmeticException in java)
import [Link].*;
public class DivByZero {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner sc=new Scanner([Link]);
[Link]("Enter Dividend : ");
double a=[Link]();
[Link]("Enter Divisor : ");
double b=[Link]();
try {
if(b==0) {
throw new ArithmeticException("Division by zero");

}
[Link]("Quotient : "+(a/b));
}
catch(Exception e) {
[Link]([Link]());
}

}
Central University Of Karnataka
33
Object Oriented Programming

Output :

32. [Link] (To demonstrate the use of multiple catch block {with
ArithmeticException and ArrayIndexOutOfBoundsException})
public class MultiCatch {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3 };
int index = 4;

try {
int result = numbers[0] / numbers[1];
[Link]("Result: " + result);

// Access an array element


[Link]("Value at index " + index + ": " + numbers[index]);
} catch (ArithmeticException e) {
[Link]("ArithmeticException: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: " + [Link]());
} catch (Exception e) {
[Link]("Generic Exception: " + [Link]());
}

[Link]("After try-catch block.");


}
}

Output :

34
Central University of Karnataka
Object Oriented Programming

33. [Link]
(To demonstrate the use of nested try blocks)
import [Link].*;
public class NestedTry {

public static void main(String[] args) {


Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
try { //Outer try block
[Link]("Enter Length of Array : ");
int n=[Link]();
int a[]=new int[n];
for(int i=0;i<[Link];i++) {
[Link]("Enter "+i+" Value : ");
a[i]=[Link]();
}
[Link]("Array Elements : \n");
[Link]("Enter Index to be Print Element : ");
int x=[Link]();
for(int i=0;i<[Link];i++) {
try { //Inner try block
if(x<0) {
throw Exception("NegativeArrayIndexBoundException");
}
else if(x>=n) {
throw new Exception("ArrayIndexOutOfBoundException");
}
else {
[Link]("Element present at "+x+" th Index is : "+a[x]);
break;
}

}
catch(Exception eobj) { //Inner catch Block
[Link]([Link]());
break;
}
}

Central University Of Karnataka


35
Object Oriented Programming

}
catch(Exception eobj) { //Outer catch Block
[Link]("An error Occurred");
}
[Link]("\nDo you want to continue(1/0)? : ");
con=[Link]();
}
}

Output:

34. [Link]
(To demonstrate the use of finally keyword)
import [Link].*;
public class FinallyDemo {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
int con=1;
while(con==1) {
36
Central University of Karnataka
Object Oriented Programming
[Link]("\n\t----------DIVISION CALCULATOR--------------- -\n");
[Link]("Enter 1st Value : ");
double a=[Link]();
[Link]("Enter 2nd Value : ");
double b=[Link]();
try {
if(b==0) {
throw new Exception("Can't be divide by Zero");
}
else {
[Link]("Div : "+(a/b));
}
}
catch(Exception eobj) {
[Link]([Link]());
}
finally {
[Link]("This is Finally block,It'll Excecute Every time
\n\t\tThanku!!! ");
}
[Link]("\nDo you want to continue(1/0)? : ");
con=[Link]();
}
}
}

Output:

35. [Link] (Creating Thread extending Thread class and using its
methods like yield(), sleep() and stop())
public class MultiThread extends Thread {
Central University Of Karnataka
37
Object Oriented Programming

private boolean isRunning = true;

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);

// Using yield() method to give a chance to other threads


[Link]();

try {
// Using sleep() method to pause the thread for a specified time
[Link](1000);
} catch (InterruptedException e) {
[Link]([Link]().getName() + "
interrupted.");
}
}
}

public void stopThread() {


isRunning = false;
}

public static void main(String[] args) {


MultiThread thread1 = new MultiThread();
MultiThread thread2 = new MultiThread();

// Set names for the threads


[Link]("Thread 1");
[Link]("Thread 2");

// Start the threads


[Link]();
[Link]();

// Let the threads run for a while


try {
[Link](5000);
} catch (InterruptedException e) {
[Link]();
}

// Stop the threads


[Link]();
[Link]();
}
}

Output :

38
Central University of Karnataka
Object Oriented Programming

36. [Link] (Creating Thread implementing Runnable Interface)


public class MultiThread2 implements Runnable {
private boolean isRunning = true;

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);

// Using [Link]() to give a chance to other threads


[Link]();

try {
// Using [Link]() to pause the thread for a specified time
[Link](1000);
} catch (InterruptedException e) {
[Link]([Link]().getName() + "
interrupted.");
}
}
}

public void stopThread() {


isRunning = false;
}

public static void main(String[] args) {


MultiThread2 multiThread = new MultiThread2();

Thread thread1 = new Thread(multiThread);


Thread thread2 = new Thread(multiThread);

// Set names for the threads


[Link]("Thread 1");
[Link]("Thread 2");

Central University Of Karnataka


39
Object Oriented Programming

// Start the threads


[Link]();
[Link]();

// Let the threads run for a while


try {
[Link](5000);
} catch (InterruptedException e) {
[Link]();
}

// Stop the threads


[Link]();
}
}

Output :

37. [Link] (To draw the rectangle on applet using drawRect() method)
import [Link].*;
import [Link].*;
public class Applet38 extends Applet
{
int height,width;
public void init()
{
height=getSize().height;
width=getSize().width;
setName("Rectangle");
}
public void paint(Graphics g)
{
[Link](10,10,100,80);
}
}

40
Central University of Karnataka
Object Oriented Programming
Html file:
<!DOCTYPE html>
<html>
<head>
<title>Draw Rectangle</title>
</head>
<body><applet code="[Link]" width=300 height=400></applet>
</body>
</html>

Output:

38. Hello [Link] / [Link] (To display the string on applet using
drawstring() by extending Applet class )
import [Link].*;
import [Link].*;
public class AppletFirst extends Applet
{
int height,width;
public void paint(Graphics g)
{
[Link]("Hello World",150,100);
}
}

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="[Link]" width=300 height=200></applet>
</body>

Central University Of Karnataka


41
Object Oriented Programming

</html>

Output:

39. [Link] (To creating a fillColor class extending Applet using setColor())
import [Link].*;
import [Link].*;
public class FillColor extends Applet
{
public void paint(Graphics g)
{
[Link](200,150,200,100);
Color c= new Color(10,50,10,100);
[Link](c);
[Link](200,150,200,100);
[Link]([Link]);
[Link]("Rectangle",300,300);
}
}

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="[Link]" width=600 height=400></applet>

42
Central University of Karnataka
Object Oriented Programming
</body>
</html>

Output:

40. [Link] (To display the image in applet window using getImage()
and drawImage() methods)
import [Link].*;

Central University Of Karnataka


43
Object Oriented Programming

import [Link].*;

public class DisplayImage extends Applet


{
Image img;
public void init()
{
img= getImage(getDocumentBase(),"[Link]");
}
public void paint(Graphics g)
{
[Link](img,0,0,this);
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>Pic Apply</title>
</head>
<body>
<applet code="[Link]" width=1000 height=700></applet>
</body>
</html>
Output:

44
Central University of Karnataka
Object Oriented Programming

41. [Link]
(To draw the different shapes like line, Oval and rectangle on Applet using
darwLine(), drawOval(), drawRect() methods)

import [Link].*;
import [Link].*;
public class Shape extends Applet
{
public void paint(Graphics g)
{
[Link](85,8,280,8);
[Link]("Line",10,15);
[Link](80,50,200,100);
[Link](85,55,190,90);
[Link]("Rectagle",5,75);
//drawOval( int X, int Y, int width, int height )
[Link](50,200,150,80);

Central University Of Karnataka


45
Object Oriented Programming

[Link]([Link]);
[Link]("Oval",5,225);
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>Shapes</title>
</head>
<body>
<applet code="[Link]" width=600 height=400></applet>
</body>
</html>

Output:

46
Central University of Karnataka
Object Oriented Programming

43. [Link] (To display the animation/image position shifting)

import [Link].*;
import [Link].*;
public class AnimationExample extends Applet

Central University Of Karnataka


47
Object Oriented Programming

{
Image Pic;
public void init()
{
Pic=getImage(getDocumentBase(),"[Link]");

}
public void paint(Graphics g)
{
for(int i=0; i<100; i++)
{
[Link](Pic,i,50,this);
try
{
[Link](100);

}
catch(Exception e)
{}
}
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>motion picture</title>
</head>
<body>
<applet code="[Link]" width=1200 height=600></applet>
</body>
</html>

Output:

48
Central University of Karnataka
Object Oriented Programming

44. [Link] (To demonstrate the KeyListener interface for showing


which key pressed. e.g. Key pressed or Key Released)
//KeyListener
import [Link].*;
import [Link].*;
import [Link].*;
public class KeyEventHand extends Applet implements KeyListener
{
Central University Of Karnataka
49
Object Oriented Programming

String msg ="Hi, Manish!!! How are you???";


public void init(){
addKeyListener(this);
}
public void keyPressed(KeyEvent k){
showStatus("key pressed");
}
public void keyReleased(KeyEvent k){
showStatus("key Released");
}
public void keyTyped(KeyEvent k){
msg= msg+[Link]();
repaint();
}
public void paint(Graphics g){
[Link](msg,10,20);
}
}
HTML Code:

<!DOCTYPE html>
<html>
<body>
<applet code="[Link]" width=600 height=400></applet>
</body>
</html>
Output:

[Link] (To demonstrate the MouseMotionListener interface to


paint the screen by mouse dragging)
import [Link].*;
//import [Link];
import [Link].*;
import [Link].*;
public class MouseDragEvent extends Applet implements MouseMotionListener
50
Central University of Karnataka
Object Oriented Programming
{
public void init()
{
addMouseMotionListener(this);
setBackground([Link]);
}
public void mouseDragged(MouseEvent e)
{
Graphics g = getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}
public void mouseMoved(MouseEvent e){}
}

HTML Code :

<!DOCTYPE html>
<html>
<head>
<title>Mouse Movement</title>
</head>
<body>
<applet code="[Link]" width=600 height=400></applet>
</body>
</html>

Output:

Central University Of Karnataka


51
Object Oriented Programming

52
Central University of Karnataka
Object Oriented Programming
46. [Link] (For showing the string in TextField on button click in
applet by implementing ActionListener interface)

import [Link].*;
import [Link].*;
import [Link].*;
public class ActionEventButton extends Applet implements ActionListener
{
Button b,b2;
TextField tf;
public void init()
{
tf = new TextField();
[Link](30,40,150,20);
b=new Button("Click");
[Link](80,150,60,50);
add(b);

b2=new Button("Clear");
[Link](160,150,60,50);
add(b2);
add(tf);

[Link](this);
[Link](this);

setLayout(null);

}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b)
{
[Link]("Welcome");
}
else
[Link]("");
}
}

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="[Link]" width=600 height=400></applet>

Central University Of Karnataka


53
Object Oriented Programming

</body>
</html>

Output:

54
Central University of Karnataka

Common questions

Powered by AI

In Java applets, the KeyListener interface allows detection of keyboard events such as key presses and releases. By implementing this interface, an applet can define methods keyPressed(), keyReleased(), and keyTyped(). These methods can execute custom logic when a key event occurs. To enable these methods, the applet registers itself as a listener using the addKeyListener() method, thereby responding to keyboard interactions and allowing functionalities like dynamic input display .

In Java applets, graphical shapes can be drawn using methods from the Graphics class, such as drawRect(), fillRect() for rectangles, and drawOval() for ovals. These methods are invoked in the paint() method of an Applet class where a Graphics object is available. Changing colors can be accomplished using setColor(), and animations or changes to graphics can be performed in loops combined with repaint() to refresh the drawing .

ArithmeticException in Java occurs when an exceptional arithmetic condition has occurred, such as dividing by zero. Handling such exceptions using multiple catch blocks allows a program to catch and handle different exception types separately in a more manageable way. For example, one catch block can handle ArithmeticException while another can address ArrayIndexOutOfBoundsException, allowing the program to continue running or fail gracefully depending on the error .

Synchronized blocks in Java multithreading are crucial for ensuring that only one thread can execute a block of code at a time when multiple threads are accessing shared resources. This prevents data inconsistencies and thread interference. Within a class implementing Runnable, synchronized blocks are used to lock a particular resource or code segment, ensuring thread-safe interactions and updating of shared data, thereby maintaining integrity while improving coordination between concurrently running threads .

The Console class in Java provides a more direct interface for reading input from the console, especially useful in command-line environments, supporting password input without echoing and formatted output. However, it lacks versatility in non-console environments. Conversely, the Scanner class offers broader functionality allowing tokenized input parsing from different sources like files and streams, with extensive methods for type-specific input. While Scanner is more flexible, Console provides stronger integration with terminal-based input scenarios .

ActionListener in Java applets facilitates responding to user actions such as button clicks. By implementing the ActionListener interface in an applet, the applet must override the actionPerformed(ActionEvent e) method. For example, when a button is clicked, actionPerformed can define specific responses like updating a text field. Buttons are added to the applet and register this listener using addActionListener(), ensuring that any user interaction triggers the appropriate response .

The lifecycle of a thread in Java begins with its creation and initiation using the start() method. The thread enters the runnable state, where it can execute when CPU resources are available. The yield() method can be called to allow other threads a chance to execute, without blocking the calling thread. The sleep() method pauses the thread for a specified time, thus moving it to a non-runnable state temporarily. Contrary to modern Java practices, the stop() method is deprecated as it can lead to inconsistencies, but it was originally used to immediately terminate a thread's execution .

Implementing the Runnable interface in Java offers more flexibility than extending the Thread class because Java supports only single inheritance, meaning a class cannot extend more than one class. By implementing Runnable, a class can extend another superclass while still defining its own thread logic. Additionally, Runnable separates the thread logic from the Thread class, simplifying thread management and code organization .

Using applets to display and manipulate images involves utilizing Graphics and Image classes, with getImage() and drawImage() methods handling image acquisition and rendering. Applets allow interactive image manipulation, beneficial for educational and graphical applications. However, their performance is constrained by Java's sandbox environment and security restrictions, affecting browser compatibility and load times. Additionally, modern web standards and security policies limit applet usage, urging developers to transition to more robust solutions like JavaFX or HTML5-based graphics .

Nested try blocks in Java are used to catch exceptions at different levels of a program execution hierarchy. Each try block can have its own catch and finally blocks. When an exception is thrown in a try block, the system searches for the first matching catch block at the same level or outer levels, thus providing precision in handling exceptions at various points in nested operations .

You might also like