Java Q and A Sem - 220801 - 194348

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

UNIT-I

1. List and explain the features of object-oriented programming.


Ans:
1. Simple:
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented programming
concepts are similar to C++.
One of the most useful features is the garbage collector it makes java more simple.
2. Secure:
Java is said to be more secure programming language because it does not have pointers concept, java
provides a feature "applet" which can be embedded into a web application.

The applet in java does not allow access to other parts of the computer, which keeps away from harmful
programs like viruses and unauthorized access.
3. Portable:
Portability is one of the core features of java which enables the java programs to run on any computer or
operating system.

For example, an applet developed using java runs on a wide variety of CPUs, operating systems, and browsers
connected to the Internet.
4. Object-oriented:
Java is said to be a pure object-oriented programming language.
In java, everything is an object. It supports all the features of the object-oriented programming paradigm.

The primitive data types java also implemented as objects using wrapper classes, but still, it allows primitive
data types to archive high-performance.
5. Robust:
Java is more robust because the java code can be executed on a variety of environments, java has a strong
memory management mechanism (garbage collector– object is no longer used then GC releases the memory
for object).
java is a strictly typed language, it has a strong set of exception handling mechanism, and many more.
6. Architecture-neutral (or) Platform Independent:
Java has invented to archive WORA="write once; run anywhere, any time, forever".
The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform-independent.
The JVM allows the java program created using one operating system can be executed on any other operating
system.
7. Multi-threaded:
Java supports multi-threading programming, which allows us to write programs that do multiple
operations simultaneously.
8. Interpreted:
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java byte code. The byte code is interpreted to any machine code so that it runs on the
native machine.
9.High performance:
Java provides high performance with the help of features like JVM, interpretation, and its simplicity.
10. Distributed:
Java programming language supports TCP/IP protocols which enable the java to support the distributed
environment of the Internet.
Java also supports Remote Method Invocation (RMI), this feature enables a program to invoke methods
across a network.
11. Dynamic:
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and de-allocation (objects and garbage collector).

2. a) What is Type Casting? List and explain types of type casting methods with suitable example.
Ans: In Java, there are two kinds of data types – primitives and references. Primitives include int, float, long,
double etc. References can be of type classes, interfaces, arrays.
A value can change its type either implicitly or explicitly.

1.Type conversion/ implicit/ automatic/widening


2. Type casting/ explicit/ narrowing
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.

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

Widening Type Casting


Example.java

public class Main


{
public static void main(String[] args)
{
int myInt = 9;
double myDouble = myInt;
System.out.println(myInt);
System.out.println(myDouble);
}
}
Output:
9
9.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.
1. double -> float -> long -> int -> char -> short -> byte

public class Main


{
public static void main(String[] args)
{
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting: double to int

System.out.println(myDouble);
System.out.println(myInt);
}
}
Output:
9.78
9
b) List the primitive data types available in Java & explain.
Ans: In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
1. Boolean Data Type:
The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
Boolean one = false
2. Byte Data Type:
It is an 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
3. Short Data Type:
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example:
short s = 10000, short r = -5000
4. Int Data Type:
The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648
(-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
Example:
int a = 100000, int b = -200000
5. Long Data Type:
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long
data type is used when you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
6. Float Data Type:
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. The float data type should never be used for precise values, such as currency. Its default value is
0.0F.
Example:
float f1 = 234.5f
7. Double Data Type:
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3
8. Char Data Type:
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'

3. Define Constructor. Illustrate various types of Constructors.


Ans: 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.
Rules for creating Java constructor:
There are two rules defined for the constructor.
Constructor name must be the same as its class name.
A Constructor must have no explicit return type.
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor

Java Default Constructor:


A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example:
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.

Java Parameterized constructor:


A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
Example:
class Student4
{
int id;
String name; Student4(int i,String n)
{
id = i;
name = n;
}
void display ()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output
111 Karan
222 Aryan

4. Explain about control statements in java with example.


Ans: Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear. However, java provides statements that can be used to control the flow
of Java code. Such statements are called control flow statements. It is one of the fundamental features of
Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
3. Jump statements
o break statement
o continue statement
Decision-making statements:
Decision-making statements evaluate the Boolean expression and control the program flow depending upon
the result of the condition provided. There are two types of decision-making statements in Java, i.e., If
statement and switch statement.
1.If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression
and enables the program to enter a block of code if the expression evaluates to true.

Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Example:
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
Switch Statement:
In Java, switch statements are similar to if-else-if statements. The switch statement contains multiple blocks
of code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Syntax:
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Example:
public class Student implements Cloneable
{
public static void main(String[] args)
{

int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0"); break;
case 1:
System.out.println("number is 1"); break;
default: System.out.println(num);
}
}
}
Output:
2
Loop Statements:
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax
and condition checking time.
1. for loop
2. while loop
3. do-while loop
Java for loop
It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we want to execute the block of
code.
Syntax:
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }

Example:
public class Calculattion
{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java while loop
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in
while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
Syntax:
1. while(condition){
2. //looping statements
3. }
Example:
public class Calculation
{
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i); i = i + 2;
}

}
}
Output:
Printing the list of first 10 even numbers 0
2
4
6
8
10

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop statements. When
the number of iteration is not known and we have to execute the loop at least once, we can use do-while
loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. Syntax:
1. do
2. {
3. //statements
4.} while (condition);
Example:
public class Calculation
{
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do
{
System.out.println(i); i = i + 2;
}
while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers 0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words,
jump statements transfer the execution control to the other part of the program. There are two types of
jump statements in Java, i.e., break and continue.

Java break statement: The break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop
in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written inside
the loop or switch statement
Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}

}
Output:
0
1
2
3
4
5
6
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of
the loop and jumps to the next iteration of the loop immediately.
Example:
public class ContinueExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++)
{
for (int j = i; j<=5; j++)
{
if(j == 4)
{
continue;
}
System.out.println(j);
}
}
}

}
Output:
0
1
2
3
5
1
2
3
5
2
3
5

5.a) Describe different levels of access specifies in Java.


Ans: As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor, variable,
method, or data member.
There are four types of access modifiers available in java:
Default – No keyword required
Private
Protected
Public

1. Default: When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
The data members, class or methods which are not declared using any access modifiers i.e. having default
access modifier are accessible only within the same package.
2. Private: The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which they are
declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces cannot be declared as private because
private means “only visible within the enclosing class”.
protected means “only visible within the enclosing class and any subclasses”
3. protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same package or subclasses
in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The
method display in class A is protected and class B is inherited from class A and this protected method is then
accessed by creating an object of class B.
4. public: The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access modifiers.
Classes, methods, or data members that are declared as public are accessible from everywhere in the
program. There is no restriction on the scope of public data members.

b) Define an Array. How do you declare and access the array in java? Give an example.
Ans: 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.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
O Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.

o Single Dimensional Array


o Multidimensional Array

DECLARATION

The general form of a one-dimensional array declaration is

type var-name[]; OR
type[] var-name;

EX:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}

Access the Elements of an Array


public class Main
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
OUTPUT:
Volvo

UNIT-II
1. Define Inheritance. Explain the following with suitable example
a) has-a-relationship
b) is-a-relationship
Ans: Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in java by
which one class is allowed to inherit the features(fields and methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or
child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the existing class.
How to use inheritance in Java
The keyword used for inheritance is extends.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
a) has-a-relationship: If a class have an entity reference, it is known as Aggregation. Aggregation
represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains
one more object named address, which contains its own informations such as city, state, country, zipcode
etc.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class 5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Program:
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){

12. op=new Operation();


13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }

Output:
78.5
b) is-a-relationship:

Programmer is the subclass and Employee is the superclass. The relationship between the two classes is
Programmer IS-A Employee. It means that Programmer is a type of Employee.

Program:

class Employee{
float salary=40000;
}

