[go: up one dir, main page]

0% found this document useful (0 votes)
8 views98 pages

OOPS (20CS0506) QB With Answers

The document is a question bank for the Object Oriented Programming through Java course at Siddharth Institute of Engineering & Technology. It covers various topics including Java programming paradigms, buzzwords, bytecode, the history and evolution of Java, and fundamental OOP concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it discusses data types in Java, including primitive and non-primitive types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views98 pages

OOPS (20CS0506) QB With Answers

The document is a question bank for the Object Oriented Programming through Java course at Siddharth Institute of Engineering & Technology. It covers various topics including Java programming paradigms, buzzwords, bytecode, the history and evolution of Java, and fundamental OOP concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it discusses data types in Java, including primitive and non-primitive types.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 98

Course Code: 20CS0506 R20

SIDDHARTH INSTITUTE OF ENGINEERING & TECHNOLOGY:: PUTTUR (AUTONOMOUS)


Siddharth Nagar, Narayanavanam Road – 517583

QUESTION BANK (DESCRIPTIVE)

Subject with Code: Object Oriented Programming through Java (20CS0506)


Course & Branch : B.Tech & CSM
Year & Sem : II & II Regulation: R20

UNIT-I
THE JAVA LANGUAGE & INTRODUCTION OF OOP

1 a) What is meant by paradigm? List the programming paradigms. [L1][CO1] [4M]

Programming paradigm is an approach to solve problem using some


programming language or also we can say it is a method to solve a
problem using tools and techniques that are available to us. There are
lots for programming language that are known but all of them need to
follow some strategy when they are implemented and this
methodology/strategy is paradigms. Apart from varieties of
programming language there are lots of paradigms to fulfill each and
every demand. They are discussed below:

b) List and Explain Java Buzz Words? [L2][CO1] [8M]


THE JAVA BUZZWORDS
The Java programming language is a high-level language that can be
characterized by all of the following buzzwords:

 Simple
 Object oriented
 Distributed
 Interpreted
 Robust
 Secure
 Architecture neutral
 Portable
 High performance
 Multithreaded
 Dynamic
Simple
 Java was designed to be easy for professional programmer to
learn and use effectively.
 It’s simple and easy to learn if you already know the basic
concepts of Object Oriented Programming.
 C++ programmer can move to JAVA with very little effort to
Course Code: 20CS0506 R20
learn.
 In Java, there is small number of clearly defined ways to
accomplish a given task.
Object Oriented
 Java is true object oriented language.
 Almost “Everything is an Object” paradigm. All program code
and data reside within objects and classes.
 The object model in Java is simple and easy to extend.
 Java comes with an extensive set of classes, arranged in packages
that can be used in our programs through inheritance.
Distributed
 Java is designed for distributed environment of the Internet. Its
used for creating applications on networks.
 Java applications can access remote objects on Internet as easily
as they can do in local system.
 Java enables multiple programmers at multiple remote
locations to collaborate and work together on a single project.
Compiled and Interpreted
 Usually a computer language is either compiled or Interpreted.
Java combines both this approach and makes it a two-stage system.
 Compiled: Java enables creation of a cross platform programs by
compiling into an intermediate representation called Java Bytecode.
 Interpreted: Bytecode is then interpreted, which generates
machine code that can be directly executed by the machine that provides
a Java Virtual machine.
Robust
 It provides many features that make the program execute reliably
in variety of environments.
 Java is a strictly typed language. It checks code both at compile
time and runtime.
 Java takes care of all memory management problems with
garbage-collection.
 Java, with the help of exception handling captures all types of
serious errors and eliminates any risk of crashing the system.
Secure
 Java provides a “firewall” between a networked application and
your computer.
 When a Java Compatible Web browser is used, downloading can
be done safely without fear of viral infection or malicious intent.
 Java achieves this protection by confining a Java program to the
java execution environment and not allowing it to access other parts of
the computer.
Architecture Neutral
 Java language and Java Virtual Machine helped in achieving the
goal of “write once; run anywhere, any time, forever.”
 Changes and upgrades in operating systems, processors and
system resources will not force any changes in Java Programs.
Portable
 Java Provides a way to download programs dynamically to all the
Course Code: 20CS0506 R20
various types of platforms connected to the Internet.
 It helps in generating Portable executable code.
High Performance
 Java performance is high because of the use of bytecode.
 The bytecode was used, so that it was easily translated into native
machine code.
Multithreaded
 Multithreaded Programs handled multiple tasks simultaneously,
which was helpful in creating interactive, networked programs.
 Java run-time system comes with tools that support multiprocess
synchronization used to construct smoothly interactive systems.
Dynamic
 Java is capable of linking in new class libraries, methods, and
objects.
 It can also link native methods (the functions written in other
languages such as C and C++).

2 a) What is Byte Code? Analyze the different states of Java Program [L4][CO1] [6M]
execution?
JAVA BYTE CODE
Java bytecode is the instruction set for the Java Virtual Machine. As
soon as a java program is compiled, java bytecode is generated. In more
apt terms, java bytecode is the machine code in the form of a .class file.
With the help of java bytecode we achieve platform independence in
java.

b) Explain History and Evolution of Java? [L2][CO1] [6M]

HISTORY AND EVOLUTION OF JAVA


The history of Java is very interesting. Java was originally designed for
interactive television, but it was too advanced technology for the digital
cable television industry at the time. The history of Java starts with the
Green Team. Java team members (also known as Green Team), initiated
this project to develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was suited for internet programming.
Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust,
Portable, Platform independent, Secured, High Performance,
Multithreaded, Architecture Neutral, Object Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the
father of Java, in 1995. James Gosling and his team members started the
Course Code: 20CS0506 R20
project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games,


e-business solutions, etc. There are given significant points that describe
the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the
Java language project in June 1991. The small team of sun engineers
called Green Team.
2) Initially designed for small, embedded systems in electronic
appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file
extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green
project.
Why Java named "Oak"?
5) Why Oak? Oak is a symbol of strength and chosen as a national tree
of many countries like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a
trademark by Oak Technologies.

7) Why had they chosen java name for Java language? The team
gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along
with Silk". Since Java was so unique, most of the team members
preferred Java than other names.
8) Java is an island of Indonesia where the first coffee was produced
(called java coffee). It is a kind of espresso bean. Java name was chosen
by James Gosling while having coffee near his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems (which is
now a subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products
of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java,
there have been many additional features added to the language. Now
Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc. Each new version adds the
new features in Java.

Java Version History


Many java versions have been released till now. The current stable
release of Java is Java SE 10.
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
Course Code: 20CS0506 R20
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11
14. Java SE 12
15. Java SE 13

3 a) What is mean by OOP? Illustrate the Concepts of OOP? [L3][CO2] [6M]

Object Oriented Programming


Concepts of OOP:
ABSTRACTION is the concept of object-oriented programming that
"shows" only essential attributes and "hides" unnecessary information.
The main purpose of abstraction is hiding the unnecessary details from
the users. Abstraction is selecting data from a larger pool to show only
relevant details of the object to the user. It helps in reducing
programming complexity and efforts. It is one of the most important
concepts of OOPs.
ENCAPSULATION
The process of binding data and corresponding methods (behavior)
together into a single unit is called encapsulation in Java.
In other words, encapsulation is a programming technique that binds the
class members (variables and methods) together and prevents them from
being accessed by other classes, thereby we can keep variables and
methods safes from outside interference and misuse.
Every Java class is an example of encapsulation because we write
everything within the class only that binds variables and methods
together and hides their complexity from other classes.
Another example of encapsulation is a capsule. Basically, capsule
encapsulates several combinations of medicine.
If combinations of medicine are variables and methods then the capsule
will act as a class and the whole process is called Encapsulation as
shown in the below figure.

INHERITANCE
 Inheritance is the mechanism by which an object acquires the
Course Code: 20CS0506 R20
some/all properties of another object.
 It supports the concept of hierarchical classification.

POLYMORPHISM

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.
If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.

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.
If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example:
Course Code: 20CS0506 R20

b) Show what is varargs in java? Write the syntax and develop a [L6][CO1] [6M]
Program showing the varargs usage.

In JDK 5, Java has included a feature that simplifies the creation of


methods that need to take a variable number of arguments. This feature
is called varargs and it is short-form for variable-length arguments. A
method that takes a variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways.
One using overloaded method(one for each) and another put the
arguments into an array, and then pass this array to the method. Both of
them are potentially error-prone and require more code. The varargs
feature offers a simpler, better option.
Syntax of varargs :
A variable-length argument is specified by three periods(…). For
Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or
more arguments. As a result, here ‘a’ is implicitly declared as an array
of type int[]. Below is a code snippet for illustrating the above
concept :
// Java program to demonstrate varargs
class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
System.out.println("Number of arguments: " + a.length);

// using for each loop to display contents of a


for (int i: a)
System.out.print(i + " ");
System.out.println();
}

// Driver code
public static void main(String… a)
{
// Calling the varargs method with different number
// of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
Course Code: 20CS0506 R20
fun(); // no parameter
}
}

o/p:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0

4 a) Define Data Type? Discuss the data types available in Java. [L2][CO1] [6M]

Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
Java Primitive Data Types
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:
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

'\u0000' 2 byte
Course Code: 20CS0506 R20
0 1 byte

short 0 2 byte

0 4 byte

0L 8 byte

0.0f 4 byte

double 0.0d 8 byte


b) Develop a Java program to read different data types using Scanner. [L6][CO1] [6M]
import java.util.Scanner;

import java.io.*;

public class RectangleArea {


public static void main(String[] args) {
int length;
float width;
double d;
Scanner console = new Scanner(System.in);
System.out.print("Enter length ");
length = console.nextInt();
System.out.print("Enter width ");
width = console.nextFloat();
System.out.print("Enter double data ");
d = console.nextDouble();
System.out.println("length= " + length);
System.out.println("width= " + width);
System.out.println("double= " + d);

}
}

5 a) Describe an identifier and give the rules to declare them. [L1][CO1] [4M]
Identifiers are used to name a variable, constant, function, class, and
array. It usually defined by the user. It uses letters, underscores, or a
dollar sign as the first character. The label is also known as a special
kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a
dollar sign. It cannot start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

b) How type casting implemented in java? Explain with an example. [L2][CO1] [4M]
In Java, type casting is a method or process that converts a data type
into another data type in both ways manually and automatically. The
automatic conversion is done by the compiler and manual conversion
performed by the programmer. In this section, we will discuss type
casting and its types with proper examples.
Course Code: 20CS0506 R20

Types of Type Casting


There are two types of type casting:
o Widening Type Casting
o Narrowing Type Casting

c) State what is a variable? Give the declaration of variable in Java and [L1][CO1] [4M]
specify the Rules to be followed over the same?
Variable is a name of memory location.
Rules to declare variable are:
o The first letter of an variable must be a letter, underscore or a
dollar sign. It cannot start with digits but may contain digits.
o The whitespace cannot be included in the variable.
variables are case sensitive
Declaration of variables
int data;
float avg
double salary;
6 Define Operator? Discriminate the type of operators in Java with [L5][CO1] [12M]
Examples.
Operators: In programming, operators are the special symbol that tells
the compiler to perform a special operation. Java provides different types
of operators that can be classified according to the functionality they
provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||
Course Code: 20CS0506 R20
Ternary (Condition) ? (Statement1) :
(Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

7 Explain the Decision Making statements in Java with example. [L2][CO1] [12M]
Decision -Making Statements
Statements that determine which statement to execute and when are
known as decisionmaking statements. The flow of the execution of the
program is controlled by the control flow statement.
There are four decision-making statements available in java.
Simple if statement
The if statement determines whether a code should be executed based on
the specified condition.
Syntax:
if (condition) {
Statement 1; //executed if condition is true
}
Statement 2; //executed irrespective of the condition
If..else statement
In this statement, if the condition specified is true, the if block is
executed. Otherwise, the else block is executed. Example:
public class Main
{
public static void main(String args[])
{
int a = 15; if (a > 20)
System.out.println("a is greater than 10");
else
System.out.println("a is less than 10");
System.out.println("Hello World!");
}
}
} Output:
a is less than 10 Hello World!

