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

Java Lab Record Gul

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java Lab Record Gul

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

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 java.util.*;
public class Check_Even {
public static void main(String[] args) {

Scanner sc=new Scanner(System.in);


System.out.print("Enter a Number : ");
int n=sc.nextInt();
if(n%2==0) {
System.out.println("Even Number");
}
else {
System.out.println("Odd Numeber");
}

Output:

4
Central University of Karnataka
Object Oriented Programming

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

Central University Of Karnataka


5
Object Oriented Programming

Output:

3. ComLineTest.java
(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<args.length;i++) {
System.out.println(args[i]);
}

Output:

6
Central University of Karnataka
Object Oriented Programming

4. Reading.java
(To read the integer and float through Console)
import java.util.Scanner;
public class Reading {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter Integer Value : ");
int a=sc.nextInt();
System.out.println("You entered Integer Value : "+a);
System.out.print("Enter Float Value : ");
float b=sc.nextFloat();
System.out.println("You entered Float Value : "+b);

Central University Of Karnataka


7
Object Oriented Programming

Output:

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

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter Number of Rows : ");
8
Central University of Karnataka
Object Oriented Programming
int n=sc.nextInt();
for(int i=1;i<=n;i++) {
for(int j=1;j<=i;j++) {
System.out.print(i+" ");
}
System.out.println();
}

Output:

6. Prime.java
(To check number is prime or not)
import java.util.Scanner;
public class Prime {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter Number : ");
int n=sc.nextInt();
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

System.out.print(n+ " is Prime Number");


}
else {
System.out.print(n+ " is Not Prime Number");
}

Output:

7. Grade.java
(To print the grade based on the given condition)
import java.util.*;
public class Grade {

public static void main(String[] args) {


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

}
else if(per>=60 && per<80) {
System.out.print("A Grade");
}
else if(per>=50 && per<60) {
System.out.print("B++ Grade");
}
else if(per>=45 && per<50) {
System.out.print("B Grade");
}
else if(per>=40 && per<45) {
System.out.print("C++ Grade");
}
else if(per>=33 && per<40) {
System.out.print("C Grade");
}
else {
System.out.print("Fail");
}
}

Output:

Central University Of Karnataka


11
Object Oriented Programming

8. RectangleArea.java
(To calculate the area of the rectangle)
import java.util.Scanner;
public class RectangleArea {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter Length of Rectangle : ");
double l=sc.nextDouble();
System.out.print("Enter Breadth of Rectangle : ");
double b=sc.nextDouble();
double area=(l*b);
System.out.print("Area of Rectagle : "+area);
}

Output:

9. ExSwitch.java
(To print the user choice by Switch case)
import java.util.*;
public class ExSwitch {

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


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int con=1;
while(con==1) {
System.out.print("Enter 1st Value : ");
double a=sc.nextDouble();
System.out.print("Enter 2nd Value : ");
double b=sc.nextDouble();

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

}
System.out.print("\nDo you want to continue(1/0)? : ");
con=sc.nextInt();
}

Output:

Central University Of Karnataka


13
Object Oriented Programming

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

Output:

11. DowhileTest.java
(To print the multiplication table using do-while)
import java.util.Scanner;
public class DowhileTest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter a Number : ");
int n=sc.nextInt();
int i=1;
do {
System.out.println(n+" * "+i+" = "+n*i);
i++;
}while(i<=10);

}
}

Output:

Central University Of Karnataka


15
Object Oriented Programming

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

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int con=1;
while(con==1) {
System.out.print("Enter Number N : ");
int n=sc.nextInt();
System.out.print("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\n5.Exit\nPress Any Option : ");
int choice=sc.nextInt();
if(choice==1) {
System.out.print(Math.pow(2, n));
}
else if(choice==2) {
System.out.print(Math.pow(2, (-n)));
}
else if(choice==3) {
System.out.print(Math.pow(n, 2));
}
else if(choice==4) {
System.out.print(Math.pow(n, -2));
}
else if(choice==5) {
System.exit(0);
}
else {
System.out.print("Please Press Valid Key!!!");
}
System.out.print("\nDo you want to continue(1/0 )");
con=sc.nextInt();
}
}

