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

Java Question Bank Answers

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

Java Question Bank Answers

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

GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

OBJECT ORIENTED PROGRAMING THROUGH JAVA


UNIT-1 QUESTION BANK SOLUJTIONS

1.Define object and class. Give an example


Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.
It represents the set of properties or methods that are common to all objects of one type. In
general, class declarations can include these components, in order:

EX: Public class Dog // Here Dog is a class


{
// methos and Variables
}
Object − An object is an instance of a class.

Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors – wagging the tail, barking, eating

Dog d1 = new Dog(); // d1 is an object


2. Explain difference between variable and parameter?

Variable:

A variable is a name given to a memory location. It is the basic unit of storage in a


program.

The value stored in a variable can be changed during program execution.

A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.

EX:

int age = 20;

Here int = datatype age , Variable Name= age , 20 is a value

Parameters:
Parameters refers to the list of variables in a method declaration.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

EX: Public void add( int a=10, int b=20)

3 What are the commands used for compilation and execution of java programs?
EX:
public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World")

}}

Compilation commands:

javac HelloWorld.java

java HelloWorld

Out Put :

Hello, World

4. Define the basic characteristics of Object Oriented Programming?

characteristics of Object Oriented Programming are

1.Abstraction 2. inheritance 3. Encapsulation 4.polymorphism

5. List out the operators in java?

1. Arithmetic Operators + - * / %
2. Unary Operators ++, --
3. Relational Operator ==, != , > ,< , >= , <=
4. Conditional Operator && (And ) , II (OR)
5. Assignment Operator = , += , -= , *= , /=
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

6.What is an abstraction?

Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces

For example phone call, we don't know the internal processing.

Ex: A car is viewed as a car rather than its individual components.

7.Explain garbage collection?

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words,it is a way to destroy the unused objects
in Java, the programmer need not to care for all those objects which are no longer in
use.
In java, garbage means unreferenced objects.
Garbage collector destroys these objects.

8. What is JVM and JRE?


JVM:
The Java Virtual Machine. JVM is the engine that converts Java bytecode into
machine language. JVM architecture in Java contains classloader, method area, heap,
JVM language stacks, PC registers, native method stacks, execution engine, native
methods interface, native methods libraries
JRE:
Java Runtime Environment (JRE) is an open-access software distribution that has a
Java class library, specific tools.
In Java, JRE is one of the interrelated components in the Java Development Kit
(JDK). It is the most common environment available on devices for running Java
programs. Java source code is compiled and converted to Java bytecode .

9. What is the syntax of else-if ladder?


The if-else-if ladder statement executes one condition from multiple statements.
else-if ladder syntax:

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Example:
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;

if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

10. Write a simple java program for addition of two numbers?

public class Add


{
public static void main(String args[])
{
int a =10, b=20, sum;
sum = a + b;
System.out.println("The sum of numbers is: "+sum);
}
}

Short Answer Questions (5 Marks)


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

1. Write a java method to find minimum value in given two values?

public class MinExample1 {

public static void main(String args[]) {

int x = 20;

int y = 50;

//print the minimum of two numbers

System.out.println(Math.min(x, y));

2. Explain different levels of access protection available in java?

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

3. What is a type casting concept?


Convert a value from one data type to another data type is known as type casting.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically. The automatic conversion is
done by the compiler and manual conversion performed by the programmer. In this section,
we will discuss type casting and its types with proper examples.

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting:

Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe because
there is no chance to lose data. It takes place when:

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other.
Let's see an example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample

{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

//automatically converts the long type into float type


float z = y;
System.out.println("Before conversion, int value "+x);

System.out.println("After conversion, long value "+y);


System.out.println("After conversion, float value "+z);
}
}
Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0
}

Narrowing Type Casting:


-----------------------------------------

Converting a higher data type into a lower one is called narrowing type casting. It is also known as
explicit conversion or casting up. It is done manually by the programmer. If we do not perform
casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

Let's see an example of narrowing type casting.

In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample

public static void main(String args[])


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

double d = 166.66;

//converting double data type into long data type

long l = (long)d;

