Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-2 SAQ N LAQ

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

UNIT – 2

SAQ and LAQ


1. Define a Package? What is its use in Java? Explain.
A java package is a group of similar types of classes, interfaces, and sub-packages. Package
in java can be categorized in two form, built-in package, and user-defined package.There are
many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Syntax: package packageName;
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

2. List out the benefits of Stream oriented I/O.


A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream
because it is like a stream of water that continues to flow.
Efficiency: Stream-oriented I/O is more efficient than traditional buffered I/O because it
eliminates the need to copy data between buffers.
Flexibility: Stream-oriented I/O is more flexible than traditional buffered I/O because it can
be used to read and write data in any format.
Readability: Stream-oriented I/O is more readable than traditional buffered I/O because it
uses a simpler and more consistent API.
Extensibility: Stream-oriented I/O is more extensible than traditional buffered I/O because it
can be easily extended to support new data formats and devices.

3. How to define a package in Java?


A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations) providing access protection and namespace management.

We use the package keyword to create or define a package in java programming language.
Syntax: package packageName;

There are two types of packages:


• Build-in packages
• User defined packages

4. What are the methods available in the character streams?


The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class used for
character stream based output operations.

5. What is the significance of the CLASSPATH environment variable in creating/using


a package?

From the word, we understand that a classpath is a path of a class. A classpath is a path for
the compiler to identify which class, or which package we use in our defined class. It
provides the compiler a way to find classes or packages that are used in our class

Prepared by Prof. Syeda Husna from CSE Department


6. Contrast between abstract class and interface?

7. What is Console class? What is its use in java?


In java, the java.io package has a built-in class Console used to read from and write to the
console, if one exists. This class was added to the Java SE 6. The Console class implements
the Flushable interface. In java, most the input functionalities of Console class are available
through System.in, and the output functionalities available through System.out. The Console
class in Java is used to read input from the console and write to the console.

8. What is the use of super keyword?


The super keyword in Java is used to call methods and access fields of the parent class. It is
often used when a subclass overrides a method from the parent class. It can also be used to
access the parent class's constructor. You can call the superclass's method from within the
subclass using super. methodName().

9.Distinguish between abstract class and concrete class.

Prepared by Prof. Syeda Husna from CSE Department


10.Explain the process of defining and creating a package with suitable examples
A Package can be defined as a grouping of related types (classes, interfaces,
enumerations and annotations) providing access protection and namespace management.
We use the package keyword to create or define a package in java programming
language.
Syntax: package packageName;
In java, the packages are divided into two types.

• Built-in Packages:
Package Name Description
java.lang Contains language support classes ( for e.g
classes which defines primitive data types,
math operations, etc.) . This package is
automatically imported.
java.io Contains classes for supporting input / output
operations.
java.util Contains utility classes which implement data
structures like Linked List, Hash Table,
Dictionary, etc and support for Date / Time
operations.
java.applet Contains classes for creating Applets.
java.awt Contains classes for implementing the
components of graphical user interface ( like
buttons, menus, etc. ).
java.net Contains classes for supporting networking
operations.
• User-defined Packages:
The user-defined packages are the packages created by the user. User is free to create
their own packages.

Accessing classes in a Built-in package in to a program :


1 ) import java.util.Vector; // import the Vector class from util package.
This statement imports Vector class from util package which is contained inside java
package.
(or )
2 ) import java.util.*; // import all the class from util package
This statement imports all the classes from util package.

There are three ways to access packages


• Import package.*
• Import package.classname
• fully qualified name

Prepared by Prof. Syeda Husna from CSE Department


1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }

To compile: javac -d . B.java


To run: java mypack.B

Output:
Hello

2) Using packagename.classname

In java, the import keyword used to import built-in and user-defined packages. When a
package has imported, we can refer to all the classes of that package using their name
directly. The import statement must be after the package statement, and before any other
statement.
Using an import statement, we may import a specific class or all the classes from a package.
Using one import statement, we may import only one package or a class.
Using an import statement, we can not import a class directly, but it must be a part of a
package.
A program may contain any number of import statements.