Output:
16
Central University of Karnataka
Object Oriented Programming

13. NestingTest.java
(To print largest of two number using nested classes)
import java.util.Scanner;

class CheckGreter {
class Check {
Scanner sc = new Scanner(System.in);
int a;
int b;

Central University Of Karnataka


17
Object Oriented Programming

public Check() {
System.out.print("Enter 1st Value : ");
a = sc.nextInt();
System.out.print("Enter 2nd Value : ");
b = sc.nextInt();
if (a > b) {
System.out.print("1st Value is Greater");
} else {
System.out.print("2nd Value is Greater");
}
}
}
}

public class NestingJava {


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

Output:

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

Output:

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

public static void main(String[] args) {


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

Central University Of Karnataka


19
Object Oriented Programming

char find=str1.charAt(index);
System.out.printf("Character at %d in %s : %c",index,str1,find);

Output:

16. Mathoperation.java
(To demonstrate the user defined mul() and divide() methods)
import java.util.*;

class Operation {
Scanner sc = new Scanner(System.in);
int a;
int b;

public Operation() {
System.out.print("Enter 1st Value : ");
a = sc.nextInt();
System.out.print("Enter 2nd Value : ");
b = sc.nextInt();
}

void mul() {
System.out.println("Multiplication : "+a * b);
}

void div() {
System.out.println("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();
obj.mul();
obj.div();
}

}
Output:

17. StringCharByChar.java
(To read the string char by char and appending these chars to StringBuffer obj
through while loop)
import java.util.Scanner;

public class {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();

StringBuffer sb = new StringBuffer();

int i = 0;
while (i < str.length()) {
char c = str.charAt(i);
sb.append(c);
i++;
}

System.out.println("The string is: " + sb.toString());


}

}
Output:

Central University Of Karnataka


21
Object Oriented Programming

19. Sort.java
(To sort the array using Bubble sort)
import java.util.*;
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++) {
System.out.print(a[i]+" ");
}
}

public static void main(String[] args) {

// TODO Auto-generated method stub


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

}
}

Output:

22
Central University of Karnataka
Object Oriented Programming

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

Output:

Central University Of Karnataka


23
Object Oriented Programming

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

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 < args.length; i++) {
languages.add(args[i]);
}

// Insert a new element at index 2


languages.insertElementAt("Cobol", 2);

// Print the contents of the Vector


System.out.println("Languages:");
for (String language : languages) {
System.out.println(language);
}
}
}
Output:

24
Central University of Karnataka
Object Oriented Programming

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

import java.util.*;
public class SimpleInterest {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.print("Enter Principle : ");
double p=sc.nextDouble();
System.out.print("Enter Rate : ");
double r=sc.nextDouble();
System.out.print("Enter Time : ");
double t=sc.nextDouble();
double interest=(p*r*t)/100;
System.out.print("Simple Interest : "+interest);
System.out.print("\nAmmount(Principle + Interest) : "+(p+interest));
}
}

Output:

Central University Of Karnataka


25
Object Oriented Programming

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

public static void main(String[] args) {


Area obj=new Area();
obj.getArea();
}
}
Output:

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

public static void main(String[] args) {


Concate obj=new Concate();
obj.getConcate();
}
}

Output:

25. Interface3.java
(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 java.util.Scanner;
interface Polygon {
double getArea();
int getSides();
}

class Rectangle implements Polygon {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = 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(System.in);
System.out.print("Enter Length : ");
double l=sc.nextDouble();
System.out.print("Enter Breadth : ");
double b=sc.nextDouble();
Rectangle rectangle = new Rectangle(l, b);
System.out.println("Area of rectangle: " + rectangle.getArea());
System.out.println("Number of sides of rectangle: " + r ectangle.getSides());
}
}

