Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views42 pages

Java Practical Exam

Java codes

Uploaded by

tanajimore78tm
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)
9 views42 pages

Java Practical Exam

Java codes

Uploaded by

tanajimore78tm
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/ 42

Java Practical Exam:

1. WAP to find greatest and smallest of three numbers


 class A{
public static void main(String args[]){
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[2]);
if((a>b)&&(a>c)){
System.out.println(a+" is greatest");
if(b>c){
System.out.println(c+" is smallest");
}
else{
System.out.println(b+" is smallest");
}
}
else if((b>a)&&(b>c)){
System.out.println(b+" is greatest");
if(a>c){
System.out.println(c+" is smallest");
}
else{
System.out.println(a+" is smallest");
}
}
else{
System.out.println(c+" is greatest");
if(a>b){
System.out.println(b+" is smallest");
}
else{
System.out.println(a+" is smallest");
}
}
}
}
2. WAP to grades to the students based on average marks as given below
 class B{
public static void main(String args[]){
int marks=Integer.parseInt(args[0]);
System.out.println("Student Grades:");
if((marks>80)&&(marks<100)){
System.out.println("Distinction");
}
else if((marks>60)&&(marks<79)){
System.out.println("First Class");
}
else if((marks>50)&&(marks<59)){
System.out.println("Second Class");
}
else if((marks>40)&&(marks<49)){
System.out.println("Pass Class");
}
else{
System.out.println("Fail");
}
}
}
3. WAP to check if the given number is divisible by 7 and 9
 class C{
public static void main(String args[]){
int no=Integer.parseInt(args[0]);
System.out.println("Entered no:"+no);
if((no%7==0)&&(no%9==0)){
System.out.println(no+" is divisible by 7 and 9");
}
else{
System.out.println(no+" is divisible not by 7 and 9");
}
}
}
4. WAP to find greatest and smallest of two numbers using ternary operator
 class D{
public static void main(String args[]){
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int f=(a>b)?0:1;
if(f==0){
System.out.println(a+" is greatest");
System.out.println(b+" is smallest");
}
else{
System.out.println(b+" is greatest");
System.out.println(a+" is smallest");
}
}}
5. WAP to display month name from month no. using switch statement
 import java.io.*;
class E{
public static void main(String args[]){
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
try{
System.out.println("Enter no. of months:");
int m=Integer.parseInt(br.readLine());
if(m!=0){
switch(m){
case 1: System.out.println("Month: January");break;
case 2: System.out.println("Month: February");break;
case 3: System.out.println("Month: March");break;
case 4: System.out.println("Month: April");break;
case 5: System.out.println("Month: May");break;
case 6: System.out.println("Month: June");break;
case 7: System.out.println("Month: July");break;
case 8: System.out.println("Month: August");break;
case 9: System.out.println("Month: September");break;
case 10: System.out.println("Month: October");break;
case 11: System.out.println("Month: November");break;
case 12: System.out.println("Month: December");break;
default:System.out.println("Invalid Month NO."); break;
}
}
}
catch(IOException e){
System.out.println(e);
}
}
}
6. WAP to print prime number from 1 to 99 using do loop
 public class F {
public static void main(String args[]) {
int n = 1;
System.out.println("Prime numbers between 1 to 99:");
do {
int j = 2;
boolean isPrime = true;
if (n > 2) {
do {
if (n % j == 0) {
isPrime = false;
break;
}
j++;
} while (j <= Math.sqrt(n));
}
if (isPrime && n != 1)
System.out.print(" " + n);
n++;
} while (n <= 99);
}
}
7. WAP to check if the given no. is palindrome or not
 import java.io.*;
class G{
public static void main(String args[]){
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
try{
System.out.print("Enter no:");
int n=Integer.parseInt(br.readLine());
int r,sum=0;
int temp=n;
while(n>0){
r=n%10;
sum=sum*10+r;
n=n/10;
}
if(temp==sum){
System.out.println(temp+" is palindrome");
}
else{
System.out.println(temp+" is not palindrome");
}
}
catch(IOException e){
System.out.println(e);
}
}
}
8. WAP to print following pyramid using for loop.
*
**
***
****
*****
******
*******
********
*********
 class H {
public static void main(String args[]) {
int rows = 9;
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 1; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
9. WAP to find the factorial of a number using while loop
 import java.io.*;
class I {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter a number: ");
int n = Integer.parseInt(br.readLine());
int result = fact(n);
System.out.println("Factorial of " + n + " is: " + result);
} catch (IOException e) {
System.out.println(e);
}
}
static int fact(int n) {
while (n == 0)
return 1;
return n * fact(n - 1);
}
}
10. WAP to find reverse of a number using do loop
 import java.io.*;
class J {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter no.:");
int no = Integer.parseInt(br.readLine());
int sum = 0;
do {
int r = no % 10;
sum = (sum * 10) + r;
no = no / 10;
} while (no > 0);
System.out.println("Reverse of number:" + sum);
} catch (IOException e) {

}
}
}
11. WAP to find sum of digits of a number using for loop
 import java.io.*;