class Programmer extends Employee{

int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is :40000.0
Bonus of programmer is:10000

2. Explain about prevention of Inheritance with suitable example.


Ans: The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted by a
subclass.

1.final method can be used for vatriables, methods and classes.


2.A variable defined with final key word then that variable can be called as final variable
3.Final variable must be initialized at the time of declaration otherwise compiler will be given error
4.Once a variable is assigned to a final variable then that variable cannot be changed

Declaration:
final datatype var=value;
final int a=100;
final int z; // error
5.whenever we want to maintain a constent value to all the objects of a class then we should use final
variable.
6.Final method: method is defined with final key word then that method can be called as final
method.
7.Final method is a method which cannot be overridden. That means a sub class cannot be override, that
means a sub class cannot work final method of its super class.

Definition
final return type method name(parameters)
{
//Body
}
final void show()
{
// Logic
}

final class

1. If a class is defined with final keyword, then that class can be called as final class.
2. final class is a class which cannot be inherited, that means there is no sub class from a final class.

Syntax:
final class name
{
// body
}
final class AlphaBeta
{
// Body of class
}

Example:
class Test
{
final int a=10; int b;
void show()
{
System.out.println("A value is "+a);
System.out.println("B value is "+b);
}
}
public class TestFinal
{
public static void main(String args[])
{
Test t1=new Test();
Test t2=new Test();
t1.b=10;
t2.b=20;
//t1.a=200; // error
t1.show();
t2.show();
}
}

Output:
A value is 10
B value is 10
A value is 10
B value is 20

3.a) Explain Super and “this” key words with suitable example.
Ans: Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword:

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Program:
1. class Animal{
2. String color="white"; 3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class 9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor(); 15. }}
Output:
Black White

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current
object.
Usage of Java this keyword
Here is given the 4 usage of java this keyword.
5. this can be used to refer current class instance variable.
6. this can be used to invoke current class method (implicitly)
7. this() can be used to invoke current class constructor.
8. this can be passed as an argument in the method call.
Program:
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11.}
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display(); 18.}}
Output:
1 null 0.0
0 null 0.0

b) Why Java does not support multiple Inheritance and Hybrid Inheritance? Explain it.
Ans: Multiple Inheritance

In Multiple inheritances, one class can have more than one superclass and inherit features from all parent
classes. Please note that Java does not support multiple inheritances with classes. In java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is derived from interface A and B.
Hybrid Inheritance

It is a mix of two or more of the above types of inheritance. Since java doesn’t support multiple inheritances
with classes, hybrid inheritance is also not possible with classes. In java, we can achieve hybrid inheritance
only through Interfaces.

Java does not support multiple and hybrid inheritance

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.

4.a) Illustrate method overloading and method overriding.


Ans: Method Overloading in Java
If class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the
program

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behavior of the method because its
name differs.

Advantage of method overloading

Method overloading increases the readability of the program.


Different ways to overload the method
There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

b) What is Polymorphism? Explain the concepts of polymorphism with suitable example.


Ans: Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is
resolved at runtime rather than compile-time.
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.
Let's first understand the upcasting before Runtime Polymorphism.
Upcasting
If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
For upcasting, we can use the reference variable of class type or an interface type. For Example:
1. interface I{}
2. class A{}
3. class B extends A implements I{} Here, the relationship of B class would be:
B IS-A A
B IS-A
IB IS-A
ObjectObject is the root class of all classes in Java, so we can write B IS-A Object.
Since
Example:
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Output:
Running safely with 60 km.

5. Define an abstraction. Illustrate abstract classes and its methods.


Ans: Abstract Classes and Methods
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 (which you will learn more about in
the next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:
• Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).

• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
From the example above, it is not possible to create an object of the Animal class: Animal myObj = new
Animal(); // will generate an error
Program:
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}
class Dog extends Animal {
public void animalSound() {
System.out.println("The Dog says: Bow Bow");
}
}
class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.animalSound();
myDog.sleep();
}
}
Output:
The Dog says: Bow Bow Zzz

UNIT-III
1. What is meant by interface? State its need and write syntax and features of interface with example
program.
Ans:
 An Interface is defined as an abstract type used to specify the behavior of a class.
 An interface in Java is a blueprint of a class.
 A Java interface contains 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 the 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.
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Why do we use an interface?
1. It is used to achieve total abstraction.Since java does not support multiple inheritances in the case of class,
by using an interface it can achieve multiple inheritances.
2. It is also used to achieve loose coupling.
3. Interfaces are used to implement abstraction. So the question arises why use interfaces when we have
abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the interface are
final, public and static.
 // A simple interface