Nested if statement

An if present inside an if block is known as a nested if block. It is similar


to an if..else statement, except they are defined inside another if..else
statement.
Course Code: 20CS0506 R20
Syntax:
if (condition1) {
Statement 1; //executed if first condition is true if (condition2) {
Statement 2; //executed if second condi tion is true
}
else {
Statement 3; //executed if second condition is false
}
}
Example:
public class Main
{
public static void main(String args[])
{ int s =
18; if (s
>
10)
{
if (s%2==0)
System.out.println("s is an even number and greater than
10!") ; else
System.out.println("s is a odd number and greater than 10!"); } else
{
System.out.println("s is less than 10");
}
System.out.println("Hello World!");
}
}
Output: s is an even number and greater than 10! Hello World!
Switch statement
A switch statement in java is used to execute a single statement from
multiple conditions. The switch statement can be used with short, byte,
int, long, enum types, etc.
One or N number of case values can be specified for a switch expression.
Case values that are duplicate are not permissible. A compile-time error
is generated by the compiler if unique values are not used.
The case value must be literal or constant. Variables are not permissible.
Usage of break statement is made to terminate the statement
sequence. It is optional to use this statement. If this statement is not
specified, the next case is executed.

Example:
public class Music {
public static void main(String[] args)
{
int instrument = 4; String musicInstrument;
Course Code: 20CS0506 R20
// switch statement with int data type switch (instrument) { case 1:
musicInstrument = "Guitar"; break; case
2:
musicInstrument = "P iano"; break; case
3:
musicInstrument = "Drums";
break; case 4: musicInstrument = "Flute"; break; case 5:
musicInstrument = "Ukelele"; break; case 6: musicInstrument =
"Violin"; break; case 7: musicInstrument = "Trumpet"; break; de fault:
musicInstrument = "Invalid";
break;
}
System.out.println(musicInstrument);
}
}
Output:
Flute
8 Give example and Explain about the Iteration Statements. [L2][CO1] [12M]
Looping Statements
Statements that execute a block of code repeatedly until a specified
condition is met are known as looping statements. Java provides the user
with three types of loops:
while
Known as the most common loop, the while loop evaluates a certain
condition. If the condition is true, the code is executed. This process is
continued until the specified condition turns out to be false.
The condition to be specified in the while loop must be a Boolean
expression. An error will be generated if the type used is int or a string.
Syntax:
while (condition)
{
statementOne;
}
Example:
public class whileTest
{
public static void main(String args[])
{
int i = 5;
while (i <= 15)
{
System.out.println(i);
i = i+2;
}
}
}
Output:
5
7
9
11
13
15
Course Code: 20CS0506 R20
Do..while
The do-while loop is similar to the while loop, the only difference being
that the condition in the do-while loop is evaluated after the execution of
the loop body. This guarantees that the loop is executed at least once.
Syntax:
do{
//code to be executed
}while(condition);
Example:
public class Main
{
public static void main(String args[])
{
int i = 20;
do
{
System.out.println(i);
i = i+1;
} while (i <= 20);
}
}

Output:
20

For

The for loop in java is used to iterate and evaluate a code multiple times.
When the number of iterations is known by the user, it is recommended
to use the for loop.
Syntax:
for (initialization; condition; increment/decrement)
{
statement;
}
Course Code: 20CS0506 R20

Example:
public class forLoop
{
public static void main(String args[])
{
for (int i = 1; i <= 10; i++)
System.out.println(i);
}
}
Output:
5
6
7
8
9
10

For-Each
The traversal of elements in an array can be done by the for-each loop. The elements
present in the array are returned one by one. It must be noted that the user does not have to
increment the value in the for-each loop.
Example:
public class foreachLoop{
public static void main(String args[]){
int s[] = {18,25,28,29,30};
for (int i : s) {
System.out.println(i);
}
}
}
Output:
18
25
28
29
30
Course Code: 20CS0506 R20
9 a) Give the Structure of Java program? [L1][CO1] [2M]
Class ClassName
{
Public static void main(String args[])
{
System.out.println(“java Stucture program”);
}
}
b) Create a java program to find the greatest of three numbers and give the [L6][CO1] [5M]
procedure for compilation and run the same.
public class ArithmeticSmallestLargest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1;
int num2; int num3; int sum; int average; int
product; double largest
System.out.print("Enter First Integer: "); num1 = input.nextInt();
System.out.print("Enter Second Integer: "); num2 = input.nextInt();
System.out.print("Enter Third Integer: "); num3 = input.nextInt();
sum = num1 + num2 + num3;
average = sum / 3; product = num1 * num2 * num3;
if (largest =num1 > num2 & num2 > num3)
System.out.println(sum);
System.out.println(average);
System.out.println(product);
System.out.println("The biggest number is " + largest);
}}
Compilation
Javac filename.java
Run
Jaba filename
c) Describe command line arguments? Develop a Java program to add two [L6][CO1] [5M]
numbers using command line arguments.
A command-line argument is an information that directly follows the
program's name on the command line when it is executed. To access the
command-line arguments inside a Java program is quite easy. They are
stored as strings in the String array passed to main( ).
Example
public class CommandLine { public static void main(String args[])
{ for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Output: compile by > javac CommandLine .java run by > java
CommandLine this is a command line 200 -100
This will produce the following result -
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]:-100
Course Code: 20CS0506 R20
10 a) Define an Array? Classify the types of arrays in Java. [L4][CO1] [6M]
An array is a group of like-typed variables that are referred to by a
common name. Arrays of any type can be created and may have one or
more dimensions.
The general form of a one-dimensional array declaration is
type var-name[ ];
int month_days[];
array-var = new type [size];
Arrays can have
1. One dimensional
2. Multi dimensional

One -Dimensional Arrays :


The general form of a one-dimensional array declaration is
type va r-name[];
OR type[] var-name;
intArray[]; or int[] intArray;
How to Initialize Arrays in Java?
int[] age = {12, 4, 5, 2, 5};
For example,
// declare an array
int[] age = new int[5];
// initializ e array
age[0] = 12;
age[1] = 4;
age[2] = 5 ;
..
Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the
array holding the reference of other array. These are also known as
Jagged Arrays. A multidimensional array is created by appending one set
of square brackets ([]) per dimension.
Examples: int[][] intArray = new int[10][20];
//a 2D array or matrix int[][][] intArray = new int[10][20][10];
//a 3D array

b) Create a Java program to read and display the array elements. [L6][CO1] [6M]
OneD
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;
// allocating memory for 5 integers.
arr = new int[5];
// initialize the first elements of the array arr[0] = 10;
// initialize the second elements of the array arr[1] = 20;
//so on... arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : "+ arr[i]);
}
}
Course Code: 20CS0506 R20
Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at i ndex 3 : 40
Element at index 4 : 50
Course Code: 20CS0506 R20

UNIT II
INTRODUCING CLASSES

1 a) Give the definition and syntax of Class, Method and Object? [L1][CO2] [6M]

Class
A class is a user defined blueprint or prototype from which objects are
created. It
represents the set of properties or methods that are common to all
objects of one type.
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized
by
convention).
4. Superclass(if any): The name of the class‘s parent (superclass), if
any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
5. Interfaces(if any): A comma-separated list of interfaces implemented
by the class,
if any, preceded by the keyword implements. A class can implement
more than one
interface.
6. Body: The class body surrounded by braces, { }.
Object
It is a basic unit of Object-Oriented Programming and represents the real
life entities. A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties
of an object.
2. Behavior: It is represented by methods of an object. It also reflects
the response
of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact
with other objects.
Ways to create object of a class
There are four ways to create objects in java.Strictly speaking there is
only one way(by
using new keyword),and the rest internally use new keyword.
Using new keyword: It is the most common and general way to create
object in
java. Example:
// creating object of class Test
Test t = new Test();
MethodA method is a collection of statements that perform some
specific task and return the result to the caller. A method can perform
some specific task without returning anything.
Methods allow us to reuse the code without retyping the code. In Java,
every method must be part of some class which is different from
languages like C, C++, and Python.
Methods are time savers and help us to reuse the code without retyping
Course Code: 20CS0506 R20

the code.
Method Declaration
In general, method declarations has six components:
Modifier-: Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access
specifiers.
public: accessible in all class in your application.
protected: accessible within the class in which it is defined and in
its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier) : accessible
within
same class and package within which its class is defined.
The return type : The data type of the value returned by the method or
void if does not return a value.
Method Name : the rules for field names apply to method names as
well, but the convention is a little different.
Parameter list : Comma separated list of the input parameters are
defined, preceded with their data type, within the enclosed parenthesis.
If there are no parameters, you must use empty parentheses ().
Exception list : The exceptions you expect by the method can throw,
you can specify these exception(s).
Method body : it is enclosed between braces. The code you need to be
executed to perform your intended operations.
b) Create a java program to display “Hello! Java” using Class, Object [L6][CO2] [6M]
and Method.
class Example
{
void message()
{
System.out.println(“Hello Java”);
}
}
Class Demo
{
Public static void main (String args[])
{
Example obj=new Example();
obj.message();
}
}
2 a) Define Constructor? Classify the types of Constructors in Java? [L4][CO2] [7M]
Constructors are used to initialize the object‘s state. Like methods, a
constructor also contains collection of statements(i.e. instructions) that
are executed at time of Object creation.
Types of constructor
There are two type of constructor in Java:
1. No-argument constructor: A constructor that has no parameter is
known as default
constructor. If we don‘t define a constructor in a class, then compiler
creates default
constructor(with no arguments) for the class. And if we write a
constructor with
Course Code: 20CS0506 R20

arguments or no-arguments then the compiler does not create a default


constructor.
Default constructor provides the default values to the object like 0, null,
etc. depending
on the type.
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
class Samba
{
int num;
String name;
// this would be invoked while an object
// of that class is created.
Samba()
{
System.out.println("Constructor called");
}
}
class Hai
{
public static void main (String[] args)
{
// this would invoke default constructor.
Samba s1 = new Samba();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(s1.name);
System.out.println(s1.num);
}
}
Output :
Constructor called
null
0
2. Parameterized Constructor: A constructor that has parameters is
known as
parameterized constructor. If we want to initialize fields of the class with
your own
values, then use a parameterized constructor.
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;
class Student
{
// data members of the class.
String name;
int id;
// constructor would initialize data members
// with the values of passed arguments while
// object of that class created.
Student (String name, int id)
{
this.name = name;
Course Code: 20CS0506 R20

this.id = id;
}
}
class Hai
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Student s1 = new Student ("kumar", 533);
System.out.println("Name :" + s1.name + " and Id :" + s1.id);
}
}
Output:
Name :kumar and Id :533
b) Write a java program to illustrate Constructor Overloading. [L6][CO2] [5M]
class Box
{
double width, height, depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
// specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
Course Code: 20CS0506 R20

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
3 a) Illustrate Garbage Collector in Java and explain the its behavior [L3][CO2] [6M]
when used.
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C+
+. But, in java it is performed automatically. So, java provides better
memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so
we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
o By nulling the reference
o By assigning a reference to another
o By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage
collection
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class
as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without new,
you can use finalize method to perform cleanup processing (destroying
remaining objects).
Course Code: 20CS0506 R20

gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing.
The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called
Garbage Collector(GC).
This thread
calls the finalize() method before object is garbage collected.
//Simple Example of garbage collection in java
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected.
b) Differentiate between the usage of static, final keywords with [L4][CO2] [6M]
Example.
The static keyword in Java is mainly used for memory management.
The static keyword in Java is used to share the same variable or
method of a given class. The users can apply static keywords with
variables, methods, blocks, and nested classes. The static keyword
belongs to the class than an instance of the class. The static keyword
is used for a constant variable or a method that is the same for every
instance of a class.
// Java program to demonstrate that a static member
// can be accessed before instantiating a class

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
Course Code: 20CS0506 R20

Final variables
When a variable is declared with final keyword, its value can‘t be
modified, essentially, a constant. This also means that you must initialize
a final variable. If the final variable is a reference, this means that the
variable cannot be re-bound to reference another object, but internal
state of the object pointed by that reference variable can be changed i.e.
you can add or remove elements from final array or final collection. It is
good practice to represent
final variables in all uppercase, using underscore to separate words.
//Java program to demonstrate different
// ways of initializing a final variable
class Gfg
{
// a final variable
// direct initialize
final int THRESHOLD = 5;
// a blank final variable
final int CAPACITY;
// another blank final variable
final int MINIMUM;
// a final static variable PI
// direct initialize
static final double PI = 3.141592653589793;
// a blank final static variable
static final double EULERCONSTANT;
// instance initializer block for
// initializing CAPACITY
{
CAPACITY = 25;
}
// static initializer block for
// initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
}
// constructor for initializing MINIMUM
// Note that if there are more than one
// constructor, you must initialize MINIMUM
// in them also
public GFG()
{
MINIMUM = -1;
}
}
When to use a final variable :
The only difference between a normal variable and a final variable is
that we can re-assign value to a normal variable but we cannot change
the value of a final variable once assigned.
Hence final variables must be used only for the values that we want to
remain constant throughout the execution of program.
4 a) Show the application of final keyword with variable, method and class [L1][CO2] [9M]
in detail with an example.
1. Final variables
Course Code: 20CS0506 R20

When a variable is declared with final keyword, its value can‘t be


modified, essentially, a constant. This also means that you must initialize
a final variable. If the final variable is a reference, this means that the
variable cannot be re-bound to reference another object, but internal
state of the object pointed by that reference variable can be changed i.e.
you can add or remove elements from final array or final collection. It is
good practice to represent
final variables in all uppercase, using underscore to separate words.
//Java program to demonstrate different
// ways of initializing a final variable
class Gfg
{
// a final variable
// direct initialize
final int THRESHOLD = 5;
// a blank final variable
final int CAPACITY;
// another blank final variable
final int MINIMUM;
// a final static variable PI
// direct initialize
static final double PI = 3.141592653589793;
// a blank final static variable
static final double EULERCONSTANT;
// instance initializer block for
// initializing CAPACITY
{
CAPACITY = 25;
}
// static initializer block for
// initializing EULERCONSTANT
static{
EULERCONSTANT = 2.3;
}
// constructor for initializing MINIMUM
// Note that if there are more than one
// constructor, you must initialize MINIMUM
// in them also
public GFG()
{
MINIMUM = -1;
}
}
When to use a final variable :
The only difference between a normal variable and a final variable is
that we can re-assign value to a normal variable but we cannot change
the value of a final variable once assigned.
Hence final variables must be used only for the values that we want to
remain constant throughout the execution of program.
2. Java final Method
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
Course Code: 20CS0506 R20

}
}
class Main extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final method named display()
inside the
FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we
run the program, we will get a compilation error with the following
message.
display() in Main cannot override display() in FinalDemo
public final void display() {
^
overridden method is final
3. Java final Class
In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}
// try to extend the final class
class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}

b) Give the difference between final and finalize. [L4][CO2] [3M]


Final When a variable is declared with final keyword, its value can‘t be
modified, essentially, a constant. This also means that you must initialize
a final variable. If the final variable is a reference, this means that the
variable cannot be re-bound to reference another object, but internal
state of the object pointed by that reference variable can be changed i.e.
you can add or remove elements from final array or
final collection. It is good practice to represent final variables in all
uppercase, using underscore to separate words.
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
Course Code: 20CS0506 R20

method is defined in Object class as:


protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are
created by new keyword. So if you have created any object without
new, you can use finalize method to perform cleanup processing
(destroying remaining objects).
5 What is Inheritance? Explain types of inheritances. [L2][CO2] [12M]
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another. With the use of inheritance
the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is
known as superclass (base class, parent class).
Inheritance represents the IS-A relationship which is also known as a
parent-child
relationship.
extends Keyword
extends is the keyword used to inherit the properties of a class.
Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other
class. It is
also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a
subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates
you to reuse the fields and methods of the existing class when you create
a new class. You can use the same fields and methods already defined in
the previous class.
single inheritance
When a class inherits another class, it is known as a single inheritance.
In the example given below, Dog class inherits the Animal class, so
there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
Course Code: 20CS0506 R20

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class
inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as
hierarchical inheritance. In the example given below, Dog and Cat
classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
Course Code: 20CS0506 R20

class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
6 Create and explain java program for the implementation of single, [L6][CO2] [12M]
Multi-level and hierarchical inheritance.
single inheritance
When a class inherits another class, it is known as a single inheritance.
In the example given below, Dog class inherits the Animal class, so
there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class
inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
Course Code: 20CS0506 R20

d.eat();
}
}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as
hierarchical inheritance. In the example given below, Dog and Cat
classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing..
7 a) Describe about the super keyword in java with example. [L2][CO2] [6M]
USING SUPER
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.
Uses of super keyword
To call methods of the superclass that is overridden in the subclass.
To access attributes (fields) of the superclass if both superclass and
subclass have attributes with the same name.
To explicitly call superclass no-arg (default) or parameterized
constructor from the subclass constructor.
Let‘s understand each of these uses.
1) super is used to refer immediate parent class instance variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
Course Code: 20CS0506 R20

}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of
current class by default. To access the parent property,we need to use
super keyword.
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It
should be used if subclass contains the same method as parent class. In
other words, it is used if method is overridden.
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if
Course Code: 20CS0506 R20

we call eat() method from Dog class, it will call the eat() method of Dog
class by default because priority is given to local.
To call the parent class method, we need to use super keyword.
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class
constructor. Let's see a simple
example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
b) Give the differences between Abstract class and Interface [L4][CO2] [6M]
ABSTRACT CLASSES
A class which is declared with the abstract keyword is known as an
abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
it shows only essential things to the user and hides the internal details,
for example,
sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.
Example:
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}}
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Course Code: 20CS0506 R20

Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
gear changed
INTERFACE
Interface is similar to a class, but it contains only abstract methods.
By default the variables declared in an interface are public, static and
final.
Interface is a mechanism to achieve full abstraction.
An interface does not contain any constructor.
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
Example: Sample program to implements multiple inheritance
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Course Code: 20CS0506 R20

Demo obj = new Demo();


obj.run();
obj.stop();
}
}
Output:
Vehicle is running.
Bike is stop.
8 a) Distinguish Method Overriding and Method Overloading. [L5][CO2] [6M]
METHOD OVERLOADING
In Java, two or more methods may have the same name if they differ in
parameters
(different number of parameters, different types of parameters, or both).
These methods are called overloaded methods and this feature is called
method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
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
By changing number of arguments
By changing the data type
Method Overloading: changing no. of arguments
In this example, we have created two methods, first add() method
performs addition of two numbers and second add method performs
addition of three numbers.
In this example, we are creating static methods so that we don't need to
create instance for calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type.
The first add method receives two integer arguments and second add
method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
Course Code: 20CS0506 R20

System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
METHOD OVERRIDING
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
Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
Method overriding is used for runtime polymorphism
Rules for Method Overriding
The argument list should be exactly the same as that of the overridden
method.
The return type should be the same or a subtype of the return type
declared in the original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's
access
level. For example: If the superclass method is declared public then the
overriding
method in the sub class cannot be either private or protected.
Instance methods can be overridden only if they are inherited by the
subclass.
A method declared final cannot be overridden.
A method declared static cannot be overridden but can be re-declared.
If a method cannot be inherited, then it cannot be overridden.
A subclass within the same package as the instance's superclass can
override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final
methods declared public or protected.
An overriding method can throw any uncheck exceptions, regardless of
whether the overridden method throws exceptions or not. However, the
overriding method
should not throw checked exceptions that are new or broader than the
ones declared by the overridden method. The overriding method can
throw narrower or fewer exceptions than the overridden method.
Constructors cannot be overridden.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Course Code: 20CS0506 R20

Output:
Vehicle is running
b) What is an abstract class? Discuss the cases to implement abstract [L2][CO2] [6M]
Class.
ABSTRACT CLASSES
A class which is declared with the abstract keyword is known as an
abstract class in Java.
It can have abstract and non-abstract methods (method with the body).
it shows only essential things to the user and hides the internal details,
for example,
sending SMS where you type the text and send the message. You don't
know the internal processing about the message delivery.
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change
the body of the method.
Example:
abstract class Bike{
abstract void run();
}
class Honda extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}}
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Output:
bike is created
running safely..
Course Code: 20CS0506 R20

gear changed.
9 a) Recall what is package? Explain how to create user defined package [L2][CO2] [6M]
in java with example program
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.
2. User defined packages
The package we create according to our need is called user defined
package.
Creating a Package
We can create our own package by creating our own classes and
interfaces together. The
package statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}
Example: Creating a Package
// Demo.java
package p1;
class Demo
{
public void m1()
{
System.out.println("Method m1..");
}
}
How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java
How to run?
To run: java p1.Demo
Example: Program to create and use a user defined package in Java.
package mypackage;
public class FirstProgram {
public void myWish()
{
System.out.println("welcome to user defined packages");
}
}
Import mypackage.*;
public class TestPackage {
public static void main(String args[])
{
FirstProgram obj=new FirstProgram();
obj.myWish();
Course Code: 20CS0506 R20

}
}
Output:
welcome to user defined packages
b) Write a java program to find the factorial value of the [L6][CO2] [6M]
given number using user defined package concept.
Fact.java
package Mypackage;
public class Fact{
public void FactMethod(int num){
long f = 1;
for(int i = 1; i <= num; ++i)
{
f = f * i;
}
System.out.println("Factorial of "+num+" = "+f);
}
}
Factorial.java
import Mypackage.Fact;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
System.out.println("enter a number to find Factorial");
int num = in.nextInt();
Fact f1=new Fact();
f1.FactMethod(num);
}
}
10 a) State what is an interface and the rules to create an interface in java [L1][CO2] [6M]
with example program
INTERFACE
Interface is similar to a class, but it contains only abstract methods.
By default the variables declared in an interface are public, static and
final.
Interface is a mechanism to achieve full abstraction.
An interface does not contain any constructor.
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
Example: Sample program to implements multiple inheritance
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
Course Code: 20CS0506 R20

}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}
Output:
Vehicle is running.
Bike is stop.

b) Develop a java program to implement an interface using your own [L6][CO2] [6M]
example program

INTERFACE
Interface is similar to a class, but it contains only abstract methods.
By default the variables declared in an interface are public, static and
final.
Interface is a mechanism to achieve full abstraction.
An interface does not contain any constructor.
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
Example: Sample program to implements multiple inheritance
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
Course Code: 20CS0506 R20

public void stop()


{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}
Output:
Vehicle is running.
Bike is stop.
Course Code: 20CS0506 R20