Output:

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

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

Output:

27. UseOfSuper.java
(To demonstrate the use of super keyword to invoke super class method)
import java.util.*;
class T{
void m() {
System.out.println("m method from Class T");
}
}
class D extends T{
void m() {
super.m();//Super Keyword is used to call super class,method,variable
System.out.println("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. BasicCalculator.java
(To peform the basic arithmetic operations)
import java.util.*;
public class BasicCalculator {

public static void main(String[] args) {


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

Output:

29. packageProg1.java
(To access the classes and their methods of different program under same
Package)
package com.Manish.demopkg;

public class PackageInto {

public void info() {


System.out.println("Name : Manish Kumar");
System.out.println("Package : com.Manish.demopkg");
System.out.println("Class : PackageInto");
System.out.println("File Name : PackageInto.java");
Central University Of Karnataka
31
Object Oriented Programming

package com.Manish.demopkg;
public class PackageCall {

public static void main(String[] args) {

PackageInto obj=new PackageInto();


obj.info();

Output :

30. packageProg2.java (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 : Balance.java
package BalancePackage;

public class Balance {


private double amount;

public Balance(double amount) {


this.amount = amount;
}

public double getAmount() {


return amount;
}
}

Save : PackageProgram.java
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++) {
System.out.println("Balance " + (i + 1) + ": " + balances[i].getAmount());
}

}
}

Output :

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

}
System.out.print("Quotient : "+(a/b));
}
catch(Exception e) {
System.out.print(e.getMessage());
}

}
Central University Of Karnataka
33
Object Oriented Programming

Output :

32. MultiCatch.java (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];
System.out.println("Result: " + result);

// Access an array element


System.out.println("Value at index " + index + ": " + numbers[index]);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Generic Exception: " + e.getMessage());
}

System.out.println("After try-catch block.");


}
}

Output :

34
Central University of Karnataka
Object Oriented Programming

33. NestedTry.java
(To demonstrate the use of nested try blocks)
import java.util.*;
public class NestedTry {

public static void main(String[] args) {


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

}
catch(Exception eobj) { //Inner catch Block
System.out.println(eobj.getMessage());
break;
}
}

Central University Of Karnataka


35
Object Oriented Programming

}
catch(Exception eobj) { //Outer catch Block
System.out.println("An error Occurred");
}
System.out.print("\nDo you want to continue(1/0)? : ");
con=sc.nextInt();
}
}

Output:

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

Output:

35. MultiThread.java (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++) {
System.out.println(Thread.currentThread().getName() + ": " + i);

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


Thread.yield();

try {
// Using sleep() method to pause the thread for a specified time
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().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


thread1.setName("Thread 1");
thread2.setName("Thread 2");

// Start the threads


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

// Let the threads run for a while


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop the threads


thread1.stopThread();
thread2.stopThread();
}
}

Output :

38
Central University of Karnataka
Object Oriented Programming

36. MultiThread2.java (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++) {
System.out.println(Thread.currentThread().getName() + ": " + i);

// Using Thread.yield() to give a chance to other threads


Thread.yield();

try {
// Using Thread.sleep() to pause the thread for a specified time
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().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


thread1.setName("Thread 1");
thread2.setName("Thread 2");

Central University Of Karnataka


39
Object Oriented Programming

// Start the threads


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

// Let the threads run for a while


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop the threads


multiThread.stopThread();
}
}

Output :