interface Player
{
final int id = 10;
int move();
}
Features of Interfaces:
There are following features of an interface in Java. They are:
1. Interface provides pure abstraction in java. It also represents the Is-A relationship.
2. It can contain three types of methods: abstract, default, and static methods.
3. All the (non-default) methods declared in the interface are by default abstract and public. So, there is no
need to write abstract or public modifiers before them.
4. The fields (data members) declared in an interface are by default public, static, and final. Therefore, they
are just public constants. So, we cannot change their value by implementing class once they are initialized.
5. Interface cannot have constructors.
6. The interface is the only mechanism that allows achieving multiple inheritance in java.
7. A Java class can implement any number of interfaces by using keyword implements.
8. Interface can extend an interface and can also extend multiple interfaces

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();
}
}
Output:
Hello

2. a) Explain how interface is used to achieve multiple Inheritances in Java with suitable example.
Ans:
6. If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as
multiple inheritance.
7. 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:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
1. 7.
7. class TestInterface3 implements Printable, Showable{
8. public void print(){System.out.println("Hello");}
9. public static void main(String args[]){
10. TestInterface3 obj = new TestInterface3();
11. obj.print();
12. }
13. }
Output:
Hello
b) Differentiate between interfaces and abstract class?

Ans:
3. Define package. How to create and access user defined package in Java? Explain it.
Ans:
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.

Example:
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

Types of Packages:
User Defined Packages:
 As the name suggests, these packages are defined by the user. We create a directory whose name
should be the same as the name of the package. Then we create a class inside the directory.
Creating a Package in Java
 To create a package, we choose a package name and to include the classes, interfaces, enumerations,
etc, inside the package, we write the package with its name at the top of every source file.
 There can be only one package statement in each type of file. If we do not write class, interfaces,
inside any package, then they will be placed in the current default package.
Example of Java Package
We can create a Java class inside a package using a package keyword.
package packagedemo; //package
class Example
{
public static void main(String args[])
{
System.out.println("Welcome to Java program");
}
}
Output:
Welcome to Java program
How do Packages in Java Work?
 The names of packages and the directory structure are closely related to each other.
 For example, if a package name is university.engineering.csedept, then there are three directories-
university, engineering, and csedept such that csedept is present in engineering and engineering is
present in university.
 The package university can be considered as a top-level package while engineering is a sub package
of university and cse dept is a sub-package of engineering.
Package Naming Conventions
 Packages names follow the reverse order of domain names. For example, in a university, the
recommended convention is university.engineering.mech or university.tech.it or
university.arts.history etc.
 In the following package:
 java.util.Vector
 java is a top-level package
 util is a sub package
 and Vector is a class which is present in the subpackage util.
Compiling a Java Package
 If you are using an IDE (Integrated Development Environment), then for compiling the package, you
need to follow the syntax given below:
 javac -d directory javaFileName
For example,
 javac -d . Example.java
 -d specifies the destination where to locate the generated class file. You can use any directory name
like /home (in case of Linux), C:/folderName (in case of windows), etc. If you want the package to be
present in the same directory, you can use the dot ( . )
Executing Java Package Program
 You need to use a fully qualified name e.g. com.techvidvan.MyClass etc to run the class.
To Compile:
 javac -d . MyClass.java
 Here -d represents the destination. The . represents the current folder.
To run:
 java com.techvidvan.MyClass

4. a) What are the ways to access package from another package? Explain with an example.
Ans: If we want to access all the classes and interfaces of an existing package then we use
the import statement. We can do it in three different ways:
 import package.*;
 import package.classname;
 fully qualified name.
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.*
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello

Using packagename.classname
 If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:
Hello

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.
Example of package by import fully qualified name
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:
Hello

b) Write a java program to extend interface assuming suitable data.


Ans: Extending interfaces:
 One interface can inherit another by using the keyword extends.
 The new sub interface will inherit all the member of the super interface.
 Any class that will implement the interface that inherits another interface, it must provide
implementations of all methods defined within the interface inheritance chain.
 General form:
interface name2 extends name1
{
//body of name2
}
 An interface cannot extends a class.
interface ItemConstant

{
int code =1001;
String name =“Pen”;
}
interface Item extends ItemConstant

{
void display();
}
Program:

interface A {
void funcA();
}
interface B extends A {
void funcB();
}
class C implements B {
public void funcA() {
System.out.println("This is funcA");
}
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();
}
}
Output:
This is funcA
This is funcB

5. a) Define inner classes. List and explain types of Inner Classes with suitable example.
Ans:
java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
Additionally, it can access all the members of the outer class, including private data members and methods.

