You are on page 1of 43

GURUNANAK INSTITUTE OF TECHNOLOGY

Name: Subhasish Ghosh

Stream: MCA Year: 2023


Sem: 2nd

Roll No: 504122011057

Subject: OBJECT ORIENTED PROGRAMMING WITH JAVA

Subject Code : MCA20-203


[Roll No:-504122011057] | [Subhasish Ghosh]

SI. Question Page


No. NO
1. WAP in Java to make a simple calculator using switch case. 5
2. WAP in java to take a score from user and print as follows- 6

If the score is less than 20, print “fail”


Or If score is greater than 21 and less than 50, print “Grade D”
Or If score is greater than 51 and less than 70, print “Grade C”
Or If score is greater than 71 and less than 90, print “Grade B”
Or If score is greater than 91and less than 100, print “Grade A”
3. Print this pattern 7
a) *
**
***
****
*****
b) *
***
*****
*******
*********
4. Take a string from user and show whether the string is palindrome or not. 8
5. Take a string from user and find the reverse of the string 9
6. Take strings from user and apply these below String class methods- 10
isEmpty( ), trim( ), compareToIgnoreCase( ),substring( ), replaceFirst( ),
replaceAll( ), indexOf( ),contains( ), valueOf( ) and split( )

7. Show the difference between equals( ) and “ == ” with a suitable program. 11

8. Take your roll no.(only last two digits), name, java lab paper code and date; initialize 12
them within constructor and print.

9. Using nested if-else do the following,Take the amount of salary and working hour of an 13
employee. If i)Salary>20K and <30K and working hour>=7 hr, increase salary by 20%
and show the new salary ii)Salary>20K and <30K and working hour>=5 hr but <7 hr,
increase salary by 10% and show the new salary iii)Salary>20K and <30K and working
hour>3 hr but <5 hr, increase salary by 5% and show the new salary If- i)Salary>8K and
<20K and working hour>7-8 hr, increase salary by 15% and show the new salary
ii)Salary>8K and <20K and working hour>=5 hr but <7 hr, increase salary by 10% and
show the new salary iii)Salary>8K and <20K and working hour>3 hr but <5 hr, print “no
increment” in salary

10. (21*3)+85%7-{66+(39-29-24)} 15
11. Create a class named ‘Flower’ with instance variables ‘color’, ’season’, ’smell’ and a 16
method common for every flower. Create two subclasses named ‘Rose’ and
‘Sunflower’. Initialize those instance variables of parent class into subclasses and also
create new methods correspond to each child class. Show the instance variables and
invoke methods creating object of child class
12. Create a class ‘Phone’. Derive two classes ‘Telephone’ and ‘Mobile’. Put methods 18
within those classes to print separate features of Telephone and Mobile like- whether
wireless or not , have display or not etc. . Derive a class from ‘mobile’ class named
‘iPhone’ and mention methods to print the basic features of that model of mobile. Invoke
the methods of parent and child class by creating object of child class.
13. Create a class ‘Student’. Take values from user. Create methods with name 20
‘calGrade’ such that-If dept= ‘English’, grade=( score + 90% of attendance)If

Page 2 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

dept= ‘Math’, grade=( score + 80% of attendance+ assignment marks)If dept=


‘Physics’, grade=( score + assignment marks+ practical marks)If dept= ‘Com.
Sc., grade=( score + + 80% of attendance +assignment marks+ practical
marks)

14. Create a Interface named 'Member' having the following members: 22


Data members ID, name, phone no., Address, Salary
It also has a method named 'printData' to print the data. Two classes 'Employee' and
'Manager' are derived from the 'Member' class. The 'Employee' and 'Manager' classes
have additional data member 'department'. Now, assign name, age, phone number,
address and salary to an employee and a manager and also define printData method. Now
invoke the method from derived classes
15. Create a method within a class. Also create a main method within another class. Now 24
call the method from main method without creating object of that class.
16. Create two classes ‘Rose’ which prints “Color is Red” and ‘Sunflower’ which prints 25
“Color is Yellow” but the method name should be ‘showColor’ for both the classes.
Create object to show the result.

17. Create a class ‘Employee’ with variables- name, dept, designation, initialize them and 26
define methods to print the information. Extend a class from employee class with two
new variables ID, salary. Now override the super class method to print parent class
variables as well as child class variables. Remember: you can only create object of sub
class.

18. Do the same as previous program but now create a constructor to initialize the variables. 27
Then in subclass create a constructor to initialize new(additional ) variables. Lastly call
the method to show the member variable values.