Importing specific class


Using an importing statement, we can import a specific class. The following syntax is
employed to import a specific class.
Syntax

import packageName.ClassName;

If you import package.classname then only declared class of this package will be accessible.

Prepared by Prof. Syeda Husna from CSE Department


Example of package by import package.classname

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.A;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }

To compile: javac -d . B.java


To run: java mypack.B

Output:
Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface. It is generally used when two packages have same
class name e.g. java.util and java.sql packages contain Date class.

6. //save by A.java
7. package pack;
8. public class A{
9. public void msg(){System.out.println("Hello");}
10. }

10. //save by B.java


11. package mypack;
12. class B{
13. public static void main(String args[]){
14. A obj = new A(); //using fully qualified name
15. obj.msg();
16. }
17. }

To compile: javac -d . B.java

Prepared by Prof. Syeda Husna from CSE Department


To run: java mypack.B

Output:
Hello

11.Give an example where interface can be used to support multiple inheritance.

Interface in Java
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. In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.

Uses of Java interface:


There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.

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.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

Implementing Interfaces

• Once an interface has been defined, one or more classes can inherit that interface by
using implements Keyword
• To implement an interface, include the implements Keyword in a class definition, and
then create the methods defined by the interface.
• The methods that implement an interface in a class must be declared with public
access Specifier.

Multiple inheritance is not supported through class in java, but it is possible by an


interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation
class. For example:

Prepared by Prof. Syeda Husna from CSE Department


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Output: Hello
Welcome

12.What is the accessibility of a public method or field inside a nonpublic class or


interface? Explain.
In Java, interfaces can only have public or no access modifiers for their methods. Methods
declared in an interface are implicitly public. If no access modifier is specified, then the
default access modifier is used. This means that the interface is only accessible to other
members of the package in which it is declared.
When a class implements an interface, it must provide public implementations for all the
methods declared in the interface. If a method is declared as public in the interface, the
implementing class must also declare it as public. You cannot define a method as private in a
class that implements an interface if the method is declared as public in the interface.

Here are the four access modifiers in Java, in order of increasing restrictiveness:

• Public: Accessible to all classes, regardless of their package.

Prepared by Prof. Syeda Husna from CSE Department


• Protected: Accessible to all classes in the same package and subclasses of the class in
which the member is declared.
• Default (no modifier): Accessible to all classes in the same package.
• Private: Accessible only to the class in which the member is declared.

Access modifiers are used to control the visibility of class members, such as fields, methods,
and constructors. This helps to ensure that classes are properly encapsulated and that only
authorized code can access their members.

13. Describe the process of importing and accessing a package with suitable examples
Same as 10th answer.

14. How to design and implement an interface in Java? Give an example.

Interface in Java
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. In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
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.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Implementing Interfaces

• Once an interface has been defined, one or more classes can inherit that interface by
using implements Keyword

• To implement an interface, include the implements Keyword in a class definition, and


then create the methods defined by the interface.

Prepared by Prof. Syeda Husna from CSE Department


• The methods that implement an interface in a class must be declared with public
access Specifier.

Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}

If a class implements more than one interface, the interfaces are separated with a comma.
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Applying interfaces

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:
Hello

15. What are the methods available in the Character Streams? Discuss.
In java, when the IO stream manages 16-bit Unicode characters, it is called a character
stream. The unicode set is basically a type of character set where each character corresponds
to a specific numeric value within the given character set, and every programming language
has a character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.

Prepared by Prof. Syeda Husna from CSE Department


The java character stream is defined by two abstract classes, Reader and Writer. The Reader
class used for character stream based input operations, and the Writer class used for charater
stream based output operations.

The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.

Reader class
The Reader class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description

1 int read()

It reads the next character from the input stream.