Syntax of Inner class

class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

Nested Inner Classes

It can access any private instance variable of outer class.

Program:

class Outer

class Inner

public void show()

System.out.println("In a nested class method");

class NestedInnerClass

public static void main(String[] args)

Outer.Inner obj = new Outer().new Inner();

obj.show();

Output:
In a nested class method

Method local inner classes:

class Outer

void outer Method ()

System.out.println("Inside outerMethod");

class Inner

void innerMethod()

System.out.println("Inside innerMethod");

Inner obj1 = new Inner();

obj1.innerMethod();

class MethodLocalInnerClass

public static void main(String[] args)

Outer obj = new Outer();

obj.outerMethod();

Output:

Inside outerMethod

Inside innerMethod
Anonymous inner class:

class Parent

void show()

System.out.println("Show method of Parent class");

class Child extends Parent

Parent obj = new Parent()

void show()

super.show();

System.out.println("Show method of Child class");

};

public static void main(String[] args)

obj.show();

Output:

Show method of Parent class

Show method of Child class

Static Inner Classes:

 A static class is created inside a class


 It doesn’t require to create an instance of outer class
Program:

class Outer

static class Inner

void show()

System.out.println("Static Nested Class Implemented");

public static void main(String args[])

Outer.Inner obj=new Outer.Inner();

obj.show();

Output:

Static Nested Class Implemented

b) List any five built-in packages from Java API along with their use.
Ans:
These packages consist of a large number of classes which are a part of Java API. Some of the commonly used
built-in packages are:

java.sql: Provides the classes for accessing and processing data stored in a database. Classes like Connection,
Driver Manager, Prepared Statement, Result Set, Statement, etc. are part of this package.
java.lang: Contains classes and interfaces that are fundamental to the design of the Java programming
language. Classes like String, String Buffer, System, Math, Integer, etc. are part of this package.
java.util: Contains the collections framework, some internationalization support classes, properties, random
number generation classes. Classes like Array List, LinkedList, HashMap, Calendar, Date, Time Zone, etc. are
part of this package.
java.net: Provides classes for implementing networking applications. Classes like Authenticator, HTTP
Cookie, Socket, URL, URL Connection, URL Encoder, URL Decoder, etc. are part of this package.
java.io: Provides classes for system input/output operations. Classes like Buffered Reader, Buffered Writer,
File, Input Stream, Output Stream, Print Stream, Serializable, etc. are part of this package.
java.awt: Contains classes for creating user interfaces and for painting graphics and images. Classes like
Button, Color, Event, Font, Graphics, Image, etc. are part of this package.

UNIT-IV
1.Define exception. How an exception can be handled in Java? And also List the benefits
of Exception Handling.
Ans:
The exception handling in java is one of the powerful mechanism to handle the runtime errors so that
normal flow of the application can be maintained.
What is exception?
 Exception is an abnormal condition.
 In java, exception is an event that disrupts the normal flow of the program.
 It is an object which is thrown at runtime.
 Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e
at run time, that disrupts the normal flow of the program’s instructions.
 Exceptions can be caught and handled by the program.
 When an exception occurs within a method, it creates an object. This object is called the exception
object. It contains information about the exception such as the name and description of the exception
and the state of the program when the exception occurred.
What is exception handling
 Exception Handling is a mechanism to handle runtime errors such as Class Not Found Exception, IO
Exception, SQL Exception, Remote Exception etc.
Advantage of Exception Handling
 The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception handling.
Advantages of Exception handling:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs

statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.
2. a) What are try, catch, and finally keywords in java? Explain it with an example.
Ans:
 Java try block is used to enclose the code that might throw an exception. It must be used within the
method.
 If an exception occurs at the particular statement in the try block, the rest of the block code will not
execute. So, it is recommended not to keep the code in try block that will not throw an exception.
 Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}

Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the parameter.
The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of exception.

Internal Working of Java try-Catch block

Program:

public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero

Java finally block is a block used to execute important code such as closing the connection, etc.
 Java finally block is always executed whether an exception is handled or not. Therefore, it contains
all the necessary statements that need to be printed regardless of the exception occurs or not.
 The finally block follows the try-catch block
Flow chart of finally block:

Example Program:
class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is executed");
}
System.out.println("rest of the code...");
}
}
Output:
5
finally block is executed
rest of the code...

