Java Q and A Sem - 220801 - 194348
Java Q and A Sem - 220801 - 194348
Java Q and A Sem - 220801 - 194348
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. byte -> short -> char -> int -> long -> float -> double
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'
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
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
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.
DECLARATION
type var-name[]; OR
type[] var-name;
EX:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}
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){
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;
}
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
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:
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
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.
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.
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.
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.
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.
• 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();
}
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
{
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.
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Program:
class Outer
class Inner
class NestedInnerClass
obj.show();
Output:
In a nested class method
class Outer
System.out.println("Inside outerMethod");
class Inner
void innerMethod()
System.out.println("Inside innerMethod");
obj1.innerMethod();
class MethodLocalInnerClass
obj.outerMethod();
Output:
Inside outerMethod
Inside innerMethod
Anonymous inner class:
class Parent
void show()
void show()
super.show();
};
obj.show();
Output:
class Outer
void show()
obj.show();
Output:
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 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.
Program:
}
}
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...
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
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)
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.
Program:
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.
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
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
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.
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.
The following table describes the enumerations that are used to customize the behavior of
various File methods.
Enumeration Description
FileShare Specifies the level of access permitted for a file that is already
in use.