19. Make a package named ‘firstPkg’ in which create a class and define a method. The 28
method takes two numbers as parameters and subtracts the smaller number from the
bigger one. Now in your program call that method and do the same with your values
given from user
20. Create a package ‘firstPkg’ where put a class ‘firstmtd’ and a method with some print 29
statement and create a package ‘MyPkg’ where put a class ‘Mymtd’ where we have main
method. Call the method from main method creating object. Show the result.
21. Create a package ‘MyPkg1’ where create a method within a class with some statements 30
inside it. Mention the method as ‘protected’. Then create a package ‘MyPkg2’ where
create a class ‘Mymtd’ which will inherit the class of ‘MyPkg1’. Now invoke the method
from main method . Show the result.

22. Let the features of a class named ‘Animal’ succeeded into class ‘Cat’ and the features of 32
Cat into class ‘Tiger’. Cat has two methods that prints “It is a domestic animal” and “It is
carnivorous” respectively. Now tiger is not domestic, so inherit Tiger in a way that this
method can’t be acquired from Cat into Tiger.

23. Assignment Take an array from user and print the even and odd numbers from the array 32
3
24. With a basic try catch block, show exception handling. 33

25. Write a program in java on arithmetic exception with finally block. 34

Page 3 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

26. WAP in java to throw any checked exception using ‘throws’ keyword. 35

27. Write an applet to create three buttons to change the background color. 35

28. Write an applet in AWT to take user name and phone number from user and print 37
those.

29. Write an applet program to take user parameters(employee name, designation, 38


salary) and print those.

30. Take two values and find the bigger one between then using applet 39

31. Using java AWT make two radio buttons named ‘BCA’ and ‘MCA’, to take the steam of 41
a student and three check box named ‘Java’ , ‘C’ and ‘C++’ , to take the subject of a
student.

Assignment-1
1. WAP in Java to make a simple calculator using switch case.
Code:-

Page 4 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

import java.util.Scanner;
class Switchcalc {
public static void main(String[] args) {
int a,b,ch;
System.out.print("Enter the number of A: ");
Scanner r=new Scanner(System.in);
a=r.nextInt();
System.out.print("Enter the number of B: ");
Scanner r1=new Scanner(System.in);
b=r1.nextInt();
System.out.print("\n");
System.out.print("1. Addition \n");
System.out.print("2. Subtraction \n");
System.out.print("3. Multiplication \n");
System.out.print("4. Division \n");
System.out.print("\n");
System.out.print("Enter your choice: ");
Scanner ref=new Scanner(System.in);
ch=ref.nextInt();
switch (ch)
{
case 1: int add= a+b;
System.out.print("Sum = " + add);
break;
case 2: int sub= a-b;
System.out.print("Sub = " + sub);
break;
case 3: int mul= a*b;
System.out.print("Mul = " + mul);
break;
case 4: int div=a/b;
System.out.print("Div = " + div);
break;
default: System.out.print("Wrong Choice !");
}
System.out.print("\n");
System.out.print("Out of the Switch Case.......");
}
}
Output:-

Page 5 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

2. WAP in java to take a score from user and print as follows-


If the score is less than 20, print “fail”
Or If score is greater than 21 and less than 50, print “Grade D”
Or If score is greater than 51 and less than 70, print “Grade C”
Or If score is greater than 71 and less than 90, print “Grade B”
Or If score is greater than 91and less than 100, print “Grade A”
Code:-
import java.util.Scanner;
public class Grade {
public static void main(String[] args)
{
int score;
System.out.print("Enter the score: ");
Scanner ref=new Scanner(System.in);
score=ref.nextInt();
if(score<=100) {
if (score >= 91 && score <= 100) {
System.out.print("Grade A");
} else if (score >= 71 && score <= 90) {
System.out.print("Grade B");
} else if (score >= 51 && score <= 70) {
System.out.print("Grade C");
} else if (score >= 21 && score <= 50) {
System.out.print("Grade D");
} else {
System.out.print("Fail");
}
}

Page 6 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

else{
System.out.print("Not a given Score");
}
}
}
Output:-

3. Print this pattern


a)
*
**
***
****
*****
Code:-
class pattern1 {
public static void main(String[] args) {

int n = 5;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");

}
System.out.print("\n");
}
}
}

Output:-

Page 7 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Print the pattern


b)
*
***
*****
*******
*********
Code:-
class pattern2 {
public static void main(String[] args) {

int n = 9;
for (int i = 1; i <= n; i=i+2) {
for (int j = 1; j <= i; j++) {
System.out.print("*");

}
System.out.print("\n");
}
}
}
Output:-

4. Take a string from user and show whether the string is palindrome or
not.
Code:-
import java.util.Scanner;
class palindrome {
public static void main(String[] args) {
String a;
System.out.print("Enter the String: ");
Scanner r=new Scanner(System.in);
a=r.nextLine();
boolean flag = true;

Page 8 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

a = a.toLowerCase();
for(int i = 0; i < a.length()/2; i++){
if(a.charAt(i) != a.charAt(a.length()-i-1)){
flag = false;
break;
}
}
if(flag)
System.out.println("Given string is palindrome");
else
System.out.println("Given string is not a palindrome");
}
}
Output:-