b) Differentiate between Checked and Unchecked exceptions?


Ans:
3. Explain the usage of throw and throws keyword in Exception Handling.
Ans:
Java throw Exception:
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or uncheked exception in java by throw keyword.
• In Java, exceptions allows us to write good quality codes where the errors are checked at the compile
time instead of runtime and we can create custom exceptions making the code recovery and
debugging easier.
• We specify the exception object which is to be thrown. The Exception has some message with it that
provides the error description. These exceptions may be related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to
throw a custom exception.

The syntax of the Java throw keyword is given below.


 throw Instance i.e.,
 throw new exception_class("error message");
Let's see the example of throw IO Exception.
 throw new IOException("sorry device error");
Where the Instance must be of type Throwable or subclass of Throwable. For example, Exception is
the sub class of Throwable and the user-defined exceptions usually extend the Exception class.

Program:
public class JavaTester
{
public void checkAge(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[])
{
JavaTester obj = new JavaTester();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at
JavaTester.checkAge(JavaTester.java:4) at JavaTester.main(JavaTester.java:10)

Throws keyword:
 The Java throws keyword is used to declare an exception. It gives an information to the programmer
that there may occur an exception. So, it is better for the programmer to provide the exception
handling code so that the normal flow of the program can be maintained.
 Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers' fault that he is not checking the code
before it being used.
Syntax of Java throws
return_type method_name() throws exception_class_name
{
//method code
}

Program:
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled normal flow...
Rule: If we are calling a

4. a) Explain in detail the process of creating thread with an example.


Ans:

Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by extending the Thread
class. These are the only two ways through which we can create a thread.

Thread Class
A Thread class has several methods and constructors which allow us to perform various operations on a
thread. The Thread class extends the Object class. The Object class implements the Runnable interface. The
thread class has the following constructors that are used to perform various operations.

o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)


The Runnable interface is required to be implemented by that class whose instances are intended to be
executed by a thread. The runnable interface gives us the run() method to perform an action for the thread.

start() method
The method is used for starting a thread that we have newly created. It starts a new thread with a new
callstack. After executing the start() method, the thread changes the state from New to Runnable. It executes
the run() method when the thread gets the correct time to execute it.

Let's take an example to understand how we can create a Java

thread by extending the Thread class:

Program:

public class ThreadExample1 extends Thread {


// run() method to perform action for thread.
public void run()
{
int a= 10;
int b=12;
int result = a+b;
System.out.println("Thread started running..");
System.out.println("Sum of two numbers is: "+ result);
}
public static void main( String args[] )
{
// Creating instance of the class extend Thread class
ThreadExample1 t1 = new ThreadExample1();
//calling start method to execute the run() method of the Thread class
t1.start();
}
}

Output:

b) What is a thread? Explain the states of a thread with a neat diagram. (Thread Life Cycle)
Ans: A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a
program to operate more efficiently by running multiple tasks simultaneously.
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code
has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The active
state contains two states within it: one is runnable, and the other is running.
 Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state,
the thread may be running or may be ready to run at any given instant of time. It is the duty of the
thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally,
the most common change in the state of a thread is from runnable to running and again back to
runnable.
 Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either
the thread is in the blocked state or is in the waiting state.
 Timed Waiting: Sometimes, waiting for leads to starvation.
Terminated: A thread reaches the termination state because of the following reasons:
 When a thread has finished its job, then it exists or terminates normally.
 Abnormal termination: It occurs when some unusual events such as an unhandled exception or
segmentation fault.

5. a) Discuss about producer consumer pattern with an example.


Ans:
In computing, the producer-consumer problem (also known as the bounded buffer problem) is a classic
example of a multi-process synchronization Problem The problem describes two processes, the producer
and the Consumer, which share a common, fixed-size butter used as a queue.
 The producer's job is to generate data, put it into the butter, and Start again.
 At the same time, the consumer is consuming the dota lie. removing it from the buffer), one piece
at a time.

Implementation of producer consumer class


 A linkedlist to store list of jobs in queue
 A variable Capacity to check fox it the list is full on not
 A mechanism to control the insertion and extraction from this list s that we do not insert into list if
it is full on remove from it if it is empty.
Program:
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
Try
{
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});

