0% found this document useful (0 votes)
16 views40 pages

Java Word

The document contains a series of Java programming tasks that involve creating classes, interfaces, and exception handling. It includes examples of inheritance, method overriding, and the implementation of abstract classes and interfaces. Each task is accompanied by code snippets demonstrating the required functionality, such as calculating wages, vehicle maintenance, and handling exceptions.

Uploaded by

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

Java Word

The document contains a series of Java programming tasks that involve creating classes, interfaces, and exception handling. It includes examples of inheritance, method overriding, and the implementation of abstract classes and interfaces. Each task is accompanied by code snippets demonstrating the required functionality, such as calculating wages, vehicle maintenance, and handling exceptions.

Uploaded by

Task Master
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Q50.

Derive sub-classes of ContractEmployee namely HourlyEmployee & WeeklyEmployee with information number of hours &
wages per hour, number of weeks & wages per week respectively & method calculateWages() to calculate their monthly salary.

abstract class ContractEmployee{


int contracttime;
abstract void contract(int contracttime);

}
class HourlyEmployee extends ContractEmployee{
int nohours;
float wagehour,wages;
void calculatewage(int nohours,float wagehour)
{ wages = nohours*wagehour;
System.out.println("the total hourly wage of the employee will be "+wages+" RS");
}
void contract(int contracttime)
{
System.out.println("the contract of the employee is "+contracttime+" hours only");
}
}
class WeeklyEmployee extends ContractEmployee {
int noofweeks;
float wageweek,salary;
void calculatewage(int noofweeks,float wageweek)
{
salary = noofweeks*wageweek;
System.out.println("the total weekly salary of the employee is "+salary+" RS");
}
void contract(int contracttime)
{
System.out.println("the contract of the employee is "+contracttime+" weeks only");
}
}
class Employee{
public static void main(String[] args) {
HourlyEmployee h = new HourlyEmployee();
WeeklyEmployee w = new WeeklyEmployee();
h.contract(50);
h.calculatewage(50, 50);
w.contract(5);
w.calculatewage(5, 2500);
}
}

Q51). Write an application to create a super class Vehicle with information vehicle number,insurance number,color and
methods getConsumption() and displayConsumption(). Derive the sub-classes TwoWheeler and FourWheeler with method
maintenance() and average() to print the maintenance And average of vehicle.
abstract class Vehicle{
String vno,colour;
int insuranceno,km;
float fuel;
abstract void displayConsumption(float fuel,int km);
abstract void info(String vno,String colour, int insuranceno);

}
class Twowheller extends Vehicle{
void info(String vno,String colour,int insuranceno)
{
System.out.println("vehicle number "+vno);
System.out.println("vehicle insurance number "+insuranceno);
System.out.println("vehicle colour "+colour);
}

void displayConsumption(float fuel,int km)


{
System.out.println("consumption of the vehicle is "+fuel+" liters for "+km+" kms");
}

void maintainence(int kms,float avg )


{
float maintain = (100/avg)*kms;

System.out.println("the maintainence of vehicle is " + maintain);

}
void average(String vno,int kilometersperliter)
{
System.out.println("the average of the vehicle "+ vno + " is "+ kilometersperliter+"
kilometersperliter");
}

}
class Q51{
public static void main(String[] args) {
Twowheller t = new Twowheller();
t.info("MP09 ay 1234", "Black", 236);
t.displayConsumption(1, 60);
t.maintainence(500, 60);
t.average("MP09 ay 1234",60);
}
}
Output:
Q36). Write an application that changes any given string with uppercase letters, displays it , changes it back to lowercase letters
and displays it?
public class Q36 {

void uppercase(char p) {
char s = Character.toUpperCase(p);
System.out.println("String after upper case conversion " + s);

void lowercase(String d) {
String f = d.toLowerCase();
System.out.println("String after upper case conversion " + f);

}
}

class A {
public static void main(String[] args) {
Q36 a = new Q36();
a.uppercase('a');
a.lowercase("AYUSH SHARMA");
}
}

Q46). Write an application that reads three nonzero value entered by the user and determines and prints sum, product,
average, smallest & largest of three?

import java.util.Scanner;

class Funholder {
Scanner s = new Scanner(System.in);
int a, b, c;

void input() {
System.out.println("enter the intergers a b c resp");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
}

void sum() {
int x = a + b + c;
System.out.println("the sum of the three numbers is " + x);
} }

void mul() {
int x = a * b * c;
System.out.println("the multiplication of the integers is " + x);
}