2 int read(char[] cbuffer)

It reads a chunk of charaters from the input stream and store them in its byte array,
cbuffer.

3 int read(char[] cbuf, int off, int len)

It reads charaters into a portion of an array.

4 int read(CharBuffer target)

It reads charaters into into the specified character buffer.

5 String readLine()

Prepared by Prof. Syeda Husna from CSE Department


S.No. Method with Description

It reads a line of text. A line is considered to be terminated by any oneof a line feed ('\n'),
a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.

6 boolean ready()

It tells whether the stream is ready to be read.

7 void close()

It closes the input stream and also frees any resources connected with this input stream.

Writer class
The Writer class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.

S.No. Method with Description

1 void flush()

It flushes the output steam by forcing out buffered bytes to be written out.

2 void write(char[] cbuf)

It writes a whole array(cbuf) to the output stream.

3 void write(char[] cbuf, int off, int len)

It writes a portion of an array of characters.

4 void write(int c)

It writes single character.

5 void write(String str)

It writes a string.

6 void write(String str, int off, int len)

It writes a portion of a string.

7 Writer append(char c)

Prepared by Prof. Syeda Husna from CSE Department


S.No. Method with Description

It appends the specified character to the writer.

8 Writer append(CharSequence csq)

It appends the specified character sequence to the writer

9 Writer append(CharSequence csq, int start, int end)

It appends a subsequence of the specified character sequence to the writer.

10 void close()

It closes the output stream and also frees any resources connected with this output
stream.

16.Distinguish between Byte Stream Classes and Character Stream Classes

Aspect Character Streams Byte Streams


Data Handling Handle character-based data Handle raw binary data
Representation Classes end with "Reader" or Classes end with "InputStream" or
"Writer" "OutputStream"
Suitable for Textual data, strings, human- Non-textual data, binary files,
readable info multimedia
Character Encoding Automatic encoding and decoding No encoding or decoding
Text vs non-Text data Text-based data, strings Binary data, images, audio, video
Performance Additional conversion may impact Efficient for handling large binary
performance data
Handle Large Text May impact performance due to Efficient, no encoding overhead
Files encoding
String Operations Convenient methods for string Not specifically designed for string
operations operations
Convenience Methods Higher-level abstractions for text Low-level interface for byte data
data
Reading Line by Line Convenient methods for reading Byte-oriented, no built-in line-
lines reading methods
File Handling Read/write text files Read/write binary files
Network Sending/receiving text data Sending/receiving binary data
Communication
Handling Not designed for handling binary Suitable for handling binary
Images/Audio/Video data directly multimedia data
Text Encoding Supports various character No specific text encoding support
encodings

17.Explain the different parameter passing mechanisms used in Java with an


example.

Prepared by Prof. Syeda Husna from CSE Department


Let’s start this discussion by understanding the storage mechanism of Java. The reference
variables, names of methods and classes are stored in stack and their values are stored in heap.
But, the primitives are stored directly in the stack memory along with their values.
As explained earlier, Java supports only pass-by-value for both primitive and reference types
which means when a method is invoked, a copy of the value of each parameter is passed to that
method.
For primitive types such as int, double and Boolean the value of the parameter is same as the
original value of the variable. For example, if we have a variable ‘x’ with a value of 10, and we
pass ‘x’ as a parameter to a method, then the method receives a copy of original value 10 as its
parameter.
Since reference variables are stored in stack, therefore, for reference types such as arrays, objects
and strings the value of the parameter is the reference or address of the given variable. For
example, if we have an array ‘arr’ with elements {1, 2, 3} and we pass ‘arr’as a parameter to a
method, then the method receives the copy of reference or address of ‘arr’ as its parameter.

Pass by Value or Call by value


