Object Oriented Programming Lab Record
Object Oriented Programming Lab Record
GULSHAN KUMAR
REG. NO.: 22PGMCA15
Object Oriented Programming - LAB
Course Code: PCATC20007
MCA 2nd Semester
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) {
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]();
}
}
Output:
3. [Link]
(Printing the Strings, input by command line argument)
public class ComLineTest {
Output:
6
Central University of Karnataka
Object Oriented Programming
4. [Link]
(To read the integer and float through Console)
import [Link];
public class Reading {
Output:
5. [Link]
(To print the pattern like):
1
22
333
4444
55555
666666
7777777
88888888
999999999
import [Link];
public class Displaying {
Output:
6. [Link]
(To check number is prime or not)
import [Link];
public class Prime {
Output:
7. [Link]
(To print the grade based on the given condition)
import [Link].*;
public class 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:
8. [Link]
(To calculate the area of the rectangle)
import [Link];
public class RectangleArea {
Output:
9. [Link]
(To print the user choice by Switch case)
import [Link].*;
public class ExSwitch {
[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:
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 {
}
}
Output:
12. [Link]
(To print “2 to the power -n || n || 2 to power n” using for and if-else)
import [Link].*;
public class ForTest {
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;
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");
}
}
}
}
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 {
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);
}
}
}
Output:
17. [Link]
(To read the string char by char and appending these chars to StringBuffer obj
through while loop)
import [Link];
public class {
int i = 0;
while (i < [Link]()) {
char c = [Link](i);
[Link](c);
i++;
}
}
Output:
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]+" ");
}
}
}
}
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:
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];
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 {
Output:
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 {
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 {
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();
}
@Override
public double getArea() {
@Override
public int getSides() {
return 4;
}
}
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 {
Output:
28. [Link]
(To peform the basic arithmetic operations)
import [Link].*;
public class BasicCalculator {
Output:
29. [Link]
(To access the classes and their methods of different program under same
Package)
package [Link];
package [Link];
public class PackageCall {
Output :
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);
Output :
34
Central University of Karnataka
Object Oriented Programming
33. [Link]
(To demonstrate the use of nested try blocks)
import [Link].*;
public class NestedTry {
}
catch(Exception eobj) { //Inner catch Block
[Link]([Link]());
break;
}
}
}
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
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
// Using sleep() method to pause the thread for a specified time
[Link](1000);
} catch (InterruptedException e) {
[Link]([Link]().getName() + "
interrupted.");
}
}
}
Output :
38
Central University of Karnataka
Object Oriented Programming
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
try {
// Using [Link]() to pause the thread for a specified time
[Link](1000);
} catch (InterruptedException e) {
[Link]([Link]().getName() + "
interrupted.");
}
}
}
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>
</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].*;
import [Link].*;
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);
[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
import [Link].*;
import [Link].*;
public class AnimationExample extends Applet
{
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
<!DOCTYPE html>
<html>
<body>
<applet code="[Link]" width=600 height=400></applet>
</body>
</html>
Output:
HTML Code :
<!DOCTYPE html>
<html>
<head>
<title>Mouse Movement</title>
</head>
<body>
<applet code="[Link]" width=600 height=400></applet>
</body>
</html>
Output:
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>
</body>
</html>
Output:
54
Central University of Karnataka
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 .