void gretest() {
if (a > b) {
if (a > c) {
System.out.println("gretest integer " + a);
} else {
System.out.println("gretest interger " + c);
}
} else {
if (b > c) {
System.out.println("gretest integer " + b);
} else {
System.out.println("gretest integer " + c);
}
}
}

void avg() {
int x = (a + b + c) / 3;
System.out.println("the avg of the three numbers is " + x);
}
}

class Numbers {
public static void main(String[] args) {

Funholder f = new Funholder();


f.input();
f.gretest();
f.avg();
f.mul();
f.sum();

}
}
Output:
Q54. Create a super class Shape with methods getName() which gives the information about the type of the shape.derive its
sub-classes TwoDim and ThreeDim with method area() and volume() respectively which prints the area and volume of a two-
dimensional and three-dimensional shape?

abstract class Shape {


abstract void getname();

class Twodim extends Shape {

void getname(String shape) {


System.out.println("the two dimensional shape is " + shape);
}

void Area(float a, float b, String shape) {


float area = a * b;
System.out.println("the area of the " + shape + " is " + area);
}
}

class Threedim extends Shape {

void getname(String shape) {


System.out.println("the three dimensional shape is " + shape);
}

void vol(float a, float b, float c, String shape) {


float vol = a * b * c;
System.out.println("the volume of the " + shape + " is " + vol);
}
}

class Q54 {
public static void main(String[] args) {
Twodim t = new Twodim();
// t.getname("square");
// t.Area(12.3f,12.3f,"square");
Threedim s = new Threedim();
s.getname("cube");
s.vol(12.3f, 12.3f, 12.3f, "cube");
}
}

Output:
Q55) Extend the class TwoDim with methods getLength(),getBreadth() which displays the length and breadth of two
dimentional shapes.Derive sub-classes rectangle, rhombus with method getArea() and getPerimeter() to calculate the area and
perimeter of this two dimensional shapes?

class Twodim {
public int length, breath, side, dim1, dim2;

void getname(String shape) {


System.out.println("null");
}

void getlength(int length, String shape) {


System.out.println("the length of the " + shape + " is " + length);
}

void getbreath(int breath, String shape) {


System.out.println("the breath of the " + shape + " is " + breath);
}
}

class Rectangle extends Twodim {


void getname(String shape) {
System.out.println("the two dimensional shape is " + shape);
}

void getArea(int length, int breath) {


System.out.println("the area of the rectangle is " + length * breath);
}

void getPerimeter(int a, int b) {


int peri = 2 * (a + b);
System.out.println("the perimeter of the rectangle is " + peri);
}
}

class Rhombus extends Twodim {


void getname(String shape) {
System.out.println("the two dimensional shape is " + shape);
}

void getArea(int dim1, int dim2) {


System.out.println("the area of the rhombus is " + (dim1 * dim2) / 2);
}

void getPerimeter(int side) {


System.out.println("the perimeter of the Rhombus is " + (4 * side));
}
}

class Q55 {
public static void main(String[] args) {
Twodim t = new Twodim();
t.getlength(10, "rectangle");
t.getbreath(20, "rectangle");
Rectangle r = new Rectangle();
// r.getname("rectangle");
r.getArea(10, 20);
r.getPerimeter(10, 20);
Rhombus d = new Rhombus();
d.getArea(10, 10);
d.getPerimeter(20);

}
}

Output:

Q57) Create a super class Student with methods getQual (), getFirstName(),getLastName(), getAddress(), getContat(), which
gives basic details of student.derive sub-classes Faculty and Scholar with method salary(), Course() resp. which gives the
additional information about the salary and course of faculty and scholar resp?

class Student {
void getQual(String qual) {
System.out.println("the qualifictions of the person is " + qual);
}

void getfirstname(String name) {


System.out.println("the name of the persons is " + name);
}

void getlastname(String lname) {


System.out.println("the last name of the persons is " + lname);
}

void getaddress(String address) {


System.out.println("the addrees of the person is " + address);
}

void contact(double x) {
System.out.println("the contact number of the person is " + x);
}
}

class Faculty extends Student {


void Salary(double s) {
System.out.println("the salary of the faculty is " + s);

}
}

class Scholar extends Student {


void course(String c) {
System.out.println("the course of the scholar is " + c);

}
}

class Q57 {
public static void main(String[] args) {
Faculty f = new Faculty();
f.getfirstname("Manju");
f.getlastname("schodeo");
f.getaddress("whatever");
f.getQual("MTech it");
f.contact(109867678);
f.Salary(100000);
Scholar s = new Scholar();
s.course("mba");
}
}

Output:

Q58) Create an abstract class Shape which calculate the area and volume of 2-d and 3-d shapes with methods getArea and
getVolume. Reuse this class to calculate the area and volume of square ,circle ,cube?