//converting long data type into int data type

int i = (int)l;

System.out.println("Before conversion: "+d);

//fractional part lost

System.out.println("After conversion into long type: "+l);

//fractional part lost

System.out.println("After conversion into int type: "+i);

Output

Before conversion: 166.66

After conversion into long type: 166

After conversion into int type: 166

4. Write a java program with this keyword?

The primary purpose of the "this" keyword is to refer to the current object.

Example:
class ThisExample
{
ThisExample ()
{

System.out.println("hello a");
}
ThisExample (int x){
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

this();
System.out.println(x);
}

}
class TestThis5{
public static void main(String args[]){
ThisExample a=new ThisExample (10);
}

5. Write java program which implements Recursion with suitable Example.?


Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.

Example:

public class RecursionExample {


static int count=0;
static void p(){ // here “p” is method name
count++;

if(count<=5){
System.out.println("hello "+count);
p();
}
}

public static void main(String[] args) {


p();
}}
Output: hello 1
hello 2
hello 3
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

hello 4
hello 5

6. What is polymorphism? Explain different types of polymorphisms with examples?


The word "poly" means many and "morphs" means forms. So polymorphism means
many forms.

There are two types of polymorphism in Java:

1. compile-time polymorphism
2. runtime polymorphism.

1. compile-time polymorphism :

Compile-time polymorphism, sometimes referred to as static polymorphism or


early binding, is the capacity of a programming language to decide which method or
function to use based on the quantity, and sequence of inputs at compile-time. In
Method overloading ,methods names are same name but different parameters within
a class.

Example:

public class Calculator {

public int add(int a, int b) {

return a + b;

public double add(double a, double b) {

return a + b;

2. Runtime polymorphism :

Runtime polymorphism is a process in which a call to an overridden method is


resolved at runtime rather than compile-time.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Example:

class Bike{

void run(){

System.out.println("running");

class Splendor extends Bike{

void run() {

System.out.println("running safely with 60km");

public static void main(String args[])

Bike b = new Splendor();//upcasting

b.run();

} }

Output:

running safely with 60km


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Long Answer Questions (10 Marks)

1. Describe Datatypes in java with example programs.?

Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

here are 8 types of primitive data types:

boolean data type


byte data type
char data type
short data type
int data type
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

long data type


float data type
double data type

Eample Program:
class GFG {

// Main driver method


public static void main(String args[])

// Creating and initializing custom character


char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

// use byte and short

// if memory is a constraint
byte b = 4;

// this will give error as number is


// larger than byte range

// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


// larger than short range
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

// short s1 = 87878787878;

// by default fraction value

// is double in java
double d = 4.355453532;

// for float use 'f' as suffix as standard


float f = 4.7333434f;

// need to hold big range of numbers then we need


// this data type
long l = 12121;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);

System.out.println("double: " + d);


System.out.println("long: " + l);
}}
Output
char: G

integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Non-Primitive Data Type or Reference Data Types :

The Reference Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings,
objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate char-type entities. Unlike
C/C++, Java strings are not terminated with a null character.

Syntax: Declaring a string


<String_Type> <string_variable> = “<sequence_of_string>”;
String s = “Anil”;

Example Program:
class Main {
public static void main(String[] args)

{
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// get the length of greet

int length = greet.length();


System.out.println("Length: " + length);
}
}

2 Arrays:
An array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

2. Explain java Buzzwords in detail?


Featues of java or Java Bazzworeds
Simple
Java was designed to be easy for professional programmer to learn and use
effectively.It’s simple and easy to learn if you already know the basic concepts of Object
Oriented Programming.
C++ programmer can move to JAVA with very little effort to learn.
In Java, there is small number of clearly defined ways to accomplish a given task

Object oriented
Java is true object oriented language.
Almost “Everything is an Object” paradigm. All program code and data reside within objects
andclasses.
The object model in Java is simple and easy to extend.
Java comes with an extensive set of classes, arranged in packages that can be used in our
programsthrough inheritance.

Distributed
Java is designed for distributed environment of the Internet. Its used for creating
applications on
networks.
Java applications can access remote objects on Internet as easily as they can do in local
system.
Java enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.

Interpreted

Usually a computer language is either compiled or Interpreted. Java combines both


this approach and makes it a two-stage system.

Compiled : Java enables creation of a cross platform programs by compiling into an


intermediaterepresentation called Java Bytecode.
Interpreted : Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Robust
It provides many features that make the program execute reliably in variety of
environments.
Java is a strictly typed language. It checks code both at compile time and runtime.

Java takes care of all memory management problems with garbage-collection.


Java, with the help of exception handling captures all types of serious errors and eliminates
any risk of crashing the system.
Secure
Java provides a “firewall” between a networked application and your computer.
When a Java Compatible Web browser is used, downloading can be done safely without fear
of viralinfection or malicious intent.
Java achieves this protection by confining a Java program to the java execution environment
and not allowing it to access other parts of the computer.
Architecture neutral

Java language and Java Virtual Machine helped in achieving the goal of “write once;
run anywhere,any time, forever.” Changes and upgrades in operatingsystems,processors
and system resources will not force any changes in Java Programs.

Portable
Java Provides away to download programs dynamically to all the various types of
platforms connected to the Internet. It helps in generating Portable executable code.
High performance:
Java performance is high because of the use of bytecode.The bytecode was used, so
that it was easily translated into native machine code.
Multithreaded:
Multithreaded Programs handled multiple tasks simultaneously, which was helpful in
creating interactive, networked programs.Java run-time system comes with tools that
support multiprocess synchronization used to construct smoothly interactive systems.
Dynamic:
Java is capable of linking in new class libraries, methods, and objects.

It can also link native methods (the functions written in other languages such as C and C++).
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

3. What is an array?How do you declare the array in java?Explain with example?


An array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.

1.Array Declaration

dataType arr[];
int a[10]
2. Array crteation
array RefVar =new datatype[size];
int a[]=new int[5]

3. Array initialization
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;

a[4]=50

Multidimensional arrays are arrays of arrays:


==============================================
1) declaration: int array[][];

2) creation: int array = new int[2][3];


3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
Example program:
class Testarray {

public static void main(String args[]){


int a[]=new int[5];//declaration and instantiation
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

a[0]=10;//initialization
a[1]=20;
a[2]=70;

a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);

}}
4.What is a constructor? Explain the purpose of constructor with Example program?

In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

1. Default constructor (no-arg constructor)

A constructor is called "Default Constructor" when it doesn't have any parameter.

Example :

class Bike {
//creating a default constructor
Bike() {
System.out.println("Bike is created");

}
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}

2. Parameterized constructor:

A constructor which has a specific number of parameters is called a parameterized


constructor.

Example Program:

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

//method to display the values

void display()

{System.out.println(id+" "+name);

public static void main(String args[]){

//creating objects and passing values

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

//calling method to display the values of object

s1.display();

s2.display();

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

II UNIT Questions & Answers

1. What are the types of Inheritance ?

Single Inheritance

Multilevel Inheritance

Hierarchical Inheritance

Multiple Inheritance

Hybrid Inheritance

2. How to define a package in java ?

PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps


organize your classes into a folder structure and make it easy to locate and use them. More
importantly, it helps improve code reusability.

package nameofPackage;

public class classname

{
Body of the class
}

3. Define object class ?

Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a class does not extend any other class then it is a direct child class of Object and if
extends another class then it is indirectly derived. Therefore the Object class methods are available to
all Java classes. Hence Object class acts as a root of the inheritance hierarchy in any Java Program.

4. Explain subclass ?

A subclass is a class derived from the superclass. It inherits the properties of the superclass and also
contains attributes of its own.

A subclass inherits the methods and instance data of its superclasses, and is related to its superclasses
by an is-a relationship

5. What is super keyword ?

The super keyword in Java is a reference variable that is used to refer to parent class when we’re
working with objects.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

6. Explain final Keyword ?

The final keyword in Java is a non-access modifier, which restricts the user and defines entities that
cannot be changed or modified. It plays a prominent role when you want a variable to always store the
same value. The final keyword in Java is used to enforce constancy or immutability and specifies that
the value of the variable or element should not be modified or extended further.

Final variable - To create constant variable

Final methods - Prevent method Overriding

Final classes -- Prevent Inheritance

7. Contrast between abstract class and interface ?

Abstract class

1) Abstract class can have abstract and non-abstract methods.

2) Abstract class doesn't support multiple inheritance.

3 ) Abstract class can provide the implementation of interface.

