0% found this document useful (0 votes)
37 views

Java QB2

This document contains 9 questions related to Java programming concepts like inheritance, polymorphism, interfaces, packages etc. Each question provides an explanation or code example to illustrate the concept. Multiple inheritance is achieved in Java using interfaces - a class can implement multiple interfaces but extend only one superclass. The key system packages mentioned are java.lang for language classes, java.util for utility classes, java.io for input/output and java.net for network programming.

Uploaded by

Amaan Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java QB2

This document contains 9 questions related to Java programming concepts like inheritance, polymorphism, interfaces, packages etc. Each question provides an explanation or code example to illustrate the concept. Multiple inheritance is achieved in Java using interfaces - a class can implement multiple interfaces but extend only one superclass. The key system packages mentioned are java.lang for language classes, java.util for utility classes, java.io for input/output and java.net for network programming.

Uploaded by

Amaan Shaikh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java QB2

1. Write a program to implem ent following inheritance.

➢ class person
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("name--->"+name);
System.out.println("age--->"+age);
}
}
class employee extends person
{
String emp_designation;
float emp_salary;
void accept_emp(String d,float s)
{
emp_designation=d;
emp_salary=s;
}
void emp_dis()
{
System.out.println("emp_designation-->"+emp_designation);
System.out.println("emp_salary-->"+emp_salary);
}
}
class single_demo
{
public static void main(String ar[])
{
employee e=new employee();
e.accept("ramesh",35);
e.display();
e.accept_emp("lecturer",35000.78f);
e.emp_dis();
}
}
2. Explain method overloading with example.
➢ Method Overloading means to define different methods with thesame name but
different parameters lists and different definitions.It is used when objects are
required to perform similar task but using different input parameters that may vary
either in number or type of arguments. Overloaded methods may have different
return types. It is a way of achieving polymorphism in java.
int add( int a, int b) // prototype 1
int add( int a , int b , int c) // prototype 2
double add( double a, double b) // prototype 3
Example:
class Sample
{
int addition(int i, int j)
{
return i + j ;
}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));
}
}
3. Define a class person with data member as Aadharno, name, Panno implement
concept of constructor overloading. Accept data for 5 object and print it.
➢ import java.util.Scanner;