import java.lang.Math;

abstract class Shape {


abstract void getarea();

abstract void getvolume();

class Square extends Shape {


void getarea(float side) {
System.out.println("the area of the square is " + Math.pow(side, 2));
}
}

class Circle extends Shape {


void getarea(float radius) {
System.out.println("the area of the circle is " + Math.PI * Math.pow(radius, 2));
}
}

class Cube extends Shape {


void getvolume(float side) {
System.out.println("the volume of the cue will be " + Math.pow(side, 3));
}

class Q58 {
public static void main(String[] args) {
Square s = new Square();
Circle c = new Circle();
Cube v = new Cube();
s.getarea(10f);
c.getarea(10f);
v.getvolume(10f);

}
}

Output:

Q60). Create an Interface payable with method getAmount ().Calculate the amount to be paid to Invoice and Employee by
implementing Interface?

interface Payable {
void getamount(int x);
}

class Employee implements Payable {


public void getamount(int attendance) {
int salary = attendance * 1000;
System.out.println("the salary of the Employee is " + salary);

}
}

class Invoice implements Payable {


public void getamount(int days) {
int amount = days * 100;
System.out.println("the amount to be paid to the invoice is " + amount);
}
}

class Q60 {
public static void main(String[] args) {
Employee e = new Employee();
Invoice i = new Invoice();
e.getamount(30);
i.getamount(30);
}
}

Output:

Q62) Create an Interface Fare with method getAmount() to get the amount paid for fare of travelling. Calculate the fare paid
by bus and train implementing interface Fare?

interface Fare {
void getamount();
}

class Train implements Fare {


public void getamount(int trips) {
int amt = trips * 200;
System.out.println("the total fare for the trips on the train is " + amt + " RS");
}
}

class Bus implements Fare {


void getamount(int trips) {
int amt = trips * 70;
System.out.println("the total fare for the trips on the bus is " + amt + " RS");
}
}

class Q62 {
public static void main(String[] args) {
Train t = new Train();
t.getamount(10);
Bus b = new Bus();
b.getamount(10);
}
}
Output:
Q64). WAP to create your own package. Package should have more than two classes. Write a class that uses the package?
package first;

class Add {
void adding(int a, int b) {
int c = a + b;
System.out.println("addition of aand b is " + c);
}
}

package first;

class Greet {
void hello(String a) {
System.out.println("hello " + a);

}
}
import java.first.Greet;
import java.first.Add;
class demo {
public static void main(String[] args) {
Greet g = new Greet();
g.hello("Ayush");
Add d = new Add();
d.adding(1, 3);
}
}

Q66). Exception Handling program for division of two numbers that accepts numbers from user?
import java.util.Scanner;

class Division {
void function() {
System.out.print("enter the integer a for division ");
Scanner s = new Scanner(System.in);
float a, b;
a = s.nextFloat();
System.out.print("enter the integer b for division ");

b = s.nextFloat();
try {
if (b == 0) {
throw new ArithmeticException();
} else {
System.out.print("the division of the intergers will be ");
float c = a / b;
System.out.print(c);
}
} catch (ArithmeticException e) {
System.out.println("the entered value of the integer b cannot be zero");
System.out.println(e);
} } }

class Q66 {
public static void main(String[] args) {
Division d = new Division();
d.function();
}
}

Output:

Q68) Exception Handling program for NullPointerException--thrown if the JVM attempts to perform an operation on an Object
that points to no data, or null?

class Null {
String a = null;
}

class Q68 {
public static void main(String[] args) {
Null n = new Null();
try {
System.out.println("string is " + n.a.length());
} catch (NullPointerException b) {
System.out.println("null pointer exception caugth the string is null " + b);
}
}
}

Output:

Q69). Exception Handling program for NumberFormatException--thrown if a program is attempting to convert a string to a
numerical datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q')?

import java.util.Scanner;
class Number {

void run() {
Scanner s = new Scanner(System.in);
System.out.println("enter any valid integer ");
try {
int b = Integer.parseInt(s.next());
System.out.println(b);
}

catch (NumberFormatException o) {
System.out.println("it is a number format exception ");
}
}
}

class Main {
public static void main(String[] args) {
Number n = new Number();
n.run();
}
}

Output:

Q71). Exception Handling program for IOException--actually contained in java.io, but it is thrown if the JVM failed to open an
I/O stream?

import java.io.*;

class Q71 {
public static void main(String[] args) throws FileNotFoundException {
try {
FileReader f = new FileReader("read.java");
System.out.println(f.read());
} catch (FileNotFoundException e) {
System.out.println("it is an io exception " + e);
} catch (IOException r) {
System.out.println("hello java");
}

}
}

