Unit-2 SAQ N LAQ
Unit-2 SAQ N LAQ
Unit-2 SAQ N LAQ
We use the package keyword to create or define a package in java programming language.
Syntax: package packageName;
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
• 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.
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. }
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.
import packageName.ClassName;
If you import package.classname then only declared class of this package will be accessible.
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. }
Output:
Hello
6. //save by A.java
7. package pack;
8. public class A{
9. public void msg(){System.out.println("Hello");}
10. }
Output:
Hello
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.
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.
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
Here are the four access modifiers in Java, in order of increasing restrictiveness:
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.
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
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.
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.
1 int read()
It reads a chunk of charaters from the input stream and store them in its byte array,
cbuffer.
5 String readLine()
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()
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.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes a string.
7 Writer append(char c)
10 void close()
It closes the output stream and also frees any resources connected with this output
stream.
Output:
Woof!
Meow!
// 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();
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;
@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;
@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);
Output:
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
• 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
}
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
Error: Could not find or load main class <class name> (e.g. GFG)
The above error is resolved when CLASSPATH is set.
8. Select OK.
Class Interface
The keyword used to create a class is The keyword used to create an interface is
“class” “interface”
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.
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.
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.
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.
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.
running safely
Another example:
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.
Return
Method Description Value
hashCode() returns the hashcode number for object being used. int
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
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.
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
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.
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.*;
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 {
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){
import java.io.*;
public class FileIO {
try {
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();
}
}
}
}
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.
import java.io.*;
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);
}
}
}
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.
import java.io.*;
public class DeserializationExample {
try {
FileInputStream fis = new FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
fis.close();
ois.close();
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
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
}
}
import java.io.*;
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.");
}
}
}