SlideShare a Scribd company logo
1 of 45
Question 1:
Create a class Employee with instance variable EmpId, Empage, EmpName and decide proper
data types and access modifiers for these variable. Define overloaded constructors
getter/setter methods and also overridden to_String() method. Demonstrate this in your class
program.
Solution:
//Creating Employee class
package employee;
import java.util.Scanner;
public class Employee{
protected int EmpId,Empage;
String EmpName;
public Employee(){
EmpId=1;
Empage=1;
EmpName="abc";
}
public Employee(int EmpId,int Empage,String EmpName){
this.EmpId=EmpId;
this.Empage=Empage;
this.EmpName=EmpName;
}
Scanner input=new Scanner(System.in);
void setter(){
System.out.println("Enter Employee Data");
System.out.println("Enter Employee ID");
EmpId=input.nextInt();
shiningstudy.com
System.out.println("Enter Employee Age");
Empage=input.nextInt();
System.out.println("Enter Employee Name");
EmpName=input.next();
}
@Override
public String toString(){
return String.format(EmpName+"Write any String You Want");
}
int getter_ID(){
return EmpId;
}
int getter_Age(){
return Empage;
}
String getter_Name(){
return EmpName;
}
public static void main(String[] args) {
Employee emp= new Employee();
emp.setter();
System.out.println("Employee Data is:::");
System.out.println("Employee Name is : "+ emp.getter_Name());
System.out.println("Employee ID is : "+ emp.getter_ID());
shiningstudy.com
System.out.println("Employee Age is : "+ emp.getter_Age());
}
}
shiningstudy.com
Question 2:
Create a class called ”SHAPE”(Should be Made an Abstract class) having two instance variables
Length(Double), Height(Double) with appropriate Access specifiers and instance method
Get_Date() to get and assign the values (to Length and Heigh) from the user, it also has an
Abstract method Display_Area() to compute and display the area of the geometrical object.
Derive two specific classes “Triangle” and “Rectangle” from the base class that Override the
base class method using these three classes design a program that will accept dimension of a
triangle /Rectangle interactively and display area.
HINT:
Area of Triangle = ½(L*H)
Area of Rectangle = (L*H)
Solution:
//Creating Shape class
package shape;
import java.util.Scanner;
public abstract class Shape {
protected double Length,Height;
Scanner input=new Scanner(System.in);
void Get_Data(){
System.out.println("Please Enter Length and Height");
Length=input.nextDouble();
Height=input.nextDouble();
}
abstract void Area();
shiningstudy.com
}
//Creating Triangle as a sub class
package shape;
public class Triangle extends Shape{
Triangle(){
Length=1;
Height=1;
}
@Override
void Get_Data(){
System.out.println("Please Enter Length and Height of Triangle");
Length=input.nextDouble();
Height=input.nextDouble();
}
@Override
void Area() {
double area=(Length*Height)/2;
System.out.println("Area of Trinagle: " + area + "Square Unit");
}
}
We are creating rectangle sublass
package shape;
shiningstudy.com
import javax.sound.midi.Receiver;
public class Rectangle extends Shape{
Rectangle(){
Length=1;
Height=1;
}
@Override
void Get_Data(){
System.out.println("Please Enter Length and Height of Rectangle");
Length=input.nextDouble();
Height=input.nextDouble();
}
@Override
void Area() {
double area=Length*Height;
System.out.println("Area of Rectnagle: " + area + "Sqaure Unit");
}
public static void main(String[] args){
Triangle tri=new Triangle();
Rectangle rec=new Rectangle();
//FOR GETTING LENGTH OF TRIANGLE
tri.Get_Data();
//FOR PRINTING AREA OF TRIANGLE
tri.Area();
shiningstudy.com
//FOR GETTING LENGTH OF RECTANGLE
rec.Get_Data();
//FOR PRINTING AREA OF RECTANGLE
rec.Area();
}
}
Question 3:
Explain Exception Handling in java and why we use Nested Try Blocks. Write a program to
Explain Exception Handling by Nested try/catch Blocks.
Solution:
Why we use Exceptional Handling in Java:
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore,
these exceptions are to be handled.
Why we use Nested Try Block:
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
EXAMPLE:
//Creating Nested class
package nested;
import java.util.InputMismatchException;
public class Nested {
public static void main(String[] args) {
shiningstudy.com
try {
System.out.println("Outer try block starts");
try {
System.out.println("Inner try block starts");
int res = 5 / 0;
}
catch (InputMismatchException e) {
System.out.println("InputMismatchException caught");
}
finally {
System.out.println("Inner final");
}
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
}
finally {
System.out.println("Outer finally");
}
}
}
Question 4:
Explain the advantages of using interface in Java? Also write a java program to show how a class
implements two Interfaces.
Solution:
shiningstudy.com
Advantages of Using Interface:
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java.
 achieve full abstraction
 achieve multiple inheritance
 achieve loose coupling
 to break up the complex designs and clear the dependencies between objects.