Output:

Q72). Write a program that shows that the order of the catch blocks is important. If you try to catch a superclass exception
type before a subclass type, the compiler should generate errors?

class Error {
public static void main(String[] args) {
try {
int a = 20;
int c = a / 0;
int arr[] = { 1, 2, 3, 4, 5 };
arr = new int[5];
System.out.println("out of bound index of arr " + arr[5]);

catch (ArithmeticException a) {
System.out.println("an arthimetic exception " + a);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("array out of bound " + e);
} catch (Exception r) {
System.out.println(" caught in super class exception " + r);

} } }

Output:

Q73). Program for demonstrating the use of throw, throws & finally - Create a class with a main( ) that throws an object of
class Exception inside a try block. Give the constructor for Exception a String argument. Catch the exception inside a catch clause
and print the String argument. Add a finally clause and print a message to prove you were there?

class D {

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


try {
System.out.println("try block ");
throw new Exception();
} catch (Exception i) {
System.out.println("exception caught");
System.out.println(i);
} finally {
System.out.println("this is a finally block");
} } }
Output:

Q74). Create your own exception class using the extends keyword. Write a constructor for this class that takes a String
argument and stores it inside the object with a String reference. Write a method that prints out the stored String. Create a try-
catch clause to exercise your new exception?

import java.util.Scanner;

class Custom extends Exception {


String s;

Custom(String a) {
s = a;
}

String print() {
return s;
}
}

class Ex {
public static void main(String[] args) {
int a;
try {
System.out.println("enter a even number ");
Scanner s = new Scanner(System.in);
a = s.nextInt();
if (a % 2 == 0) {
System.out.println("valid even number");
} else {
throw new Custom("invalid integer");
}

} catch (Custom c) {
System.out.println(c.print());

}
}
}

Output:
Q75). Write a program to rethrow an exception – Define methods one() & two(). Method two() should initially throw an
exception. Method one() should call two(), catch the exception and rethrow it Call one() from main() and catch the rethrown
exception?

import java.util.Scanner;

class Q75 {
int a;

void two() throws Exception {


Scanner s = new Scanner(System.in);
System.out.println("enter the password to access secret data");
a = s.nextInt();

if (a == 1234) {
System.out.println("login succesfull ☻");

} else {
throw new Exception();
}

void one() throws Exception {


try {
two();
} catch (Exception e) {
System.out.println("Exception caught");
throw e;
}

}
}

class EXX {
public static void main(String[] args) {
Q75 q = new Q75();
try {
q.one();
} catch (Exception a) {
System.out.println("exception recaught in main" + a);
}
} }

Output:
Q76). Write a program to change the priority of thread?
class threading1 extends Thread {
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println("threading1");
}
}
}

class threading2 extends Thread {


public void run() {
for (int i = 0; i < 4; i++) {
System.out.println("threading2");
}
}
}

class Z {
public static void main(String[] args) {
threading1 t1 = new threading1();
t1.setPriority(1);
t1.start();
// System.out.println(t1.getPriority());
threading2 t2 = new threading2();
t2.setPriority(10);
t2.start();
// System.out.println(t2.getPriority());

} }
Output:

Q78). Open a text file so that you can read the file one line at a time. Read each line as a String and send the results to
System.out?
import java.io.*;

class Eader {
public static void main(String[] args) throws FileNotFoundException {
FileReader f = new FileReader("C:\\Users\\vinis\\OneDrive - GMA & Associates\\
Desktop\\a.txt");
int i;
try {
while ((i = f.read()) != -1) {
System.out.print((char) i);
}
} catch (IOException w) {
System.out.println("error");
}
}
}

Output:

Q79). Modify Exercise 1 so that the name of the file you read is provided as a command-line argument?
import java.io.*;

class Reader {
public static void main(String[] args) throws FileNotFoundException {
String path = args[0];

FileReader f = new FileReader(path);


int i;
try {
while ((i = f.read()) != -1) {
char a = (char) i;

}
} catch (IOException w) {
System.out.println("error");
}
}
}
Output:

Q80). Modify Exercise 2 to force all the lines in the results to upper case and send the results to System.out?
import java.io.*;
class Reader {
public static void main(String[] args) throws FileNotFoundException {
FileReader f = new FileReader("C:\\Users\\vinis\\OneDrive - GMA & Associates\\
Desktop\\a.txt");
int i;
try {
while ((i = f.read()) != -1) {
System.out.print(Character.toUpperCase((char) i));

}
} catch (IOException w) {
System.out.println("error");
}
}
}
Output:

Q89). WAP in java to create a file?