class K {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter no.: ");
int num = Integer.parseInt(br.readLine());
int sum = 0;
int n = num;
for (int i = num; i > 0; i /= 10) {
int digit = i % 10;
sum += digit;
}
System.out.println("Sum of digits in the number " + n + " is: " + sum);
} catch (Exception e) {
}
}
}
12. WAP to check whether the given number is prime or not using while loop.
 import java.io.*;
class L {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter no.: ");
int num = Integer.parseInt(br.readLine());
int prime = 0;
if (num <= 1) {
System.out.println(num + " is not prime");
} else {
int i = 2;
while (i <= Math.sqrt(num)) {
if (num % i == 0) {
prime = 1;
break;
}
i++;
}
if (prime == 1) {
System.out.println(num + " is not prime");
} else {
System.out.println(num + " is prime");
}
}
} catch (Exception e) {
}
}
}
13. Define the class cube having data members length, breath and height. Initialize three
objects using different constructors and display its volume.
 class Cube {
private float length;
private float breadth;
private float height;
public Cube(float l,float b,float h) {
length = l;
breadth = b;
height = h;
}
public Cube(float side) {
length = side;
breadth = side;
height = side;
}
public Cube() {
length = 2;
breadth = 4;
height = 3;
}
public float Volume() {
return length * breadth * height;
}
}
public class M{
public static void main(String[] args) {
Cube cube1 = new Cube(3, 4, 5);
Cube cube2 = new Cube(8);
Cube cube3 = new Cube();
System.out.println("Volume of cube1: " + cube1.Volume());
System.out.println("Volume of cube2: " + cube2.Volume());
System.out.println("Volume of cube3: " + cube3.Volume());
}
}
14. Define a class employee with data members as empid, name and salary. Accept data
for five objects and print it. (use parameterized constructor)
 import java.io.*;
class Employee {
private int empId;
private String name;
private double salary;
public Employee(int e,String n,double s) {
empId = e;
name = n;
salary = s;
}
public void Details() {
System.out.println("EmpID Name Salary");
System.out.println(" "empId +" "+name+" "+salary);
System.out.println();
}
}
public class N{
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Employee[] employees = new Employee[5];
try {
for (int i = 0; i < 5; i++) {
System.out.println("Enter details for Employee " + (i + 1) + ":");
System.out.print("Employee ID: ");
int empId = Integer.parseInt(br.readLine());
System.out.print("Name: ");
String name = br.readLine();
System.out.print("Salary: ");
double salary = Double.parseDouble(br.readLine());
employees[i] = new Employee(empId, name, salary);
}
} catch (Exception e) {
}
System.out.println("\nEmployee Details:");
for (Employee emp : employees) {
emp.Details();
}
}
}
15. WAP to calculate gross salary of five employees if basic, HRA and DA are given. Use
parameterized constructor.
 import java.io.*;
class Employee {
private int empId;
private double basic;
private double hra;
private double da;
private double gross;
public Employee(int e,double b,double h,double d) {
empId = e;
basic= b;
hra = h;
da =d;
}
public void calculate(){
gross=basic+hra+da;
}
public void Details() {
System.out.println("Employee ID:"+empId);
System.out.println("Basic Salary:"+basic);
System.out.println("HRA:"+hra);
System.out.println("DA:"+da);
System.out.println("Gross Salary:"+gross);
System.out.println();
}
}
public class O{
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Employee[] employees = new Employee[5];
try {
for (int i = 0; i < 5; i++) {
System.out.println("Enter details for Employee " + (i + 1) + ":");
System.out.print("Employee ID: ");
int empId = Integer.parseInt(br.readLine());
System.out.print("Basic Salary:");
double basic = Double.parseDouble(br.readLine());
System.out.print("HRA Salary: ");
double hra = Double.parseDouble(br.readLine());
System.out.print("DA Salary: ");
double da = Double.parseDouble(br.readLine());
System.out.println();
employees[i] = new Employee(empId, basic, hra,da);
employees[i].calculate();
}
} catch (Exception e) {
}
System.out.println("\nEmployee Salary Details:");
for (int i=0;i<5;i++) {
employees[i].Details();
}
}
}
16. . WAP to define class Employee with members as id and salary. Accept data for five
employees and display details of employees getting highest salary
 import java.io.*;
class Employee {
int empId;
double salary;
public Employee(int e,double s) {
empId = e;
salary = s;
}
public void Details() {
System.out.println("EmpID:"+empId);
System.out.println("Salary:"+salary);
System.out.println();
}
}
public class P{
public static void main(String[] args) {
double maxsalary;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Employee[] employees = new Employee[5];
try {
for (int i = 0; i < 5; i++) {
System.out.println("Enter details for Employee " + (i + 1) + ":");
System.out.print("Employee ID: ");
int empId = Integer.parseInt(br.readLine());
System.out.print("Salary: ");
double salary = Double.parseDouble(br.readLine());
employees[i] = new Employee(empId,salary);
}
} catch (Exception e) {
}
maxsalary=employees[0].salary;
int a=0;
System.out.println("\nEmployee Details:");
for (int i = 0; i < 5; i++) {
if(employees[i].salary>maxsalary)
{
a=i;
maxsalary=employees[i].salary;
}
}
employees[a].Details();
}
}
17. WAP to check whether the given string is a palindrome or not
 import java.io.*;