UNIT III
EXCEPTION HANDLING & MULTITHREADED
PROGRAMMING

1 a) Summarize what is Java Exception and its Types [L2][CO3] [6M]

An exception (or exceptional event) is a problem that arises during the


execution of a program. When an Exception occurs the normal flow of
the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are
to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.

A user has entered an invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or


the JVM has run out of memory.

Some of these exceptions are caused by user error, others by


programmer error, and others by physical resources that have failed in
some manner.
EXCEPTION TYPES
There are mainly two types of exceptions: checked and unchecked.
Here, an error is considered as the unchecked exception. According to
Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked
exceptions
Course Code: 20CS0506 R20

e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoun
dsException etc.Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
b) Illustrate about try, catch, and throw statements using a java program. [L3][CO3] [6M]
Try : The "try" keyword is used to specify a block where we should
place exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
Catch:The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.
Throw :The "throw" keyword is used to throw an exception.
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 of try block, the rest
of the block code will not execute. So, it is recommended not to
keeping the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block
Notice that the call to println( ) inside the try block is never executed.
Once an exception is thrown, program control transfers out of the try
block into the catch block.
Put differently, catch is not ―called, so execution never ―returns to
the try block from a catch.
Thus, the line "This will not be printed." is not displayed.
Once the catch statement has executed, program control continues with
the next line in the program following the entire try /catch mechanism.
A try and its catch statement form a unit. The scope of the catch clause
is restricted to those statements specified by the immediately preceding
try statement.
A catch statement cannot catch an exception thrown by another try
statement (except in the case of nested try statements, described
shortly).
The statements that are protected by try must be surrounded by curly
braces. (That is, they must be within a block.) You cannot use try on a
single statement.
Internal working of java try-catch block
Syntax of Java try-catch
Try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Example:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
Course Code: 20CS0506 R20

}
catch (ArithmeticException e)
{
// catch divide-by-zero error System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
THROW
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom
exception. We will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;
Example
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}}
2 a) Discuss in detail Java exception hierarchy [L2][CO3] [6M]

An exception (or exceptional event) is a problem that arises during the


execution of a program. When an Exception occurs the normal flow of
the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are
to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or
the JVM has run out of memory.

Some of these exceptions are caused by user error, others by


programmer error, and others by physical resources that have failed in
some manner.

b) Give the difference between checked and unchecked exceptions? [L4][CO3] [6M]
Course Code: 20CS0506 R20

1) Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked
exceptions
e.g.ArithmeticException,NullPointerException,ArrayIndexOutOfBoun
dsException etc.Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
3 a) Explain about Nested try statements with an example. [L2][CO3] [6M]
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
} ....
Example
class Excep6
{
public static void main(String args[])
{
try
{
try
{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e){System.out.println(e);
}
try
{
int a[]=new int[5];
Course Code: 20CS0506 R20

a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e){System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handeled");
}
System.out.println("normal flow..");
}
}
b) What are Java’s Built-in Exception? Write the importance of finally [L1][CO3] [6M]
block.

FINALLY
A finally block contains all the crucial statements that must be executed
whether exception occurs or not. The statements present in this block
will always execute regardless of whether exception occurs in try block
or not such as closing a connection, stream etc.
Syntax of Finally block
try {
//Statements that may cause an exception
}
catch
{
//Handling exception
}
Finally
{
//Statements to be executed
}
A Simple Example of finally block
Here you can see that the exception occurred in try block which has
been handled in catch block, after that finally block got executed.
class Example
{
Course Code: 20CS0506 R20

public static void main(String args[])


{
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block */

finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}}
Output:
Number should not be divided by zero
This is finally block
Out of try-catch-finally
Few Important points regarding finally block
1. A finally block must be associated with a try block, you cannot use
finally without a try block. You should place those statements in this
block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a
try-catch block is sufficient for exception handling, however if you
place a finally block then it will always run after the execution of try
block.
3. In normal case when there is no exception in try block then the
finally block is executed after try block. However if an exception
occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other
exception.
5. The statements present in the finally block execute even if the try
block contains control transfer statements like return, break or continue.

Cases when the finally block doesn’t execute


The circumstances that prevent execution of the code in a finally block
are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.
4 a) Show about creating your own Exception clauses [L2][CO3] [5M]
Java exceptions cover almost all the general types of exceptions that
may occur in the programming. However, we sometimes need to create
custom exceptions.
Following are a few of the reasons to use custom exceptions:
 To catch and provide specific treatment to a subset of existing Java
exceptions.
 Business logic exceptions: These are the exceptions related to
business logic and workflow. It is useful for the application users or the
developers to understand the exact problem.
Course Code: 20CS0506 R20

In order to create a custom exception, we need to extend the Exception


class that belongs to java.lang package.
Example:
class InvalidAgeException extends Exception
{
InvalidAgeException (String s)
{
super (s);
}
}
class TestCustomException
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException (“not valid”);
else
System.out.println(“welcome to vote”);
}
public static void main(String args [])
{
try
{
Validate(13)
}catch(Exception m)
{
System.out.println(“Exception occurred:”+m);
}
System.out.println(“rest of the code…”);
}
}
b) Develop a java program to create own exception for Negative Value [L6][CO3] [7M]
Exception if the user enters negative value.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class MyException extends Exception
{
public MyException(String str)
{
System.out.println(str);
}
}
public class SignException
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader (new
InputStreamReader(System.in));
System.out.print(“Input number:”);
try
{
Course Code: 20CS0506 R20

int num=Integer.parseInt(br.readLine());
if(num<0)
throw new MyException (“Number is negative”);
else
throw new MyException (“Number is positive”);
}
catch(MyException m)
{
System.out.println(m);
}
}
}
5 a) State what is Multithreading? Illustrate the ways to create [L2][CO4] [6M]
multiple Threads in java.
In the most general sense, you create a thread by instantiating an object
of type Thread.
Java defines two ways in which this can be accomplished:
• You can implement the Runnable interface.

• You can extend the Thread class, itself.

The following two sections look at each method, in turn.


Implementing Runnable
The easiest way to create a thread is to create a class that implements
the Runnable interface. Runnable abstracts a unit of executable code.
You can construct a thread on any object that implements Runnable. To
implement Runnable, a class need only implement a single method
called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It
is important to understand that run( ) can call other methods, use other
classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate
an object of type Thread from within that class. Thread defines several
constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName)
After the new thread is created, it will not start running until you call its
start( )
method, which is declared within Thread.
In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.

public void run()


Course Code: 20CS0506 R20

{
Try
{
for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[ ] )
{
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Extending Thread
The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class. The extending class
must override the run( ) method, which is the entry point for the new
thread. It must also call start( ) to begin execution of the new thread.
Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread class NewThread


extends Thread

{
NewThread() {
// Create a new, second thread

super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread. public void run() {

try {
for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i);
Course Code: 20CS0506 R20

Thread.sleep(500);
}
} catch (InterruptedException e) { System.out.println("Child
interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread
{
public static void main(String args[])
{
new NewThread(); // create a new thread try
{
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
b) Sketch and explain Thread Life Cycle. [L3][CO4] [6M]
A thread goes through various stages in its life cycle. For example, a
thread is born, started, runs, and then dies. The following diagram
shows the complete life cycle of a thread.
Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It remains in
this state until the program starts the thread. It is also referred to as a
born thread.

Runnable − After a newly born thread is started, the thread becomes


runnable. A thread in this state is considered to be executing its task.

Waiting − Sometimes, a thread transitions to the waiting state while the


thread waits for another thread to perform a task. A thread transitions
back to the runnable state only when another thread signals the waiting
thread to continue executing.

Timed Waiting − A runnable thread can enter the timed waiting state
for a specified interval of time. A thread in this state transitions back to
the runnable state when that time interval expires or when the event it is
Course Code: 20CS0506 R20

waiting for occurs.

Terminated (Dead) − A runnable thread enters the terminated state


when it completes its task or otherwise terminates.

6 a) Discriminate what is Daemon Threads and its implementation with an [L5][CO4] [6M]
example.
Daemon thread is a low priority thread (in context of JVM) that runs
in background to perform tasks such as garbage collection (gc) etc.
public class DaemonThreadExample1 extends Thread
{
public void run()
{
// Checking whether the thread is Daemon or not
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread executing");
}
else
{
System.out.println("user(normal) thread executing");
}
}
public static void main(String[] args)
{
/* Creating two threads: by default they are * user threads (non-daemon
threads) */
DaemonThreadExample1 t1=new DaemonThreadExample1();
DaemonThreadExample1 t2=new DaemonThreadExample1();
//Making user thread t1 to Daemon
t1.setDaemon(true);
//starting both the threads
t1.start();
t2.start();
}
}
public class DaemonThreadEx2 extends Thread
{
public void run()
{
System.out.println("Thread is running");
}
public static void main(String[] args)
{
DaemonThreadEx2 t1=new DaemonThreadEx2();
t1.start();
// It will throw IllegalThreadStateException
t1.setDaemon(true);
}
}
b) Apply join () method in multithreading java program to show its usage [L3][CO4] [6M]

Join() : When the join() method is called, the current thread will simply
Course Code: 20CS0506 R20

wait until the thread it is joining with is no longer alive.Or we can say
the method that you will more commonly use to wait for a thread to
finish is called join( ).
This method waits until the thread on which it is called terminates. Its
name comes from the concept of the calling thread waiting until the
specified thread joins it.
Additional forms of join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to terminate.
Syntax :
final void join( ) throws InterruptedException
// Using join() to wait for threads to finish.

class NewThread implements Runnable


{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.

public void run() {


try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{
System.out.println(name + " interrupted.");
}
System.out.println(name + " exiting.");
}
}
class DemoJoin {
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
Course Code: 20CS0506 R20

} catch (InterruptedException e)
{ System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
7 a) Describe how to set the priority to threads? what are the different [L2][CO4] [6M]
ranges.
Each thread have a priority. Priorities are represented by a number
between 1 and 10. In most cases, thread schedular 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.
a thread‘s priority is used to decide when to switch from one running
thread to the next. This is called a context switch. The rules that
determine when a context switch takes place are simple:

A thread can voluntarily relinquish control. This is done by


explicitly yielding, sleeping, or blocking on pending I/O. In this
scenario, all other threads are examined, and the highest-priority thread
that is ready to run is given the CPU.

A thread can be preempted by a higher-priority thread. In this case,


a lower-priority thread that does not yield the processor is simply
preempted—no matter what it is doing— by a higher-priority thread.
Basically, as soon as a higher-priority thread wants to run, it does. This
is called preemptive multitasking.

3 constants defined in Thread class:


1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY

3. 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 of priority of a Thread:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name
is:"+Thread.currentThread().getName()); System.out.println("running
thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1(); TestMultiPriority1
m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
Course Code: 20CS0506 R20

m1.start();
m2.start();
}}
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

b) Write a java program to create two threads and execute simultaneously [L6][CO4] [6M]

class NewThread
implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.

public void run()


{
Try
{
for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo
{
public static void main(String args[ ] )
{
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--)
{
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
Course Code: 20CS0506 R20

}
}
8 a) Illustrate creating of Thread in Java. [L2][CO4] [5M]
// Create multiple threads.
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.

public void run()


{
try
{
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[])
{
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end

Thread.sleep(10000);
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Sample output from this program is shown here. (Your output may vary
based upon the specific execution environment.)
New thread: Thread[One,5,main]
Course Code: 20CS0506 R20

New thread: Thread[Two,5,main]


New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
b) Write a Java program that creates three threads. First thread displays [L6][CO4] [7M]
―Good Morning, every one second, the second thread displays Hello,
every two seconds and the third thread displays Welcome every three
seconds.
class GoodMorning extends Thread {
synchronized public void run() {
try {
int i=0;
while (i<5) {
sleep(1000);
System.out.println("Good morning ");
i++;
}
} catch (Exception e) {
}
}
}
class Hello extends Thread {
synchronized public void run() {
try {
int i=0;
while (i<5) {
sleep(2000);
System.out.println("hello");
i++;
}
} catch (Exception e) {
}
}
}
class Welcome extends Thread {
synchronized public void run() {
try {
int i=0;
while (i<5) {
sleep(3000);
System.out.println("welcome");
i++;
}
} catch (Exception e) {
Course Code: 20CS0506 R20

}
}
}
class MultithreadDemo {
public static void main(String args[]) {
GoodMorning t1 = new GoodMorning();
Hello t2 = new Hello();
Welcome t3 = new Welcome();
t1.start();
t2.start();
t3.start();
9 a) What is synchronization? How many types? Explain in detail. [L2][CO3] [6M]
When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at
a time. The process by which this is achieved is called synchronization.
Key to synchronization is the concept of the monitor. A monitor is an
object that is used as a mutually exclusive lock. Only one thread can
own a monitor at a given time. When a thread acquires a lock, it is said
to have entered the monitor. All other threads attempting to enter the
locked monitor will be suspended until the first thread exits the
monitor. These other threads are said to be waiting for the monitor. A
thread that owns a monitor can reenter the same monitor if it so desires.
1.Using Synchronized Methods
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end

try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e) { System.out.println("Interrupted");
}
Course Code: 20CS0506 R20

}
}
Here is the output produced by this program:
Hello[Synchronized[World]
2.The synchronized Statement
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized

}
// This program uses a synchronized block.

class Callme {
void call(String msg)
{
System.out.print("[" + msg);
Try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s)
{
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()

public void run()


{
synchronized(target)
{
// synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[])
{
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Course Code: 20CS0506 R20

Caller ob2 = new Caller(target, "Synchronized");


Caller ob3 = new Caller(target, "World");
// wait for threads to end

try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e)
{
System.out.println("Interrupted");
}
}
}
b) Write a java program to sort the given names into ascending order. [L3][CO4] [6M]
class Sorting
{
void sortStrings()
{
Scanner s = new Scanner(System.in);
System.out.println("Enter the value of n: ");
int n = s.nextInt();
String[] str = new String[n];
System.out.println("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String(s.next());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
System.out.println(str[i]);
}
}
}
class Driver
{
public static void main(String[] args)
{
Sorting obj = new Sorting();
obj.sortStrings();
Course Code: 20CS0506 R20

}
}
10 a) Define String? Write the difference between String and String Buffer [L4][CO4] [6M]
classes.
In Java, a string is an object that represents a sequence of characters or
char values. The java.lang.String class is used to create a Java string
object.

No. String StringBuffer


1) The String class is The StringBuffer
immutable. class is mutable.
2) String is slow and StringBuffer is fast
consumes more and consumes less
memory when we memory when we
concatenate too many concatenate t strings.
strings because every
time it creates new
instance.
3) String class overrides StringBuffer class
the equals() method doesn't override the
of Object class. So equals() method of
you can compare the Object class.
contents of two
strings by equals()
method.
4) String class is slower StringBuffer class is
while performing faster while
concatenation performing
operation. concatenation
operation.
5) String class uses StringBuffer uses
String constant pool. Heap memory