There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the
calling method.
In this way of passing parameters, a copy of parameter value is passed to the given method.
That method can modify the copy, but it cannot affect the original value of the parameter.
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
1. class Operation{
2. int data=50;
3. void change(int data){
4. data=data+100;//changes will be in the local variable only
5. }
6. public static void main(String args[]){
7. Operation op=new Operation();
8. System.out.println("before change "+op.data);
9. op.change(500);
10. System.out.println("after change "+op.data);
11. }
12. }
Output: before change 50
after change 50

Pass by Reference or Call by Reference


In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed. In
this example we are passing object as a value.
In this way of passing parameters, a reference or an address of the parameter is passed to the
given method. That method can modify the original value of the parameter by using the
reference.
1. class Operation2{
2. int data=50;
3. void change(Operation2 op){
4. op.data=op.data+100; //changes will be in the instance variable. The original value
will be changed as we are trying to pass the objects. Objects are passed by reference.

Prepared by Prof. Syeda Husna from CSE Department


5. }
6. public static void main(String args[]){
7. Operation2 op=new Operation2();
8. System.out.println("before change "+op.data);
9. op.change(op);// passing the object as a value using pass-by-reference
10. System.out.println("after change "+op.data);
11. }
12. }

Output: before change 50


after change 150

18.Write a runtime polymorphism program in Java by using an interface reference


variable.
Program:
interface Animal {
void makeSound();
}

class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Woof!");
}
}

class Cat implements Animal {


@Override
public void makeSound() {
System.out.println("Meow!");
}
}

public class RuntimePolymorphism {


public static void main(String[] args) {
Animal animal = new Dog(); // This is a runtime polymorphism example
animal.makeSound(); // This will print "Woof!"

animal = new Cat();


animal.makeSound(); // This will print "Meow!"
}
}

Output:
Woof!
Meow!

Prepared by Prof. Syeda Husna from CSE Department


19.Write a program to demonstrate hierarchical and multiple inheritance using
interfaces.
// Interface 1
interface Animal {
void eat();
}

// Interface 2
interface Carnivore {
void hunt();
}

// Interface 3
interface Herbivore {
void graze();
}

// Class Lion
class Lion implements Animal, Carnivore {
@Override
public void eat() {
System.out.println("Lion is eating");
}

@Override
public void hunt() {
System.out.println("Lion is hunting");
}
}

// Class Deer
class Deer implements Animal, Herbivore {
@Override
public void eat() {
System.out.println("Deer is eating");
}

@Override
public void graze() {
System.out.println("Deer is grazing");
}
}

// Class Main
public class Main {
public static void main(String[] args) {
Lion lion = new Lion();
lion.eat();
lion.hunt();

Prepared by Prof. Syeda Husna from CSE Department


Deer deer = new Deer();
deer.eat();
deer.graze();
}
}

Output:
Lion is eating
Lion is hunting
Deer is eating
Deer is grazing

20.Design an interface called Shape with methods draw() and getArea(). Further
design two classes called Circle and Rectangle that implements Shape to compute
area of respective shapes. Use appropriate getter and setter methods. Write a java
program for the same.

// Shape interface
interface Shape {
void draw();
double getArea();
}

// Circle class
class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}

@Override
public double getArea() {
return Math.PI * radius * radius;
}
}

// Rectangle class
class Rectangle implements Shape {
private double width;
private double height;

public Rectangle(double width, double height) {

Prepared by Prof. Syeda Husna from CSE Department


this.width = width;
this.height = height;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with width " + width + " and height " + height);
}

@Override
public double getArea() {
return width * height;
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create a Circle object
Circle circle = new Circle(5);

// Draw the circle


circle.draw();

// Get the area of the circle


double circleArea = circle.getArea();

System.out.println("The area of the circle is " + circleArea);

// Create a Rectangle object


Rectangle rectangle = new Rectangle(10, 20);

// Draw the rectangle


rectangle.draw();

// Get the area of the rectangle


double rectangleArea = rectangle.getArea();

System.out.println("The area of the rectangle is " + rectangleArea);


}
}

Output:

Drawing a circle with radius 5.0