EXAMPLE:
interface printable{
void print_text();
}
class One implements printable{
public void print_text(){
System.out.println("Hello World");
}
public static void main(String args[]){
One o= new One();
o.print_text();
}
}
Question 5:
Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide
member function that calculate the area of the rectangle also provide set and get functions for
the length and width attributes. The set function should verify that Length and Width are each
floating numbers larger then 0.0 and less than 20.0.
Solution:
shiningstudy.com
package pkgtry;
//Creating Rectangle class
import java.util.Scanner;
public class Rectangle {
Scanner input = new Scanner(System.in);
float length,width;
Rectangle (){
length=1;
width=1;
}
float area(){
float area=length*width;
return area;
}
void set_length(){
System.out.println("Enter length");
float a=input.nextFloat();
if(a>0 && a<20){
length=a;
}
else
System.out.println("Condition Not Satify");
}
void set_width(){
System.out.println("Enter Width");
shiningstudy.com
float a=input.nextFloat();
if(a>0 && a<20){
width=a;
}
else
System.out.println("Condition Not Satify");
}
float get_length(){
return length;
}
float get_width(){
return width;
}
public static void main(String[] args) {
Rectangle rec=new Rectangle ();
rec.set_length();
rec.set_width();
System.out.println("Area of Rectangle is : "+ rec.area());
}
}
shiningstudy.com
Question 6:
Write a class name operator that have only one data member count the class has the following
member functions.
1-Constructor to Initialize the count.
2-show function to show the count.
3-Overload ++ Operator to increase the count by 1.
Solution:
//Creating Operator class
package operator;
public class Operator {
int count;
Operator(){
count=2;
}
void show(){
System.out.println(count);
}
void Overload(){
count++;
System.out.println(count);
}
public static void main(String[] args) {
Operator op = new Operator();
op.show();
shiningstudy.com
op.Overload();
}
}
Question 7:
Explain Constructor Overloading with the Help of One Example?
Solution:
public class Name{
String name;
Name(){
name=”Ubaid”;
}
//Constructor Overloading
Name(String name){
this.name=name;
}
public static void main(String[] args){
Name obj = new Name(); //It will Call Default Constructor
Name obj1 = new Name(“Adeel”); //It will Call Overloaded Constructor
System.out.println(obj.name);
System.out.println(obj1.name);
}
}
Question 8:
shiningstudy.com
Define a class for bank account that includes the following data members. Name of Depositor,
Account Number, Type of Account, balance amount in the Bank.
The class also contain following Member functions,
1-A constructor to assign initial values
2- Deposit Function to deposit amount it should accept value as s parameter.
3- Withdraw function to withdraw an amount after checking the balance, it should accept the
value as a parameter. Display function to display name and balance.
Solution:
//Creating Bank class
package bank_account;
import java.util.Scanner;
public class Bank_Account {
final String name,acc_type;
String d_name;
final int account_num;
int bank_bal;
public Bank_Account() {
name="Ubaid";
acc_type="Saving";
d_name="Adeel";
account_num=3415976;
bank_bal=150000;
}
void deposit(int amount){
bank_bal+=amount;
shiningstudy.com
}
void withdraw(int amount){
bank_bal-=amount;
}
void Display(){
System.out.println("Account Name is :: "+ name);
System.out.println("Your Name is :: "+ d_name);
System.out.println("Your Bank Balance is :: "+ bank_bal);
}
public static void main(String[] args) {
Bank_Account bank= new Bank_Account();
Scanner input= new Scanner(System.in);
System.out.println("Please Enter the Depositor Name");
bank.d_name=input.next();
System.out.println("Please Enter an Amount U want to Deposit");
bank.deposit(input.nextInt());
bank.Display();
System.out.println("Please Enter an Amount U want to Withdraw");
bank.withdraw(input.nextInt());
bank.Display();
}
}
Question 9:
Write a class local phone that contains an attribute phone o store a local phone number. The
class contains memebre Functions to input and display phone Number. Write a child class
NarPhone for National Phone Numbers that inherit localPhone class. It additionally contains an
shiningstudy.com
attribute to store city code. It also contains member function to input and show city code.
Write another class IntPhone for international phone Numbers that inherit NatPhoneclass. It
additionally contains an attribute to store country code. It also contains member Functions to
input and show the country code.
Solution:
//Creating Localphone class
package localphone;
import java.util.Scanner;
public class Localphone {
int phone_num;
Scanner input = new Scanner(System.in);
void setNum(){
System.out.println("Please enter Your Local Phone Number : ");
phone_num=input.nextInt();
}
void Display(){
System.out.println("Your Phone Number is : " + phone_num);
}
void input(){
}
}
//Creating NatPhone as sub class
package localphone;
shiningstudy.com
public class Natphone extends Localphone {
int ci_code=0;
void setCi_code(){
System.out.println("Please enter Your City Code : ");
ci_code=input.nextInt();
System.out.println("Your City Code is : 0"+ ci_code);
}
}
//Creating IntPhone as sub class
package localphone;
public class Intphone extends Natphone{
int co_code;
void setCo_code(){
System.out.println("Please enter Your Country Code : ");
co_code=input.nextInt();
System.out.println("Your City Code is : 00"+ co_code);
}
public static void main(String[] args) {
Intphone inter= new Intphone();
Natphone nat= new Natphone();
inter.setCo_code();
inter.setCi_code();
shiningstudy.com
nat.setNum();
nat.Display();
}
}
Question 10:
Write a Time class that has three fields hours, minutes, seconds. To Initialize these fields it has
constructors, Getter and Setter Methods, and print time methods to display time. Also override
toString methods in this class.
Solution:
//Creating Time class
package time;
import java.util.Scanner;
public class Time {
int hours,minutes,seconds;
Time(){
hours=1;
minutes=30;
seconds=30;
}
Time(int hours , int minutes , int seconds){
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
shiningstudy.com
Scanner input= new Scanner(System.in);
void setter(){
System.out.println("Please enter Hours");
hours=input.nextInt();
System.out.println("Please enter Minutes");
minutes=input.nextInt();
System.out.println("Please enter Seconds");
seconds=input.nextInt();
}
int getter_hours(){
return hours;
}
int getter_minutes(){
return minutes;
}
int getter_seconds(){
return seconds;
}
void Print_time(){
System.out.print("Time is ::::: ");
System.out.println(hours+":"+minutes+":"+seconds);
}
@Override
public String toString(){
return String.format(hours+":"+minutes+":"+seconds);
}
public static void main(String[] args) {
shiningstudy.com
Time t1 = new Time(); //Object of Default constructor
Time t2 = new Time(2,36,50); //Object of Argumented constructor
//dISPLAY VALUES OF ATTRIBUTES OF USER DEFINED CONSTRUCOR
t1.Print_time();
//DISPLAY VALUES OF ATTRIBUTES OF USER DEFINED CONSTRUCOR
t2.Print_time();
//DISPLAY VALUES OF ATTRIBUTE AFTER SETTING VALUES
t1.setter();
t1.Print_time();
}
}
Question 11:
Write a java class that has two classes Point and Circle, Circle extends Point class. Demonstrate
Up-casting by using Circle class.
Solution:
//Creating Point class
package point;
public class Point {
float radius;
void show(){
System.out.println("Point class");
}
shiningstudy.com
}
//Creating Circle as sub class
package point;
public class Circle extends Point{
float rad=5;
public Circle() {
super.radius=rad;
}
public static void main(String[] args) {
Circle cir = new Circle();
//UpCasting
System.out.println("Radius of Circle is :" + cir.radius);
//UpCasting
cir.show();
}
}
Question 12:
shiningstudy.com
Write a java program that has Shape class and subclasses Rectangle, Oval,Triangle. Use These
classes to Demonstrate the polymorphic behavior.
Solution:
//Creating Shape class
package shapes;
public class Shapes {
void sides(int sid){
System.out.println("ENter the Object sides");
}
}
//Creating Rectangle as sub class
package shapes;
public class rectange extends Shapes{
@Override
void sides(int sid){
System.out.println("Sides Of Rectwangel"+ +sid);
}
}
//Creating Oval as sub class
package shapes;
shiningstudy.com
public class oval extends Shapes{
@Override
void sides(int sid){
System.out.println("Sides Of Oval"+ +sid);
}
}
//Creating Triangle as sub class
package shapes;
public class triangel extends Shapes{
@Override
void sides(int sid){
System.out.println("Sides Of Triangel"+ +sid);
}
public static void main(String[] args) {
rectange re=new rectange();
oval ov=new oval();
triangel tri=new triangel();
re.sides(4);
ov.sides(0);
tri.sides(3);
}
}
shiningstudy.com
Question 13:
What is Exceptional Handling in Java? Write a java program to handle multiple Exceptions?
Solution:
Exception Handling:
Exception is an error event that can happen during the execution of a program and disrupts its
normal flow. Java provides a robust and object oriented way to handle exception scenarios,
known as Java Exception Handling.
Example:
package testmultiplecatchblock;
import java.util.*;
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a;
a=30/0;
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("task 2 completed");
}
finally{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
shiningstudy.com
} }
Question 14:
Write a program that creates a class Student with name as its attribute, Derive class scholar
that stores title of his thesis (that designates in as a scholar). Derive another class Salaried
Scholar from scholar that earns some salary (attribute of the class). Write suitable constructor
(multiple) and other methods or the class to create and display the two objects of the Salaried
Scholar.
Solution:
//Creating Student class
package student;
public class Student {
String name;
Student(){
name="Ubaid";
}
Student(String name){
this.name=name;
}
void Display(){
System.out.println(name);
}
}
//Creating Scholar as sub class
shiningstudy.com
package student;
public class Scholar extends Student{
String t_topic;
Scholar(){
t_topic="Poorty";
}
Scholar(String t_topic){
this.t_topic=t_topic;
}
@Override
void Display(){
System.out.println("Scholar Name : " + name);
System.out.println("Thesis Topic : " + t_topic);
}
}
//Creating Salaried as sub class
package student;
public class Salaried_Scholar extends Scholar{
int salary;
public Salaried_Scholar() {
shiningstudy.com
salary=50000;
}
public Salaried_Scholar(int salary) {
this.salary=salary;
}
@Override
void Display(){
System.out.println("Scholar Name : " + name);
System.out.println("Thesis Topic : " + t_topic);
System.out.println("Scholar Salary : " + salary);
}
public static void main(String[] args) {
Salaried_Scholar sch1= new Salaried_Scholar();
Salaried_Scholar sch2= new Salaried_Scholar(45000);
sch1.Display();
}
}
Question 15
Create a class publication (title, price). Create two classes named books (no of pages) and tape
(playing time) from it. Write appropriate constructors, print () and get () functions for each
class. Write an applications that demonstrates using objects of each class.
Solution:
//Creating Publication class
package publication;
public class Publication {
shiningstudy.com
String title;
float price;
Publication(){
title="TITLE HERE";
price=450;
}
Publication(String title , float price){
this.title=title;
this.price=price;
}
String get_title(){
return title;
}
float get_price(){
return price;
}
void print(){
System.out.println("Title of Book is : "+ title);
System.out.println("Price of Book is : "+ price);
}
}
shiningstudy.com
//Creating Books as a sub class
package publication;
public class Books extends Publication{
int no_of_pages;
Books(){
no_of_pages=500;
}
Books(int no_of_pages)
{
this.no_of_pages=no_of_pages;
}
float get_no_of_pages(){
return no_of_pages;
}
@Override
void print(){
System.out.println("Title of Book is : "+ title);
System.out.println("Price of Book is : "+ price);
System.out.println("No. of Pages of Book is : "+ no_of_pages);
}
shiningstudy.com
}
//Creating Tape as a sub class
package publication;
public class Tape extends Publication{
int play_time;
Tape(){
play_time=5;
}
Tape(int play_time){
this.play_time=play_time;
}
float get_play_time(){
return play_time;
}
@Override
void print(){
System.out.println("Title of Book is : "+ title);
System.out.println("Price of Book is : "+ price);
System.out.println("Play Time of Book is : "+ play_time);
}
public static void main(String[] args) {
Publication pub=new Publication();
Publication pub1=new Publication("Sahi Bukhari",600);
shiningstudy.com
Books book=new Books();
Books book1=new Books(450);
Tape tape=new Tape();
Tape tape1=new Tape(4);
book.print();
tape.print();
//Argumented constructors values
book1.print();
tape1.print();
}
}
Question 16
Create an abstract Auto class with fields for the car make and price. Include het and set
methods for these fields, the setPrice() methods is abstract. Create two subclasses automobiles
maker (for Example Mehran, Toyota) and include appropriate setPrice() methods in each
class(i.e Rs 600000 or Rs 1800000). Finally, write an application what uses auto class and
subclasses to display information amount different cars.
Solution:
//Creating Auto class
package auto;
public abstract class Auto {
String car_make;
float price;
void set_carmake(String car_make){
this.car_make=car_make;
}
shiningstudy.com
String get_carmake(){
return car_make;
}
abstract void set_price();
float get_price(){
return price;
}
}
//Creating Mehran as a sub class
package auto;
public class Mehran extends Auto{
@Override
void set_price() {
price=600000;
}
}
//Creating Toyota as a sub class
package auto;
public class Toyota extends Auto{
@Override
shiningstudy.com
void set_price() {
price=1800000;
}
public static void main(String[] args) {
Mehran meh=new Mehran();
Toyota toyo = new Toyota();
meh.set_carmake("Mehran");
meh.set_price();
toyo.set_carmake("TOYOTA");
toyo.set_price();
System.out.println("Car Make : "+ meh.get_carmake());
System.out.println("Car Price : "+ meh.get_price());
System.out.println("Car Make : "+ toyo.get_carmake());
System.out.println("Car Price : "+ toyo.get_price());
}
}
Question 17
Write down the class Time having fields (hrs, min, secs) containing no argument constructor,
three argument constructor and copy constructor. Also write down a method inc_time() that
increment seconds by 1 if seconds are equal to 60 then increment minute by 1 and set seconds
to 0. If minutes become 60 then increment hrs by 1 and set minutes to 0. Write down a
methods that compare two time objects and return true time if they are Equal else return False.
Solution:
//Creating Tim class
package tim;
public class Tim {
int hrs,min,secs;
shiningstudy.com
public Tim() {
hrs=2;
min=30;
secs=59;
}
public Tim(int hrs, int min, int secs) {
this.hrs=hrs;
this.min=min;
this.secs=secs;
}
//Coping Object to Constructor
public Tim(Tim c) {
this.hrs=c.hrs;
this.min=c.min;
this.secs=c.secs;
}
void inc_time(){
secs++;
if(secs==60)
{
secs=0;
min++;
}
if(min==60)
shiningstudy.com
{
min=0;
hrs++;
}
if(hrs==24)
{
hrs=0;
}
}
void display_time(){
System.out.println("Time is");
System.out.println(hrs +":"+min+":"+secs);
}
public static void main(String[] args) {
Tim time1=new Tim();
Tim time2=new Tim(2,30,59);
//Coping time1 OBJECT to the time3 OBJECT
Tim time3=new Tim(time1);
time1.inc_time();
time2.inc_time();
time1.display_time();
if(time1.hrs==time2.hrs && time1.min==time2.min && time1.secs==time2.secs)
System.out.println("TRUE");
shiningstudy.com
else
System.out.println("FALSE");
//Object Copied
System.out.println("AFTER COPING OBJECT");
time3.display_time();
}
}
Question 17(a):
What is compositions: Explain Your answer with Example.
Solution:
COMPOSITION:
Composition is the design technique to implement has-a relationship in classes. We can
use java inheritance or Object composition for code reuse. Java composition is achieved by
using instance variables that refers to other objects
Example:
package com.journaldev.composition;
public class Job {
private String role;
private long salary;
private int id;
public String getRole() {
return role;
}
shiningstudy.com
public void setRole(String role) {
this.role = role;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.journaldev.composition;
public class Person {
//composition has-a relationship
private Job job;
public Person(){
shiningstudy.com
this.job=new Job();
job.setSalary(1000L);
}
public long getSalary() {
return job.getSalary();
}
}
package com.journaldev.composition;
public class TestPerson {
public static void main(String[] args) {
Person person = new Person();
long salary = person.getSalary();
}
}
Question 17(b):
What is this keyword and Its Purpose. Give an Example.
Solution:
What is this keyword and its Purpose:
shiningstudy.com
Keyword THIS is a reference variable in Java that refers to the current object. It can be used to
refer instance variable of current class. It can be used to invoke or initiate current class
constructor. It can be passed as an argument in the method call.
Example:
package pkgthis;
public class This {
int a,b,sum;
public This(int a , int b) {
this.a=a;
this.b=b;
}
public static void main(String[] args) {
This thi=new This(5,6);
thi.sum=thi.a+thi.b;
System.out.println("Sum of Integers is :" + thi.sum);
}
}
Question 18:
Write down a program that makes a text file and make its copy in another file. Add exceptional
handling where necessary.
Solution:
package copy;
import java.io.FileReader;
import java.io.FileWriter;
shiningstudy.com
import java.io.IOException;
import java.io.FileNotFoundException;
public class copy{
public static void main (String[] args) throws IOException
{
FileWriter obj1= new FileWriter("copied.txt");
int c;
try // no throw statement necessary
{
FileReader obj= new FileReader("abc.txt");
while((c=obj.read())!=-1)
{
obj1.write((char)c);
}
obj.close();
}
catch (FileNotFoundException e) // exception is explicitly caught
{
System.out.println("File not found : ");
System.out.println("Program terminated");
System.out.println(e);
System.exit(0); // ends program
}
obj1.close();
}
}
shiningstudy.com
Question 19:
Create a class Distance with instance variable feet and inches. Write a suitable parameterized
constructor, getter and setter Methods and a Method to add two objects in such a way that is a
resultant inches exceed 12, feet should be incremented by 1 and inches decremented by 12
using the statement dist3.add(dist1,dist2): where dist1, dist2, dist3 are the objects of the
Distance class.
Solution:
package distance;
public class Distance {
int inches,feets;
public Distance(int inches,int feets) {
this.inches=inches;
this.feets=feets;
}
void setter(){
inches=1;
feets=1;
}
int getter_inches(){
return inches;
}
int getter_feets(){
return feets;
}
shiningstudy.com
void add(Distance dst1,Distance dst2)
{
feets=dst1.feets+dst2.feets;
inches=dst1.inches+dst2.inches;
}
public static void main(String[] args) {
Distance dist1=new Distance(2,3);
Distance dist2=new Distance(2,3);
Distance dist3=new Distance(1,1);
dist3.add(dist1,dist2);
if(dist3.inches>12){
dist3.feets++;
dist3.inches-=12;
System.out.println("feets="+dist3.feets);
System.out.println("inches="+dist3.inches);
}
else{
System.out.println("feets="+dist3.feets);
System.out.println("inches="+dist3.inches);
}
}
}
Question 20:
Write a program that has Shape class and subclasses as Square and Circle, Use these classes
demonstrate the Polymorphism.
shiningstudy.com
Solution:
package shap;
public class Shap {
void show(){
System.out.println("Your are in Shape Class");
}
}
package shap;
public class Square extends Shap{
@Override
void show(){
System.out.println("Your are in Square Class");
}
}
package shap;
public class Circle extends Shap{
@Override
void show(){
System.out.println("Your are in Circle Class");
}
public static void main(String[] args) {
Shap sh = new Shap();
shiningstudy.com
Square sq=new Square();
Circle cir=new Circle();
sh.show();
sq.show();
cir.show();
}
}
Question 21:
Write a java text stream class from java.io package to read text from one file and write to
another text file.
Solution:
package fileinputoutput;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class FileInputOutput {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("in.txt");
shiningstudy.com
OutputStream os = new FileOutputStream("out.txt");
int c;
while ((c = is.read()) != -1) {
System.out.println((char) c);
os.write(c);
}
is.close();
os.close();
}
}
shiningstudy.com

More Related Content

What's hot

What's hot (20)

Interface in java
Interface in javaInterface in java
Interface in java
 
CONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGECONDITIONAL STATEMENT IN C LANGUAGE
CONDITIONAL STATEMENT IN C LANGUAGE
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
C# loops
C# loopsC# loops
C# loops
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
Files in c++
Files in c++Files in c++
Files in c++
 
Tokens expressionsin C++
Tokens expressionsin C++Tokens expressionsin C++
Tokens expressionsin C++
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
String in java
String in javaString in java
String in java
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)Nested structure (Computer programming and utilization)
Nested structure (Computer programming and utilization)
 