5. Take a string from user and find the reverse of the string.
Code:-
import java.util.Scanner;
class Reverse {
public static void main(String[] args) {
String a,b="";
int l;
System.out.print("Enter the String: ");
Scanner r=new Scanner(System.in);
a=r.nextLine();
l=a.length();
for(int i=l-1;i>=0;i--)
{
b=b+a.charAt(i);
}
System.out.print(b);
}
}
Output:-

Page 9 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

6. Take strings from user and apply these below String class methods-
isEmpty( ), trim( ), compareToIgnoreCase( ),substring( ),
replaceFirst( ), replaceAll( ), indexOf( ),contains( ), valueOf( ) and
split( )
Code:-
import java.util.Scanner;
public class StringMethodsDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// isEmpty()
boolean isEmpty = inputString.isEmpty();
System.out.println("isEmpty(): " + isEmpty);
// trim()
String trimmedString = inputString.trim();
System.out.println("trim(): " + trimmedString);
// compareToIgnoreCase()
System.out.print("Enter another string to compare: ");
String compareString = scanner.nextLine();
int comparisonResult = inputString.compareToIgnoreCase(compareString);
System.out.println("compareToIgnoreCase(): " + comparisonResult);
// substring()
String str3 = new String("Rs 1000");
System.out.println("substring(): " + str3.substring(3));
// replaceFirst()
System.out.print("Enter the regular expression for replaceFirst: ");
String regex = scanner.nextLine();
System.out.println("replaceFirst(): " + regex.replaceFirst("aa", "zz"));
// replaceAll()
String s1="Java is a good language";
String replaceString=s1.replaceAll("a","e");
System.out.println("replaceAll(): " + replaceString);
// indexOf()
String searchStr = "Hello planet earth, you are a great planet.";
System.out.println("indexOf(): " + searchStr.indexOf("e",2));
// contains()
System.out.print("Enter the substring to check for contains: ");
String subStr = scanner.nextLine();
System.out.println("contains(): " + subStr.contains("Hel"));
// valueOf()
int value=30;

Page 10 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

String s2=String.valueOf(value);
System.out.println("valueOf(): " + s2+10);
// split()
String text = "Java is a fun programming language";
String[] result = text.split(" ");
System.out.print("result = ");
for (String str : result)
{
System.out.print(str + ", ");
}
scanner.close();
}
}
Output:-

7. Show the difference between equals( ) and “ == ” with a suitable


program.
Code:-
class Equals {
public static void main(String[] args) {

String a = "hello";
String b=new String("hello");
if(a==b)
{
System.out.print("True \n");
}

Page 11 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

else
{
System.out.print("False \n");
}
if(a.equals(b))
{
System.out.print("True \n");
}
else
{
System.out.print("False \n");
}
}
}
Output:-

8. Take your roll no.(only last two digits), name, java lab paper code
and date; initialize them within constructor and print.
Code:-
class studentdetails
{
int roll;
String name,jlpcode,date;
studentdetails(int Roll,String Name,String Jlpcode,String Date)
{
roll = Roll;
name = Name;
jlpcode = Jlpcode;
date = Date;
}
void display()
{
System.out.print("\n Student Roll number is: " + roll);
System.out.print("\n Student Name is: " + name);
System.out.print("\n Student java lab paper code number is: " + jlpcode);
System.out.print("\n Lab paper submitted date is: " + date);
}
}

Page 12 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

class demo9
{
public static void main(String[] args)
{
studentdetails s = new studentdetails(43,"Saikat Dey","MCA20-293","02/06/2023");
s.display();
}
}
Output:-

9. Using nested if-else do the following,