b) Create a java program to check the given string is palindrome or not. [L6][CO4] [6M]
public class Palindrome
{
public static void main(String args[])
{
String a, b = "";
Scanner s = new Scanner(System.in);
System.out.print("Enter the string you want to check:");
a = s.nextLine();
int n = a.length();
for(int i = n - 1; i >= 0; i--)
{
b = b + a.charAt(i);
}
if(a.equalsIgnoreCase(b))
{
System.out.println("The string is palindrome.");
}
else
{
System.out.println("The string is not palindrome."); } } }
Course Code: 20CS0506 R20

Output:
Enter the string you want to check: NeveroddoreveN
Course Code: 20CS0506 R20

UNIT IV
GENERICS & INTRODUCING FILE HANDLING

1 a) Define Generics. State the importance of generics in java [L1][CO2] [4M]

Generics means parameterized types. The idea is to allow type (Integer,


String, etc., and user-defined types) to be a parameter to methods,
classes, and interfaces.
Using Generics, it is possible to create classes that work with different
data types.
An entity such as class, interface, or method that operates on a
parameterized type is called generic entity.
Object is the superclass of all other classes and Object reference can
refer to any type object. These features lack type safety. Generics adds
that type safety feature.
// A Simple Java program to show working of user defined Generic
classes

// We use < > to specify Parameter type

class Test<T>
{
// An object of type T is declared T obj;

Test(T obj)
{
this.obj = obj;
} // constructor
public T getObject()
{
return this.obj;
}
}
// Driver class to test above class Main

{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println (iObj.getObject ());
// instance of String type
Test <String> sObj = new Test<String>("siva"); System.out.println
(sObj.getObject ());
}
}
Output:
15 siva
b) Demonstrate the implementation of Generics in java with an [L2][CO2] [8M]
example program.

A Simple Java program to show working of user defined Generic classes


Course Code: 20CS0506 R20
// We use < > to specify Parameter type
class Test<T>
{
// An object of type T is declared T obj;

Test(T obj)
{
this.obj = obj;
} // constructor
public T getObject()
{
return this.obj;
}
}
// Driver class to test above class Main

{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(15);
System.out.println (iObj.getObject ());
// instance of String type
Test <String> sObj = new Test<String>("siva"); System.out.println
(sObj.getObject ());
}
}
Output:
15
siva
2 Illustrate General form of Generic class with an example. [L2][CO2] [12M]
A generic class declaration looks like a non-generic class declaration,
except that the class name is followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can
have one or more type parameters separated by commas. These classes are
known as parameterized classes or parameterized types because they accept
one or more parameters.
Example
Following example illustrates how we can define a generic class –
// A Simple Java program to show multiple

// type parameters in Java Generics

// We use < > to specify Parameter type

class Test<T, U>


{
T obj1; // An object of type T
U obj2; // An object of type U
// constructor Test(T obj1, U obj2)

{
this.obj1 = obj1;
this.obj2 = obj2;
}
// To print objects of T and
public void print()
{
Course Code: 20CS0506 R20
System.out.println(obj1);
System.out.println(obj2);
}
}
//Driver class
{
Public class void main(String args[])
{
Test <String, Integer> obj = new Test <String, Integer>(“siva”,15);
Obj.print();
}}
Output
Siva
15
3 a) List and describe about collection class in java. [L2][CO2] [6M]
Java provides a set of standard collection classes that implement Collection
interfaces. Some of the classes provide full implementations that can be used
as-is and others are abstract class, providing skeletal implementations that are
used as starting points for creating concrete collections

Sr. Class &


No. Description

1 AbstractCollection
Implements most of the Collection interface.

2 AbstractList
Extends AbstractCollection and implements
most of the List interface.
3 AbstractSequentialList
Extends AbstractList for use by a collection
that uses sequential rather than
random access of its elements.

4 LinkedList
Implements a linked list by extending
AbstractSequentialList.
5 ArrayList
Implements a dynamic array by extending
AbstractList.
6 AbstractSet Extends AbstractCollection and
implements most of the Set interface

7 HashSet
Extends AbstractSet for use with a hash table.

8 LinkedHashSet
Extends HashSet to allow insertion-order iterations.

9 TreeSet
Implements a set stored in a tree. Extends AbstractSet.

10 AbstractMap
Implements most of the Map interface.
Course Code: 20CS0506 R20
11 HashMap
Extends AbstractMap to use a hash table.

12 TreeMap
Extends AbstractMap to use a tree.

13 WeakHashMap
Extends AbstractMap to use a hash table with weak keys.

14 LinkedHashMap
Extends HashMap to allow insertion-order iterations.

15 IdentityHashMap
Extends AbstractMap and uses reference equality when comparing
documents.

b) Implement the following concepts with java programs [L4][CO6] [6M]


a) Array list b) Tree Set c) Linked HashMap
a)Array List
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
// ArrayList
List a1 = new ArrayList(); a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements"); System.out.print("\t" + a1);
}
}

b) TreeSet
import java.util.*;

// Main class class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating a Set interface with reference to
// TreeSet
Set<String> ts1 = new TreeSet<>();

// Elements are added using add() method ts1.add("A");


ts1.add("B");

ts1.add("C");

// Duplicates will not get insert ts1.add("C");


Course Code: 20CS0506 R20
// Elements get stored in default natural
// Sorting Order(Ascending) System.out.println(ts1);
}
}

C) LinkedHashMap
import java.util.*;

public class CollectionsDemo


{
public static void main(String[] args)
{
Map m1 = new HashMap(); m1.put("Zara", "8");
m1.put("Mahnaz", "31");
m1.put("Ayan", "12");
m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map
Elements");
System.out.print("\t" + m1); } }

4 a) Discuss in detail on collection interfaces and their methods [L2][CO6] [6M]

Sr.No. Interface & Description

1 The Collection Interface


This enables you to work with groups of objects; it is at the top of
the collection hierarchy

2 The List Interface


This extends Collection and an instance of List stores an ordered
collection of elements

3 The Set
This extends Collection to handle sets, which must contain unique
elements.

4 The SortedSet
This extends Set to handle sorted sets.

5 The Map
This maps unique keys to values.

6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of map

7 The SortedMap
This extends Map so that the keys are maintained in an ascending
order.
Course Code: 20CS0506 R20
8 The Enumeration
This is legacy interface defines the methods by which you can
enumerate the elements in a collection of objects.
(obtain one at a time) This legacy interface has been superceded by
Iterator.

Method & Description


1 boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj was added to the
collection. Returns false if obj is already a member of the collection, or if the
collection does not allow duplicates.
2 boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the
operation succeeds (i.e., the elements were added). Otherwise, returns false.

3 void clear( )
Removes all elements from the invoking collection.

4 boolean contains(Object obj)


Returns true if obj is an element of the invoking collection. Otherwise,
returns false.
5 boolean containsAll(Collection c)

Returns true if the invoking collection contains all elements of c.


Otherwise

6 boolean equals(Object obj)


Returns true if the invoking collection and obj are equal. Otherwise, returns
false.

7 int hashCode( )
Returns the hash code for the invoking collection.

8 boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.

9 Iterator iterator( )
Returns an iterator for the invoking collection.

10 boolean remove(Object obj)


Removes one instance of obj from the invoking collection. Returns true
the
element was removed. Otherwise, returns false.

11 boolean removeAll(Collection c)
Removes all elements of c from the invoking collection. Returns true if the
collection changed (i.e., elements were removed). Otherwise, returns false.
b) Apply the following interfaces with java programs [L3][CO6] [6M]
a) The Collection Interface b) The Set c) The Map.Entry

a) The Collection Interface


import java.util.*;
public class CollectionsDemo {
Course Code: 20CS0506 R20
public static void main(String[] args) { List l1 = new LinkedList();
l1.add("Zara");
l1.add("Mahnaz");

l1.add("Ayan"); System.out.println();
System.out.println(" LinkedList Elements"); System.out.print("\t" + l1);
b).The Set
import java.util.*;

// Main class public class GFG {

// Main driver method


public static void main(String[] args)
{
// Demonstrating Set using HashSet
// Declaring object of type String
Set<String> hash_Set = new HashSet<String>();

// Adding elements to the Set


// using add() method hash_Set.add("Geeks"); hash_Set.add("For");
hash_Set.add("Geeks"); hash_Set.add("Example");
hash_Set.add("Set");

// Printing elements of HashSet object System.out.println(hash_Set);


}
}
c)The Map.Entry