The area of the circle is 78.53981633974483
Drawing a rectangle with width 10.0 and height 20.0
The area of the rectangle is 200.0

Prepared by Prof. Syeda Husna from CSE Department


21. How can you extend one interface by the other interface? Discuss

Interface in Java
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. In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
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.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Implementing Interfaces

• Once an interface has been defined, one or more classes can inherit that interface by
using implements Keyword

• To implement an interface, include the implements Keyword in a class definition, and


then create the methods defined by the interface.

• The methods that implement an interface in a class must be declared with public
access Specifier.

Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}

Prepared by Prof. Syeda Husna from CSE Department


If a class implements more than one interface, the interfaces are separated with a comma.
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }
Output:
Hello
Welcome

22.Discuss about CLASSPATH environment variables.


From the word, we understand that classpath is a path of a class. A classpath is a path for the
compiler to identify which class, or which package we use in our defined class. It provides
the compiler a way to find classes or packages that are used in our class.
CLASSPATH describes the location where all the required files are available which are
used in the application. Java Compiler and JVM (Java Virtual Machine) use
CLASSPATH to locate the required files. If the CLASSPATH is not set, Java Compiler
will not be able to find the required files and hence will throw the following error.

Error: Could not find or load main class <class name> (e.g. GFG)
The above error is resolved when CLASSPATH is set.

// If the following code is run when the CLASSPATH is not


// set, it will throw the above error.
// If it is set, we get the desired result
import java.io.*;
class GFG {
public static void main(String[] args)
{
System.out.println(Hello World");
}
}

Prepared by Prof. Syeda Husna from CSE Department


Set the CLASSPATH in JAVA in Windows
Command Prompt:
set PATH=.;C:\Program Files\Java\JDK1.6.20\bin
Note: Semi-colon (;) is used as a separator and dot (.) is the default value
of CLASSPATH in the above command.
GUI:
1. Select Start
2. Go to the Control Panel

3. Select System and Security

4. Select Advanced System settings

5. Click on Environment Variables

Prepared by Prof. Syeda Husna from CSE Department


6. Click on New under System Variables

7. Add CLASSPATH as variable name and path of files as a variable value.

8. Select OK.

Prepared by Prof. Syeda Husna from CSE Department


23. Differences between Classes and Interfaces

Class Interface

The keyword used to create a class is The keyword used to create an interface is
“class” “interface”

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


a class can be created. objects cannot be created.

Classes do not support multiple


The interface supports multiple inheritance.
inheritance.

It can be inherited from another class. It cannot inherit a class.

It can be inherited by a class by using the


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

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be


declared using any access All variables and methods in an interface are
specifier(public, private, default, declared as public.
protected).

Variables in a class can be static, final, or


All variables are static and final.
neither.

24. Define inheritance. What are the benefits of inheritance? What costs are associated
with inheritance? How to prevent a class from inheritance?

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

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.

Prepared by Prof. Syeda Husna from CSE Department


Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

Why use inheritance in java

• For Method Overriding (so runtime polymorphism can be achieved).


• For Code Reusability.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality. In the
terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Benefits and Costs of Inheritance in Java


Inheritance is the core and more useful concept Object Oriented Programming. 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, and a few of them are listed below.
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.

Prevent a class from inheritance.


To prevent a class from being inherited in Java, you can use the keyword final when creating
the class:
• Declare the class as final
• All of its methods are also declared as final

Prepared by Prof. Syeda Husna from CSE Department


• The class cannot be extended

If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2. class Honda1 extends Bike{
3. void run(){System.out.println("running safely with 100kmph");}
4. public static void main(String args[]){
5. Honda1 honda= new Honda1();
6. honda.run();
7. }
8. }

Output: Bike.java:3: error: cannot inherit from final Bike

class Honda1 extends Bike{

1 error

25. What is inheritance? Explain the types of inheritance and how does it help to create
new classes quickly.

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviours of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.

Terms used in Inheritance.


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

Prepared by Prof. Syeda Husna from CSE Department


o Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass,
and the new class is called child or subclass.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in Java: single, multilevel, and
hierarchical.
In Java programming, multiple and hybrid inheritance is supported through the interface only.
We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }

Prepared by Prof. Syeda Husna from CSE Department


7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }

Prepared by Prof. Syeda Husna from CSE Department


10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8. public static void main(String args[]){
9. C obj=new C();
10. obj.msg();//Now which msg() method would be invoked?
11. }
12. }
Compile Time Error

26. Explain about abstract classes with example?


A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.

Prepared by Prof. Syeda Husna from CSE Department


Example of abstract class
1. abstract class A{}

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
1. abstract class Bike{
2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
Output:

running safely

Another example:

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();
15. s.draw();
16. }
17. }
OUTPUT:
drawing circle

Prepared by Prof. Syeda Husna from CSE Department


27. List the methods supported by Object class and explain them?

In java, the Object class is the super most class of any class hierarchy. The Object class in the
java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java, it can refer to any type of object.

Methods of Object class


The following table depicts all built-in methods of Object class in java.

Return
Method Description Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object compares the argument object to calling object. boolean


obj)

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() returns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's monitor. void

notifyAll() wakes up all the threads, waiting on invoking object's monitor. void

wait() causes the current thread to wait, until another thread notifies. void

wait(long,int) causes the current thread to wait for the specified milliseconds void

Prepared by Prof. Syeda Husna from CSE Department


Return
Method Description Value

and nanoseconds, until another thread notifies.

finalize() It is invoked by the garbage collector before an object is being void


garbage collected.

28. Define Object Class?


Object Class in Java is the topmost class among all the classes in Java. We can also say that
the Object class in Java is the parent class for all the classes. It means that all the classes in
Java are derived classes and their base class is the Object class. All the classes directly or
indirectly inherit from the Object class in Java.

Now, look at this example-

class Vehicle{
//body of class Vehicle
}
class Car extends Vehicle{
//body of class Car
}

Here we can see that the Car class directly inherits the Vehicle class. The extends keyword is
used to establish inheritance between two classes. But we have seen in the above example
that if we define a class without inheriting it from some other class, it directly inherits the
Object class. Since Car inherits the Vehicle and the Vehicle inherits the Object class, the Car
indirectly inherits the Object class.

Prepared by Prof. Syeda Husna from CSE Department


29. Explain the significance of final keyword?

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.
1. final with variables
When a variable defined with the final keyword, it becomes a constant, and it does not allow
us to modify the value. The variable defined with the final keyword allows only a one-time
assignment, once a value assigned to it, never allows us to change it again.
Let's look at the following example java code.
public class FinalVar {
public static void main(String[] args) {
final int a = 10;
a = 100;
System.out.println("a = " + a);
// Can't be modified
}
}
Output:
FinalVar.java:7: error: cannot assign a value to final variable a
a = 100;
^
1 error

2. final with methods


When a method defined with the final keyword, it does not allow it to override. The final
method extends to the child class, but the child class can not override or re-define it. It must
be used as it has implemented in the parent class.
Let's look at the following example java code.
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{

Prepared by Prof. Syeda Husna from CSE Department


System.out.println("running safely with 100kmph");
}
}
public class FinalM
{
public static void main(String args[])
{
Honda hon= new Honda();
hon.run();
}
}

Output: Compile Time Error