Take the amount of salary and working hour of an employee. If
i)Salary>20K and <30K and working hour>=7 hr, increase salary
by 20% and show the new salary
ii)Salary>20K and <30K and working hour>=5 hr but <7 hr,
increase salary by 10% and show the new salary
iii)Salary>20K and <30K and working hour>3 hr but <5 hr,
increase salary by 5% and show the new salary
If-
i)Salary>8K and <20K and working hour>7-8 hr, increase salary
by 15% and show the new salary
ii)Salary>8K and <20K and working hour>=5 hr but <7 hr,
increase salary by 10% and show the new salary
iii)Salary>8K and <20K and working hour>3 hr but <5 hr, print
“no increment” in salary
Code:-
import java.util.Scanner;
class Conditional
{
public static void main(String[] args)
{
int hr;
double sal,salint;

Page 13 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

System.out.print("Enter the Salary: ");


Scanner ref=new Scanner(System.in);
sal=ref.nextDouble();
System.out.print("Enter the Work Hour: ");
Scanner r=new Scanner(System.in);
hr=r.nextInt();
if(sal>20000 && sal<30000)
{
if(hr>3 && hr<5)
{
salint=(sal*0.05);
System.out.print("New salary is: " + (salint+sal));
}
else if(hr>=5 && hr<7)
{
salint=sal*0.1;
System.out.print("New salary is: " + (salint+sal));
}
else
{
salint = sal * 0.2;
System.out.print("New salary is: " + (salint+sal));
}
}
else if(sal>8000 && sal<20000)
{

if(hr>3 && hr<5)


{
System.out.print("No increment salary");
}
else if(hr>=5 && hr<7)
{
salint=sal*0.1;
System.out.print("New salary is: " + (salint+sal));
}
else
{
salint=sal*0.15;
System.out.print("New salary is: " + (salint+sal));
}
}
else
{

Page 14 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

System.out.print("Data not Found!");


}
}
}
Output:-

10. Evaluate the expression with nested method call-

(21*3)+85%7-{66+(39-29-24)}

[ Hint: you can create method based on operator precedence


perform i.e. each operation within parentheses’( )’ is within a method.
Then call the higher precedence method from lower precedence
method]

Code:-
class Eevaluation
{
static int expression()
{
int s1 = multiply(21,3);
int s2 = module(85,7);
int s3 = subtract(39,29,24);
int s4 = add(66,s3);
int s5 = subtract(s4,s1);
int s6 = add(s1,s2);
int s7 = subtract(s6,s5);
return s7;
}
static int multiply(int a,int b)
{
return a*b;
}
static int module(int a,int b)
{
return a%b;
}
Page 15 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

static int subtract(int a,int b,int c)


{
return a-b-c;
}
static int add(int a,int b)
{
return a+b;
}
static int subtract(int a,int b)
{
return a-b;
}
public static void main(String[] args)
{
int result = expression();
System.out.print("Result of the expression is: " + result);
}
}
Output:-

Assignment-2
1. Create a class named ‘Flower’ with instance variables ‘color’,
’season’, ’smell’ and a method common for every flower. Create two
subclasses named ‘Rose’ and ‘Sunflower’. Initialize those instance
variables of parent class into subclasses and also create new methods
correspond to each child class. Show the instance variables and
invoke methods creating object of child class.
Code:-
class Flower
{
String color,Season,Smell;
void flo()
{
System.out.print("\n Name of the Flower ------- ");

Page 16 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

}
}
class Rose extends Flower
{
@Override
void flo()
{
String name = "Rose";
color = "Red";
Season = "Winter";
Smell = "floral and tea aromas to spicy,fruity,and musky scents";
super.flo();
System.out.print("is: " + name);
System.out.print("\n Rose color is: "+color);
System.out.print("\n Season is: "+Season);
System.out.print("\n Smell of the flower rose: "+Smell);
}
}
class Sunflower extends Flower
{
@Override
void flo()
{
String name = "Sunflower";
color = "Yellow";
Season = "Summer and into autumn";
Smell = "Slightly sweet,grassy or hay-like aroma";
super.flo();
System.out.print("is: " + name);
System.out.print("\n Sunflower color is: "+color);
System.out.print("\n Season is: "+Season);
System.out.print("\n Smell of the flower Sunflower: "+Smell);
}
}
class demo
{
public static void main(String[] args)
{
Rose r = new Rose();
Sunflower r1 = new Sunflower();
r.flo();
r1.flo();
}
}

Page 17 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Output:-

2. Create a class ‘Phone’. Derive two classes ‘Telephone’ and ‘Mobile’.