public class Person {


private String aadharNo;
private String name;

public Person(String aadharNo, String name) {


this.aadharNo = aadharNo;
this.name = name;
}

@Override
public String toString() {
return "Person{" +
"aadharNo='" + aadharNo + '\'' +
", name='" + name + '\'' +
'}';
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter Aadhar No for person1: ");


String aadharNo1 = scanner.nextLine();
System.out.print("Enter name for person1: ");
String name1 = scanner.nextLine();

System.out.print("Enter Aadhar No for person2: ");


String aadharNo2 = scanner.nextLine();
System.out.print("Enter name for person2: ");
String name2 = scanner.nextLine();

Person person1 = new Person(aadharNo1, name1);


Person person2 = new Person(aadharNo2, name2);

System.out.println(person1);
System.out.println(person2);
}
}
4. Explain method overriding with suitable example.
➢ Method Overriding in Java: If subclass (child class) has the same method as declared
in the parent class, it is known as method overriding in java. If subclass provides the
specific implementation of the method that has been provided by one of its parent
class, it is known as method overriding. Method overriding is used for runtime
polymorphism.
Example:
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
5. Describe final method and final variable with respect to inheritance.
➢ final method: making a method final ensures that the functionality defined in this
method will never be altered in any way, ie a final method cannot be overridden.
E.g.of declaring a final method:
final void findAverage() {
//implementation
}
EXAMPLE
class A
{ final void show()
{
System.out.println(“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
}
}
final variable: the value of a final variable cannot be changed. final variable behaves
like class variables and they do not take any space on individual objects of the class.
E.g. of declaring final variable:
final int size = 100;
6. Describe use of “super” and “this” with respect to inheritance.
➢ Using inheritance, you can create a general class that defines traits common to a set
of related items. This class can then be inherited by other, more specific classes, each
adding those things that are unique to it. In the terminology of Java, a class that is
inherited is called a superclass. The class that does the inheriting is called a subclass.
Therefore, a subclass is a specialized version of a superclass.
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of
the keyword super.
Super has two general forms. The first calls the super class constructor. The second is
used to access a member of the superclass that has been hidden by a member of a
subclass. super() is used to call base class constructer in derived class. Super is used
to call overridden method of base class or overridden data or evoked the overridden
data in derived class.

e.g use of super()


class BoxWeightextends Box
{
BowWeight(int a ,intb,int c ,int d)
{
super(a,b,c) // will call base class constructer Box(int a, int b, int c)
weight=d // will assign value to derived class member weight.
}
e.g. use of super.
Class Box
{
Box()
{
}
void show()
{
//definition of show
}
} //end of Box class
Class BoxWeight extends Box
{
BoxWeight()
{
}
void show() // method is overridden in derived
{
Super.show() // will call base class method
}
}
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this,
Java defines the this keyword. this can be used inside any method to refer to the
current object. That is, this is always a reference to the object on which the method
was invoked. You can use this anywhere a reference to an object of the current class‟
type is permitted. To better understand what this refers to, consider the following
version of Box( ): // A redundant use of this. Box(double w, double h, double d)
{ this.width = w; this.height = h; this.depth = d; }
Instance Variable Hiding
when a local variable has the same name as an instance variable, the local variable
hides the instance variable. This is why width, height, and depth were not used as the
names of the parameters to the Box( ) constructor inside the Box class. If they had
been, then width would have referred to the formal parameter, hiding the
instance variable width.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
7. Write major differences between interface and a class.

8. How multiple inheritance is achieved in java? Explain with proper program.
➢ Inheritance is a mechanism in which one object acquires all the properties and
behaviours of parent object. The idea behind inheritance in java is that new classes
can be created that are built upon existing classes. Multiple inheritance happens
when a class is derived from two or more parent classes. Java classes cannot extend
more than one parent classes, instead it uses the concept of interface to implement
the multiple inheritance. It contains final variables and the methods in an interface
are abstract. A sub class implements the interface. When such implementation
happens, the class which implements the interface must define all the methods of
the interface. A class can implement any number of interfaces.
Eg:
import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2;
Student(String name, introll_no, double m1, double m2)
{
this.name = name;
this.roll_no = roll_no;
this.m1 = m1;
this.m2 = m2;
}
}
interface exam
{
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of the
student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
}
catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
9. State any four system packages along with their use.
➢ a) java.lang - language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions
b) java.util – language utility classes such as vectors, hash tables, random numbers,
date etc.
c) java.io – input/output support classes. They provide facilities for the input and
output of data
d) java.awt – set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on
e) java.net – classes for networking. They include classes for communicating with
local computers as well as with internet servers.
f) java.applet – classes for creating and implementing applets.
10.What is package? How to create package? Explain with suitable example.
➢ Java provides a mechanism for partitioning the class namespace into more
manageable parts called package (i.e package are container for a classes). The
package is both naming and visibility controlled mechanism. Package can be created
by including package as the first statement in java source code. Any classes declared
within that file will belong to the specified package. The syntax for creating package
is:
package pkg;
Here, pkg is the name of the package
eg : package mypack;
Packages are mirrored by directories. Java uses file system directories to store
packages. The class files of any classes which are declared in a package must be
stored in a directory which has same name as package name. The directory must
match with the package name exactly. A hierarchy can be created by separating
package name and sub package name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
The classes and methods of a package must be public.
Syntax:
To access package In a Java source file, import statements occur
immediately following the package statement (if it exists) and
before any class definitions.
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h)); }
}
}
Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}
11. State and explain types of errors in java?
➢ Types of Error
a) Compile Time Errors:
All syntax errors given by Java Compiler are called compile time errors. When
program is compiled, java checks the syntax of each statement. If any syntax
error occurs, it will be displayed to user, and .class file will not be created.

Common compile time Errors


I. Missing semicolon
II. Missing of brackets in classes and methods
III. Misspelling of variables and keywords.
IV. Missing double quotes in Strings.
V. Use of undeclared variable.
VI. Incompatible type of assignment/initialization.
VII. Bad reference to object.