Thread t2 = new Thread(new Runnable() {


@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();

t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"+ value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();
System.out.println("Consumer consumed-"+ val);
notify();
Thread.sleep(1000);
}
}
}
}
}
Output:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2

b) Distinguish between multi-tasking and multi-threading?


Ans:
Multi-tasking Multi threading

1)the process of multi-tasking lets a cpu execute 1)the process of multi-threading lets a cpu generate
various tasks at the very same time multiple threads out of a task and process all of
them simultaneously.
2)a user can easily perform various tasks
simultaneously with their CPU using multi-tasking 2)a cpu gets to divide a single progrom into various
threads so that it can work more efficiently and
3)the system needs to allocatee separate resources conveniently. thus, multi threading increases
and memory to different. programs working computer power
simultaneously in multi-tasking
3)the system allocates a single memory to any given
4)there is the constant switching blw various process in multi-threading. the various threads
programs by the cpu.. generated out of it share that very same resource
and memory that the cpu allocated to them.
5)it involves multiprocessing among. the various
components 4)the cpu constantly switches blw the threads and
not programs.
6)executing multi-tasking is comparatively slower.
5)it does not involve multiprocessing among its
7)the termination of a process takes up various components
comparatively more time in multi-tasking.
6)executing multi-threading is comparatively much
faster

7)the termination of a process takes up


comparatively less time in multithreading

c) How do we set priorities for threads? Explain it.


Ans:
 Each thread has a priority. Priorities are represented by a number between 1 and 10.
 In most cases, the thread scheduler schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a
thread explicitly in a Java program.
Setter & Getter Method of Thread Priority
 public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the
given thread.
 public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or
assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).
The three static variables associated with priority are −
 MAX_PRIORITY − The maximum priority that a thread has, whose default value is 10.
 NORM_PRIORITY − The default priority that a thread has, whose default value is 5.
 MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1.
 The ‘getPriority()’ method in Java helps in returning the priority of the thread bound as value to it.
 The ‘setPriority()’ method changes the priority value of a given thread. It throws the
IllegalArgumentException when the thread priority is less than 1 or greater than 10.
 public static int MIN_PRIORITY
 public static int NORM_PRIORITY
 public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
EXAMPLE
import java.lang.*;
public class Demo extends Thread{
public void run(){
System.out.println("Now, inside the run method");
}
public static void main(String[]args){
Demo my_thr_1 = new Demo();
Demo my_thr_2 = new Demo();
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
my_thr_1.setPriority(5);
my_thr_2.setPriority(3);
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of first thread is : " + my_thr_2.getPriority());
System.out.print(Thread.currentThread().getName());
System.out.println("The thread priority of main thread is : " +
Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("The thread priority of main thread is : " +
Thread.currentThread().getPriority());
}
}
Output
The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 3
The thread priority of main thread is : 5
The thread priority of main thread is : 10
UNIT-V
1. Explain the concept of Java collection frame. Write a brief overview on it.
Ans:
 The Collection in Java is a framework that provides an architecture to store and manipulate the group
of objects.
 Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.
 Java Collection means a single unit of objects.
 Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
What is a framework in Java
 It provides readymade architecture.
 It represents a set of classes and interfaces.
 It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group of objects.
It has:
 Interfaces and its implementations, i.e., classes
 Algorithm
Hierarchy of collection frame work:

Iterator interface:
Iterator interface provides the facility of iterating the elements in a forward direction only.
Iterable interface:
The iterable interface is the root interface for all the collection classes. The collection interface extends the
iterable interface and therefore all the subclasses of collection interface also implement the iterable
interface.
Collection frame:
The collection interface is the interface which is implemented by all the classes in the collection frame work.
List interface:
List interface is the child interface of collection interface it habits a list type data structure in which ordered
collection of objects.it can have duplicate values.
Array list:
The array list class implements the list interface. It uses a dynamic array to store the duplicate element of
different data types.
Linked list:
 Linked list implements the collection interface.
 It uses a doubly linked list internally to store the elements.
 It can store the duplicate elements.
Vector:
 Vector uses a dynamic array to store the data elements.
 It is similar to array list.
Stack:
 The stack is the subclass of vector. It implements the last-in-first-out data structure. i.e,stack.
 The stack contains all of the methods of vector class and also provides its method like Boolean push(),
Boolean peek(), Boolean push(object 0), which defines its properties.
Tree set:
 Java tree set classes implements the set interface that uses a tree for storage.
 Like Hashset, tree set also contains unique elements.

2. a) Explain briefly about Vector class with an example.