Put methods within those classes to print separate features of
Telephone and Mobile like- whether wireless or not , have display or
not etc. . Derive a class from ‘mobile’ class named ‘iPhone’ and
mention methods to print the basic features of that model of mobile.
Invoke the methods of parent and child class by creating object of
child class.
Code:-
class Phone
{
void features()
{
System.out.print("\n Print the Features of the Communication devices.");
}
}
class Telephone extends Phone
{
@Override
void features()
{
super.features();
System.out.print("\n Features of the Telephone----: ");
System.out.print("\n Telephone is an electronic device that use for conversations over great
distance.");
System.out.print("Telephone is a wired device.");
System.out.print("Not have any display of the telephone.");
}
}
class Mobile extends Phone

Page 18 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

{
//@Override
void features()
{
//super.features();
System.out.print("\n Features of the Mobile----: ");
System.out.print("\n Mobile is an electronic device that use for conversations over great
distance.");
System.out.print("Mobile is a wireless device.");
System.out.print("Mobile have a display.");
}
}
class Iphone extends Mobile
{
@Override
void features()
{
super.features();
System.out.print("\n Features of the Iphone----: ");
System.out.print("\n 1. Iphone reveals the data collection.\n 2. Ihone restricts online
activities storage.\n 3. Apple app store offers secure apps.\n 4. Malware activities.\n 5. Iphone
shows if the mi or camera is open by any app.");
}
}
class demo1
{
public static void main(String[] args)
{
Iphone r = new Iphone();
Phone r1 = new Telephone();
r1.features();
r.features();
}
}
Output:-

Page 19 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

3. Create a class ‘Student’. Take values from user. Create methods with
name ‘calGrade’ such that-
a. If dept= ‘English’, grade=( score + 90% of attendance)
b. If dept= ‘Math’, grade=( score + 80% of attendance+
assignment marks)
c. If dept= ‘Physics’, grade=( score + assignment marks+
practical marks)
d. If dept= ‘Com. Sc., grade=( score + + 80% of attendance
+assignment marks+ practical marks)
Code:-
import java.util.Scanner;
class Student
{
private String dept;
private double score;
private double attendance;
private double assignmentMarks;
private double practicalMarks;
public Student(String dept, double score, double attendance, double assignmentMarks,
double practicalMarks)
{
this.dept = dept;
this.score = score;
this.attendance = attendance;

Page 20 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

this.assignmentMarks = assignmentMarks;
this.practicalMarks = practicalMarks;
}
public double calGrade()
{
double grade = 0.0;
if (dept.equals("English"))
{
grade = score + (0.9 * attendance);
}
else if (dept.equals("Math"))
{
grade = score + (0.8 * attendance) + assignmentMarks;
}
else if (dept.equals("Physics"))
{
grade = score + assignmentMarks + practicalMarks;
}
else if (dept.equals("Com. Sc.")) {
grade = score + (0.8 * attendance) + assignmentMarks + practicalMarks;
}
else
{
System.out.println("Invalid department!");
}
return grade;
}
}

public class demo6


{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter department (English, Math, Physics, or Com. Sc.): ");
String dept = scanner.nextLine();
System.out.print("Enter score: ");
double score = scanner.nextDouble();
System.out.print("Enter attendance: ");
double attendance = scanner.nextDouble();
System.out.print("Enter assignment marks: ");
double assignmentMarks = scanner.nextDouble();
System.out.print("Enter practical marks: ");
double practicalMarks = scanner.nextDouble();

Page 21 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Student student = new Student(dept, score, attendance, assignmentMarks,


practicalMarks);
double grade = student.calGrade();
System.out.println("Grade: " + grade);
}
}
Output:-

4. Create a Interface named 'Member' having the following members:


Data members ID, name, phone no., Address, Salary
It also has a method named 'printData' to print the data. Two classes
'Employee' and 'Manager' are derived from the 'Member' class. The
'Employee' and 'Manager' classes have additional data member
'department'. Now, assign name, age, phone number, address and
salary to an employee and a manager and also define printData
method. Now invoke the method from derived classes.
Code:-
interface Member
{
void printData();
}
class Employee implements Member
{
private int ID;
private String name;
private String phoneNo;
private String address;
private double salary;
private String department;
public Employee(int ID, String name, String phoneNo, String address, double salary, String
department)

Page 22 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

{
this.ID = ID;
this.name = name;
this.phoneNo = phoneNo;
this.address = address;
this.salary = salary;
this.department = department;
}
public void printData()
{
System.out.println("Employee Details:");
System.out.println("ID: " + ID);
System.out.println("Name: " + name);
System.out.println("Phone No: " + phoneNo);
System.out.println("Address: " + address);
System.out.println("Salary: " + salary);
System.out.println("Department: " + department);
}
}
class Manager implements Member
{
private int ID;
private String name;
private String phoneNo;
private String address;
private double salary;
private String department;
public Manager(int ID, String name, String phoneNo, String address, double salary, String
department)
{
this.ID = ID;
this.name = name;
this.phoneNo = phoneNo;
this.address = address;
this.salary = salary;
this.department = department;
}
public void printData()
{
System.out.println("Manager Details:");
System.out.println("ID: " + ID);
System.out.println("Name: " + name);
System.out.println("Phone No: " + phoneNo);
System.out.println("Address: " + address);

Page 23 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

System.out.println("Salary: " + salary);


System.out.println("Department: " + department);
}
}
public class demo8
{
public static void main(String[] args)
{
Employee e = new Employee(1, "Akilesh", "1234567890", "123 ABC Street", 5000, "HR");
Manager m = new Manager(2, "Karan", "9876543210", "456 XYZ Street", 8000,
"Operations");
e.printData();
System.out.println();
m.printData();
}
}
Output:-

5. Create a method within a class. Also create a main method within


another class. Now call the method from main method without
creating object of that class.
Code:-
class M
{

Page 24 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

static void method()


{
System.out.print("\n Method calling from another class without creating class object.......");
}
}
class demo4
{
public static void main(String[] args)
{
M.method();
}
}
Output:-

6. Create two classes ‘Rose’ which prints “Color is Red” and


‘Sunflower’ which prints “Color is Yellow” but the method name
should be ‘showColor’ for both the classes. Create object to show the
result.
Code:-
class Rose
{
void showcolor()
{
System.out.print("\n Color is Red");
}
}
class Sunflower
{
void showcolor()
{
System.out.print("\n Color is Yellow");
}
}
class demo2
{
public static void main(String[] args)

Page 25 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

{
Rose r = new Rose();
Sunflower s = new Sunflower();
r.showcolor();
s.showcolor();
}
}
Output:-

7. Create a class ‘Employee’ with variables- name, dept, designation,


initialize them and define methods to print the information. Extend a
class from employee class with two new variables ID, salary. Now
override the super class method to print parent class variables as well
as child class variables. Remember: you can only create object of sub
class.
Code:-
class Employees
{
String name = "Ankush",dept = "Finance",designation = "HR";
void show()
{
System.out.print("\n Name of the employee: " +name);
System.out.print("\n The depatmant is: " +dept);
System.out.print("\n Designation of the employee is: " +designation);
}
}
class Emp1 extends Employees
{
@Override
void show()
{
super.show();
String ID = "E0167548";
long salary = 70000;
System.out.print("\n Employee ID is: "+ID);

Page 26 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

System.out.print("\n Employee salary is: "+salary);


}
}
class demo3
{
public static void main(String[] args)
{
Employees e = new Emp1();
e.show();
}
}
Output:-

8. Do the same as previous program but now create a constructor to


initialize the variables. Then in subclass create a constructor to
initialize new(additional ) variables. Lastly call the method to show
the member variable values.
Code:-
class Employees
{
String name,dept,designation;
Employees() //Default constructor
{
name = "Akilesh";
dept = "Salesman";
designation = "HR";
}
public void display()
{
System.out.print("\n Name of the employee: " +name);
System.out.print("\n The depatmant is: " +dept);
System.out.print("\n Designation of the employee is: " +designation);
}

Page 27 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

}
class Emp1 extends Employees
{
String id;
long salary;
Emp1(String ID,long Salary) //parametarized constructor
{
id = ID;
salary = Salary;
}
public void show()
{
System.out.print("\n Employee ID is: "+id);
System.out.print("\n Employee salary is: "+salary);
}
}
public class demo5
{
public static void main(String[] args)
{
Emp1 e1 = new Emp1("S0167548",40000);
e1.display();
e1.show();
}
}
Output:-

9. Make a package named ‘firstPkg’ in which create a class and define a


method. The method takes two numbers as parameters and subtracts
the smaller number from the bigger one. Now in your program call
that method and do the same with your values given from user.
Code:-
package firstpkg;

Page 28 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

import java.util.Scanner;
class pkg1
{
int method_pkg(int a,int b)
{
int c;
c=a-b;
return c;
}
public static void main(String[] args)
{
pkg1 p = new pkg1();
int x,y,z;
System.out.print("\n Enter the Bigger number: ");
Scanner r = new Scanner(System.in);
x = r.nextInt();
System.out.print("\n Enter the Smaller number: ");
Scanner r1 = new Scanner(System.in);
y = r1.nextInt();
z = p.method_pkg(x,y);
System.out.print("result is: " + z);
}
}
Output:-

10. Create a package ‘firstPkg’ where put a class ‘firstmtd’ and a


method with some print statement and create a package ‘MyPkg’
where put a class ‘Mymtd’ where we have main method. Call the
method from main method creating object. Show the result.

Code:-
package firstpkg;
public class pkg1
{
public int method_pkg(int a,int b)

Page 29 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

{
int c;
c=a-b;
return c;
}
}

package Mypkg;
import firstpkg.pkg1;
import java.util.Scanner;
public class Mymtd
{
public static void main(String[] args)
{
pkg1 p = new pkg1();
int x,y,z;
System.out.print("\n Enter the Bigger number: ");
Scanner r = new Scanner(System.in);
x = r.nextInt();
System.out.print("\n Enter the Smaller number: ");
Scanner r1 = new Scanner(System.in);
y = r1.nextInt();
z = p.method_pkg(x,y);
System.out.print("result is: " + z);
}
}
Output:-

11. Create a package ‘MyPkg1’ where create a method within a class


with some statements inside it. Mention the method as ‘protected’.
Then create a package ‘MyPkg2’ where create a class ‘Mymtd’ which
will inherit the class of ‘MyPkg1’. Now invoke the method from main
method . Show the result.
Page 30 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Code:-
package Mypkg1;
public class pkg2
{
protected int method_pkg(int a,int b)
{
int c;
c=a-b;
return c;
}
}

package Mypkg2;
import Mypkg1.pkg2;
import java.util.Scanner;
class Mymtd extends pkg2
{
public static void main(String[] args)
{
Mymtd p = new Mymtd();
int x,y,z;
System.out.print("\n Enter the Bigger number: ");
Scanner r = new Scanner(System.in);
x = r.nextInt();
System.out.print("\n Enter the Smaller number: ");
Scanner r1 = new Scanner(System.in);
y = r1.nextInt();
z = p.method_pkg(x,y);
System.out.print("result is: " + z);
}
}
Output:-

12. Let the features of a class named ‘Animal’ succeeded into class
‘Cat’ and the features of Cat into class ‘Tiger’. Cat has two methods
Page 31 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

that prints “It is a domestic animal” and “It is carnivorous”


respectively. Now tiger is not domestic, so inherit Tiger in a way that
this method can’t be acquired from Cat into Tiger.
Code:-
class Animal {
// Some features of an animal
}
class Cat extends Animal {
public void printDomestic() {
System.out.println("It is a domestic animal.");
}
public void printCarnivorous() {
System.out.println("It is carnivorous.");
}
}
class Tiger extends Cat {
// The Tiger class inherits both methods from Cat
// However, we can override the printDomestic method
@Override
public void printDomestic() {
System.out.println("It is not a domestic animal.");
}
}

Assignment-3

1. Take an array from user and print the even and odd numbers from the
array
Code:-
import java.util.Scanner;
class arrayoddeven
{
public static void main(String[] args)
{
int n,i;
System.out.print("\n Enter the array size: ");
Scanner r = new Scanner(System.in);
n = r.nextInt();

Page 32 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

int a[] = new int[n+1];


System.out.print("\n Enter the array element: \n");
for(i=0;i<n;i++)
{
a[i] = r.nextInt();
}
System.out.print("\n Print Even and odd number: ");
for(i=0;i<n;i++)
{
if(a[i]%2==0)
{
System.out.print("\n" + i+"th Index Even number is: " + a[i]);
}
else
{
System.out.print("\n" + i+"th Index Odd number is: " + a[i]);
}
}
}
}
Output:-

2. With a basic try catch block, show exception handling.


Code:-
class excepex
{
public static void main(String[] args)
{
String str = null;

Page 33 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

try
{
System.out.print(str.toUpperCase());
}
catch(NullPointerException e)
{
System.out.print("\n Null can not be casted.");
}
}
}
Output:-

3. Write a program in java on arithmetic exception with finally block.


Code:-
class arithexcep
{
public static void main(String[] args)
{
try
{
System.out.print("\n 1st Statement.");
int a=12,b=0,c;
c=a/b;
System.out.print("\n Print the result: " + c);
}
catch(ArithmeticException i)
{
System.out.print("\n 3rd Statement." + i);
}
finally
{
System.out.print("\n [Exception occur or not occur finally block always execute] 4th
Statement .");
}
System.out.print("\n 5th Statement.");
}
}
Output:-

Page 34 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

4. WAP in java to throw any checked exception using ‘throws’


keyword.
Code:-
import java.io.*;
class filewrite
{
public static void main(String[] args)throws IOException
{
FileWriter f = new FileWriter("C:\\Users\\ACER\\Documents\\Java\\newfile.txt");
f.write("Java is the best language");
f.close();
System.out.print("\n Checked exception.");
System.out.print("\n Succesfully data wroted.");
}
}
Output:-

5. Write an applet to create three buttons to change the background


color.
Code:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class changecolor extends Applet
implements ActionListener
{
Button b = new Button("RED");
Button b1 = new Button("GREEN");

Page 35 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Button b2 = new Button("YELLOW");


public void init()
{
add(b);
add(b1);
add(b2);
b.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b){
setBackground(Color.red);
}
else if(e.getSource() == b1){
setBackground(Color.green);
}
else{
setBackground(Color.yellow);
}
}
}

<html>
<head>
<title> Print the User input</title>
<body>
<applet code = changecolor.class height = 400 width = 400>
</applet>
</body>
</html>
Output:-

6. Write an applet in AWT to take user name and phone number from
user and print those.

Page 36 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

Code:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class unapn extends Applet
implements ActionListener
{
TextField t1 = new TextField(20);
TextField t2 = new TextField(20);
Label l1 = new Label("User Name:");
Label l2 = new Label("Phone Number:");
Button b = new Button("Submit");
TextArea t3 = new TextArea(5,27);
Label l3 = new Label("Print:");
public void init()
{
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);
add(t3);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
String Name = t1.getText();
String Phonenumber = t2.getText();
t3.setText("\n User Name is: " +Name+ "\n Phone Number is: " +Phonenumber);
}
}
}