import java.util.*;

// Main class public class GFG {

// Main driver method


public static void main(String[] args)
{

Map m1 = new HashMap(); m1.put("Zara", "8");


m1.put("Mahnaz", "31");

m1.put("Ayan", "12");

m1.put("Daisy", "14"); System.out.println(); System.out.println(" Map


Elements"); System.out.print("\t" + m1);
}

}
5 Create program illustrating following framework. [L6][CO6] [12M]
a)Vector
b) Array List
c) Hash Table
Course Code: 20CS0506 R20
d)Stack
import java.util.Iterator; import java.util.Vector;

class Main {
public static void main(String[] args) { Vector<String>
animals= new Vector<>(); animals.add("Dog");
animals.add("Horse"); animals.add("Cat");
// Using get()
String element = animals.get(2); System.out.println("Element
at index 2: " + element);

// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: "); while(iterate.hasNext()) {
System.out.print(iterate.next()); System.out.print(", ");
}
}
}
b)Array List
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
// ArrayList
List a1 = new ArrayList(); a1.add("Zara");
a1.add("Mahnaz");
a1.add("Ayan");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
}
}
C)Hsah Table
import java.util.*;
public class CollectionsDemo { public static void
main(String[] args)
{
Set s1 = new HashSet(); s1.add("Zara");
s1.add("Mahnaz");
s1.add("Ayan"); System.out.println();
System.out.println(" Set Elements");
System.out.print("\t" + s1);
}
}
d)Stack
import java.util.Stack;
public class StackEmptyMethodExample
Course Code: 20CS0506 R20
{
public static void main(String[] args)
{
//creating an instance of Stack class Stack<Integer>
stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty(); System.out.println("Is the
stack empty? " + result);
// pushing elements into stack stk.push(78);
stk.push(113); stk.push(90); stk.push(120);

//prints elements of the stack


System.out.println("Elements in Stack: " + stk); result =
stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
6 Illustrate file handling using File class. [L3][CO4] [12M]
File handling in Java implies reading from and writing data to a
file. The File class from the java.io package, allows us to work with
different formats of files. In order to use the File class, you need to
create an object of the class and specify the filename or directory
name.

For example:

import java.io.File

File obj = new File("filename.txt");


1. Create a File

2. Get File Information

3. Write To a File

4. Read from a File

Now, let‘s get into the details of each of these operations


1. CREATE A FILE

In this case, to create a file you can use the createNewFile() method.
This method returns true if the file was successfully created, and false if
the file already exists. package FileHandling;

// Import the File class import java.io.File;

// Import the IOException class to handle errors import


java.io.IOException;

public class CreateFile {

public static void main(String[] args) { try {


Course Code: 20CS0506 R20
// Creating an object of a file

File myObj = new File("D:FileHandlingNewFilef1.txt"); if


(myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

Output:

File created: NewFilef1.txt

2. GET FILE INFORMATION

Let‘s see how to get file information using various methods with the
help of below example code

package FileHandling;

import java.io.File; // Import the File class public class FileInformation


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

// Creating an object of a file

File myObj = new File("NewFilef1.txt"); if (myObj.exists()) {


// Returning the file name

System.out.println("File name: " + myObj.getName());

// Returning the path of the file

System.out.println("Absolute path: " + myObj.getAbsolutePath());

// Displaying whether the file is writable System.out.println("Writeable:


" + myObj.canWrite());

// Displaying whether the file is readable or not


System.out.println("Readable " + myObj.canRead());

// Returning the length of the file in bytes System.out.println("File size


in bytes " + myObj.length()); } else {
Course Code: 20CS0506 R20
System.out.println("The file does not exist.");

Output:

File name: NewFilef1.txt

Absolute path: D:FileHandlingNewFilef1.txt Writable: true


Readable true

File size in bytes 52

3. WRITE TO A FILE

In the following example, I have used the FileWriter class together with
its write() method to write some text into the file. Let‘s understand this
with the help of a code.

package FileHandling;

// Import the FileWriter class import java.io.FileWriter;

// Import the IOException class to handle errors import


java.io.IOException;

public class WriteToFile {

public static void main(String[] args) { try {


FileWriter myWriter = new
FileWriter("D:FileHandlingNewFilef1.txt"); // Writes this content into
the specified file
myWriter.write(Java is the prominent programming language of the
millenium!");

// Closing is necessary to retrieve the resources allocated


myWriter.close(); System.out.println("Successfully wrote to the file.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

}
4. READ FROM A FILE

In the following example, I have used the Scanner class to read the
contents of the text file. package FileHandling;
// Import the File class import java.io.File;

// Import this class to handle errors import


java.io.FileNotFoundException;
Course Code: 20CS0506 R20
// Import the Scanner class to read text files import java.util.Scanner;

public class ReadFromFile {

public static void main(String[] args) { try {


// Creating an object of the file for reading the data File myObj = new
File("D:FileHandlingNewFilef1.txt"); Scanner myReader = new
Scanner(myObj);

while (myReader.hasNextLine()) { String data = myReader.nextLine();


System.out.println(data);
}

myReader.close();

} catch (FileNotFoundException e) { System.out.println("An error


occurred."); e.printStackTrace();

Output:

Java is the prominent programming language of the millennium!

7 a) Develop a java Program to read from a file using File Reader class? [L6][CO4] [8M]
// Import the File class import java.io.File;

// Import this class to handle errors import


java.io.FileNotFoundException;

// Import the Scanner class to read text files import java.util.Scanner;

public class ReadFromFile {

public static void main(String[] args) { try {


// Creating an object of the file for reading the data File myObj = new
File("D:FileHandlingNewFilef1.txt"); Scanner myReader = new
Scanner(myObj);

while (myReader.hasNextLine()) { String data = myReader.nextLine();


System.out.println(data);
}

myReader.close();

} catch (FileNotFoundException e) { System.out.println("An error


occurred."); e.printStackTrace();

}
Course Code: 20CS0506 R20
}

Output:

Java is the prominent programming language of the millennium!


b) Explain File operations in java? [L2][CO4] [4M]
1. CREATE A FILE

In this case, to create a file you can use the createNewFile() method.
This method returns true if the file was successfully created, and false if
the file already exists. package FileHandling;

// Import the File class import java.io.File;

// Import the IOException class to handle errors import


java.io.IOException;

public class CreateFile {

public static void main(String[] args) { try {


// Creating an object of a file

File myObj = new File("D:FileHandlingNewFilef1.txt"); if


(myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

Output:

File created: NewFilef1.txt

2. GET FILE INFORMATION

Let‘s see how to get file information using various methods with the
help of below example code

package FileHandling;

import java.io.File; // Import the File class public class FileInformation


{
public static void main(String[] args) {
Course Code: 20CS0506 R20
// Creating an object of a file

File myObj = new File("NewFilef1.txt"); if (myObj.exists()) {


// Returning the file name

System.out.println("File name: " + myObj.getName());

// Returning the path of the file

System.out.println("Absolute path: " + myObj.getAbsolutePath());

// Displaying whether the file is writable System.out.println("Writeable:


" + myObj.canWrite());

// Displaying whether the file is readable or not


System.out.println("Readable " + myObj.canRead());

// Returning the length of the file in bytes System.out.println("File size


in bytes " + myObj.length()); } else {

System.out.println("The file does not exist.");

Output:

File name: NewFilef1.txt

Absolute path: D:FileHandlingNewFilef1.txt Writable: true


Readable true

File size in bytes 52

3. WRITE TO A FILE

In the following example, I have used the FileWriter class together with
its write() method to write some text into the file. Let‘s understand this
with the help of a code.

package FileHandling;

// Import the FileWriter class import java.io.FileWriter;

// Import the IOException class to handle errors import


java.io.IOException;

public class WriteToFile {

public static void main(String[] args) { try {


FileWriter myWriter = new
FileWriter("D:FileHandlingNewFilef1.txt"); // Writes this content into
Course Code: 20CS0506 R20
the specified file
myWriter.write(Java is the prominent programming language of the
millenium!");

// Closing is necessary to retrieve the resources allocated


myWriter.close(); System.out.println("Successfully wrote to the file.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

}
4. READ FROM A FILE

In the following example, I have used the Scanner class to read the
contents of the text file. package FileHandling;
// Import the File class import java.io.File;

// Import this class to handle errors import


java.io.FileNotFoundException;

// Import the Scanner class to read text files import java.util.Scanner;

public class ReadFromFile {

public static void main(String[] args) { try {


// Creating an object of the file for reading the data File myObj = new
File("D:FileHandlingNewFilef1.txt"); Scanner myReader = new
Scanner(myObj);

while (myReader.hasNextLine()) { String data = myReader.nextLine();


System.out.println(data);
}

myReader.close();

} catch (FileNotFoundException e) { System.out.println("An error


occurred."); e.printStackTrace();

Output:

Java is the prominent programming language of the millennium!

8 Describe in detail about various stream classes in java. [L2][CO4] [12M]


Java performs I/O through Streams. A Stream is
linked to a physical layer by java I/O system to
make input and output operation in java. In
general, a stream means continuous flow of data.
Streams are clean way to deal with input/output
Course Code: 20CS0506 R20
without having every part of your code
understand the physical.

Java encapsulates Stream under java.io package. Java defines two


types of streams. They are,

1. Byte Stream : It provides a convenient means for handling


input and output of byte.

2. Character Stream : It provides a


convenient means for handling input and
output of characters. Character stream uses
Unicode and therefore can be
internationalized.

Byte Stream

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStrea Used for Buffered Output Stream.


m

DataInputStream Contains method for reading java standard datatype

DataOutputStream An output stream that contain method for writing java standard
data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

OutputStream Abstract class that describe stream output.

PrintStream Output Stream that contain print() and println() method

Java Character Stream Classes


Course Code: 20CS0506 R20

Character stream is also defined by using


two abstract class at the top of hierarchy,
they are Reader and Writer.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

InputStreamReader Input stream that translate byte to character

OutputStreamReader Output stream that translate character to byte.

PrintWriter Output Stream that contain print() and println() method.

Reader Abstract class that define character stream input

Writer Abstract class that define character stream output

9 Discuss about the File Input Stream and File Output Stream in java [L2][CO4] [12M]
with examples.
package com.javatpoint;
import java.io.*;
Course Code: 20CS0506 R20
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
10. }
11. }

10 a) Interpret how to create a file in java with example program. [L3][CO4] [6M]
Create a File
import java.io.File;

// Import the IOException class to handle errors import


// java.io.IOException; public class CreateFile {
public static void main(String[] args) { try {
// Creating an object of a file

File myObj = new File("D:FileHandlingNewFilef1.txt"); if


(myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());

} else {

System.out.println("File already exists.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

Output:

File created: NewFilef1.txt


b) Develop a java program to show Read and Write a file in java with an [L6][CO4] [6M]
example program.
READ FROM A FILE

In the following example, I have used the Scanner class to read the
contents of the text file. package FileHandling;
// Import the File class import java.io.File;

// Import this class to handle errors import


java.io.FileNotFoundException;
Course Code: 20CS0506 R20
// Import the Scanner class to read text files import java.util.Scanner;

public class ReadFromFile {

public static void main(String[] args) { try {


// Creating an object of the file for reading the data File myObj = new
File("D:FileHandlingNewFilef1.txt"); Scanner myReader = new
Scanner(myObj);

while (myReader.hasNextLine()) { String data = myReader.nextLine();


System.out.println(data);
}

myReader.close();

} catch (FileNotFoundException e) { System.out.println("An error


occurred."); e.printStackTrace();

}}}
Output:
Java is the prominent programming language of the millennium!
WRITE TO A FILE
// Import the FileWriter class import java.io.FileWriter;

// Import the IOException class to handle errors import


java.io.IOException;
public class WriteToFile {
public static void main(String[] args) { try {
FileWriter myWriter = new
FileWriter("D:FileHandlingNewFilef1.txt"); // Writes this content into
the specified file
myWriter.write(Java is the prominent programming language of the
millenium!");

// Closing is necessary to retrieve the resources allocated


myWriter.close(); System.out.println("Successfully wrote to the file.");

} catch (IOException e) { System.out.println("An error occurred.");


e.printStackTrace();

UNIT-V
INTRODUCING THE AWT & JAVA8 FEATURES

1 Develop a java Program to design Simple Registration page window [L6][CO5] [12M]
Course Code: 20CS0506 R20
using AWT Controls.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class loginform extends Frame implements ActionListener
{
Label l1=new Label("User name : ");//OBJECT CREATE
Label l2=new Label("Surname : ");//OBJECT CREATE
Label l3=new Label(" ");//OBJECT CREATE
TextField t1=new TextField();//OBJECT CREATE
TextField t2=new TextField();//OBJECT CREATE
Button b=new Button("submit");//OBJECT CREATE
public loginform()
{
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);
l1.setBounds(20,45,70,20);//set co-ordinates
t1.setBounds(180,45,200,20);
l2.setBounds(20,95,70,20);
t2.setBounds(180,95,200,20);
b.setBounds(150,150,100,50);
b.addActionListener(this);
addWindowListener(new A());
}
public void actionPerformed(ActionEvent e)
{
l3.setText("SUBMITTED "+t1.getText());
}
public static void main(String s[])
{
loginform l=new loginform();
l.setSize(new Dimension(400,400));
l.setTitle("Login");
l.setVisible(true);
}//end of main
}//end of class loginform
class A extends WindowAdapter
{
public A(){}
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}//end of class A
Course Code: 20CS0506 R20

2 Apply an AWT based calculator with basic operations using java. [L3][CO5] [12M]

import java.awt.*;
import java.awt.event.*;
class Calculator implements ActionListener
{
//Declaring Objects
Frame f=new Frame();
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("Add");
Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
Button b5=new Button("Cancel");
Calculator()
{
//Giving Coordinates
l1.setBounds(50,100,100,20);
l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);
//Adding components to the frame
f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
Course Code: 20CS0506 R20
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}
}
public static void main(String...s)
{
new Calculator();
}
}

3 a) State the features of swing in java. [L1][CO5] [4M]


1. Platform Independent: It is platform-independent; the swing components that
are used to build the program are not platform-specific. It can be used on any
platform and anywhere.
2. Lightweight: Swing components are lightweight, which helps in creating the
UI lighter. The swings component allows it to plug into the operating system
user interface framework that includes the mappings for screens or devices and
other user interactions like keypress and mouse movements.
3. Plugging: It has a powerful component that can be extended to provide
support for the user interface that helps in a good look and feel to the
application. It refers to the highly modular-based architecture that allows it to
plug into other customized implementations and frameworks for user
interfaces. Its components are imported through a package called java.swing.
Course Code: 20CS0506 R20
4. Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time as well. The
uniform changes can be provided to the user interface without doing any
changes to the application code.
5. MVC: They mainly follow the concept of MVC that is the Model View
Controller. With the help of this, we can do the changes in one component
without impacting or touching other components. It is known as loosely
coupled architecture as well.
6. Customizable: Swing controls can be easily customized. It can be changed,
and the visual appearance of the swing component application is independent
of its internal representation.
b) Difference between AWT and SWING [L4][CO5] [8M]
S.NO AWT Swing
1. Java AWT is an API to Swing is a part of Java Foundation Classes and is used to create
develop GUI various applications.
applications in Java
2. The components of Java The components of Java Swing are light weighted.
AWT are heavy
weighted.
3. Java AWT has Java Swing has more functionality as compared to AWT.
comparatively less
functionality as
compared to Swing.
4. The execution time of The execution time of Swing is less than AWT.
AWT is more than
Swing.
5. The components of Java The components of Java Swing are platform independent.
AWT are platform
dependent.
6. MVC pattern is not MVC pattern is supported by Swing.
supported by AWT.
7. AWT provides Swing provides more powerful components.
comparatively less
powerful components.
4 Illustrate the steps for creating simple Login Page using java swing with [L3][CO5] [12M]
an example program.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginFrame extends JFrame implements ActionListener {
Container container=getContentPane();
JLabel userLabel=new JLabel("USERNAME");
JLabel passwordLabel=new JLabel("PASSWORD");
JTextField userTextField=new JTextField();
JPasswordField passwordField=new JPasswordField();
JButton loginButton=new JButton("LOGIN");
JButton resetButton=new JButton("RESET");
JCheckBox showPassword=new JCheckBox("Show Password");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
addActionEvent();//calling addActionEvent() method
}
public void setLayoutManager()
Course Code: 20CS0506 R20
{
container.setLayout(null);
}
public void setLocationAndSize()
{
userLabel.setBounds(50,150,100,30);
passwordLabel.setBounds(50,220,100,30);
userTextField.setBounds(150,150,150,30);
passwordField.setBounds(150,220,150,30);
showPassword.setBounds(150,250,150,30);
loginButton.setBounds(50,300,100,30);
resetButton.setBounds(200,300,100,30);
}
public void addComponentsToContainer()
{
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void addActionEvent()
{
//adding Action listener to components
loginButton.addActionListener(this);
resetButton.addActionListener(this);
showPassword.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
public class Login {
public static void main(String[] a){
LoginFrame frame=new LoginFrame();
frame.setTitle("Login Form");
frame.setVisible(true);
frame.setBounds(10,10,370,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
}
}
5 What is Swing? Discuss about Swing controls. [L2][CO5] [12M]
Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets
for building optimized window based applications. It is a part of the JFC( Java
Foundation Classes). It is build on top of the AWT API and entirely written in
java. It is platform independent unlike AWT and has lightweight components.
JButton Class
It is used to create a labelled button. Using the ActionListener it will result in
some action when the button is pushed. It inherits the AbstractButton class and
is platform independent.
Example:
import javax.swing.*;
public class example
{
public static void main(String args[])
Course Code: 20CS0506 R20
{
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
JTextField Class
It inherits the JTextComponent class and it is used to allow editing of single
line text.
Example:
import javax.swing.*;
public class example
{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible
JScrollBar Class
It is used to add scroll bar, both horizontal and vertical.
import javax.swing.*;
class example
{
example()
{
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true); }
public static void main(String args[])
{
new example();
JPanel Class
It inherits the JComponent class and provides space for an application which
can attach any
other component.
import java.awt.*;
import javax.swing.*;
public class Example
{
Example()
{
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
Course Code: 20CS0506 R20
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}}
JMenu Class
It inherits the JMenuItem class, and is a pull down menu component which is
displayed from the menu bar.
import javax.swing.*;
class Example
{
JMenu menu;
JMenuItem a1,a2;
Example()
{
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
JList Class
It inherits JComponent class, the object of JList class represents a list of text
items.
import javax.swing.*;
public class Example
{
Example()
{
JFrame a = new JFrame("example");
DefaultListModel<String> l = new DefaultListModel< >();
l.addElement("first item");
l.addElement("second item");
JList<String> b = new JList< >(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
Course Code: 20CS0506 R20
{
new Example();
}
}
JLabel Class
It is used for placing text in a container. It also inherits JComponent class.
import javax.swing.*;
public class Example
{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JLabel b1;
b1 = new JLabel("edureka");
b1.setBounds(40,40,90,20);
a.add(b1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}}
JComboBox Class
It inherits the JComponent class and is used to show pop up menu of choices.
import javax.swing.*;
public class Example
{
JFrame a;
Example()
{
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();}
6 a) State the importance of Lambda Expression with syntax [L1][CO5] [6M]
Lambda expressions are an anonymous function, meaning that they have no
name or identifier. They can be passed as a parameter to another function. They
are paired with a functional interface and feature a parameter with an
expression that references that parameter.
The syntax of a basic lambda expression is:
parameter -> expression
The expression is used as the code body for the abstract method (a named but
empty method) within the paired functional interface.
Unlike most functions in Java, lambda expressions exist outside of any object‘s
scope. This means they are callable anywhere in the program and can be passed
around. In the simplest terms, lambda expressions allow functions to behave
like just another piece of data.
lambda expressions are added in Java 8 and provide below functionalities.
Enable to treat functionality as a method argument, or code as data.
A function that can be created without belonging to any class.
A lambda expression can be passed around as if it was an object and executed
on demand.
Course Code: 20CS0506 R20
interface FuncInterface
{
An abstract function
void abstractFun(int x);
A non-abstract (or default) function
default void normalFun()
{
System.out.println("Hello");
}
}
class Test
{
public static void main(String args[])
{
abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);
This calls above lambda expression and prints 10. fobj.abstractFun(5);
b) Develop a java program to pass multiple parameters with Lambda [L6][CO5] [6M]
Expression
public class Test
{
interface FuncInter1
{
int operation(int a, int b);
}
interface FuncInter2
{
void sayMessage(String message);
}
private int operate(int a, int b, FuncInter1 fobj)
{
return fobj.operation(a, b);
}
public static void main(String args[])
{
interface FuncInter1 add = (int x, int y) -> x + y;
interface FuncInter1 multiply = (int x, int y) -> x * y;
Test tobj = new Test();
System.out.println("Addition is " + tobj.operate(6, 3, add));
System.out.println("Multiplication is " +tobj.operate(6, 3, multiply));
FuncInter2 fobj = message ->System.out.println("Hello")
fobj.sayMessage("Geek"); } }
7 List and Explain Java Method References with an example. [L2][CO5] [12M]
Java provides a new feature called method reference in Java 8. Method
reference is used to refer method of functional interface. It is compact and easy
form of lambda expression.
Each time when you are using lambda expression to just referring a method,
you can replace your lambda expression with method reference Types of
Method References
There are following types of method references in java:
Reference to a static method.
Reference to an instance method.
Reference to a constructor.
1)Reference to a static method:
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax
Course Code: 20CS0506 R20
ContainingClass::staticMethodName
Example 1
In the following example, we have defined a functional interface and referring
a static method to it's functional method say().
interface Sayable
{
void say();
}
public class MethodReference
{
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args)
{
Sayable sayable = MethodReference::saySomething;
sayable.say();
}
}
Output:
Hello, this is static method.
Example-2
import java.util.function.BiFunction;
class Arithmetic
{
public static int add(int a, int b)
{
return a+b;
}
}
public class MethodReference3
{
public static void main(String[] args)
{
BiFunction<Integer, Integer, Integer>adder = Arithmetic::add;
int result = adder.apply(10, 20);
System.out.println(result);
}
}
2) Reference to an Instance Method
like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
Syntax containingObject::instanceMethodName
Example 1
In the following example, we are referring non-static methods. You can refer
methods by class object and anonymous object.
interface Sayable
{
void say();
}
public class InstanceMethodReference
{
public void saySomething()
{
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args)
{
Course Code: 20CS0506 R20
InstanceMethodReference methodReference = new
InstanceMethodReference();
Sayable sayable = methodReference::saySomething;
sayable.say();
Sayable sayable2 = new InstanceMethodReference()::saySomething;
sayable2.say();
}
}
Output: Hello, this is non-static method.
Hello, this is non-static method
3) Reference to a Constructor
You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.
Syntax ClassName::new
Example
interface Messageable
{
Message getMessage(String msg);
}
class Message
{
Message(String msg)
{
System.out.print(msg);
}
}
public class ConstructorReference
{
public static void main(String[] args)
{
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}
Output:
Hello
8 Explain the following methods in java. [L2][CO5] [12M]
a) Default method
b) Static method
c) forEach()method

DEFAULT METHOD
Java provides a facility to create default methods inside the interface. Methods
which are defined inside the interface and tagged with default are known as
default methods. These methods are non-abstract methods.
Java Default Method Example
In the following example, Sayable is a functional interface that contains a
default and an abstract method. The concept of default method is used to define
a method with default implementation. You can override default method also to
provide more specific implementation for the method.
interface Sayable{
Default method
default void say(){ System.out.println("Hello, this is default method");
}
Abstract method
void sayMore(String msg);
}
Course Code: 20CS0506 R20
public class DefaultMethods implements Sayable
{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args)
{
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method
}
}
Output:
Hello, this is default method
Work is worship
STATIC METHOD
You can also define static methods inside the interface. Static methods are used
to define utility
methods.
The following example explain, how to implement static method in interface?
interface Sayable
{
default method default void say()
{
System.out.println("Hello, this is default method");
}
Abstract method
void sayMore(String msg);
// static method
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable
{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args)
{
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method dm.sayMore("Work is worship"); // calling
abstract method Sayable.sayLouder("Helloooo..."); // calling static method
}
}
Output:
Hello there
Work is worship
Helloooo...
FOREACH() METHOD
Java provides a new method forEach() to iterate the elements. It is defined in
Iterable and Stream interface. It is a default method defined in the Iterable
interface. Collection classes which extends Iterable interface can use forEach
loop to iterate elements.
This method takes a single parameter which is a functional interface. So, you
can pass lambda expression as an argument.
forEach() Signature in Iterable Interface
default void forEach(Consumer<super T>action)
Course Code: 20CS0506 R20
import java.util.ArrayList;
import java.util.List;
public class ForEachExample
{
public static void main(String[] args)
{
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Hocky");Sys Iterating by passing lambda ");
tem.out.println("------------ expression--------------
9 a) Illustrate with an example to explain the similarities for method reference [L3][CO5] [6M]
operator and Lambda Expression
The double colon operator (::) introduced in java 8, also known as method
reference operator in java.
It is used to call a method by referring to it with the help of its class/instance.
They behave exactly as the lambda expressions.
The only difference it has from lambda expressions is that this uses direct
reference to the method by name instead of providing a delegate to the method.
1. Double Colon Operator and Lambda
Double colon operator (::) also a short hand for lambdas. Let‘s see a very
simple example that print list items.
Using Lambda:
List<String> list = List.of("Peter", "Thomas", "Edvard", "Gerhard");
// print using lambda
list.forEach(item -> System.out.println(item));
Using :: operator :
To concise code and readable, we used Lambda in above example. Java method
reference makes it even more shorter and readable.
print using :: (method reference operator) list.forEach(System.out::println);
To reference a method or to reference a constructor, we must use double colon
operator.
Following are the various scenarios where it can used.
Reference to static method.
Reference to an instance method of a particular object.
Reference to an instance method of an arbitrary object of a particular type
Reference to a Constructor
1.Reference to static method.
You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.
Syntax:
<target class name>::<static method name>
interface MyFunctionalInterface {
boolean isEvenNumber(int i);
}
public class MethodReferenceDemo {
static boolean myImplementation(int i) {
return i%2 == 0;
}
public static void main(String[] args) {
MyFunctionalInterface mi = MethodReferenceDemo::myImplementation;
System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi.isEvenNumb);
2. Reference to an instance method of a particular object.
Like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
Syntax:
<target class object>::<instance method>
Course Code: 20CS0506 R20
@FunctionalInterface
interface MyFunctionalInterface {
boolean isEvenNumber(int i);
}
public class MethodReferenceDemo {
//instance method
boolean myImplementation(int i) {
return i%2 == 0;
}
public static void main(String[] args) {
MethodReferenceDemo demo = new MethodReferenceDemo();
MyFunctionalInterface mi = demo::myImplementation;
MyFunctionalInterface mi2 = new
MethodReferenceDemo()::myImplementation;
System.out.println(mi.isEvenNumber(15));//false
System.out.println(mi2.isEvenNumber(20));//true
}
}
3. Reference to an instance method of an arbitrary object of a particular
type
Like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
Syntax:
<arbitary object type>::<instance method>
Look into the example, String::toUpperCase, usually toUpperCase() method is
called on a string reference but we have written class name ―String‖ as like
reference to static method. In the following example, String is particular type
and the arbitrary object is the instance of String that is used during method
invoke. When reference to an instance method of an arbitrary object of a
particular type, that invokes a method onto the current object.
@FunctionalInterface
interface MyFunctionalInterface {
String processString(String name);
}
public class MethodReferenceDemo {
public static void main(String[] args) {
MyFunctionalInterface f1 = s -> s.toUpperCase();
System.out.println(f1.processString("Peter")); // PETER
Above two lines equalant to following lines MyFunctionalInterface f2 =
String::toUpperCase; System.out.println(f2.processString("Peter")); // PETER
}
}
b) Describe Reference to an instance method of an arbitrary object of a [L2][CO5] [6M]
particular type
Like static methods, you can refer instance methods also. In the following
example, we are describing the process of referring the instance method.
Syntax:
<arbitary object type>::<instance method>
Look into the example, String::toUpperCase, usually toUpperCase() method is
called on a string reference but we have written class name ―String‖ as like
reference to static method. In the following example, String is particular type
and the arbitrary object is the instance of String that is used during method
invoke. When reference to an instance method of an arbitrary object of a
particular type, that invokes a method onto the current object.
@FunctionalInterface
interface MyFunctionalInterface {
String processString(String name);
Course Code: 20CS0506 R20
}
public class MethodReferenceDemo {
public static void main(String[] args) {
MyFunctionalInterface f1 = s -> s.toUpperCase();
System.out.println(f1.processString("Peter")); // PETER
Above two lines equalant to following lines MyFunctionalInterface f2 =
String::toUpperCase; System.out.println(f2.processString("Peter")); // PETER
}
}
10 a) Interpret the usage of Date and Time API with an example program. [L3][CO6] [8M]
Java 8 introduces a new date-time API under the package java.time. Following
are some of the important classes introduced in java.time package.
Local − Simplified date-time API with no complexity of timezone handling.
Zoned − Specialized date-time API to deal with various timezones.
Local Date-Time API
LocalDate/LocalTime and LocalDateTime classes simplify the development
where timezones are not required. Let's see them in action.
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
public class Java8Tester {
public static void main(String args[]) {
Java8Tester java8tester = new Java8Tester();
java8tester.testLocalDateTime();
}
public void testLocalDateTime() {
// Get the current date and time
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("Current DateTime: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("date1: " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("Month: " + month +"day: " + day +"seconds: " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date2: " + date2);
//12 december 2014
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date3: " + date3);
//22 hour 15 minutes
LocalTime date4 = LocalTime.of(22, 15);
System.out.println("date4: " + date4);
//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
}
Output:
F:\JAVA NOTES\programs> javac Java8Tester.java F:\JAVA NOTES\
programs> java Java8Tester C
urrent DateTime: 2021-05-01T14:46:14.350006500
date1: 2021-05-01
Month: MAY day: 1 seconds: 14
date2: 2012-05-10T14:46:14.350006500
date3: 2014-12-12
date4: 22:15
Course Code: 20CS0506 R20
date5: 20:15:30
Zoned Date-Time API
Zoned date-time API is to be used when time zone is to be considered. Let us
see them in action.
import java.time.ZonedDateTime;
import java.time.ZoneId;
public class Java8Tester {
public static void main(String args[]) {
Java8Tester java8tester = new Java8Tester();
java8tester.testZonedDateTime();
}
public void testZonedDateTime()
{
// Get the current date and time
ZonedDateTime date1 = ZonedDateTime.parse("2007-12-
03T10:15:30+05:30[Asia/Karachi]");
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("CurrentZone: " + currentZone);
}}
b) Discuss in detail the operations on Streams. [L2][CO6] [4M]
Stream Creation
There are many ways to create a stream instance of different sources. Once
created, the instance will not modify its source, therefore allowing the creation
of multiple instances from a single source.
Empty Stream
We should use the empty() method in case of the creation of an empty stream:
Stream<String> streamEmpty = Stream.empty();
We often use the empty() method upon creation to avoid returning null for
streams with no element:
public Stream<String> streamOf(List<String> list) {
return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}
Stream of Collection
We can also create a stream of any type of Collection (Collection, List, Set):
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> streamOfCollection = collection.stream();
Stream of Array
An array can also be the source of a stream:
Stream<String> streamOfArray = Stream.of("a", "b", "c");
We can also create a stream out of an existing array or of part of an array:
String[] arr = new String[]{"a", "b", "c"}; Stream<String> streamOfArrayFull
= Arrays.stream(arr); Stream<String> streamOfArrayPart = Arrays.stream(arr,
1, 3);
Stream.builder()
When builder is used, the desired type should be additionally specified in the
right part of the statement, otherwise the build() method will create an instance
of the Stream<Object>:
Stream.generate()
The generate() method accepts a Supplier<T> for element generation. As the
resulting stream is infinite, the developer should specify the desired size, or the
generate() method will work until it reaches the memory limit:
Stream<String> streamGenerated = Stream.generate(() ->
"element").limit(10);
Stream.iterate()
Another way of creating an infinite stream is by using the iterate() method:
Course Code: 20CS0506 R20
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20); The
first element of the resulting stream is the first parameter of the iterate()
method. When creating every following element, the specified function is
applied to the previous element. In the example above the second element will
be 42.
Stream of Primitives
Java 8 offers the possibility to create streams out of three primitive types: int,
long and double. As Stream<T> is a generic interface, and there is no way to
use primitives as a type parameter with generics, three new special interfaces
were created: IntStream, LongStream, DoubleStream.
Stream of String
We can also use String as a source for creating a stream with the help of the
chars() method of the String class. Since there is no interface for CharStream in
JDK, we use the IntStream to represent a stream of chars instead.
IntStream streamOfChars = "abc".chars();
The following example breaks a String into sub-strings according to specified
RegEx:
Stream<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b,
c");
Stream of File
Furthermore, Java NIO class Files allows us to generate a Stream<String> of a
text file through the lines() method. Every line of the text becomes an element
of the stream:
Path path = Paths.get("C:\\file.txt"); Stream<String> streamOfStrings =
Files.lines(path); Stream<String> streamWithCharset =
Files.lines(path, Charset.forName("UTF-8"));
The Charset can be specified as an argument of the lines() method.
Referencing a Stream
We can instantiate a stream, and have an accessible reference to it, as long as
only intermediate operations are called. Executing a terminal operation makes a
stream inaccessible.
To demonstrate this, we will forget for a while that the best practice is to chain
the sequence of operation. Besides its unnecessary verbosity, technically the
following code is valid:
Stream<String> stream = Stream.of("a", "b", "c").filter(element ->
element.contains("b")); Optional<String> anyElement = stream.findAny();
However, an attempt to reuse the same reference after calling the terminal
operation will trigger the IllegalStateException:
Optional<String> firstElement = stream.findFirst();
Stream Pipeline
To perform a sequence of operations over the elements of the data source and
aggregate their results, we need three parts: the source, intermediate
operation(s) and a terminal operation.
Intermediate operations return a new modified stream. For example, to create
a new stream of the existing one without few elements, the skip() method
should be used:

Prepared by

Mr. J.Jerin Jose


Associate Professor, Dept.of CSE

You might also like