Text field and textarea
Text field and textareaText field and textarea
Text field and textarea
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
 
Python ppt
Python pptPython ppt
Python ppt
 

Similar to Object Oriented Solved Practice Programs C++ Exams

Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Palak Sanghani
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploaddashpayal697
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
11slide
11slide11slide
11slideIIUM
 

Similar to Object Oriented Solved Practice Programs C++ Exams (20)

Java practical
Java practicalJava practical
Java practical
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]Lec 5 13_aug [compatibility mode]
Lec 5 13_aug [compatibility mode]
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Thread
ThreadThread
Thread
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Java Lab Manual
Java Lab ManualJava Lab Manual
Java Lab Manual
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
abstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx uploadabstract,final,interface (1).pptx upload
abstract,final,interface (1).pptx upload
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
C#2
C#2C#2
C#2
 
11slide
11slide11slide
11slide
 

More from MuhammadTalha436

Analysis modeling in software engineering
Analysis modeling in software engineeringAnalysis modeling in software engineering
Analysis modeling in software engineeringMuhammadTalha436
 
Software Process in software engineering
Software Process in software engineeringSoftware Process in software engineering
Software Process in software engineeringMuhammadTalha436
 
Software Process Model in software engineering
Software Process Model in software engineeringSoftware Process Model in software engineering
Software Process Model in software engineeringMuhammadTalha436
 