Ans:
 Vector uses a dynamic array to store the data elements.
 It is similar to ArrayList.
 However, It is synchronized and contains many methods that are not the part of Collection
framework.
Program:
import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
b) What is hash table? Explain with an example.
Ans: Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary class and
implements the Map interface.
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is
identified by calling the hashcode() method. A Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable class declaration
Let's see the declaration for java.util.Hashtable class.
1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializabl
e
Hashtable class Parameters
Let's see the Parameters for java.util.Hashtable class.
o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.
Java Hashtable Example
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit

3.a) Demonstrate about stack class with an example.


Ans:
 The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack.
 The stack contains all of the methods of Vector class and also provides its methods like boolean
push(), boolean peek(), boolean push(object o), which defines its properties.
Program:
import java.util.*;
public class TestJavaCollection4
{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
b) Explain briefly about Array List with an Example.
Ans:
 The ArrayList class implements the List interface.
 It uses a dynamic array to store the duplicate element of different data types.
 The ArrayList class maintains the insertion order and is non-synchronized.
 The elements stored in the ArrayList class can be randomly accessed.
Program:
import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay

4.a) Illustrate text input/output File operations.


Ans:
Java input and output are provided by a collection of library classes that ultimately provide an astonishly
uniform interface to all sorts of input and output, from the simplest to the most sophisticated A Java program
can read a web page from the other side of the world in much the same way it reads a simple string of text
from the keyboard: it can send text to a network Server in much the same way it sends text to a user at
computer's console. The drawback to this powerful 1/o system is that Simple 1/0 (particularly input) seems
more complicated than necessary of first This document introduces programmers to some of the concepts
underlying input and output in java, and to some simple methods for reading and writing text.

Text input:
The general strategy for doing text input is to create a reader for the input source, and then send it read or
read line messages to input individual characters or lines there are several kinds of reader that you might
use, the most common being a class named Buffered Reader

Text output:
The general strategy for outputting text is to create a kind of writer Known as a print writer connected to the
place you want to send your output, and then to use print or println messages to output the text.

b) Illustrate binary input/output file operations with examples.


Ans:
Java Binary Input and output.
 Data streams
 object streams
Binary input and output:
Java provides two types of streams to address binary input and output operations.
Data streams:
 Data Stream -API Supports binary input /output of java primitive data types (boolean, char, byte,
short, int, long, float, and double) and string values.
 Java provides two important interface for Data Streams - Data input or data output And the classes
implementing these interfaces are - Data input Stream & Data output stream respectively.
Object streams:
 Similar to Data streams, object streams Support binary 1/0 of objects All these classes implement
Serializable interface
 Object Input and object output interfaces are sub interfaces of Data Input and Data Output
interfaces respectively
 Basic Implementations of above two interfaces are -object input stream & Object Output Stream
respectively.
5.How a file can be managed using file class? Explain it
Ans:
 Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and
aids in the creation of File Stream objects.
 Use the File class for typical operations such as copying, moving, renaming, creating, opening,
deleting, and appending to a single file at a time. You can also use the File class to get and set file
attributes or Date Time information related to the creation, access, and writing of a file. If you want
to perform operations on multiple files,
 Many of the File methods return other I/O types when you create or open files. You can use these
other types to further manipulate a file. For more information, see specific File members such
as OpenText, CreateText, or Create.
 Because all File methods are static, it might be more efficient to use a File method rather than a
corresponding FileInfo instance method if you want to perform only one action. All File methods
require the path to the file that you are manipulating.
 The static methods of the File class perform security checks on all methods. If you are going to
reuse an object several times, consider using the corresponding instance method of FileInfo instead,
because the security check will not always be necessary.
 By default, full read/write access to new files is granted to all users.

The following table describes the enumerations that are used to customize the behavior of
various File methods.

Enumeration Description

FileAccess Specifies read and write access to a file.

FileShare Specifies the level of access permitted for a file that is already
in use.

FileMode Specifies whether the contents of an existing file are preserved


or overwritten, and whether requests to create an existing file
cause an exception.

You might also like