import java.io.File;

class CreateFile {
public static void main(String[] args) throws IOException {

try {
File f = new File("ayush.txt");
if (f.createNewFile()) {
System.out.println("file created");
System.out.println(f.getName());
} else {
System.out.println("file not created");
}
} catch (IOException e) {
System.out.println(e);

} } }
Output:

Q90). WAP in java to delete a file?


import java.io.File;
class Delete {
public static void main(String[] args) {

File obj = new File("ayush.txt");


if (obj.delete()) {
System.out.println("deleted");
} else {
System.out.println("not deleted ");
}
}
}
Output:

Q 91). WAP in java to determine a file or dir exist or not?


import java.io.File;
import java.io.IOException;

class Exists {
public static void main(String[] args) throws IOException {

File obj = new File("ayush.txt");


if (obj.exists()) {
System.out.println("the file " + obj.getName() + " exists");
} else {
System.out.println("the file do not Exists");
}
}
}

Output:

Q 95). WAP in java to read a file using FileReader and break the contets using StringTokenizer?

import java.io.IOException;
import java.nio.file.*;
import java.util.StringTokenizer;
class Reader {
public static void main(String[] args) throws IOException{

String str;
str = new String(Files.readAllBytes(Paths.get("D:\\ayush\\abc.txt")));
StringTokenizer s = new StringTokenizer(str,":",true);
while(s.hasMoreTokens())
{
System.out.println(s.nextToken());
}
}
}
Output:

Q 94). WAP in java to move a file?

import java.io.*;
import java.nio.file.*;
class Move {
public static void main(String[] args) throws IOException {
try{
Files.move(Paths.get("D:\\abc.txt"), Paths.get("D:\\ayush\\abc.txt"));
System.out.println("file moved successfully");

}
catch(IOException e){
System.out.println("file do not exist ");
System.out.println(e);
}
}
}

Output:

Q 96) WAP in java to write into a file using FileWriter?


import java.io.FileWriter;
import java.io.IOException;

class CreateFile {
public static void main(String[] args) throws IOException {

FileWriter w = new FileWriter("D:\\ayush\\abc.txt");


w.write("writing content in created file");

System.out.println("writing finished successfully");


w.close();

}
}
Output:

Q 99) WAP in java to get file length ?

import java.io.File;
class Length{
public static void main(String[] args) {
File f = new File("D:\\ayush\\abc.txt");
System.out.println("the length of the file is " + f.length());
}
}
Output:

Q 98) WAP in java to rename a file?

import java.io.File;
class Rename{
public static void main(String[] args) {
File oldname = new File("D:\\ayush\\ayush.txt");
File newname = new File("D:\\ayush\\a.txt");

if(oldname.renameTo(newname))
{
System.out.println("file renamed to "+ newname);
}
else{
System.out.println("error");
}
}
}

Output:
Q 101) WAP in java to demonstrate StringTokenizer class?

import java.util.StringTokenizer;
class Strings{
public static void main(String[] args) {
StringTokenizer s = new StringTokenizer("my name is ayushsharma"," ");

while(s.hasMoreTokens()) {
System.out.println(s.nextToken());
}

}
}
Output:

Q 103) WAP in java to create thread that print counting by extending Thread class?

class Threading extends Thread {

public void run()


{
int i = 0;
for(i= 0;i<100;i++)
{
System.out.println(i);
}
}
}
class E{
public static void main(String[] args) throws InterruptedException{
Threading t = new Threading ();
t.start();
}}

Output:
Q104) WAP in java to demonstrate current thread?

class Thread1 extends Thread {


public void run(){
System.out.println("running thread");

}
}
class Main{
public static void main(String[] args) {
Thread1 t = new Thread1();
t.setName("Ayush");
// System.out.println( "Name of the thread is "+t.getName());
t.start();
System.out.println( t.currentThread());
}
}

Output:

Q105) WAP in java to create a thread using Runnable interface?

class Thread1 implements Runnable{

public void run() {


int i=0;
while(i<50){
System.out.println("thread 1");
}
}
}
class Thread2 implements Runnable{
public void run(){
int i=0;
while(i<50){
System.out.println("thread 2");
}
}
}
class B{
public static void main(String[] args) {

Thread1 t = new Thread1();


Thread a = new Thread (t);
a.start();
Thread2 u = new Thread2();
Thread f = new Thread (u);
f.start();
}
}

Output:

Q106) WAP in java to determine whether a thread is alive or not?