Software engineering interview questions
Software engineering interview questionsSoftware engineering interview questions
Software engineering interview questionsMuhammadTalha436
 
Software Engineering (Short & Long Questions)
Software Engineering (Short & Long Questions)Software Engineering (Short & Long Questions)
Software Engineering (Short & Long Questions)MuhammadTalha436
 
Prototype model (software engineering)
Prototype model (software engineering)  Prototype model (software engineering)
Prototype model (software engineering) MuhammadTalha436
 
Incremental model (software engineering)
Incremental model (software engineering)Incremental model (software engineering)
Incremental model (software engineering)MuhammadTalha436
 
V model (software engineering)
V model (software engineering)V model (software engineering)
V model (software engineering)MuhammadTalha436
 
Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)  Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering) MuhammadTalha436
 
Software Quality Assurance in software engineering
Software Quality Assurance in software engineeringSoftware Quality Assurance in software engineering
Software Quality Assurance in software engineeringMuhammadTalha436
 
A Risk Analysis and Management in Software Engineering
A Risk Analysis and Management in Software Engineering A Risk Analysis and Management in Software Engineering
A Risk Analysis and Management in Software Engineering MuhammadTalha436
 
Testing strategies in Software Engineering
Testing strategies in Software EngineeringTesting strategies in Software Engineering
Testing strategies in Software EngineeringMuhammadTalha436
 