class Q {
public static void main(String args[]) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter String:");
String str = br.readLine();
int len = str.length() - 1;
int i = 0;
int r = len;
int flag = 1;
while (i < r) {
if (str.charAt(i) == str.charAt(r)) {
i++;
r--;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
System.out.println("String is palindrome");
} else {
System.out.println("String is not palindrome");
}
} catch (IOException e) {
System.out.println("Error reading input!");
}
}
}
18. WAP to show the use of following methods of String class on a String.  compareTo()
 charAt()  replace()  substring()
 public class R {
public static void main(String[] args) {
String str = "hello";
// Using compareTo() method
String str2 = "Hello";
int compareResult = str.compareTo(str2);
System.out.println("compareTo(): " + compareResult);

// Using charAt() method


char c= str.charAt(2);
System.out.println("charAt(2): " + c);

// Using replace() method


String r = str.replace('l', 'z');
System.out.println("replace(): " + r);

// Using substring() method


String sub = str.substring(2);
System.out.println("substring(2): " + sub);
}
}
19. WAP to show the use of following methods of StringBuffer class on a String. 
append()  insert()  reverse()  setCharAt()
 public class S {
public static void main(String[] args) {
StringBuffer str = new StringBuffer("hello");

// Using append() method


str.append(" world");
System.out.println("append(): " + str);

// Using insert() method


str.insert(5, ", ");
System.out.println("insert(): " + str);

// Using reverse() method


str.reverse();
System.out.println("reverse(): " + str);

// Using setCharAt() method


str.setCharAt(0, 'H');
System.out.println("setCharAt(0, 'H'): " + str);
}
}
20. Write a program to create and sort an integer array.
 import java.io.*;