class Thread1 extends Thread{


public void run()
{
System.out.println("this is thread 1");
}
}
class D{
public static void main(String[] args) throws InterruptedException {
Thread1 a = new Thread1();

a.start();
a.sleep(1000);

if (a.isAlive())
{
System.out.println("yes the thread is alive");
}
else{
System.out.println("the thread is not alive");
}
}
}

Output:
Q107) WAP in java to demonstrate join() method of Thread class.?

class A1 extends Thread {


public void run()
{
System.out.println("Table of 10 ");
for(int i= 1; i<=10;i++)
{
System.out.print(10*i+" ");

}
System.out.println("\n");
}
}
class A2 extends Thread{
public void run(){
System.out.println("Table of 11");
for(int i= 1; i<=10;i++)
{
System.out.print(11*i+" ");
}
}
}
class A3{
public static void main(String[] args) throws InterruptedException {
A1 a = new A1();
A2 b = new A2();
a.start();
a.join();//throws interruppted exception
b.start();
}
}

Output:

Q108) WAP in java to implement toString() method in your class to print objects?
class Info{
String name;
int age;
Info(String n,int a){
name = n;
age = a;
}
public String toString() {
return name +" "+age;
}

public static void main(String[] args) {


Info i = new Info("Ayush", 19);
System.out.println(i);
Info f = new Info("Dev", 19);
System.out.println(f);

}
}
Output:

Q82) Create an application to draw a horizontal line?


import java.applet.*;
import java.awt.*;
public class drawline extends Applet
{
public void init(){
setBackground(Color.red);
}
public void paint(Graphics g)
{
g.drawLine(50, 150, 250, 150);
}
}

Output:

Q83) Create an application to draw one line perpendicular to other. One line parallel to other?
import java.applet.*;
import java.awt.*;
public class pline extends Applet {
public void init()
{
setBackground(Color.orange);
}
public void paint(Graphics g )
{
g.drawLine(200,300,200,500);
g.drawLine(100,500,400,500);
}
}

Output:

Q84). Create an application to display a circle within rectangle?


import java.applet.*;
import java.awt.*;
public class rectcircle extends Applet {
public void paint(Graphics g)
{
g.drawRect(100, 100, 300, 150);
g.drawOval(100, 100, 150, 150);
}
}

Output:

Q85). In the above application fill different colors in the circle & rectangle?
import java.applet.*;
import java.awt.*;
public class rectcircle extends Applet {
public void paint(Graphics g)
{
g.drawRect(100, 100, 300, 150);
g.setColor(Color.blue);
g.fillRect(100, 100, 300, 150);
g.drawOval(100, 100, 150, 150);
g.setColor(Color.yellow);
g.fillOval(100, 100, 150, 150);

}
}

Output:

Q86) Write an application that displays any string. Choose color from combo box to change the color of this displayed string.?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import javax.swing.JFrame;
//import javax.swing.JComboBox;
class Combobox implements ItemListener{
JComboBox j;
JLabel label;
JFrame f;
Combobox b;

Combobox(){
f = new JFrame("Select colour");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
String s[] = {"Red","Blue","Orange"};
j = new JComboBox<>(s);
j.setBounds(50,50,90,20);

f.add(j);
f.setSize(400,400);
f.setVisible(true);
label = new JLabel();
j.addItemListener(this);
label.setText("A program for ComboBox");
f.add(label);

public void itemStateChanged(ItemEvent e) {


String str = (String)j.getSelectedItem();

if(str.equals("Red")){

label.setForeground(Color.RED);
label.setText("A program for ComboBox");
f.add(label);
f.setVisible(true);

}
else{
if(str.equals("Blue")){

label.setForeground(Color.BLUE);
label.setText("A program for ComboBox");
f.add(label);
f.setVisible(true);

}
else if(str.equals("Orange")){
label.setForeground(Color.ORANGE);
label.setText("A program for ComboBox");
f.add(label);
f.setVisible(true);
}
}
}
public static void main(String[] args) {
Combobox b = new Combobox();
}

Output:

Q87) WAP to demonstrat AWT buttons with event handling?


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

import javax.swing.*;

class Button1 implements ActionListener {


JFrame f = new JFrame();
Button b1;
Button b2;
Button b3;
Label l;
Button1(){
f = new JFrame();
b1= new Button("Red");
b2= new Button("Blue");
b3= new Button("Green");
l=new Label();
f.add(b1);
f.add(b2);
f.add(b3);
f.add(l);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.setSize(400,200);
f.setVisible(true);
}
public void actionPerformed(ActionEvent a)
{
String str = a.getActionCommand();
if(str.equals("Red"))
{
l.setForeground(Color.red);
l.setText("red color");
f.add(l);
f.setVisible(true);

// System.out.println("string in red color");


}
if(str.equals("Green"))
{

l.setForeground(Color.green);
l.setText("Green color");
f.add(l);
f.setVisible(true);
// System.out.println("string in yellow color");
}
if(str.equals("Blue"))

l.setForeground(Color.blue);
l.setText("blue color");
f.add(l);
f.setVisible(true);
// System.out.println("string in blue color");
}
}

public static void main(String[] args) {


Button1 b = new Button1();

}
}

