OOPS (20CS0506) QB With Answers
OOPS (20CS0506) QB With Answers
UNIT-I
THE JAVA LANGUAGE & INTRODUCTION OF OOP
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.
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.
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
b) Show what is varargs in java? Write the syntax and develop a [L6][CO1] [6M]
Program showing the varargs usage.
// 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
'\u0000' 2 byte
Course Code: 20CS0506 R20
0 1 byte
short 0 2 byte
0 4 byte
0L 8 byte
0.0f 4 byte
import java.io.*;
}
}
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
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 = , += , -= , *= , /= , %= , ^=
Logical && , ||
Course Code: 20CS0506 R20
Ternary (Condition) ? (Statement1) :
(Statement2);
Bitwise &,|,^,~
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
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
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
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
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");
}
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
}
}
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();
}
}
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
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
UNIT III
EXCEPTION HANDLING & MULTITHREADED
PROGRAMMING
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]
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
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.
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.
{
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:
{
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.
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
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.
} 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:
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.
}
}
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.
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
}
}
}
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()
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.
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
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.
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
{
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
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) TreeSet
import java.util.*;
ts1.add("C");
C) LinkedHashMap
import java.util.*;
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.
3 void clear( )
Removes all elements from the invoking collection.
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.
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
l1.add("Ayan"); System.out.println();
System.out.println(" LinkedList Elements"); System.out.print("\t" + l1);
b).The Set
import java.util.*;
import java.util.*;
m1.put("Ayan", "12");
}
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);
For example:
import java.io.File
3. Write To 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;
} else {
Output:
Let‘s see how to get file information using various methods with the
help of below example code
package FileHandling;
Output:
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;
}
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;
myReader.close();
Output:
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;
myReader.close();
}
Course Code: 20CS0506 R20
}
Output:
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;
} else {
Output:
Let‘s see how to get file information using various methods with the
help of below example code
package FileHandling;
Output:
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;
}
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;
myReader.close();
Output:
Byte Stream
DataOutputStream An output stream that contain method for writing java standard
data type
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;
} else {
Output:
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;
myReader.close();
}}}
Output:
Java is the prominent programming language of the millennium!
WRITE TO A FILE
// Import the FileWriter class import java.io.FileWriter;
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();
}
}
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