FinalM.java:10: error: run() in Honda cannot override run() in Bike
void run()
^
overridden method is final
1 error

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
9. final class Bike{}
10. class Honda1 extends Bike{
11. void run(){System.out.println("running safely with 100kmph");}
12. public static void main(String args[]){
13. Honda1 honda= new Honda1();
14. honda.run();
15. }
16. }
Output:Bike.java:3: error: cannot inherit from final Bike
class Honda1 extends Bike{
^
1 error

30. Explain byte stream and character stream?

In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows us
to read from and write to it. A stream can be linked to a data source, or data destination, like a
console, file or network connection by java IO system. The stream-based IO operations are
faster than normal IO operations.
The Stream is defined in the java.io package.
Java provides two types of streams, and they are as follows.
• Byte Stream
• Character Stream
The following picture shows how streams are categorized, and various built-in classes used
by the java IO system.

Prepared by Prof. Syeda Husna from CSE Department


Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.
Byte Streams in Java
• Java byte streams are used to perform input and output of 8-bit bytes. Though there
are many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream.
• In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to
transmit 8 bits of data. The java byte stream is defined by two abstract
classes, InputStream and OutputStream. The InputStream class used for byte
stream based input operations, and the OutputStream class used for byte stream based
output operations.
• The InputStream and OutputStream classes have several concrete classes to perform
various IO operations based on the byte stream.
The following picture shows the classes used for byte stream operations.

Prepared by Prof. Syeda Husna from CSE Department


Character Stream in java
• In java, when the IO stream manages 16-bit Unicode characters, it is called a
character stream. The unicode set is basically a type of character set where each
character corresponds to a specific numeric value within the given character set, and
every programming language has a character set.
• In java, the character stream is a 16 bits carrier. The character stream in java allows us
to transmit 16 bits of data.
• The java character stream is defined by two abstract classes, Reader and Writer. The
Reader class used for character stream based input operations, and the Writer class
used for charater stream based output operations.
• The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.

31. Define Explicit & Implicit Import


There are two types of import Explicit & Implicit. When we use predefined java classes in our
java code then we need to load that class by the using import keyword at the very first line of
our program.
Explicit import: Classes are available inside the package, Explicit means direct or when we
give the proper path of the java class it will call as explicit import.
e.g: import java.util.ArrayList;

Implicit import : Implicit means indirect, When we load all the classes of the package in our
java code by using (*) it will call as implicit import.
e.g: import java.util.*;

Prepared by Prof. Syeda Husna from CSE Department


Here we have loaded all the classes from util package.

32. Explain about File Reading & Writing in Java with examples?
In java, there multiple ways to read data from a file and to write data to a file. The most
commonly used ways are as follows.
• Using Byte Stream (FileInputStream and FileOutputStream)
• Using Character Stream (FileReader and FileWriter)
File Handling using Byte Stream
In java, we can use a byte stream to handle files. The byte stream has the following built-in
classes to perform various operations on a file.
• FileInputStream - It is a built-in class in java that allows reading data from a file.
This class has implemented based on the byte stream. The FileInputStream class
provides a method read() to read data from a file byte by byte.
• FileOutputStream - It is a built-in class in java that allows writing data to a file. This
class has implemented based on the byte stream. The FileOutputStream class provides
a method write() to write data to a file byte by byte.
Let's look at the following example program that reads data from a file and writes the
same to another file using FileInputStream and FileOutputStream classes.
Example

import java.io.*;
public class FileReadingTest {

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


FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream(new File("C:\\Raja\\Output-File.txt"));

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e){

Prepared by Prof. Syeda Husna from CSE Department


System.out.println(e);
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

When we run the above program, it produce the following output.

File Handling using Character Stream


In java, we can use a character stream to handle files. The character stream has the following
built-in classes to perform various operations on a file.
• FileReader - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the character stream. The FileReader class provides a
method read() to read data from a file character by character.
• FileWriter - It is a built-in class in java that allows writing data to a file. This class
has implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.
Let's look at the following example program that reads data from a file and writes the
same to another file using FIleReader and FileWriter classes.
Example

import java.io.*;
public class FileIO {

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


FileReader in = null;
FileWriter out = null;

try {

Prepared by Prof. Syeda Husna from CSE Department


in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

When we run the above program, it produce the following output.

33. Explain about Serialization and Deserialization in Java

In java, the Serialization is the process of converting an object into a byte stream so that it
can be stored on to a file, or memory, or a database for future access. The deserialization is
the reverse of serialization. The deserialization is the process of reconstructing the object
from the serialized state.
Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.

Prepared by Prof. Syeda Husna from CSE Department


Serialization in Java
In a java programming language, the Serialization is achieved with the help of
interface Serializable. The class whose object needs to be serialized must implement the
Serializable interface.
We use the ObjectOutputStream class to write a serialized object to write to a destination.
The ObjectOutputStream class provides a method writeObject() to serializing an object.
We use the following steps to serialize an object.
• Step 1 - Define the class whose object needs to be serialized; it must implement
Serializable interface.
• Step 2 - Create a file reference with file path using FileOutputStream class.
• Step 3 - Create reference to ObjectOutputStream object with file reference.
• Step 4 - Use writeObject(object) method by passing the object that wants to be
serialized.
• Step 5 - Close the FileOutputStream and ObjectOutputStream.
Example

import java.io.*;

public class SerializationExample {

public static void main(String[] args) {

Student stud = new Student();


stud.studName = "Rama";
stud.studBranch = "IT";

try {
FileOutputStream fos = new FileOutputStream("my_data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(stud);
oos.close();
fos.close();
System.out.println("The object has been saved to my_data
file!");
}
catch(Exception e) {
System.out.println(e);
}
}
}

Output: The object have been saved to my_data file!

Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of
class ObjectInputStream. This class provides a method readObject() to deserializing an
object.
We use the following steps to serialize an object.

Prepared by Prof. Syeda Husna from CSE Department


• Step 1 - Create a file reference with file path in which serialized object is available
using FileInputStream class.
• Step 2 - Create reference to ObjectInputStream object with file reference.
• Step 3 - Use readObject() method to access serialized object, and typecaste it to
destination type.
• Step 4 - Close the FileInputStream and ObjectInputStream.
Let's look at the following example program for deserializing an object.
Example

import java.io.*;
public class DeserializationExample {

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

try {
FileInputStream fis = new FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);

Student stud2 = (Student) ois.readObject();


System.out.println("The object has been deserialized.");

fis.close();
ois.close();

System.out.println("Name = " + stud2.studName);


System.out.println("Department = " + stud2.studBranch);
}
catch(Exception e) {
System.out.println(e);
}
}
}

Output:
The object has been deserialized
Name= Rama
Department=IT

34. Explain about Writing console output using print() and println() methods
The PrintStream is a bult-in class that provides two methods print() and println() to write
console output. The print() and println() methods are the most widely used methods for
console output.
Both print() and println() methods are used with System.out stream.
The print() method writes console output in the same line. This method can be used with
console output only.
The println() method writes console output in a separete line (new line). This method can be
used with console ans also with other output sources.
Let's look at the following code to illustrate print() and println() methods.
Example

Prepared by Prof. Syeda Husna from CSE Department


public class WritingDemo {

public static void main(String[] args) {

int[] list = new int[5];

for(int i = 0; i < 5; i++)


list[i] = i*10;

for(int i:list)
System.out.print(i); //prints in same line

System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines

}
}

35. Explain Reading console input using Console class in java


Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.
• Using BufferedReader class
• Using Scanner class
• Using Console class
Reading input data using the Console class is the most commonly used method. This class
was introduced in Java 1.6 version.
The Console class has defined in the java.io package.

Prepared by Prof. Syeda Husna from CSE Department


Consider the following example code to understand how to read console input using Console
class.
Example

import java.io.*;

public class ReadingDemo {

public static void main(String[] args) {

String name;
Console con = System.console();

if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}

output: Please enter your name : husna


Hello, husna !!

36. Define System.out, System.in, System.err?

• System.out: standard output stream for console output operations.


• System.in: standard input stream for console input operations.
• System.err: standard error stream for console error output operations.

Prepared by Prof. Syeda Husna from CSE Department

You might also like