Project Management Complete Concept
Project Management Complete Concept Project Management Complete Concept
Project Management Complete Concept MuhammadTalha436
 
Introduction of Software Engineering
Introduction of Software EngineeringIntroduction of Software Engineering
Introduction of Software EngineeringMuhammadTalha436
 
Software Engineering Solved Past Paper 2020
Software Engineering Solved Past Paper 2020 Software Engineering Solved Past Paper 2020
Software Engineering Solved Past Paper 2020 MuhammadTalha436
 
Sofware Engineering Important Past Paper 2019
Sofware Engineering Important Past Paper 2019Sofware Engineering Important Past Paper 2019
Sofware Engineering Important Past Paper 2019MuhammadTalha436
 
Software Engineering Past Papers Notes
Software Engineering Past Papers Notes Software Engineering Past Papers Notes
Software Engineering Past Papers Notes MuhammadTalha436
 
Software Engineering Important Short Question for Exams
Software Engineering Important Short Question for ExamsSoftware Engineering Important Short Question for Exams
Software Engineering Important Short Question for ExamsMuhammadTalha436
 
Software Engineering Past Papers (Short Questions)
Software Engineering Past Papers (Short Questions)Software Engineering Past Papers (Short Questions)
Software Engineering Past Papers (Short Questions)MuhammadTalha436
 

More from MuhammadTalha436 (20)

Analysis modeling in software engineering
Analysis modeling in software engineeringAnalysis modeling in software engineering
Analysis modeling in software engineering
 
Software Process in software engineering
Software Process in software engineeringSoftware Process in software engineering
Software Process in software engineering
 
Software Process Model in software engineering
Software Process Model in software engineeringSoftware Process Model in software engineering
Software Process Model in software engineering
 
Software engineering interview questions
Software engineering interview questionsSoftware engineering interview questions
Software engineering interview questions
 
Software Engineering (Short & Long Questions)
Software Engineering (Short & Long Questions)Software Engineering (Short & Long Questions)
Software Engineering (Short & Long Questions)
 
Prototype model (software engineering)
Prototype model (software engineering)  Prototype model (software engineering)
Prototype model (software engineering)
 
Incremental model (software engineering)
Incremental model (software engineering)Incremental model (software engineering)
Incremental model (software engineering)
 
V model (software engineering)
V model (software engineering)V model (software engineering)
V model (software engineering)
 
Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)  Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)
 
Requirements Engineering
Requirements EngineeringRequirements Engineering
Requirements Engineering
 
Software Quality Assurance in software engineering
Software Quality Assurance in software engineeringSoftware Quality Assurance in software engineering
Software Quality Assurance in software engineering
 
A Risk Analysis and Management in Software Engineering
A Risk Analysis and Management in Software Engineering A Risk Analysis and Management in Software Engineering
A Risk Analysis and Management in Software Engineering
 
Testing strategies in Software Engineering
Testing strategies in Software EngineeringTesting strategies in Software Engineering
Testing strategies in Software Engineering
 
Project Management Complete Concept
Project Management Complete Concept Project Management Complete Concept
Project Management Complete Concept
 
Introduction of Software Engineering
Introduction of Software EngineeringIntroduction of Software Engineering
Introduction of Software Engineering
 
Software Engineering Solved Past Paper 2020
Software Engineering Solved Past Paper 2020 Software Engineering Solved Past Paper 2020
Software Engineering Solved Past Paper 2020
 
Sofware Engineering Important Past Paper 2019
Sofware Engineering Important Past Paper 2019Sofware Engineering Important Past Paper 2019
Sofware Engineering Important Past Paper 2019
 
Software Engineering Past Papers Notes
Software Engineering Past Papers Notes Software Engineering Past Papers Notes
Software Engineering Past Papers Notes
 
Software Engineering Important Short Question for Exams
Software Engineering Important Short Question for ExamsSoftware Engineering Important Short Question for Exams
Software Engineering Important Short Question for Exams
 
Software Engineering Past Papers (Short Questions)
Software Engineering Past Papers (Short Questions)Software Engineering Past Papers (Short Questions)
Software Engineering Past Papers (Short Questions)
 