Output:

Q93) WAP in java to exit from a Frame window when we click on Close button?
import java.awt.*;
import javax.swing.*;
class frame1 {
JFrame f = new JFrame();

Label l;
frame1(){
f = new JFrame();

l=new Label();

f.add(l);
l.setForeground(Color.RED);
Font f1 = new Font("Georgia",Font.BOLD,20);
l.setFont(f1);
l.setText("Press close button to exit the frame");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
f.setSize(400,200);
f.setVisible(true);
}

public static void main(String[] args) {


frame1 b = new frame1();

}
Output:

Q125). WAP to draw a string and choose its size respectively from combo box?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import javax.swing.JFrame;
//import javax.swing.JComboBox;
class Comboboxfont implements ItemListener{
JComboBox <Integer> j;
JLabel label;
JFrame f;
Comboboxfont b;

Comboboxfont(){
f = new JFrame("Select text size");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
Integer [] s = {10,20,30};///generic type do not support int primitive type
j = new JComboBox (s);
j.setBounds(50,50,10,20);
f.add(j);
f.setSize(1000,1000);
f.setVisible(true);
label = new JLabel();
j.addItemListener(this);
label.setForeground(Color.RED);
Font f1 = new Font("Serif",Font.BOLD,10);
label.setFont(f1);
label.setText("Select the size of the text from combobox");

f.add(label);
}

public void itemStateChanged(ItemEvent e) {


int i = j.getSelectedIndex();

if(i==0){

label.setForeground(Color.RED);
Font f1 = new Font("Serif",Font.BOLD,10);
label.setFont(f1);
label.setText("Select the size of the text from combobox");

f.add(label);

f.setVisible(true);

}
else{
if(i==1){
label.setForeground(Color.RED);
Font f1 = new Font("Serif",Font.BOLD,20);
label.setFont(f1);

label.setText("Select the size of the text from combobox");

f.add(label);
f.setVisible(true);

}
else if(i==2)
{

label.setForeground(Color.RED);
Font f1 = new Font("Serif",Font.BOLD,30);
label.setFont(f1);

label.setText("Select the size of the text from combobox");

f.add(label);
f.setVisible(true);
}
}
}
public static void main(String[] args) {
Comboboxfont b = new Comboboxfont();
}
}

Output:

Q131). Write a small application with a default date 01/01/2000 and three combo boxes displaying valid days, months &
year(1990 – 2050). Change the displayed date with the one chosen by user from these combo boxes?
import java.awt.event.*;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
class Dateselector implements ItemListener {
JFrame frame;
JComboBox <Integer> days;
JComboBox <String> Month; //Ayush Sharma 23
JComboBox <Integer> Year;
JLabel label;
int Defaultyear = 2000;

Dateselector (){
frame = new JFrame();
frame.getContentPane().setBackground(Color.cyan);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

frame.setSize(1000,1000);
label = new JLabel();
// days combobox
Integer [] validdays = new Integer[31];
for(int i = 0; i<31; i++)
{
validdays[i] = i+1;
}

days = new JComboBox<Integer>(validdays);


// days.setBounds(10,10,10,50);

//Month combobox
String[] months =
{"January","Febuary","March","April","May","June","July","August","September","October","Nove
mber","December"};
Month = new JComboBox<>(months);
// Month.setBounds(10,10,50,50);

//year combobox
Integer [] validyears = new Integer[61];
for(int i = 0; i<61; i++)
{
validyears[i] = 1990+i;
}
Year = new JComboBox<>(validyears);
Year.setSelectedItem(Defaultyear);
// Year.setBounds(10,10,50,50);

frame.add(days);
frame.add(Month);
frame.add(Year);
days.addItemListener(this);
Month.addItemListener(this);
Year.addItemListener(this);
label.setText("1/January/2000");
frame.add(label);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent event){
int selectedDay = (int)days.getSelectedItem();
String selectedMonth = (String)Month.getSelectedItem();
int selectedYear = (int)Year.getSelectedItem();
label.setText(selectedDay+" /"+selectedMonth+" /"+selectedYear);

frame.add(label);
}
public static void main(String[] args) {
Dateselector d = new Dateselector();
}
}

Output:

Q111). WAP in java to demonstrate all mouse events?