b) Run time error:


After creating .class file, Errors which are generated, while program is running
are known as runtime errors. Results in termination of program.

Common runtime Errors


I. Dividing an integer by zero.
II. Accessing an element that is out of the bounds of an
array.
III. Trying to store data at negative index value.
IV. Opening file which does not exist.
V. Converting invalid string to a number.
12. Define an exception. How it is handled?
➢ Exception: An exception is an event, which occurs during the execution of a program,
that stop the flow of the program's instructions and takes appropriate actions if
handled.
a) try: This block applies a monitor on the statements written inside it. If there exist
any exception, the control is transferred to catch or finally block
b) catch: This block includes the actions to be taken if a particular exception occurs.
c) finally: finally block includes the statements which are to be executed in any case,
in case the exception is raised or not.
d) throw: This keyword is generally used in case of user defined exception, to
forcefully raise the exception and take the required action.
e) throws: throws keyword can be used along with the method definition to name the
list of exceptions which are likely to happen during the execution of that method. In
that case, try … catch block is not necessary in the code.
13.With suitable diagram explain life cycle of thread.

Thread Life Cycle


Thread has five different states throughout its life

Newborn State
Runnable State
Running State
Blocked State
Dead State

Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.

a) Newborn state: When a thread object is created it is said to be in a new born state.
When the thread is in a new born state it is not scheduled running from this state it
can be scheduled for running by start() or killed by stop(). If put in a queue it moves
to runnable state
b) Runnable State: It means that thread is ready for execution and is waiting for the
availability of the processor i.e. the thread has joined the queue and is waiting for
execution. If all threads have equal priority then they are given time slots for
execution in round robin fashion. The thread that relinquishes control joins the queue
at the end and again waits for its turn. A thread can relinquish the control to another
before its turn comes by yield().
c) Running State: It means that the processor has given its time to the thread for
execution. The thread runs until it relinquishes control on its own or it is pre-empted
by a higher priority thread.
d) Blocked state: A thread can be temporarily suspended or blocked from entering
into the runnable and running state by using either of the following thread method
suspend() : Thread can be suspended by this method. It can be rescheduled by
resume().
wait(): If a thread requires to wait until some event occurs, it can be done using wait
method and can be scheduled to run again by notify().
sleep(): We can put a thread to sleep for a specified time period using sleep(time)
where time is in ms. It reenters the runnable state as soon as period has
elapsed /over
e) Dead State: Whenever we want to stop a thread form running further we can call
its stop(). The statement causes the thread to move to a dead state. A thread will also
move to dead state automatically when it reaches to end of the method. The stop
method may be used when the premature death is required.
14.Write a program to create two thread one to print odd number only and other to
print even numbers.
➢ class EvenThread extends Thread
{
EvenThread()
{
start();
}
public void run()
{
try
{
for(inti = 0;i <= 10;i+=2)
{
System.out.println("Even Thread : "+i);
Thread.sleep(500);
}
}
catch (InterruptedExceptione){}
}
}
class OddThread implements Runnable
{
OddThread()
{
Thread t = new Thread(this);
t.start();
}
public void run()
{
try
{
for(inti = 1;i <= 10;i+=2)
{
System.out.println("Odd Thread : "+i);
Thread.sleep(1500);
}
}
catch (InterruptedExceptione){}
}
}
class Print
{
public static void main(String args[])
{
new EvenThread();
new OddThread();
}
}
15.With syntax and example explain try & catch statement.
➢ try- Program statements that you want to monitor for exceptions are contained
within a try block. If an exception occurs within the try block, it is thrown.
Syntax: try
{
// block of code to monitor for errors
}
catch- Your code can catch this exception (using catch) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java runtime
system. A catch block immediately follows the try block. The catch block can have
one or more statements that are necessary to process the exception.
Syntax: catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
E.g.
class DemoException {
public static void main(String args[])
{
try
{
int b=8;
int c=b/0;
System.out.println("Answer="+c);
}
catch(ArithmeticException e)
{
System.out.println("Division by Zero");
}}}

You might also like