Recently uploaded

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Recently uploaded (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Object Oriented Solved Practice Programs C++ Exams

  • 1. Question 1: Create a class Employee with instance variable EmpId, Empage, EmpName and decide proper data types and access modifiers for these variable. Define overloaded constructors getter/setter methods and also overridden to_String() method. Demonstrate this in your class program. Solution: //Creating Employee class package employee; import java.util.Scanner; public class Employee{ protected int EmpId,Empage; String EmpName; public Employee(){ EmpId=1; Empage=1; EmpName="abc"; } public Employee(int EmpId,int Empage,String EmpName){ this.EmpId=EmpId; this.Empage=Empage; this.EmpName=EmpName; } Scanner input=new Scanner(System.in); void setter(){ System.out.println("Enter Employee Data"); System.out.println("Enter Employee ID"); EmpId=input.nextInt(); shiningstudy.com
  • 2. System.out.println("Enter Employee Age"); Empage=input.nextInt(); System.out.println("Enter Employee Name"); EmpName=input.next(); } @Override public String toString(){ return String.format(EmpName+"Write any String You Want"); } int getter_ID(){ return EmpId; } int getter_Age(){ return Empage; } String getter_Name(){ return EmpName; } public static void main(String[] args) { Employee emp= new Employee(); emp.setter(); System.out.println("Employee Data is:::"); System.out.println("Employee Name is : "+ emp.getter_Name()); System.out.println("Employee ID is : "+ emp.getter_ID()); shiningstudy.com
  • 3. System.out.println("Employee Age is : "+ emp.getter_Age()); } } shiningstudy.com
  • 4. Question 2: Create a class called ”SHAPE”(Should be Made an Abstract class) having two instance variables Length(Double), Height(Double) with appropriate Access specifiers and instance method Get_Date() to get and assign the values (to Length and Heigh) from the user, it also has an Abstract method Display_Area() to compute and display the area of the geometrical object. Derive two specific classes “Triangle” and “Rectangle” from the base class that Override the base class method using these three classes design a program that will accept dimension of a triangle /Rectangle interactively and display area. HINT: Area of Triangle = ½(L*H) Area of Rectangle = (L*H) Solution: //Creating Shape class package shape; import java.util.Scanner; public abstract class Shape { protected double Length,Height; Scanner input=new Scanner(System.in); void Get_Data(){ System.out.println("Please Enter Length and Height"); Length=input.nextDouble(); Height=input.nextDouble(); } abstract void Area(); shiningstudy.com
  • 5. } //Creating Triangle as a sub class package shape; public class Triangle extends Shape{ Triangle(){ Length=1; Height=1; } @Override void Get_Data(){ System.out.println("Please Enter Length and Height of Triangle"); Length=input.nextDouble(); Height=input.nextDouble(); } @Override void Area() { double area=(Length*Height)/2; System.out.println("Area of Trinagle: " + area + "Square Unit"); } } We are creating rectangle sublass package shape; shiningstudy.com
  • 6. import javax.sound.midi.Receiver; public class Rectangle extends Shape{ Rectangle(){ Length=1; Height=1; } @Override void Get_Data(){ System.out.println("Please Enter Length and Height of Rectangle"); Length=input.nextDouble(); Height=input.nextDouble(); } @Override void Area() { double area=Length*Height; System.out.println("Area of Rectnagle: " + area + "Sqaure Unit"); } public static void main(String[] args){ Triangle tri=new Triangle(); Rectangle rec=new Rectangle(); //FOR GETTING LENGTH OF TRIANGLE tri.Get_Data(); //FOR PRINTING AREA OF TRIANGLE tri.Area(); shiningstudy.com
  • 7. //FOR GETTING LENGTH OF RECTANGLE rec.Get_Data(); //FOR PRINTING AREA OF RECTANGLE rec.Area(); } } Question 3: Explain Exception Handling in java and why we use Nested Try Blocks. Write a program to Explain Exception Handling by Nested try/catch Blocks. Solution: Why we use Exceptional Handling in Java: An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. Why we use Nested Try Block: Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested. EXAMPLE: //Creating Nested class package nested; import java.util.InputMismatchException; public class Nested { public static void main(String[] args) { shiningstudy.com
  • 8. try { System.out.println("Outer try block starts"); try { System.out.println("Inner try block starts"); int res = 5 / 0; } catch (InputMismatchException e) { System.out.println("InputMismatchException caught"); } finally { System.out.println("Inner final"); } } catch (ArithmeticException e) { System.out.println("ArithmeticException caught"); } finally { System.out.println("Outer finally"); } } } Question 4: Explain the advantages of using interface in Java? Also write a java program to show how a class implements two Interfaces. Solution: shiningstudy.com
  • 9. Advantages of Using Interface: An interface in java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.  achieve full abstraction  achieve multiple inheritance  achieve loose coupling  to break up the complex designs and clear the dependencies between objects. EXAMPLE: interface printable{ void print_text(); } class One implements printable{ public void print_text(){ System.out.println("Hello World"); } public static void main(String args[]){ One o= new One(); o.print_text(); } } Question 5: Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide member function that calculate the area of the rectangle also provide set and get functions for the length and width attributes. The set function should verify that Length and Width are each floating numbers larger then 0.0 and less than 20.0. Solution: shiningstudy.com
  • 10. package pkgtry; //Creating Rectangle class import java.util.Scanner; public class Rectangle { Scanner input = new Scanner(System.in); float length,width; Rectangle (){ length=1; width=1; } float area(){ float area=length*width; return area; } void set_length(){ System.out.println("Enter length"); float a=input.nextFloat(); if(a>0 && a<20){ length=a; } else System.out.println("Condition Not Satify"); } void set_width(){ System.out.println("Enter Width"); shiningstudy.com
  • 11. float a=input.nextFloat(); if(a>0 && a<20){ width=a; } else System.out.println("Condition Not Satify"); } float get_length(){ return length; } float get_width(){ return width; } public static void main(String[] args) { Rectangle rec=new Rectangle (); rec.set_length(); rec.set_width(); System.out.println("Area of Rectangle is : "+ rec.area()); } } shiningstudy.com
  • 12. Question 6: Write a class name operator that have only one data member count the class has the following member functions. 1-Constructor to Initialize the count. 2-show function to show the count. 3-Overload ++ Operator to increase the count by 1. Solution: //Creating Operator class package operator; public class Operator { int count; Operator(){ count=2; } void show(){ System.out.println(count); } void Overload(){ count++; System.out.println(count); } public static void main(String[] args) { Operator op = new Operator(); op.show(); shiningstudy.com
  • 13. op.Overload(); } } Question 7: Explain Constructor Overloading with the Help of One Example? Solution: public class Name{ String name; Name(){ name=”Ubaid”; } //Constructor Overloading Name(String name){ this.name=name; } public static void main(String[] args){ Name obj = new Name(); //It will Call Default Constructor Name obj1 = new Name(“Adeel”); //It will Call Overloaded Constructor System.out.println(obj.name); System.out.println(obj1.name); } } Question 8: shiningstudy.com
  • 14. Define a class for bank account that includes the following data members. Name of Depositor, Account Number, Type of Account, balance amount in the Bank. The class also contain following Member functions, 1-A constructor to assign initial values 2- Deposit Function to deposit amount it should accept value as s parameter. 3- Withdraw function to withdraw an amount after checking the balance, it should accept the value as a parameter. Display function to display name and balance. Solution: //Creating Bank class package bank_account; import java.util.Scanner; public class Bank_Account { final String name,acc_type; String d_name; final int account_num; int bank_bal; public Bank_Account() { name="Ubaid"; acc_type="Saving"; d_name="Adeel"; account_num=3415976; bank_bal=150000; } void deposit(int amount){ bank_bal+=amount; shiningstudy.com
  • 15. } void withdraw(int amount){ bank_bal-=amount; } void Display(){ System.out.println("Account Name is :: "+ name); System.out.println("Your Name is :: "+ d_name); System.out.println("Your Bank Balance is :: "+ bank_bal); } public static void main(String[] args) { Bank_Account bank= new Bank_Account(); Scanner input= new Scanner(System.in); System.out.println("Please Enter the Depositor Name"); bank.d_name=input.next(); System.out.println("Please Enter an Amount U want to Deposit"); bank.deposit(input.nextInt()); bank.Display(); System.out.println("Please Enter an Amount U want to Withdraw"); bank.withdraw(input.nextInt()); bank.Display(); } } Question 9: Write a class local phone that contains an attribute phone o store a local phone number. The class contains memebre Functions to input and display phone Number. Write a child class NarPhone for National Phone Numbers that inherit localPhone class. It additionally contains an shiningstudy.com
  • 16. attribute to store city code. It also contains member function to input and show city code. Write another class IntPhone for international phone Numbers that inherit NatPhoneclass. It additionally contains an attribute to store country code. It also contains member Functions to input and show the country code. Solution: //Creating Localphone class package localphone; import java.util.Scanner; public class Localphone { int phone_num; Scanner input = new Scanner(System.in); void setNum(){ System.out.println("Please enter Your Local Phone Number : "); phone_num=input.nextInt(); } void Display(){ System.out.println("Your Phone Number is : " + phone_num); } void input(){ } } //Creating NatPhone as sub class package localphone; shiningstudy.com
  • 17. public class Natphone extends Localphone { int ci_code=0; void setCi_code(){ System.out.println("Please enter Your City Code : "); ci_code=input.nextInt(); System.out.println("Your City Code is : 0"+ ci_code); } } //Creating IntPhone as sub class package localphone; public class Intphone extends Natphone{ int co_code; void setCo_code(){ System.out.println("Please enter Your Country Code : "); co_code=input.nextInt(); System.out.println("Your City Code is : 00"+ co_code); } public static void main(String[] args) { Intphone inter= new Intphone(); Natphone nat= new Natphone(); inter.setCo_code(); inter.setCi_code(); shiningstudy.com
  • 18. nat.setNum(); nat.Display(); } } Question 10: Write a Time class that has three fields hours, minutes, seconds. To Initialize these fields it has constructors, Getter and Setter Methods, and print time methods to display time. Also override toString methods in this class. Solution: //Creating Time class package time; import java.util.Scanner; public class Time { int hours,minutes,seconds; Time(){ hours=1; minutes=30; seconds=30; } Time(int hours , int minutes , int seconds){ this.hours=hours; this.minutes=minutes; this.seconds=seconds; } shiningstudy.com
  • 19. Scanner input= new Scanner(System.in); void setter(){ System.out.println("Please enter Hours"); hours=input.nextInt(); System.out.println("Please enter Minutes"); minutes=input.nextInt(); System.out.println("Please enter Seconds"); seconds=input.nextInt(); } int getter_hours(){ return hours; } int getter_minutes(){ return minutes; } int getter_seconds(){ return seconds; } void Print_time(){ System.out.print("Time is ::::: "); System.out.println(hours+":"+minutes+":"+seconds); } @Override public String toString(){ return String.format(hours+":"+minutes+":"+seconds); } public static void main(String[] args) { shiningstudy.com
  • 20. Time t1 = new Time(); //Object of Default constructor Time t2 = new Time(2,36,50); //Object of Argumented constructor //dISPLAY VALUES OF ATTRIBUTES OF USER DEFINED CONSTRUCOR t1.Print_time(); //DISPLAY VALUES OF ATTRIBUTES OF USER DEFINED CONSTRUCOR t2.Print_time(); //DISPLAY VALUES OF ATTRIBUTE AFTER SETTING VALUES t1.setter(); t1.Print_time(); } } Question 11: Write a java class that has two classes Point and Circle, Circle extends Point class. Demonstrate Up-casting by using Circle class. Solution: //Creating Point class package point; public class Point { float radius; void show(){ System.out.println("Point class"); } shiningstudy.com
  • 21. } //Creating Circle as sub class package point; public class Circle extends Point{ float rad=5; public Circle() { super.radius=rad; } public static void main(String[] args) { Circle cir = new Circle(); //UpCasting System.out.println("Radius of Circle is :" + cir.radius); //UpCasting cir.show(); } } Question 12: shiningstudy.com
  • 22. Write a java program that has Shape class and subclasses Rectangle, Oval,Triangle. Use These classes to Demonstrate the polymorphic behavior. Solution: //Creating Shape class package shapes; public class Shapes { void sides(int sid){ System.out.println("ENter the Object sides"); } } //Creating Rectangle as sub class package shapes; public class rectange extends Shapes{ @Override void sides(int sid){ System.out.println("Sides Of Rectwangel"+ +sid); } } //Creating Oval as sub class package shapes; shiningstudy.com
  • 23. public class oval extends Shapes{ @Override void sides(int sid){ System.out.println("Sides Of Oval"+ +sid); } } //Creating Triangle as sub class package shapes; public class triangel extends Shapes{ @Override void sides(int sid){ System.out.println("Sides Of Triangel"+ +sid); } public static void main(String[] args) { rectange re=new rectange(); oval ov=new oval(); triangel tri=new triangel(); re.sides(4); ov.sides(0); tri.sides(3); } } shiningstudy.com
  • 24. Question 13: What is Exceptional Handling in Java? Write a java program to handle multiple Exceptions? Solution: Exception Handling: Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java Exception Handling. Example: package testmultiplecatchblock; import java.util.*; public class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a; a=30/0; } catch(ArithmeticException e){ System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed"); } finally{ System.out.println("common task completed"); } System.out.println("rest of the code..."); shiningstudy.com
  • 25. } } Question 14: Write a program that creates a class Student with name as its attribute, Derive class scholar that stores title of his thesis (that designates in as a scholar). Derive another class Salaried Scholar from scholar that earns some salary (attribute of the class). Write suitable constructor (multiple) and other methods or the class to create and display the two objects of the Salaried Scholar. Solution: //Creating Student class package student; public class Student { String name; Student(){ name="Ubaid"; } Student(String name){ this.name=name; } void Display(){ System.out.println(name); } } //Creating Scholar as sub class shiningstudy.com
  • 26. package student; public class Scholar extends Student{ String t_topic; Scholar(){ t_topic="Poorty"; } Scholar(String t_topic){ this.t_topic=t_topic; } @Override void Display(){ System.out.println("Scholar Name : " + name); System.out.println("Thesis Topic : " + t_topic); } } //Creating Salaried as sub class package student; public class Salaried_Scholar extends Scholar{ int salary; public Salaried_Scholar() { shiningstudy.com
  • 27. salary=50000; } public Salaried_Scholar(int salary) { this.salary=salary; } @Override void Display(){ System.out.println("Scholar Name : " + name); System.out.println("Thesis Topic : " + t_topic); System.out.println("Scholar Salary : " + salary); } public static void main(String[] args) { Salaried_Scholar sch1= new Salaried_Scholar(); Salaried_Scholar sch2= new Salaried_Scholar(45000); sch1.Display(); } } Question 15 Create a class publication (title, price). Create two classes named books (no of pages) and tape (playing time) from it. Write appropriate constructors, print () and get () functions for each class. Write an applications that demonstrates using objects of each class. Solution: //Creating Publication class package publication; public class Publication { shiningstudy.com
  • 28. String title; float price; Publication(){ title="TITLE HERE"; price=450; } Publication(String title , float price){ this.title=title; this.price=price; } String get_title(){ return title; } float get_price(){ return price; } void print(){ System.out.println("Title of Book is : "+ title); System.out.println("Price of Book is : "+ price); } } shiningstudy.com
  • 29. //Creating Books as a sub class package publication; public class Books extends Publication{ int no_of_pages; Books(){ no_of_pages=500; } Books(int no_of_pages) { this.no_of_pages=no_of_pages; } float get_no_of_pages(){ return no_of_pages; } @Override void print(){ System.out.println("Title of Book is : "+ title); System.out.println("Price of Book is : "+ price); System.out.println("No. of Pages of Book is : "+ no_of_pages); } shiningstudy.com
  • 30. } //Creating Tape as a sub class package publication; public class Tape extends Publication{ int play_time; Tape(){ play_time=5; } Tape(int play_time){ this.play_time=play_time; } float get_play_time(){ return play_time; } @Override void print(){ System.out.println("Title of Book is : "+ title); System.out.println("Price of Book is : "+ price); System.out.println("Play Time of Book is : "+ play_time); } public static void main(String[] args) { Publication pub=new Publication(); Publication pub1=new Publication("Sahi Bukhari",600); shiningstudy.com
  • 31. Books book=new Books(); Books book1=new Books(450); Tape tape=new Tape(); Tape tape1=new Tape(4); book.print(); tape.print(); //Argumented constructors values book1.print(); tape1.print(); } } Question 16 Create an abstract Auto class with fields for the car make and price. Include het and set methods for these fields, the setPrice() methods is abstract. Create two subclasses automobiles maker (for Example Mehran, Toyota) and include appropriate setPrice() methods in each class(i.e Rs 600000 or Rs 1800000). Finally, write an application what uses auto class and subclasses to display information amount different cars. Solution: //Creating Auto class package auto; public abstract class Auto { String car_make; float price; void set_carmake(String car_make){ this.car_make=car_make; } shiningstudy.com
  • 32. String get_carmake(){ return car_make; } abstract void set_price(); float get_price(){ return price; } } //Creating Mehran as a sub class package auto; public class Mehran extends Auto{ @Override void set_price() { price=600000; } } //Creating Toyota as a sub class package auto; public class Toyota extends Auto{ @Override shiningstudy.com
  • 33. void set_price() { price=1800000; } public static void main(String[] args) { Mehran meh=new Mehran(); Toyota toyo = new Toyota(); meh.set_carmake("Mehran"); meh.set_price(); toyo.set_carmake("TOYOTA"); toyo.set_price(); System.out.println("Car Make : "+ meh.get_carmake()); System.out.println("Car Price : "+ meh.get_price()); System.out.println("Car Make : "+ toyo.get_carmake()); System.out.println("Car Price : "+ toyo.get_price()); } } Question 17 Write down the class Time having fields (hrs, min, secs) containing no argument constructor, three argument constructor and copy constructor. Also write down a method inc_time() that increment seconds by 1 if seconds are equal to 60 then increment minute by 1 and set seconds to 0. If minutes become 60 then increment hrs by 1 and set minutes to 0. Write down a methods that compare two time objects and return true time if they are Equal else return False. Solution: //Creating Tim class package tim; public class Tim { int hrs,min,secs; shiningstudy.com
  • 34. public Tim() { hrs=2; min=30; secs=59; } public Tim(int hrs, int min, int secs) { this.hrs=hrs; this.min=min; this.secs=secs; } //Coping Object to Constructor public Tim(Tim c) { this.hrs=c.hrs; this.min=c.min; this.secs=c.secs; } void inc_time(){ secs++; if(secs==60) { secs=0; min++; } if(min==60) shiningstudy.com
  • 35. { min=0; hrs++; } if(hrs==24) { hrs=0; } } void display_time(){ System.out.println("Time is"); System.out.println(hrs +":"+min+":"+secs); } public static void main(String[] args) { Tim time1=new Tim(); Tim time2=new Tim(2,30,59); //Coping time1 OBJECT to the time3 OBJECT Tim time3=new Tim(time1); time1.inc_time(); time2.inc_time(); time1.display_time(); if(time1.hrs==time2.hrs && time1.min==time2.min && time1.secs==time2.secs) System.out.println("TRUE"); shiningstudy.com
  • 36. else System.out.println("FALSE"); //Object Copied System.out.println("AFTER COPING OBJECT"); time3.display_time(); } } Question 17(a): What is compositions: Explain Your answer with Example. Solution: COMPOSITION: Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse. Java composition is achieved by using instance variables that refers to other objects Example: package com.journaldev.composition; public class Job { private String role; private long salary; private int id; public String getRole() { return role; } shiningstudy.com
  • 37. public void setRole(String role) { this.role = role; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } } package com.journaldev.composition; public class Person { //composition has-a relationship private Job job; public Person(){ shiningstudy.com
  • 38. this.job=new Job(); job.setSalary(1000L); } public long getSalary() { return job.getSalary(); } } package com.journaldev.composition; public class TestPerson { public static void main(String[] args) { Person person = new Person(); long salary = person.getSalary(); } } Question 17(b): What is this keyword and Its Purpose. Give an Example. Solution: What is this keyword and its Purpose: shiningstudy.com
  • 39. Keyword THIS is a reference variable in Java that refers to the current object. It can be used to refer instance variable of current class. It can be used to invoke or initiate current class constructor. It can be passed as an argument in the method call. Example: package pkgthis; public class This { int a,b,sum; public This(int a , int b) { this.a=a; this.b=b; } public static void main(String[] args) { This thi=new This(5,6); thi.sum=thi.a+thi.b; System.out.println("Sum of Integers is :" + thi.sum); } } Question 18: Write down a program that makes a text file and make its copy in another file. Add exceptional handling where necessary. Solution: package copy; import java.io.FileReader; import java.io.FileWriter; shiningstudy.com
  • 40. import java.io.IOException; import java.io.FileNotFoundException; public class copy{ public static void main (String[] args) throws IOException { FileWriter obj1= new FileWriter("copied.txt"); int c; try // no throw statement necessary { FileReader obj= new FileReader("abc.txt"); while((c=obj.read())!=-1) { obj1.write((char)c); } obj.close(); } catch (FileNotFoundException e) // exception is explicitly caught { System.out.println("File not found : "); System.out.println("Program terminated"); System.out.println(e); System.exit(0); // ends program } obj1.close(); } } shiningstudy.com
  • 41. Question 19: Create a class Distance with instance variable feet and inches. Write a suitable parameterized constructor, getter and setter Methods and a Method to add two objects in such a way that is a resultant inches exceed 12, feet should be incremented by 1 and inches decremented by 12 using the statement dist3.add(dist1,dist2): where dist1, dist2, dist3 are the objects of the Distance class. Solution: package distance; public class Distance { int inches,feets; public Distance(int inches,int feets) { this.inches=inches; this.feets=feets; } void setter(){ inches=1; feets=1; } int getter_inches(){ return inches; } int getter_feets(){ return feets; } shiningstudy.com
  • 42. void add(Distance dst1,Distance dst2) { feets=dst1.feets+dst2.feets; inches=dst1.inches+dst2.inches; } public static void main(String[] args) { Distance dist1=new Distance(2,3); Distance dist2=new Distance(2,3); Distance dist3=new Distance(1,1); dist3.add(dist1,dist2); if(dist3.inches>12){ dist3.feets++; dist3.inches-=12; System.out.println("feets="+dist3.feets); System.out.println("inches="+dist3.inches); } else{ System.out.println("feets="+dist3.feets); System.out.println("inches="+dist3.inches); } } } Question 20: Write a program that has Shape class and subclasses as Square and Circle, Use these classes demonstrate the Polymorphism. shiningstudy.com
  • 43. Solution: package shap; public class Shap { void show(){ System.out.println("Your are in Shape Class"); } } package shap; public class Square extends Shap{ @Override void show(){ System.out.println("Your are in Square Class"); } } package shap; public class Circle extends Shap{ @Override void show(){ System.out.println("Your are in Circle Class"); } public static void main(String[] args) { Shap sh = new Shap(); shiningstudy.com
  • 44. Square sq=new Square(); Circle cir=new Circle(); sh.show(); sq.show(); cir.show(); } } Question 21: Write a java text stream class from java.io package to read text from one file and write to another text file. Solution: package fileinputoutput; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class FileInputOutput { public static void main(String[] args) throws Exception { InputStream is = new FileInputStream("in.txt"); shiningstudy.com
  • 45. OutputStream os = new FileOutputStream("out.txt"); int c; while ((c = is.read()) != -1) { System.out.println((char) c); os.write(c); } is.close(); os.close(); } } shiningstudy.com