class T{
public static void main(String args[]){
int[] arr=new int[5];
int n=arr.length;
int i,j,temp;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
try{
System.out.println("Enter "+n+" no.:");
for(i=0;i<n;i++){
arr[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<n;i++){
for(j=0;j<n-1-i;j++){
if(arr[j]>arr[j+1]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
System.out.println("Sorted array:");
for(i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
}
catch(Exception e){
}
}
}
21. Write a Java program to test if an array contains a specific value
 import java.io.*;
class V{
public static void main(String args[]){
int[] arr={1,4,7,8,9};
int n=arr.length;
int key,i,flag=0;
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
try{
System.out.print("Enter element to be find:");
key=Integer.parseInt(br.readLine());
for(i=0;i<n;i++){
if(key==arr[i]){
flag=1;
break;
}
}
if(flag==1){
System.out.println(key+" element is found at index "+i);
}
else{
System.out.println("element is not found!!");
}
}
catch(Exception e){}
}
}

22. Define the class mobile with data members ‘company_name’ & ‘screen_size’.
Initialize and display values of data members for five mobiles using array of objects.
 import java.io.*;
class mobile{
String company_name;
double screen_size;
mobile(String c,double s){
company_name=c;
screen_size=s;
}
void display(){
System.out.println("Mobile Details:");
System.out.println("Company Name:"+company_name);
System.out.println("Screen Size:"+screen_size);
System.out.println();
}
}
class U{
public static void main(String args[]){
mobile m[]=new mobile[5];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
for(int i=0;i<5;i++){
System.out.print("Company name:");
String c=br.readLine();
System.out.print("Screen Size:");
double s=Double.parseDouble(br.readLine());
System.out.println();
m[i]=new mobile(c,s);
}
for(int i=0;i<5;i++){
m[i].display();
}
}
catch(Exception e){}
}
}
23. Implement program to accomplished the following task using Vector class To add
two integers, two float, two characters, two string objects,To search a particular
object of the vector.
 import java.util.*;
public class W {
public static void main(String[] args) {
Vector v = new Vector();
// Adding integers
v.addElement(new Integer(10));
v.addElement(new Integer(20));
// Adding floats
v.addElement(new Float(10.5f));
v.addElement(new Float(20.5f));
// Adding characters
v.addElement(new Character('A'));
v.addElement(new Character('B'));
// Adding strings
v.addElement(new String("Hello"));
v.addElement(new String("World"));
// Displaying the vector
for(int i = 0; i < v.size(); i++) {
System.out.println("Vector element at index " + i + ": " + v.elementAt(i));
}
// Searching for a particular object
Object searchObject = 20;
if (v.contains(searchObject)) {
System.out.println("Object " + searchObject + " found at index " +
v.indexOf(searchObject));
} else {
System.out.println("Object " + searchObject + " not found in the vector.");
}
}
}
24. Implement program to accomplished the following task using Vector class . To
display all objects along with their position , To delete the object mentioned by the
user from vector
 import java.util.*;
import java.io.*;
public class X {
public static void main(String[] args) throws IOException {
Vector v = new Vector();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Adding integers
v.addElement(new Integer(10));
v.addElement(new Integer(20));
// Adding floats
v.addElement(new Float(10.5f));
v.addElement(new Float(20.5f));
// Adding characters
v.addElement(new Character('A'));
v.addElement(new Character('B'));
// Adding strings
v.addElement(new String("Hello"));
v.addElement(new String("World"));
// Displaying the vector
for(int i = 0; i < v.size(); i++) {
System.out.println("Vector element at index " + i + ": " + v.elementAt(i));
}
// Removing a particular object
System.out.println("Enter value of object to remove:");
String d = br.readLine();
if (v.contains(d)) {
v.removeElement(d);
System.out.println("Object '" + d + "' is removed" );
} else {
System.out.println("Object '" + d + "' not found in the vector.");
}
for(int i = 0; i < v.size(); i++) {
System.out.println("Vector element at index " + i + ": " + v.elementAt(i));
} }}
25. WAP to convert String value into Integer Wrapper class object
 public class Y {
public static void main(String[] args) {
// String value
String str = "123";
// Method 1: Using Integer.valueOf()
int Value1 = Integer.valueOf(str);
System.out.println("Using Integer.valueOf(): " + Value1);
// Method 2: Using Integer.parseInt()
int Value2 = Integer.parseInt(str);
System.out.println("Using Integer.parseInt(): " + Value2);
}
}
26. WAP to convert Integer object into primitive data type, short and double value.
 import java.io.*;
import java.util.*;
public class Z {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter no.:");
String input = br.readLine();
// Converting the String value to Integer object
Integer value = Integer.valueOf(input);
// Converting the Integer object to primitive data type int (not needed)
int i = value.intValue();
System.out.println("Converted to int: " + i);
// Converting the Integer object to primitive data type short
short s = value.shortValue();
System.out.println("Converted to short: " + s);
// Converting the Integer object to primitive data type double
double d = value.doubleValue();
System.out.println("Converted to double: " + d);
}
}
27. WAP to create class employee with data members name and id and display()
method. Create a subclass salary with data members bas_salary. Override display()
method and display the net salary.(Assume additional data if necessary)
 class Employee {
String name;
int id;
public Employee(String n, int i) {
name = n;
id = i;
}
public void display() {
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + id);
}
}
class Salary extends Employee {
double baseSalary;
double allowances;
public Salary(String n, int i, double b, double a) {
super(n, i);
baseSalary = b;
allowances = a;
}
public void display() {
super.display();
double netSalary = baseSalary + allowances;
System.out.println("Base Salary: " + baseSalary);
System.out.println("Allowances: " + allowances);
System.out.println("Net Salary: " + netSalary);
}
}
public class AA {
public static void main(String[] args) {
Salary emp1 = new Salary("John Doe", 1001, 50000, 2000);
System.out.println("Details of Employee:");
emp1.display();
}
}
28. WAP to extend class dog from class animal to override move() method.
 class Animal {
public void move() {
System.out.println("Animal is moving.");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dog is running.");
}
}
public class BB {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.move();
dog.move();
}
}
29. WAP to calculate the room area and volume using single inheritance.
class Room {
double length;
double width;
double height;
public Room(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double Area() {
return 2 * (length * width + length * height + width * height);
}
public double Volume() {
return length * width * height;
}
}
public class CC extends Room {
public CC(double l, double w, double h) {
super(l, w, h);
}
public static void main(String[] args) {
double length = 5.0;
double width = 4.0;
double height = 3.0;
CC r = new CC(length, width, height);
double area = r.Area();
double volume = r.Volume();
System.out.println("Room Area: " + area);
System.out.println("Room Volume: " + volume);
}
}
30. WAP to calculate the room area and volume using multilevel inheritance
 class Room {
double length;
double width;
double height;
public Room(double l, double w, double h) {
length = l;
width = w;
height = h;
}
public double Area() {
return 2 * (length * width + length * height + width * height);
}
public double Volume() {
return length * width * height;
}
}
class Bedroom extends Room {
double doorWidth;
double doorHeight;
public Bedroom(double l, double w, double h, double dw, double dh) {
super(l, w, h);
doorWidth = dw;
doorHeight = dh;
}
public double Area1() {
return Area() - (doorWidth * doorHeight);
}
}
public class DD extends Bedroom {
public DD(double l, double w, double h, double dw, double dh) {
super(l, w, h, dw, dh);
}
public static void main(String[] args) {
double l = 5.0;
double w = 4.0;
double h = 3.0;
double dw = 1.0;
double dh = 2.0;
DD d = new DD(l, w, h, dw, dh);
double area = d.Area();
double volume = d.Volume();
double availableArea = d.Area1();
System.out.println("Room Area: " + area);
System.out.println("Room Volume: " + volume);
System.out.println("Available Area " + availableArea);
}
}
31. WAP to create a class Student with data members sid, sname and display() method.
Create a subclass Marks with data members m1, m2 (Marks in subjects 1 and 2) and
override display() method. Create a subclass of class marks having data member
spmarks and override display() method. Calculate total marks and display.
 class Student {
int sid;
String sname;
public Student(int i, String n) {
sid = i;
sname = n;
}
public void display() {
System.out.println("Student ID: " + sid);
System.out.println("Student Name: " + sname);
}
}
class Marks extends Student {
int m1;
int m2;
public Marks(int i, String n, int a1, int a2) {
super(i, n);
m1 = a1;
m2 = a2;
}
public void display() {
super.display();
System.out.println("Marks in Subject 1: " + m1);
System.out.println("Marks in Subject 2: " + m2);
}
public int Total() {
return m1 + m2;
}
}
class SportsMarks extends Marks {
int spmarks;
public SportsMarks(int i, String n, int a1, int a2, int s) {
super(i, n, a1, a2);
spmarks = s;
}
public void display() {
super.display();
System.out.println("Sports Marks: " + spmarks);
int totalMarks = Total() + spmarks;
System.out.println("Total Marks (including sports): " + totalMarks);
}
}
public class EE {
public static void main(String[] args) {
Marks s1 = new Marks(101, "John", 85, 90);
s1.display();
SportsMarks s2 = new SportsMarks(102, "Alice", 75, 80, 10);
s2.display();
}
}
32. WAP to implement the following.

Class :Device Interface : Loader

Company_name, loadOS();
RAM
OS_version

Class : Mobile

loadOS()
 interface Loader {
void loadOS();
}
class Device {
String companyName;
int RAM;
String OSVersion;
Device(String n, int r, String o) {
companyName = n;
RAM = r;
OSVersion = o;
}
}
class Mobile extends Device implements Loader {
Mobile(String n, int r, String o) {
super(n,r,o);
}
public void display()
{
System.out.println("Company Name: " + companyName);
System.out.println("RAM: " + RAM + "GB");
System.out.println("OS Version: " + OSVersion);
}
public void loadOS() {
System.out.println("Loading OS for Mobile...");
}
}
public class FF {
public static void main(String[] args) {
Mobile m = new Mobile("Samsung", 4, "Android");
m.display();
m.loadOS();
}
}
33. WAP to implement the following.
Class : Student Interface : Exam

name,rollno, percent_cal();
m1,m2

Class : Result

display()