4 ) The abstract keyword is used to declare abstract class.

Interface

1) Interface can have only abstract methods. Since Java 8, it can have default and static methods

Also

2 ) Interface supports multiple inheritance

3 ) Interface has only static and final variables

4 ) Interface cannot provide implementation of abstract class

8 . What does java API Package contain ?

An application programming interface (API), in the context of Java, is a collection of prewritten


packages, classes, and interfaces with their respective methods, fields and constructors. Similar to a
user interface, which facilitates interaction between humans and computers, an API serves as a
software program interface facilitating interaction.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

9. List out the benefits of stream oriented I / O ?

The java.io package is used to handle input and output operations. Java IO has various classes that
handle input and output sources. A stream is a sequence of data.

Java input stream classes can be used to read data from input sources such as keyboard or a file.
Similarly output stream classes can be used to write data on a display or a file again.

10. Differentiate between implements and extends keywords ?

We use the extends keyword to inherit properties and methods from a class. The class that acts as a
parent is called a base class, and the class that inherits from this base class is called a derived or a child
class. Mainly, the extends keyword is used to extend the functionality of a parent class to the derived
classes

On the other hand, we use the implements keyword to implement an interface. An interface consists
only of abstract methods. A class will implement the interface and define these abstract methods as
per the required functionality. Unlike extends, any class can implement multiple interfaces.