<html>
<head>
<title> Print the User input</title>
<body>
<applet code = unapn.class height = 400 width = 400>

Page 37 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

</applet>
</body>
</html>
Output:-

7. Write an applet program to take user parameters(employee name,


designation, salary) and print those.
Code:-
import java.awt.*;
import java.applet.*;
public class empdetails extends Applet
{
String ename,designation;
int salary;
public void start()
{
String str;
ename = getParameter("Employee name");
if(ename == null){
ename = "not found";
}
str = getParameter("Your Designation");
if(str!=null){
designation = str;
}
else{
designation = "No Job";
}
str = getParameter("Salary");
try
{

Page 38 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

if(str!=null){
salary = Integer.parseInt(str);
}
else{
salary = 0;
}
}
catch(NumberFormatException e){
}
}
public void paint(Graphics g)
{
g.drawString("\n Employee name: " + ename,20,10);
g.drawString("\n Employee Designation: " + designation,20,30);
g.drawString("\n Employee Salary: " + salary,20,50);
}
}

<html>
<head>
<title> Print the User input</title>
<body>
<applet code = empdetails.class height = 400 width = 400>
<param name = "Employee name" value = "Ankit">
<param name = "Your Designation" value = "HR">
<param name = "Salary" value = 40000>
</applet>
</body>
</html>
Output:-