37. Rectangle.java (To draw the rectangle on applet using drawRect() method)
import java.applet.*;
import java.awt.*;
public class Applet38 extends Applet
{
int height,width;
public void init()
{
height=getSize().height;
width=getSize().width;
setName("Rectangle");
}
public void paint(Graphics g)
{
g.drawRect(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="Applet38.class" width=300 height=400></applet>
</body>
</html>

Output:

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

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="AppletFirst.class" width=300 height=200></applet>
</body>

Central University Of Karnataka


41
Object Oriented Programming

</html>

Output:

39. fillColor.java (To creating a fillColor class extending Applet using setColor())
import java.applet.*;
import java.awt.*;
public class FillColor extends Applet
{
public void paint(Graphics g)
{
g.drawRect(200,150,200,100);
Color c= new Color(10,50,10,100);
g.setColor(c);
g.fillRect(200,150,200,100);
g.setColor(Color.yellow);
g.drawString("Rectangle",300,300);
}
}

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="FillColor.class" width=600 height=400></applet>

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

Output:

40. DisplayImage.java (To display the image in applet window using getImage()
and drawImage() methods)
import java.applet.*;

Central University Of Karnataka


43
Object Oriented Programming

import java.awt.*;

public class DisplayImage extends Applet


{
Image img;
public void init()
{
img= getImage(getDocumentBase(),"cuk.png");
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>Pic Apply</title>
</head>
<body>
<applet code="DisplayImage.class" width=1000 height=700></applet>
</body>
</html>
Output:

44
Central University of Karnataka
Object Oriented Programming

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

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

Central University Of Karnataka


45
Object Oriented Programming

g.setColor(Color.yellow);
g.drawString("Oval",5,225);
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>Shapes</title>
</head>
<body>
<applet code="Shape.class" width=600 height=400></applet>
</body>
</html>

Output:

46
Central University of Karnataka
Object Oriented Programming

43. AnimationExample.java (To display the animation/image position shifting)

import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet

Central University Of Karnataka


47
Object Oriented Programming

{
Image Pic;
public void init()
{
Pic=getImage(getDocumentBase(),"cuk.png");

}
public void paint(Graphics g)
{
for(int i=0; i<100; i++)
{
g.drawImage(Pic,i,50,this);
try
{
Thread.sleep(100);

}
catch(Exception e)
{}
}
}
}

HTML Code:

<!DOCTYPE html>
<html>
<head>
<title>motion picture</title>
</head>
<body>
<applet code="AnimationExample.class" width=1200 height=600></applet>
</body>
</html>

Output:

48
Central University of Karnataka
Object Oriented Programming

44. keyEventHand.java (To demonstrate the KeyListener interface for showing


which key pressed. e.g. Key pressed or Key Released)
//KeyListener
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
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+k.getKeyChar();
repaint();
}
public void paint(Graphics g){
g.drawString(msg,10,20);
}
}
HTML Code:

<!DOCTYPE html>
<html>
<body>
<applet code="KeyEventHand.class" width=600 height=400></applet>
</body>
</html>
Output:

45.MousedragEvent.java (To demonstrate the MouseMotionListener interface to


paint the screen by mouse dragging)
import java.awt.*;
//import java.awt.event.KeyListener;
import java.awt.event.*;
import java.applet.*;
public class MouseDragEvent extends Applet implements MouseMotionListener
50
Central University of Karnataka
Object Oriented Programming
{
public void init()
{
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent e)
{
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillOval(e.getX(),e.getY(),5,5);
}
public void mouseMoved(MouseEvent e){}
}

HTML Code :

<!DOCTYPE html>
<html>
<head>
<title>Mouse Movement</title>
</head>
<body>
<applet code="MouseDragEvent.class" 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. actionEventButton.java (For showing the string in TextField on button click in
applet by implementing ActionListener interface)

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

b2=new Button("Clear");
b2.setBounds(160,150,60,50);
add(b2);
add(tf);

b.addActionListener(this);
b2.addActionListener(this);

setLayout(null);

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText("Welcome");
}
else
tf.setText("");
}
}

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<applet code="ActionEventButton.class" width=600 height=400></applet>

Central University Of Karnataka


53
Object Oriented Programming

</body>
</html>

Output:

54
Central University of Karnataka

You might also like