Short Answer ( 5 Marks )

1. Explain benefits and costs of Inheritance ?

Benefits of Inheritance :

Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.

Inheritance can save time and effort as the main code need not be written again.

Inheritance provides a clear model structure which is easy to understand.

An inheritance leads to less development and maintenance costs.

With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance leads
to less development and maintenance costs.

In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.

Costs of Inheritance :

Inheritance decreases the execution speed due to the increased time and effort it takes, the program
to jump through all the levels of overloaded classes.

Inheritance makes the two classes (base and inherited class) get tightly coupled. This means one
cannot be used independently of each other.

The changes made in the parent class will affect the behavior of child class too.

The overuse of inheritance makes the program more complex


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

2. Write a program to demonstrate hierarchical and Multiple inheritance using interface?

Hierarchical Inheritance :

interface MyInf {

//Method Declaration

void Method1();

class Sample1 implements MyInf {

//Method definition

public void Method1() {

System.out.println("Method1() called");

class Sample2 extends Sample1 {

//Method definition

public void Method2() {

System.out.println("Method2() called");

class Sample3 extends Sample1 {

//Method definition

public void Method3() {

System.out.println("Method3() called");

public class Main {

public static void main(String[] args) {

Sample2 S2 = new Sample2();


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Sample3 S3 = new Sample3();

S2.Method1();

S2.Method2();

S3.Method1();

S3.Method3();

Multiple Inheritance :

interface Printable{

void print();

interface Showable{

void show();

class A7 implements Printable,Showable{

public void print(){System.out.println("Hello");}

public void show(){System.out.println("Welcome");}

public static void main(String args[]){

A7 obj = new A7();

obj.print();

obj.show();

3. What is the use of super Keyword with an example program?

To call methods of the superclass that is overridden in the subclass.

To access attributes (fields) of the superclass if both superclass and subclass have attributes with the
same name.

To explicitly call superclass no-arg (default) or parameterized constructor from the subclass
constructor.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

class Animal {

protected String type="animal";

class Dog extends Animal {

public String type="mammal";

public void printType() {

System.out.println("I am a " + type);

System.out.println("I am an " + super.type);

class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printType();

4. Write the benefits of packages and interfaces ?

Benefits of packages :

Make easy searching or locating of classes and interfaces.

Avoid naming conflicts. For example, there can be two classes with the name Student in two packages,
university.csdept.Student and college.itdept.Student

Implement data encapsulation (or data-hiding).

Provide controlled access: The access specifiers protected and default have access control on package
level. A member declared as protected is accessible by classes within the same package and its
subclasses. A member without any access specifier that is default specifier is accessible only by classes
in the same package.

Reuse the classes contained in the packages of other programs.

Uniquely compare the classes in other packages.

Benefits of Interfaces :
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Achieving Abstraction: Interfaces allow you to achieve total abstraction, where you define a contract
without specifying the implementation details. This enables you to separate the interface from the
implementation, making your code more modular and maintainable.

Java Interfaces Can Have Multiple Inheritance: Java classes can only inherit from a single superclass,
but interfaces can implement multiple interfaces. This allows you to receive behavior from multiple
sources, enhancing code reusability and flexibility.

Achieving Loose Coupling: Interfaces facilitate loose coupling between components of your code. By
depending on them rather than concrete classes, you can easily swap implementations without
affecting the clients that use those interfaces.

5. Explain difference in between classes and interfaces with suitable example?

Class Interface

The keyword used to The keyword used to create an interface is


create a class is “class” “interface”

A class can be
An Interface cannot be instantiated i.e. objects
instantiated i.e., objects of
cannot be created.
a class can be created.

Classes do not support


The interface supports multiple inheritance.
multiple inheritance.

It can be inherited from


It cannot inherit a class.
another class.

It can be inherited by It can be inherited by a class by using the


another class using the keyword ‘implements’ and it can be inherited by
keyword ‘extends’. an interface using the keyword ‘extends’.

It can contain
It cannot contain constructors.
constructors.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

6. Discuss about CLASSPATH environment variables ?

A classpath environment variable is the location from which classes are loaded at runtime by JVM in
java.

Classes may may include system classes and user-defined classes.

What is Path? A path is a unique location of a file/ folder in a OS. PATH variable is also called system
variable or environment variable.

Then we will set environment variables

JAVA_HOME &

PATH >

1. set JAVA_HOME >

Variable name : JAVA_HOME

variable value: C:\Program Files\Java\jdk1.7.0_51 (Directory in which java has been installed)

2. set PATH >

Again click on New..

Then enter -

Variable name : PATH

variable value: C:\Program Files\Java\jdk1.7.0_51\bin

Long Answer Questions ( 10 Marks )


1. What is Inheritance ? Explain different forms of Inheritance ?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).

Types of Inheritance

Single Inheritance

Multi-level Inheritance

Hierarchical Inheritance

Hybrid Inheritance

Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes it is also known as simple inheritance.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Let's implement the single inheritance mechanism in a Java program.

class Employee

float salary=34534*12;

public class Executive extends Employee

float bonus=3000*6;

public static void main(String args[])

Executive obj=new Executive();

System.out.println("Total salary credited: "+obj.salary);

System.out.println("Bonus of six months: "+obj.bonus);

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived from another class is
called multi-level inheritance. In simple words, we can say that a class that has more than one parent
class is called multi-level inheritance. Note that the classes must be at different levels. Hence, there
exists a single base class and single derived class but multiple intermediate base classes.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Let's implement the multi-level inheritance mechanism in a Java program.

class Student

int reg_no;

void getNo(int no)

reg_no=no;

void putNo()

System.out.println("registration number= "+reg_no);

//intermediate sub class

class Marks extends Student

float marks;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

void getMarks(float m)

marks=m;

void putMarks()

System.out.println("marks= "+marks);

//derived class

class Sports extends Marks

float score;

void getScore(float scr)

score=scr;

void putScore()

System.out.println("score= "+score);

public class MultilevelInheritanceExample

public static void main(String args[])

Sports ob=new Sports();

ob.getNo(0987);

ob.putNo();

ob.getMarks(78);

ob.putMarks();
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

ob.getScore(68.7);

ob.putScore();

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical inheritance.

Let's implement the hierarchical inheritance mechanism in a Java program.

class Student

public void methodStudent()

System.out.println("The method of the class Student invoked.");

class Science extends Student

public void methodScience()

{
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

System.out.println("The method of the class Science invoked.");

class Commerce extends Student

public void methodCommerce()

System.out.println("The method of the class Commerce invoked.");

class Arts extends Student

public void methodArts()

System.out.println("The method of the class Arts invoked.");

public class HierarchicalInheritanceExample

public static void main(String args[])

Science sci = new Science();

Commerce comm = new Commerce();

Arts art = new Arts();

//all the sub classes can access the method of super class

sci.methodStudent();

comm.methodStudent();

art.methodStudent();

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

2.Write the procedure to create a package with multiple public classes and also explain how to
access a package ?

Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes collectively
based on functionality. When software is written in the Java programming language, it can be
composed of hundreds or even thousands of individual classes. It makes sense to keep things organized
by placing related classes and interfaces into packages.

Creating packages

First declare the name of the package using the package keyword followed by a package name

Then we define a class , just as we normally define a class

Package firstpackage;

Public class firstclass

----------------------

---------------------

--------------------- body of the class

Here the package name is firstpackage, the class firstclass is now considered a part of this package

package mypack;

public class Box

int length,breadth,height;

public Box(int l,int b,int h)

length=l;

breadth=b;

height=h;

public int vol()

return length*breadth*height;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

public class circle

int r;

public circle(int rr)

r=rr;

public float area()

return (3.14f*r*r);

3 . Explain the concept of importing packages and write a program that implements the importing
concept

The general form of import statement

Import pkg1 [ pkg2]. Classname *

Here pkg1 is the name of top level package , and pkg2 is the name of subordinate package inside
outer package separated by a dot. * indicate that the java compiler should import the entire package

Import java.util ..Date;

Import java.io.*

Package Mypack;

Public class Balance

String name;

Double bal;

Public Balance( String n , double b )

name = n;
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

bal = b;

Public void show ( )

If ( bal < 0 )

System.out.print( “ ---- > “);

System.out.println(“ name + “ : $ “ + bal );

The Balance class is now public and its show ( ) method are public . this means that they can be
accessed by any type of code outside the mypack package

Example here TestBalance imports MyPack and is then able to make use of the Balance class

Import MyPack. *;

Class TestBalance

Public static void main( String args [ ] )

Balance test = new Balance ( “ J J John “ , 99.77);

Test . show ( );

4. How do you design and implement an interface in java ? how can you extend one interface by the
other 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.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in
the interface.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

interface <interface_name>{

// declare constant fields

// declare methods that abstract

// by default.

Java Interface Example

interface printable{

void print();

class A6 implements printable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){

A6 obj = new A6();

obj.print();

An interface contains variables and methods like a class but the methods in an interface are abstract
by default unlike a class. An interface extends another interface like a class implements an interface in
interface inheritance.

interface A {

void funcA();

interface B extends A {

void funcB();

class C implements B {

public void funcA() {

System.out.println("This is funcA");
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

public void funcB() {

System.out.println("This is funcB");

public class Demo {

public static void main(String args[]) {

C obj = new C( );

obj.funcA( );

obj.funcB( );

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

UNIT 3: Exception Handling and Threading


Very Short Answer Questions (1 Mark)

1. What is an Error?

An error is a serious problem that typically occurs during compilation (before the program
runs). Errors often indicate syntax violations or resource limitations that prevent the program from
being created or executed correctly.

2. What is an Exception? What are two exception types?

An exception is an event that disrupts the normal flow of a program's execution at runtime. It
usually signals an unexpected condition or error.

Two common exception types are:

Checked Exceptions: These exceptions must be declared in the method's signature using
throws keyword. They represent recoverable errors, like IOException for file operations.

Unchecked Exceptions: These exceptions don't need explicit declaration. They represent
programming errors or runtime conditions, like NullPointerException when accessing a null reference.

3. Write syntax for try block?

Java

try {

// Code that might throw exceptions

} catch (ExceptionType1 e1) {

// Code to handle ExceptionType1

} catch (ExceptionType2 e2) {

// Code to handle ExceptionType2

} finally {

// Code that always executes (optional)

.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

4. What are built-in Exceptions?

Java provides a rich set of built-in exception classes for common error scenarios. Some
examples include:

ArithmeticException (division by zero)

ArrayIndexOutOfBoundsException (accessing an invalid array index)

FileNotFoundException (file not found)

NumberFormatException (invalid number format for parsing)

5. What are the runtime errors and logical errors in Java?

Runtime errors: Exceptions are a specific type of runtime error that occurs during program
execution. Other runtime errors could be memory access violations or infinite loops.

Logical errors: These are mistakes in the program's logic that cause incorrect behavior even
if it executes without errors. Examples include typos in variable names or flawed algorithms.

Short Answer Questions (5 Marks)

1. Write about some Java's built-in exceptions?

Java provides a rich set of built-in exception classes to handle common error scenarios during
program execution. Here are some frequently encountered exceptions:

1. ArithmeticException: Thrown when an attempt is made to perform an illegal arithmetic


operation, such as division by zero.

2. ArrayIndexOutOfBoundsException: Occurs when you try to access an element in an array


using an invalid index (either negative or greater than or equal to the array's length).

3. ClassCastException: Thrown when you attempt to cast an object to a type that it's not
compatible with. For example, trying to cast a String object to an Integer object.
4. FileNotFoundException: Thrown when a file you're trying to open or access cannot be found
in the specified location.

5. IOException: A broader exception class for various input/output (I/O) related errors, like
network connection issues or file access problems.
6. NullPointerException: Thrown when you attempt to use a reference variable that has not
been initialized (i.e., it's null) and try to access its members or methods.

7. NumberFormatException: Occurs when you try to convert a string that doesn't represent a
valid number format (e.g., "hello") into a numerical type (e.g., int or double).

8. StringIndexOutOfBoundsException: Similar to ArrayIndexOutOfBoundsException, but for


strings. It's thrown when you try to access a character at an invalid index within a string.

9. IndexOutOfBoundsException: A more general exception for out-of-bounds access, not


limited to arrays or strings. It might be thrown by certain collections or iterators if you attempt to
access an element at an invalid position.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

10. UnsupportedOperationException: Indicates that an operation is not supported by a


particular object or class.

This is not an exhaustive list, but it covers some of the most common built-in exceptions you'll
encounter in Java programming. By understanding these exceptions and how to handle them
appropriately, you can write more robust and user-friendly code.

2. Explain Benefits of Exception handling mechanism?

Improved program robustness: Exception handling allows programs to gracefully recover from
unexpected errors instead of crashing abruptly.

Enhanced code readability: Exception handling separates error handling code from the main
program logic, making the code more maintainable and easier to understand.

Increased reusability: Exception handling mechanisms can be reused across different parts of
a program, promoting code reuse and consistency.

Better error diagnostics: Exceptions provide detailed information about the error, aiding
debugging and troubleshooting.

3. Write a Java program that illustrates the application of multiple catch statements?

public class MultipleCatchExample {

public static void main(String[] args) {

try {

int num = Integer.parseInt("hello"); // This will throw NumberFormatException

} catch (NumberFormatException e) {

System.out.println("Invalid number format: " + e.getMessage());

} catch (Exception e) {

// Catch-all for other exceptions

System.out.println("Unexpected error:" + e.getMessage());

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

Explanation:

The try block attempts to parse the string "hello" into an integer, which will trigger a
NumberFormatException.

The first catch block specifically handles NumberFormatException, providing a user-friendly


message.

The second catch block serves as a catch-all for any other exceptions that might occur.

Long Answer Questions

1.write a Java Program Implementing Exception Handling in Detail?

public class ExceptionHandlingExample {

public static void main (String [] args) {

int [] numbers = {1, 2, 3};

try {

// Code that might throw exceptions

System.out.println(numbers[4]); // ArrayIndexOutOfBoundsException

int result = 10 / 0; // ArithmeticException

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Index out of bounds: " + e.getMessage());

System.out.println("Accessing element at index 4 is not possible (array size is 3)");

// Provide alternative logic or handle the error gracefully

catch (ArithmeticException e)

System.out.println("Cannot divide by zero: " + e.getMessage());

// Provide recovery mechanism (e.g., set result to a default value)


GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

} catch (Exception e) { // Catch-all for other unhandled exceptions

System.out.println("An unexpected error occurred: " + e.getMessage());

// Log the error or provide a generic error message

} finally {

System.out.println("This block always executes, regardless of exceptions.");

// Release resources (e.g., closing files, database connections)

System.out.println("Continuing program execution..."); // Executes only if no exceptions occur

Explanation:

• The try block contains code that might throw exceptions.

• Multiple catch blocks handle specific exceptions:

o The first catch handles ArrayIndexOutOfBoundsException if an invalid array index is accessed.

o The second catch handles ArithmeticException if division by zero occurs.

o The final catch acts as a catch-all for other exceptions.

• The finally block executes always, regardless of exceptions within the try block. It's ideal for
releasing resources or performing cleanup tasks.

• The program continues execution after exception handling (if no exceptions were thrown).

2.Write a program with nested try statements for handling exceptions and how to create a user
defined exception?

public class NestedTryExample {

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

try {

int age = validateAge(-2); // Throws Age Exception if age is invalid

} catch (ageException e) {

System.out.println(e.getMessage());
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

try {

System.out.println("Granting access..."); // This might also throw an exception

} catch (Exception e) {

System.out.println("Unexpected access error: " + e.getMessage());

static int validateAge(int age) throws AgeException {

if (age < 0) {

throw new AgeException("Age cannot be negative."); // Throwing user-defined exception

return age;

class AgeException extends Exception { // User-defined exception class

public AgeException(String message) {

super(message);

Explanation:

• The main method demonstrates nested try-catch blocks.

• The validateAge method throws a custom AgeException if the age is invalid. This exception is
handled in the main method's outer catch block.

• The inner try-catch handles any exceptions that might occur within the System.out.println
statement.
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

3.Explain the use of try,catch,throw,throws and finally in detail with example program?

try:

• Encloses code that might throw exceptions.

catch:

• Captures specific exceptions thrown within the try block.

• The exception type is specified in the catch block's parameter.

• Multiple catch blocks can be chained to handle different exception types.

throw:

• Explicitly throws an exception from a method or block.

• It allows for propagating specific error conditions to the calling code.

throws:

• Declares exceptions that a method might throw but doesn't handle itself.

• It informs the caller that the method might throw these exceptions.

finally:

• Executes always, regardless of whether exceptions occur within the try block.

• It's commonly used for resource management (closing files, database connections) or
performing cleanup tasks.

public class TryCatchThrowFinallyExample {

public static void main(String[] args) {

try {

divideByZero(); // Throws ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero: " + e.getMessage());

} finally {

System.out.println("Cleaning up resources...");

System.out.println("Continuing program execution...");

}
GURU NANAK INSTITUTIONS TECHNICAL CAMPUS (AUTONOMOUS) SCHOOL OF ENGINEERING & TECHNOLOGY

static void divideByZero() throws ArithmeticException { // Declares throws clause

int result = 10 / 0;

Explanation:

1. main method:

o The try block calls the divideByZero method, which might throw an exception.

o The catch block specifically handles ArithmeticException if it occurs during division.

o The finally block executes regardless, even if no exception is thrown.

2. divideByZero method:

o This method performs a division by zero, which will throw an ArithmeticException.

o The throws ArithmeticException clause in the method signature declares that this exception
might be thrown.

Key Points:

• try and catch: Work together for exception handling. try encloses risky code, and catch
captures thrown exceptions.

• throw: Used to explicitly throw an exception from a method or block.

• throws: Declares potential exceptions that a method might throw, informing the caller.

• finally: Always executes, regardless of exceptions, making it ideal for resource management
and cleanup.

Remember:

• Use exception handling strategically to make your code more robust and easier to maintain.

• Choose appropriate exception types to handle specific error conditions.

• Provide meaningful error messages for better debugging and user experience.

You might also like