8. Take two values and find the bigger one between then using applet
Code:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Page 39 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

public class bigerone extends Applet


implements ActionListener
{
TextField t1 = new TextField(10);
TextField t2 = new TextField(10);
TextField t3 = new TextField(10);
Label l1 = new Label("First No:");
Label l2 = new Label("Seacond No:");
Label l3 = new Label("Biggest No:");
Button b = new Button("Find");
public void init()
{
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b)
{
int n1 = Integer.parseInt(t1.getText());
int n2 = Integer.parseInt(t2.getText());
if(n1>n2){
t3.setText(" " + n1);
}
else{
t3.setText(" " + n2);
}
}
}
}

<html>
<head>
<title> Find The biggest value</title>
<body>

Page 40 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

<applet code = bigerone.class height = 400 width = 400>


</applet>
</body>
</html>
Output:-

9. Using java AWT make two radio buttons named ‘BCA’ and ‘MCA’,
to take the steam of a student and three check box named ‘Java’ , ‘C’
and ‘C++’ , to take the subject of a student. Show the
outputs.Example: if you click on stream ‘MCA’ and choose subjects
‘C’ and ‘Java’
Code:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class streamlanguage extends Applet
implements ActionListener
{
String lang1,lang2,lang3,stream;
Label l1 = new Label("Strem:");
Label l2 = new Label("Language:");
CheckboxGroup cg1 = new CheckboxGroup();
Checkbox b = new Checkbox("BCA",cg1,false);
Checkbox b1 = new Checkbox("MCA",cg1,false);
//CheckboxGroup cg = new CheckboxGroup();
Checkbox c1 = new Checkbox("JAVA");
Checkbox c2 = new Checkbox("C");
Checkbox c3 = new Checkbox("C++");
TextArea t1 = new TextArea(5,27);
Button B = new Button("Submit");
public void init()
{
add(l1);

Page 41 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

add(b);
add(b1);
add(l2);
add(c1);
add(c2);
add(c3);
add(B);
add(t1);
B.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == B){
stream = cg1.getSelectedCheckbox().getLabel();
if (c1.getState()){
lang1 = "java";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang1);
}
else if(c2.getState()){
lang2 = "C";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang2);
}
else if(c3.getState()){
lang3 = "C++";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang3);
}
if (c1.getState() && c2.getState() && c3.getState()){
lang1 = "Java ";
lang2 = "C";
lang3 = "C++";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang1 + "\n " + lang2 + "\n" + lang3);
}
else if (c1.getState() && c2.getState()){
lang1 = "Java ";
lang2= "C ";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang1 + "\n " + lang2);
}
else if (c1.getState() && c3.getState()){
lang1 = "Java ";
lang3= "C++";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang1 + "\n " + lang3);
}
else if(c2.getState() && c3.getState()){
lang2 = "C";

Page 42 of 43
[Roll No:-504122011057] | [Subhasish Ghosh]

lang3= "C++";
t1.setText("\n Stream: " + stream + "\n Subject is: " + lang2 + "\n " + lang3);
}
}
}
}

<html>
<head>
<title> Print the User input</title>
<body>
<applet code = streamlanguage.class height = 400 width = 400>
</applet>
</body>
</html>
Output:-

Page 43 of 43

You might also like