 interface Exam {
double percent_cal();
}
class Student {
String name;
int rollNo;
double m1, m2;
public Student(String n, int r, double a1, double a2) {
name = n;
rollNo = r;
m1 = a1;
m2 = a2;
}
}
class Result extends Student implements Exam {
public Result(String n, int r, double a1, double a2) {
super(n, r, a1, a2);
}
public double percent_cal() {
return (m1 + m2) / 2;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Roll No: " + rollNo);
System.out.println("Marks 1: " + m1);
System.out.println("Marks 2: " + m2);
System.out.println("Percentage: " + percent_cal());
}
}
public class GG {
public static void main(String[] args) {
Result result = new Result("John", 123, 85, 90);
result.display();
}
}
34. WAP to implement the following
Class : Employee Interface : Gross

name, bas_sal ta, da, gross_sal();

Class : Salary

hra, display_net()

 interface Gross {
double TA = 1000;
double DA = 2000;
double gross_sal();
}
class Employee {
String name;
double basicSalary;
public Employee(String n, double b) {
name = n;
basicSalary = b;
}
}
class Salary extends Employee implements Gross {
double HRA;
public Salary(String n, double b, double h) {
super(n, b);
HRA = h;
}
public double gross_sal() {
return basicSalary + TA + DA;
}
public void display_net() {
double netSalary = gross_sal() + HRA;
System.out.println("Name: " + name);
System.out.println("Net Salary: " + netSalary);
}
}
public class HH {
public static void main(String[] args) {
Salary e1 = new Salary("John", 5000, 1500);
System.out.println("Gross Salary: " + e1.gross_sal());
e1.display_net();
}
}
35. Define a package named ‘useful’ with the class name ‘UseMe’ having a method to
calculate the salary. Import the above package ‘useFul’ and make use of salary()
method.
 //package……..
package useful;
public class UseMe {
public double Salary(double basicSalary, double TA, double DA) {
double salary = basicSalary + TA + DA;
return salary;
}
}
//class importing package
import useful.UseMe;
public class II {
public static void main(String[] args) {
UseMe u = new UseMe();
double basicSalary = 5000;
double TA = 1000;
double DA = 2000;
double salary = u.Salary(basicSalary, TA, DA);
System.out.println("Calculated Salary: " + salary);
}
}
36. Define a package named ‘useful’ with the class names ‘UseMe’ having a method to
calculate the area of two different shapes. Import the above package ‘useFul’ and
make use of methods to calculate area.
 //package ……..
package useful;
public class UseMe1 {
public double RectangleArea(double length, double width) {
return length * width;
}
public double CircleArea(double radius) {
return 3.14 * radius * radius;
}
}
//class importing package
import useful.UseMe1;
public class JJ {
public static void main(String[] args) {
UseMe1 u = new UseMe1();
double length = 5;
double width = 3;
double rArea = u.RectangleArea(length, width);
System.out.println("Area of Rectangle: " + rArea);
double radius = 4;
double cArea = u.CircleArea(radius);
System.out.println("Area of Circle: " + cArea);
}
}
37. Define a package named ‘useful’ with the class name ‘UseMe’ having a method to
calculate the percentage. Import the above package ‘useFul’ and make use of
method to calculate percentage
 //package…….
package useful;
public class UseMe3 {
public double Percentage(double obtainedMarks, double totalMarks) {
return (obtainedMarks / totalMarks) * 100;
}
}
//class importing package
import useful.UseMe3;
public class KK{
public static void main(String[] args) {
UseMe3 u = new UseMe3();
double obtainedMarks = 450;
double totalMarks = 500;
double percentage = u.Percentage(obtainedMarks, totalMarks);
System.out.println("Percentage: " + percentage + "%");
}
}
38. Develop a program to create two threads. One thread print number from 1 to 10 &
the other thread prints numbers from 10 to 1. Use Thread class.
 class Numbers1 extends Thread {
public void run() {
System.out.println("Printing numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
class Numbers2 extends Thread {
public void run() {
System.out.println("Printing numbers from 10 to 1:");
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println();
}
}
public class LL {
public static void main(String[] args) {
Numbers1 thread1 = new Numbers1();
Numbers2 thread2 = new Numbers2();
thread1.start();
try{
thread1.sleep(100);
}
catch(InterruptedException e){
System.out.println(e);
}
thread2.start();
}
}
39. Develop a program to create two threads. One thread print number from 1 to 10 &
the other thread prints prime numbers between 50 to 100. . Use Thread class.
 class Numbers extends Thread {
public void run() {
System.out.println("Printing numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
class Prime extends Thread {
public void run() {
System.out.println("Printing prime numbers between 50 to 100:");
for (int i = 50; i <= 100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
public boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
public class MM {
public static void main(String[] args) {
Numbers thread1 = new Numbers();
Prime thread2 = new Prime();
thread1.start();
try{
thread1.sleep(100);
}
catch(InterruptedException e)
{
System.out.print(e);
}
thread2.start();
}
}
40. Develop a program to create two threads. One thread print multiples of 5 & the
other thread prints multiples of 7. Use Thread class. Introduce a delay of 1000ms
after printing every number
 class Five extends Thread {
public void run() {
System.out.println("Numbers divisible by 5:");
for (int i = 1; i <= 50; i++) {
if (i % 5 == 0) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.print(e);
}
}
}
}
}
class Seven extends Thread {
public void run() {
System.out.println("\nNumbers divisible by 7:");
for (int i = 1; i <= 50; i++) {
if (i % 7 == 0) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.print(e);
}
}
}
}
}
public class NN {
public static void main(String args[]) {
Five a = new Five();
Seven b = new Seven();
a.start();
try{
a.sleep(10000);
}
catch(InterruptedException e){}
b.start();
}
}
41. Develop a program to create two threads. One thread print even numbers from 1 to
100 & the other thread prints odd numbers from 200 to 300. Use Runnable interface
 class Even implements Runnable {
public void run() {
System.out.println("Even numbers from 1 to 100:");
for (int i = 2; i <= 100; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
class Odd implements Runnable {
public void run() {
System.out.println("Odd numbers from 200 to 300:");
for (int i = 201; i <= 299; i += 2) {
System.out.print(i + " ");
}
System.out.println();
}
}
public class OO {
public static void main(String[] args) throws InterruptedException{
Even e = new Even();
Odd o = new Odd();
Thread thread1 = new Thread(e);
Thread thread2 = new Thread(o);
thread1.start();
thread1.sleep(100);
thread2.start();
}
}
42. Develop a program to create two threads. One thread print prime numbers between
1 to 100 & the other thread prints non prime numbers from 200 to 250. Use
Runnable interface
 class Prime implements Runnable {
public void run() {
System.out.println("Prime numbers between 1 to 100:");
for (int i = 2; i <= 100; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
public boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
class NonPrime implements Runnable {
public void run() {
System.out.println("Non-prime numbers between 200 to 250:");
for (int i = 200; i <= 250; i++) {
if (!isPrime(i)) {
System.out.print(i + " ");
}
}
System.out.println();
}
public boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
public class PP {
public static void main(String[] args) throws InterruptedException {
Prime Y = new Prime();
NonPrime N = new NonPrime();
Thread thread1 = new Thread(Y);
Thread thread2 = new Thread(N);
thread1.start();
thread1.sleep(100);
thread2.start();
}
}
43. Develop a program to create two threads. One thread print numbers from 1 to 10 &
the other thread prints odd numbers from 20 to 30. Use Runnable interface.
Introduce a delay of 1000ms after printing every number.
 class Numbers implements Runnable {
public void run() {
System.out.print("Numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.print(e);
}
}
System.out.println();
}
}
class Odd implements Runnable {
public void run() {
System.out.println();
System.out.print("Odd no. from 20 to 30:");
for (int i = 21; i <= 30; i+=2) {
System.out.print(i + " ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.print(e);
}
}
System.out.println();
}
}
public class QQ {
public static void main(String[] args) throws InterruptedException {
Numbers N = new Numbers();
Odd O = new Odd();
Thread thread1 = new Thread(N);
Thread thread2 = new Thread(O);
thread1.start();
thread1.sleep(10000);
thread2.start();
}
}
44. WAP to throw ArrayIndexOutOfBoundsException
public class RR {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
try {
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught!");
}
}
}
45. WAP to throw ArithmaticException
public class SS {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught!");
}
}
}
46. WAP to accept a password rom the user and throw an “Authentication Failure”
exception if the password does not match.
 import java.io.*;
public class TT {
public static void main(String[] args) throws IOException {
String str1= "password123";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter password: ");
String str2 = reader.readLine();
if (str2.equals(str1)) {
System.out.println("Authentication Successful!");
} else {
throw new AuthenticationFailureException("Authentication Failure: Password does
not match");
}
}
catch (AuthenticationFailureException e) {
System.out.println(e);
}
}
}
class AuthenticationFailureException extends Exception {
public AuthenticationFailureException(String message) {
super(message);
}
}
47. WAP to accept a number from the user and throw “Not a prime number “ exception
if the number is not a prime number.
 import java.io.*;
public class UU {
public static void main(String[] args) throws IOException,NumberFormatException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter a number: ");
int number = Integer.parseInt(reader.readLine());
if (isPrime(number)) {
System.out.println("The number " + number + " is a prime number.");
} else {
throw new NotPrimeNumberException("Not a prime number: " + number);
}
} catch (NotPrimeNumberException e) {
System.out.println(e);
}
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
class NotPrimeNumberException extends Exception {
public NotPrimeNumberException(String message) {
super(message);
}
}
48. WAP to handle IOException using throws clause.
 import java.io.*;
public class VV {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your name: ");
String name = reader.readLine();
System.out.println("Hello, " + name + "! Welcome to our program.");
}
}
49. WAP to handle StringIndexOutOfBoundsException using throws clause.
 public class XX{
public static void main(String[] args) throws StringIndexOutOfBoundsException {
String str = "Hello";
try {
char ch = str.charAt(10);
System.out.println("Character at index 10: " + ch);
} catch (StringIndexOutOfBoundsException e) {
System.out.println(e);
}
}
}
50. Design an applet to draw three concentric circles in different colors. Also draw four
arcs around the circles.
 import java.applet.*;
import java.awt.*;
/*<applet code=BBB.class width=200 height=300></applet>*/
public class BBB extends Applet {
public void paint(Graphics g) {
// Set background color
setBackground(Color.white);
// Draw the first circle
g.setColor(Color.red);
g.fillOval(50, 50, 200, 200);
// Draw the second circle
g.setColor(Color.green);
g.fillOval(75, 75, 150, 150);
// Draw the third circle
g.setColor(Color.blue);
g.fillOval(100, 100, 100, 100);
// Draw arcs around the circles
g.setColor(Color.black);
g.drawArc(25, 25, 250, 250, 0, 90);
g.drawArc(25, 25, 250, 250, 90, 90);
g.drawArc(25, 25, 250, 250, 180, 90);
g.drawArc(25, 25, 250, 250, 270, 90);
}
}
51. Design an applet to show the use of following methods of Graphics class. Use
different colors for different figures.
a. drawArc()
b. drawPolygon()
c. drawLine()
d. drawRect()

 import java.applet.*;

import java.awt.*;

/*<applet code= DrawShapes.class width=200 height=300></applet>*/

public class DrawShapes extends Applet {

public void paint(Graphics g) {

// Set background color

setBackground(Color.white);

// Draw arcs with different colors

g.setColor(Color.red);

g.drawArc(50, 50, 100, 100, 0, 90);

g.setColor(Color.blue);

g.drawArc(200, 50, 100, 100, 0, 180);

// Draw polygons with different colors

int[] xPoints = {150, 250, 200};

int[] yPoints = {200, 200, 100};

Polygon polygon = new Polygon(xPoints, yPoints, 3);

g.setColor(Color.green);
g.drawPolygon(polygon);

// Draw lines with different colors

g.setColor(Color.orange);

g.drawLine(50, 250, 150, 350);

g.setColor(Color.magenta);

g.drawLine(200, 250, 300, 350);

// Draw rectangles with different colors

g.setColor(Color.yellow);

g.drawRect(50, 400, 100, 50);

g.setColor(Color.cyan);

g.fillRect(200, 400, 100, 50);

52. Design an applet to display “Welcome to java Programming” in Dialog, with bold and
Italic and size 12. Draw six circles one below the other. Alternate circles should be
filled with different colors
 import java.applet.Applet;
import java.awt.*;
/*<applet code=WelcomeApplet.class width=200 height=300></applet>*/
public class WelcomeApplet extends Applet {
public void init() {
setBackground(Color.white);
}
public void paint(Graphics g) {
Font font = new Font("Arial", Font.BOLD | Font.ITALIC, 12);
g.setFont(font);
g.drawString("Welcome to Java Programming", 50, 50);
int x = 50;
int y = 100;
int diameter = 50;
Color[] colors = {Color.red, Color.blue, Color.green, Color.yellow, Color.orange,
Color.pink};
for (int i = 0; i < 6; i++) {
g.setColor(colors[i]);
g.fillOval(x, y, diameter, diameter);
y += 70;
}
}
}
53. Design an applet to draw a cube and a cylinder in different colors.
 import java.applet.*;
import java.awt.*;
/*<applet code= CubeAndCylinderApplet.class width=200 height=300></applet>*/
public class CubeAndCylinderApplet extends Applet {
public void paint(Graphics g) {
// Set background color
setBackground(Color.WHITE);
// Draw cube
g.setColor(Color.RED);
g.drawRect(50, 50, 100, 100); // front face
g.drawRect(100, 100, 100, 100); // right face
g.drawLine(50, 50, 100, 100);
g.drawLine(150, 50, 200, 100);
g.drawLine(150, 150, 200, 200);
g.drawLine(50, 150, 100, 200);
// Draw cylinder
g.setColor(Color.BLUE);
g.drawOval(250, 50, 100, 100); // top ellipse
g.drawOval(250, 150, 100, 100); // bottom ellipse
g.drawLine(250, 100, 250, 200); // left side
g.drawLine(350, 100, 350, 200); // right side
g.drawArc(250, 50, 100, 100, 0, 180); // top arc
g.drawArc(250, 150, 100, 100, 0, 180); // bottom arc
}
}
54. Design an applet to draw a square inside a circle and a cylinder in different colors.
 import java.applet.*;;
import java.awt.*;

/*<applet code= SquareCircleCylinderApplet.class width=200 height=200></applet>*/

public class SquareCircleCylinderApplet extends Applet {

public void paint(Graphics g) {

// Set background color

setBackground(Color.WHITE);

// Draw circle

g.setColor(Color.RED);

g.drawOval(50, 50, 100, 100); // circle

// Draw square inside the circle

g.setColor(Color.BLUE);

g.drawRect(75, 75, 50, 50); // square

// Draw cylinder

g.setColor(Color.GREEN);

// Top ellipse

g.drawOval(200, 50, 100, 100);

// Bottom ellipse

g.drawOval(200, 150, 100, 100);

// Lines connecting top and bottom ellipses

g.drawLine(200, 100, 200, 200);

g.drawLine(300, 100, 300, 200);

// Lines connecting top and bottom ellipses diagonally

g.drawLine(200, 50, 200, 100);

g.drawLine(300, 50, 300, 100);

g.drawLine(200, 150, 200, 200);


g.drawLine(300, 150, 300, 200);

55. Design an applet to draw a cone and circle inside a square in different colors
 import java.applet.*;
import java.awt.*;
/*<applet code= ConeCircleSquareApplet.class width=200 height=200></applet>*/

public class ConeCircleSquareApplet extends Applet {


public void paint(Graphics g) {
// Set background color
setBackground(Color.WHITE);
// Draw square
g.setColor(Color.BLUE);
g.drawRect(50, 50, 100, 100); // square
// Draw circle inside the square
g.setColor(Color.RED);
g.drawOval(65, 65, 70, 70); // circle
// Draw cone
g.setColor(Color.GREEN);
// Lines connecting top of the cone to the square
g.drawLine(85, 50, 100, 20);
g.drawLine(100, 20, 135, 50);
// Arc for base of the cone
g.drawArc(65, 120, 70, 20, 0, 180);
}
}
56. WAP to copy characters from one file to another.
 import java.io.*;
public class YY {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
try (FileReader reader = new FileReader(sourceFile);
FileWriter writer = new FileWriter(destinationFile)) {
int character;
while ((character = reader.read()) != -1) {
writer.write(character);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println(e);
}
}
}
57. WAP to write bytes from one file to another
 import java.io.*;
public class ZZ {
public static void main(String[] args) {
String sourceFile = "source.txt";
String destinationFile = "destination.txt";
try (FileInputStream inputStream = new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
System.out.println(e);
}
}
}
58. WAP to display the contents file supplied as command line argument.
 import java.io.*;
public class AAA {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java AAA source");
return;
}
String fileName = args[0];
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}

You might also like