import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame.*;
import javax.swing.JFrame;
import javax.swing.JLabel;

class Mouse implements MouseListener {


JFrame f ;
JLabel l ;
Button b;
Mouse ()
{
f = new JFrame();
b = new Button("Color button");
l = new JLabel(null, null, 10);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 200);
f.setLayout(new FlowLayout(0));
f.add(b);
f.add(l);
b.addMouseListener(this);

f.setVisible(true);
}
public void mouseClicked(MouseEvent e){

f.getContentPane().setBackground(Color.cyan);
l.setText("Mouse Clicked");

}
public void mouseEntered(MouseEvent e){
f.getContentPane().setBackground(Color.RED);
l.setText("Mouse Entered");

}
public void mouseExited(MouseEvent e){
f.getContentPane().setBackground(Color.MAGENTA);
l.setText("Mouse Exited");

}
public void mousePressed(MouseEvent e){
f.getContentPane().setBackground(Color.YELLOW);
l.setText("Mouse Pressed");

public static void main(String[] args) {


Mouse m = new Mouse();
}
}

Output:

Q137) Create a GUI application for fees receipt which contains checkboxes for selecting the course, radio buttons for selecting
gender and labels and corresponding textboxes for name, class, date and amount paid ?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JLabel.*;
import javax.swing.JFrame.*;
class Fees implements ItemListener {
JFrame f ;
JLabel l1,l2,l3,l4,l5,l6;
JCheckBox cb1,cb2,cb3;
JRadioButton rb1,rb2;
JTextField tf1,tf2,tf3,tf4;
Fees(){
f= new JFrame("Fess interface", null);
f.setSize(600, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
f.getContentPane().setBackground(Color.orange);

//check boxes

cb1 = new JCheckBox("MCA", null, true);


cb2 = new JCheckBox("MTECH", null, false);
cb3 = new JCheckBox("MBA", null, false);
l1 = new JLabel(null, null, 0);
l2 = new JLabel(null, null, 0);
l1.setText("SELECT COURSE ");
l1.setBounds(200, 25, 400, 30);
f.add(cb1);
f.add(cb2);
f.add(cb3);
cb1.setBounds(300, 50, 100, 30);
cb2.setBounds(400, 50,100,30);
cb3.setBounds(500, 50,100,30);

f.add(l1);

// radiobuttons

rb1 = new JRadioButton("Male", null, false);


rb2 = new JRadioButton("Female", null, false);
l2.setText("SELECT GENDER");
l2.setBounds(200, 90, 400, 30);
f.add(l2);
f.add(rb1);
f.add(rb2);
rb1.setBounds(300, 120, 100, 30);
rb2.setBounds(400, 120, 100, 30);
f.setVisible(true);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
rb1.addItemListener(this);
rb2.addItemListener(this);
// labels and textfields
//name label and textf
l3 = new JLabel("NAME -", null, 0);
l3.setBounds(100, 200, 400, 30);
tf1 = new JTextField(null, "Name OF Student", 0);
tf1.setBounds(400,200,300,40);
f.add(l3);
f.add(tf1);
// class
l4 = new JLabel("CLASS -", null, 0);
l4.setBounds(100, 260, 400, 30);

tf2 = new JTextField(null, "Enter your class", 0);


tf2.setBounds(400,260,300,40);
f.add(l4);
f.add(tf2);

// ENROLL NO
l5 = new JLabel("ENROLL NO -", null, 0);
l5.setBounds(100, 310, 400, 30);

tf3 = new JTextField(null, "Enter Enroll No", 0);


tf3.setBounds(400,310,300,40);
f.add(l5);
f.add(tf3);

//AMOUNT PAID
l6 = new JLabel("AMT PAID -", null, 0);
l6.setBounds(100, 370, 400, 30);

tf4 = new JTextField(null, "Rs", 0);


tf4.setBounds(400,370,300,40);
f.add(l6);
f.add(tf4);

}
public void itemStateChanged(ItemEvent e){
if(cb1.isSelected() )
{
cb2.setSelected(false);
cb3.setSelected(false);
}
if(cb2.isSelected())
{
cb1.setSelected(false);
cb3.setSelected(false);
}
if(cb3.isSelected())
{
cb2.setSelected(false);
cb1.setSelected(false);

}
if(rb1.isSelected())
{
rb2.setSelected(false);
}
if(rb2.isSelected())
{
rb1.setSelected(false);
}
}
public static void main(String[] args) {
Fees f = new Fees();
}

Output:

You might also like