0% found this document useful (0 votes)
2 views310 pages

Java

The document provides an overview of Java, detailing its history, features, and various editions such as J2ME, J2EE, and J2SE. It also explains key components like JVM, JRE, and JDK, and includes instructions for compiling and executing a basic Java program. Additionally, it discusses integrated development environments (IDEs) like NetBeans and Eclipse, and outlines Java data types.

Uploaded by

zakkisutar72
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views310 pages

Java

The document provides an overview of Java, detailing its history, features, and various editions such as J2ME, J2EE, and J2SE. It also explains key components like JVM, JRE, and JDK, and includes instructions for compiling and executing a basic Java program. Additionally, it discusses integrated development environments (IDEs) like NetBeans and Eclipse, and outlines Java data types.

Uploaded by

zakkisutar72
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.

(AFFILIATED TO SAURASHTRA UNIVERSITY)


2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

B.C.A./[Link]-SEMESTER-4
SUB :- JAVA

Shree [Link] College Shree [Link] College


Street No. 2, Vaishali Nagar, Street No. 3, Vaishali Nagar,
Nr. Amrapali Under Bridge, Nr. Amrapali Under Bridge,
Raiya Road, Rajkot. Raiya Road, Rajkot.
Ph. (0281)2440478, 2472590 Ph. (0281)2471645

1
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-1 Explain history and features of Java


Ans:
❖ Java is a programming language that:
1. Is exclusively object oriented
2. Has full GUI support
3. Has full network support
4. Is platform independent
5. Executes stand-alone or “on-demand” in web browser as
applets
Features:
1) Simple:
• Java inherits the C/C++ syntax and many of the object oriented features
of C++,
• Java supports OOP and does not support pointer which makes it
simpler.

2) Security:
• Java is best known for its security. With Java, we can develop virus-
free systems. Java is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

3) Portable:
• Java is portable because it facilitates you to carry the Java bytecode
to any platform. It doesn't require any implementation. It can be
implemented in any OS.

2
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

4) Object-Oriented:

• Object-oriented programming (OOPs) is a methodology that


simplifies software development and maintenance by providing some
rules.
• Basic concepts of OOPs are:

1) Object
2) Class
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation

5) Robust (Healthy, Strong):


• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java
Virtual Machine to get rid of objects which are not being used by a Java
application anymore.
• There are exception handling and the type checking mechanism in Java.
All these points make Java robust.

6) Multi-threaded:
• A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining

3
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

multiple threads. The main advantage of multi-threading is that it


doesn't occupy memory for each thread. It shares a common memory
area.

7) Architecture-neutral:
• Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
• In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

8) Interpreted:
• Usually a computer language is either compiled or interpreted. Java
combines these approaches thus making java a two-stage system.
• Java compiler translates source code into byte code instructions. Byte
codes are not machine instructions and so java interpreter generates
machine code that can be directly executed by the machine that is
running the java program.

9) High Performance:
• Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code.
• Java does not support pointer which increases the performance.

10) Distributed:
• Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications.

11) Dynamic:
• Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand.

4
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Which type of architecture java Neutral
supports?
2 Robust means……. Strong/healthy
3 Java is ………….programming OOP
language
4 Class and object are the concepts of OOP
…….

Q-2 Explain editions of Java


Ans:

1) Java Platform, Micro Edition (J2ME):

• Java ME, is designed for mobile phones (especially feature phones) and
set-top boxes. Java ME was formerly known as Java 2 Platform, Micro
Edition (J2ME).

5
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

• Java ME was designed by Sun Microsystems, acquired by Oracle


Corporation in 2010; the platform replaced a similar technology,
PersonalJava.

2) Java Platform, Enterprise Edition (J2EE):


❖ J2EE stands for Java 2 Platform, Enterprise Edition. J2EE is the
standard platform for developing applications in the enterprise and is
designed for enterprise applications that run on servers.

3) Java Platform, Standard Edition (J2SE):


❖ It has concepts for developing software for Desktop based (standalone)
CUI (command user interface) and GUI (graphical user interface)
applications, applets.

MCQ
Sr Question Answer
No.
1 J2ME stands for ……… Java 2 platform Micro
Edition
2 J2EE stands for ……… Java 2 platform Enterprise
Edition
3 J2SE stands for ……… Java 2 Platform Standard
Edition

Q-3 Write a short note on JVM, JRE and JDK


Ans:
JVM:
❖ JVM stands for Java Virtual Machine.
❖ All language compilers translate source code into machine code for a specific
computer. Java compiler also does the same thing.

6
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ Java compiler produces an intermediate code known as byte code for a machine
that does not exist.
❖ This machine is called the Java Virtual Machine and it exists only inside the
computer memory.

Java Program Java Compiler Virtual Machine


Process of Compilation

❖ The virtual machine code (Byte Code) is not machine specific.


❖ The machine specific code is generated by the Java Interpreter by acting as an
intermediary between the virtual machine and the real machine as shown in fig.
Interpreter is different for different machine.

JRE:
Process of converting Byte Code into Machine Code
Byte Code Java Interpreter Machine Code
Virtual Machine

❖ The Java Runtime Environment (JRE), also known as Java Runtime, is


part of the Java Development Kit (JDK), a set of programming tools for
developing Java applications. The Java Runtime Environment provides
the minimum requirements for executing a Java application; it consists of
the Java Virtual Machine (JVM), core classes, and supporting files.

JDK:

❖ JDK stands for Java Development Kit.


❖ It is a collection of tools which are used for developing and running the java
program.

Components:-
1) Applet viewer :- it used to view the java applets without using the browser.

7
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2) Javac :- the java compiler translate source code to byte code.


3) Java :- java interpreter runs the applets and application by reading the byte
code.
4) Javadoc: - it creates html format documentation from java source code.
5) Javah :- it produce header file.
6) Javap :- it enables to convert byte code into program description.
7) Jdb :- it is java debugger used for find errors from the programs.

MCQ
Sr Question Answer
No.
1 JVM stands for ……… Java Virtual Machine
2 JRE stands for ……… Java Runtime Environment
3 JDK stands for ……… Java Development Kit
4 What is javac? Compiler of java
5 Which component of jdk produce javah
header file?
6 Which component of jdk is used to java
execute or run the application?
7 Which component of jdk is used to jdb
find the errors from the program

Q-4 Write a short note on compiling and executing basic java program.
Ans:
class hello
{
public static void main(String args[])
{
[Link](“Hello”);
}
}

Steps:
Step 1: Save the program with .java extension (Note: Name of the program
must be same as the name of the class)

8
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Step 2: Open the command prompt and compile your program


javac [Link] (where [Link] is the name of your file)
Step 3: Execute/run the program
java hello
Output: hello
MCQ
Sr Question Answer
No.
1 The program of java should have Program name
the same name as …….
2 Java program should be saved with .java
…….extension

Q-5 Write a short note on java IDE


Ans:
IDE stands for Integrated Development Environment

Netbeans:

❖ NetBeans is an integrated development environment (IDE) for developing


primarily with Java, but also with other languages, in particular PHP,
C/C++, and HTML5 .It is also an application platform framework for Java
desktop applications and others.
❖ The NetBeans IDE is written in Java and can run on Windows, OS X,
Linux, Solaris and other platforms supporting a compatible JVM.
❖ The NetBeans Platform allows applications to be developed from a set of
modular software components called modules. Applications based on the

9
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

NetBeans Platform (including the NetBeans IDE itself) can be extended


by third party developers.
❖ NetBeans IDE is an open-source integrated development environment.
NetBeans IDE supports development of all Java application types (Java
SE (including JavaFX), Java ME, web, EJB and mobile applications).

Eclipse:

• Eclipse is an integrated development environment (IDE). It started in 2001,


when IBM released Eclipse into open source.
• It contains a base workspace and an extensible plug-in system for customizing
the environment.
• Eclipse can be used to develop applications in Java. By means of various plug-
ins, Eclipse may also be used to develop applications in other programming
languages: Ada, C, C++, COBOL, Fortran,

MCQ
Sr Question Answer
No.
1 IDE stands for Integrated Development
Environment
2 Which editors or platform are NetBeans and Eclipse
provided by java?

Q-6 Write a short note on data types in java

Ans:

10
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ Data type means the type of data.

Integer
❖ Java provides four integer types: byte, short, int, long.
❖ All of these are signed, positive and negative values.

Type Size/bits Range


Byte 8 -128 to 127
Short 16 -32,768 to 32,767
Int 32 -2,147,483,648 to 2,147,483,647

11
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Long 64 -9,223,372,036,854,775,808
9,223,372,036,854,775,807

Floating-Point Types
❖ Floating-Point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
❖ For example, calculations such as square root, or transcendental such as sine
and cosine, result in a value whose precision requires a floating-point type.
❖ There are two kinds of floating-point types, float and double, which
represent single and double-precision numbers, respectively.

Type Size/bytes Range


Float 32 1.4e – 045 to 3.4e + 038
Double 64 4.9e - 324 to 1.8e + 308

Character
❖ The data type used to store characters is char.

Type Size/bytes Range


Char 16 0 to 65,536

Boolean:
❖ Java has primitive type, called boolean, for logical values.
❖ It can have only one of two possible values, true or false.

Type Size/bytes Range


Boolean 1 True/False , Yes/No , 0/1

MCQ
Sr Question Answer
No.
1 short requires ……….bits 16 bits(2 byte)

12
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2 int requires ……………bits 32 bits (4 bytes)


3 Boolean data type can only the true, false
value either ………..or ……….
4 char requires ……. 16 bits (2 bytes)

Q-7 Write a short note on java tokens

Ans:

❖ Token is the smallest individual unit of a program.


❖ Tokens are the various Java program elements which are identified by the
compiler
❖ Tokens supported in Java include keywords, variables, constants, special
characters, operations etc.

13
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 The smallest individual unit of Token
program is known as ….
2 ……….are the reserved words keyword
3 Literals means the …….. value
4 How many tokens are available in Variables, Operators,
java? Keywords, Special
Characters, Literals

Q-8 Write a short note on Operators in java

Ans:

❖ An operator is a symbol that tells the computer to perform certain


mathematical or logical manipulations.

❖ Following are the types of operators in java:


1) Arithmetic
2) Relational
3) Logical
4) Assignment
5) Conditional
6) Instance Of
7) Sizeof
8) Bitwise
9) Increment/Decrement

1) Arithmetic Operators:

14
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Addition=” +(a+b));
[Link](“Sub is” +(a-b));
[Link](“Mul is” +(a*b));
[Link](“Div is”+(a/b));
[Link](“Modulas is” +(a%b));
}
}

15
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2) Relational Operators:

Example:

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“> than” +(a>b));
[Link](“< than” +(a<b));
[Link](“>= is” +(a>=b));
3) Logical Operators:
[Link](“<=”+(a<=b));
[Link](“== is” +(a==b));
[Link](“!= is” +(a!=b));
}
}

16
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();
if(a>b && a>c)
[Link](“a is max”);
4) Assignment Operators:
else if(b>c && b>a)
❖ Assignment operator is indicated by =
[Link](“b is max”);
else
Case 1: [Link](“c
(Copy the value tois the variable)
max”);
} a=5
} In the above case, 5 is assigned the value to a

Case 2: (Copy the variable value to another variable)

17
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

a=4,b=5
a=b
In the above case, the value of b is assigned to a

Case 3: (Copy the expression to the variable)


a=5,b=4
c=a+b
In the above case, the value of a+b is assigned to c.

Note: Assignment operator is also known as shorthand operator because it


represent shorthand ways to represent the variable.

Example:
a=a+5 a+=5
a=a-4 a-=4
a=a*2 a*=2

5) Conditional Operators:

❖ Conditional operator is indicated by ?


❖ It is also known as ternary operator because it requires 3 parts:

Syntax:
Condition? True part: false part

Example:
(a>b) ? “a is max” : “b is max”

6) Instance of Operator:
❖ It is used to test whether the object is an instance of the specified type
❖ It is also known as type comparison operator because it compares
instance with the class type.

Syntax:

18
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

objectname=classname
Example:
test t1=new test();

The above example checks whether the t1 is object of the class test or not

7) size of Operator:
❖ It is used to find the size of the variable or the type.

Syntax:
sizeof(variable name);

Example:
int a;
sizeof(a)=4 bytes

8) Bitwise Operator:
❖ Bitwise operator operates on the bits(0 and 1)
❖ Following are the types of bitwise operators.
o Bitwise AND (&)
o Bitwise OR(|)
o Bitwise ExclusiveOR(^)

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

9) Increment/Decrement Operator:
❖ This operator is used to increment or decrement the value by 1.
❖ There are 2 types of increment and decrement:
o pre-increment (++a)
o Post-increment(a++)
o pre-decrement(--a)

19
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

o post-decrement(a--)

Pre-increment Post-Increment
1) In this, value is increment first 1) In this, value is first assigned to
and then it is assigned to the the variable and then it is
variable incremented.

2) ++a 2) a++

Example:
class inc
{
public static void main(String args[])
{
int i=0,j=0;
[Link](i++); //post increment
[Link](++j); // pre-increment
}

Pre-decrement Post-decrement
2) In this, value is decremented 3) In this, value is first assigned to
first and then it is assigned to the variable and then it is
the variable decremented.

4) --a 2) a--

20
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:
class dec
{
public static void main(String args[])
{
int i=0,j=0;
[Link](i- -); //post increment
[Link](- -j); // pre-increment
}

MCQ
Sr Question Answer
No.
1 Assignment Operator is also known Shorthand Operator
as …..
2 Conditional Operator is also known Ternary Operator
as ….
3 Which operator is used to test instance of
whether the object is an instance of
the specified type?

4 Relational operator is also known Comparison


as ……..operator

21
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-9 Write a short note on Decision Control structures

Ans:

❖ Following are the types of decision control structures:

◆ if
◆ if-else
◆ Nested if
◆ else-if ladder
◆ switch case

1) if:

Description: This decision control structure only deals with the true part of
the condition and it works only with one condition.

Syntax:

if(condition)
True part
{
statements;

Example:

22
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
if(a==b)
[Link](“Equal”);
}
}

2) if-else:

Description: This decision control structure deals with the true and false part
of the condition and it works only with one condition.

If the condition is true then statements inside if are executed and if the
condition is false then statements inside false are executed.

23
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Syntax:

if(condition)
{ True part
statement1;
}
else
{ False part
statement 2;
}

Example:

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
if(a==b)
[Link](“Equal”);
else
[Link],println(“Not Equal”);
}
}
3) Nested if:

Description:

❖ Nested if means one if inside another if. It is used when you have more
than 1 condition.

24
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ In Nested if, there are two if-else, one is inner if-else and other is outer
if-else

Syntax:

if(condition1)
{
if(condition2)
{
Statement1;
} Inner if-else
Outerif-else

else
{
Statement2;
}
}
else
{
Statement 3;
}

25
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();

if(a>b)
{
if(a>c)
[Link](“a is max”);
else
[Link],println(“c is max”);
}
else
{
if(b>c)
[Link](“b is max”);
else
[Link](“c is max”);
4) else-if ladder:
}
}
Description:
}

26
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ If-elseif-elseif-elseif….else is known as else-if ladder.


❖ It is used when you have more than 2 conditions.
❖ In else-if ladder, when all the conditions are false then else part is
executed

Syntax:

if(condition1)
{
statement1;
}
elseif(condition2)
{
statement2;
}
elseif(condition3)
{
statement3;
}
….
….
else
{
statement4;
}

27
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();

if(a>b && a>c)


[Link](“a is max”);
else if(b>c && b>a)
[Link](“b is max”);
else
5) switch case: [Link](“c is max”);

}
}

Description:

❖ switch case is used with multiple options.


❖ In switch case, the value of the variable is passed which is compared
with the different cases, the case which matches the value is executed.
❖ switch case have 4 keywords: switch, case, default, break
❖ break keyword is used to exit from the particular case
28
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ When no case is executed, at that time default case is executed

Syntax:
switch(variable)
{
case 1: statement1;
break;
case 2: statement2;
break;
case 3: statement3;
break;
case4: statement4;
break;
default: statement5;
break;
}

29
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,ch;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter [Link] [Link] [Link] [Link]”);
ch=[Link]();
switch(ch)
{
case 1: [Link](a+b);
break;

case 2: [Link](a-b);
break;

case 3: [Link](a*b);
break;

case 4: [Link](a/b);
break;

default: [Link](“Invalid”);
break;
}

}
}

30
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Which decision control structure is Switch case
used when we have multiple
options?
2 In switch case, there are 4
…….keywords
3 break in switch case is used to ……. Exit from the particular case

4 if inside another if is known as …… Nested if


5 Which decision control sturucture If
only deals with true part

Q-10 what is loop? List out types of looping structures and explain in detail

Ans:

❖ When same task is to be performed multiple times, then in that case


loop is used.
❖ Following are the types of loop

Loop

Entry Controlled Loop Exit Controlled Loop

for loop
do-whileloop

while loop

31
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1) Entry Controlled Loop:

❖ When the condition is checked in the starting of the loop, it is known


as entry controlled loop.
❖ for loop and while loop are known as entry controlled loop.

* for loop:

Syntax:

for(initialization ;condition ;increment/decrement)

{
Statements;

Example:

class loop
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
[Link](i);
}
}

32
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

* while loop:

Syntax:

Initialization;
while(condition)

{
Statements;
Increment/decrement;

Example:

class loop
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
[Link](i);
i++;
2) Exit }Controlled Loop:
}

❖ When the condition is checked in the end of the loop, it is known as


exit controlled loop.
❖ do-while loop is example of exit controlled loop
❖ In do-while loop, statements are executed atleast once without
checking the condition.

33
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Syntax:
Initialization;
do
{
Statements;
Increment/decrement;
} while (condition);

Example:

class loop
{
public static void main(String args[])
{
int i=1;
do
{
[Link](i);
i++;
}while(i<=5);
}

*** Difference between while and do-while loop


while loop do-while loop
It is known as entry controlled loop It is known as exit controlled loop
If the condition is true then only The statements are executed atleast
statements are executed once and after that the condition is
checked.
While loop does not have semicolon do-while loop have terminating
semicolon

34
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Which 3 things all the loops have? initialization, condition,
increment/decrement
2 for loop is known as ……. Entry controlled loop
3 do-while loop is known as …… Exit controlled loop
4 Which loop have terminating semi- do-while
colon at the end?
5 In which loop, without checking the do-while
condition the statements are
executed at least once?

Q-11 Write a short note on jumping statements in java

Ans:

❖ Jumping statements transfers the control from one location to


another location.
❖ Following are the types of jumping statements:
o break
o continue

1) break statement:

❖ This statement is used to exit immediately from the loop or program


❖ When the break statement is encountered in the program, the
control directly moves to the end of the program.

Syntax:

for(; ;)
{
if(condition)
break;
}
35
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
[Link](i);
}
}
2) contine statement:

❖ This statement is used to continue back to the re-evaluation of the


condition.
❖ Using continue statement, certain statements are bypassed.

Syntax:

for(; ;)
{
if(condition)
continue;
}

36
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
[Link](i);
}
}

*** Difference between break and continue statement


break continue
it is used to exit immediately from It transfers the cursor back to the
the loop re-evaluation of the condition
Using break, certain statements Using continue statement, certain
cannot be bypassed statements can be bypassed/

MCQ
Sr Question Answer
No.
1 Which are the jumping statements break,continue
in java?
2 In which type of jumping continue
statement, certain statements are
bypassed
3 Which jumping statement is used to break
immediately exit from the loop or
program?

37
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-12 Write a short note on typecasting

Ans:

❖ Typecasting means converting one data type into another datatype.


❖ There are 2 types of type casting in java.

1) Widening data type

❖ Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down. It is
done automatically.

Example:

class type
{
public static void main(String args[])
{
int x=10;
float y;
y=x;
[Link](y);
2) Narrowing
}
data type
}

38
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ Converting a higher data type into a lower one is called narrowing type
casting. It is also known as explicit conversion or casting up. It is done
manually by the programmer.

Example:
class exp1
{
public static void main(String args[])
{
int x;
double f=2.5;
x=(int)f;
[Link](x);
}
}

MCQ
Sr Question Answer
No.
1 Converting one data type into Type casting
another data type is known as …..
2 In which type of typecasting, Widening
smaller data type is automatically
type casted to larger data type?
3 Narrowing data type is known as Explicit type casting
…….

Q-13 Write a short note on Arrays

Ans:

❖ Array is the collection of elements that have same data type. All the
elements of array share same array name

39
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ The main concept of array is index

Advantages:

o Code Optimization: It makes the code optimized, we can retrieve or sort


the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages:
Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime.

Array

1-d array Multi-dimensional array

1) 1-d array (One Dimensional Array):

❖ The array having only one dimension is known as 1-d array.

Syntax:
Declaration of array:
datatype[] arrayname OR
datatype arrayname[] OR

Initialization of array:
datatype arrayname[]=new datatype[size];
Example 1:

40
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class exp1
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
a[0]=10;
a[1]=11;
a[2]=12;
a[3]=13;
a[4]=14;
for(i=0;i<[Link];i++)
[Link](a[i]);
}
}

Example 2:

class exp1
{
public static void main(String args[])
{
int i;
int a[]={10,11,12,13,14};

for(i=0;i<[Link];i++)
Example: 3 inputting array elements from user
[Link](a[i]);
}
}

41
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
class arr
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
Scanner sc=new Scanner([Link]);
for(i=0;i<5;i++)
{
[Link]("Enter array elements");
a[i]=[Link]();
}
for(i=0;i<5;i++)
{
[Link]("Array ele" +a[i]);
}
}
}

2) Multi-Dimensional array:
❖ In this array, the data is stored in row and column based index (also
known as matrix form)

Syntax:
Declaration of array:
datatype[][] arrayname OR
datatype arrayname[][] O

Initialization of array:
datatype arrayname[][]=new datatype[rowsize][columnsize];
Example 1:

42
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class array
{
public static void main(String args[])
{
int i,j;
int a[][]={{1,2},{3,4}};
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
[Link](a[i][j] +" ");
Example 2: inputing} the array from user
[Link]();
}
}
}

43
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
class arr
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[2][3];
Scanner sc=new Scanner([Link]);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
[Link]("Enter array elements");
a[i][j]=[Link]();
}

}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
[Link]("Array ele" +a[i][j]);
}
}
}
}

44
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 The collection of elements having Array
same data type and same array
name is known as ……
2 Which type of array have both row Multi-dimensional array
and column size?
3 In which type of array, data is Multi-dimensional array
stored in matrix form?

Q-14 Write a short note on Command Line arguments

Ans:

❖ The java command-line argument is an argument i.e. passed at the


time of running the java program.
❖ The arguments passed from the console can be received in the java
program and it can be used as an input.

Example 1:

class cmd1
{
public static void main(String args[])
{
[Link](args[0]);
}
Example
} 2:

45
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class cmd1
{
public static void main(String args[])
{
int i;
for(i=0;i<[Link];i++)
{
[Link](args[i]);
}
}
}

MCQ
Sr Question Answer
No.
1 The arguments passed at runtime Command line arguments
of program is known as……
2 Passing of arguments in command args[0]
line arguments starts with ……

46
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Unit 1 –Class Fundas (Part 2)

Q-1 Explain class and object

Ans:

❖ A class is a template from which objects are created. That is objects are
instance of a class
❖ When you create a class, you are creating a new data-type. You can use
this type to declare objects of that type.
❖ An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc.
❖ An object is an instance of a class.
❖ Class defines structure and behavior (data & code) that will be shared
by a set of objects
❖ Each object contains its own copy of each variable defined by the class

47
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Syntax:

class ClassName
{
type instance variable1; Instance
type instance variable2; Variables

type methodname1 (parameter list)


{
body of method;
} Method of class
type methodname2 (parameter list)
48
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

{
body of method;
}

Example:

class student
{
int roll;
String name;
}
class sample
{
public static void main(String args[])
{
student s=new student();
[Link]=1;
[Link]="xyz";
[Link]([Link]);
[Link]([Link]);
}
}

MCQ
Sr Question Answer
No.
1 Which are the features or state,behavior,identity
characteristics of object?
2 A ……. is a template from which class
objects are created

49
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3 ………….and …………are the class, object


main concept of OOP

Q-2 Explain Encapsulation

Ans:

❖ Encapsulation is one of the fundamental concept of OOP


❖ Encapsulation in Java is a mechanism of wrapping the data (variables) and
code acting on the data (methods) together as a single unit.
❖ In encapsulation, the variables of a class will be hidden from other classes,
and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.

To achieve encapsulation in Java:


❖ Declare the variables of a class as private.
❖ Provide public setter and getter methods to modify and view the variables
values.
❖ To achieve encapsulation in Java :
Advantages of Encapsulation:
❖ The fields of a class can be made read-only or write-only.
❖ A class can have total control over what is stored in its fields.

50
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class test
{
private int age;
public void get()
{
[Link](age);
}
public void set(int age)
{
[Link]=age;
}
}

class enc
{
public static void main(String args[])
{
test t=new test();
[Link](1);
[Link]();
}
}

MCQ
Sr Question Answer
No.
1 Wrapping of variables and Encapsulation
methods in single unit is known
as……
2 The main concept of encapsulation Data Hiding
is ……….

51
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3 To achieve encapsulation, the Private


variables have to be declared …….
4 To access the private variable of get() and set()
the class which methods are used?

Q-3 Write a short note on Inheritance

Ans:

❖ Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviours of a parent object. It is an important part
of OOPs (Object Oriented programming system).

Terms used in inheritance:

1) Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
2) 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.
3) 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

Advantage of Inheritance:

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.

52
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Syntax:

class subclass extends superclass


{
//methods and fields
}
The extends keyword indicates that you are making a new class that
derives from an existing class.

Types of Inheritance:

53
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Note: Multiple inheritance is not supported in Java through class.

1) Single Inheritance :

❖ When a class inherits another class, it is known as a single


inheritance.

Example:
In the below example, Dog is the subclass and Animal is the Parent
Class. So Dog inherits the methodc of the Animal Class and also it have its
own method.

54
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class Animal
{
void eat()
{
[Link]("Eating");
}
}

class Dog extends Animal


{
void bark()
{
[Link]("Barking");
}
}

class single
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}

2) Multilevel Inheritance :
❖ When there is a chain of inheritance, it is known as multilevel
inheritance.

55
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ In Multilevel inheritance, one class inherits from another class, another


class inherits from next class and so on.

class Animal
{
void eat()
{
[Link]("Eating");
}
}

class Dog extends Animal


{
void bark()
{
[Link]("Barking");
}
}
class BabyDog extends Dog
{
void sleep()
{
[Link](“Sleeping”);
}
}

class single
{
public static void main(String args[])
{
BabyDog bd=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}

56
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3) Hierarchical Inheritance :

❖ When two or more classes inherits a single class, it is known


as hierarchical inheritance.
class Animal
{
void eat()
{
[Link]("Eating");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barking");
}
}
class cat extends Animal
{
void sleep()
{
[Link](“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
cat c=new cat();
[Link]();
[Link]();
Dog d=new Dog();
[Link]();
[Link]();
}
}

57
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

4) Multiple Inheritance :

❖ Multiple inheritance is not supported in java by class. The reason is


suppose A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.

Example:

class A
{
void msg()
{
[Link](“Hello”);
}
}
class B
{
void msg()
{
[Link](“Hi”);
}
}
class C extends A,B
{
public static void main(String args[])
{
C c1=new C();
[Link]();//Which msg() method will be called?
}
}

Will generate compile time error

58
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5) Hybrid Inheritance :
❖ Hybrid inheritance is the combination of more than 1 type of inheritance.

Example:
class Animal
{
void eat()
{
[Link]("Eating");
}
}

class Dog extends Animal //Single level inheritance


{
void bark()
{
[Link]("Barking");
}
}
class cat extends Animal //Multilevel inheritance
{
void sleep()
{
[Link](“Sleeping”);
}
}

class single
{
public static void main(String args[])
{
cat c=new cat();
[Link]();
[Link]();
Dog d=new Dog();
[Link]();
[Link](); 59

}
}
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 The parent child concept is known Inheritance
as ………
2 The main advantage of inheritance reusability
is …..
3 Which inheritance is not supported Multiple Inheritance
in java?
4 In …………inheritance, there is Hierarchical
one parent class and multiple child
class and all child class access same
parent class
5 Which inheritance is known as Multilevel
chain of inheritance?
6 ……..inheritance is the Hybrid
combination of more than one type
of inheritance

Q-3 Write a short note on Polymorphism


Ans:

❖ 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.

60
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Polymorphism

Compile Time Runtime


Polymorphism Polymorphism

Method Overloading Method Overriding

Operator Overloading

1) Compile time Polymorphism:


❖ It is also known as static polymorphism which is achieved by method
overloading.
❖ Method overloading means methods with same name but different
parameters.
❖ Method can be overloaded by change in number of arguments or change
in type of arguments.

61
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class overload
{
void add(int a,int b,int c)
{
[Link](a+b+c);
}
void add(int a,int b)
{
[Link](a+b);
}
}
class method1
{
public static void main(String args[])
{
overload o1=new overload();
[Link](2,3,4);
[Link](1,2);
}
}

2) Run time Polymorphism:


❖ It is also known as dynamic polymorphism which is achieved by method
overriding.
❖ It is a process in which a function call to the overridden method is
resolved at Runtime.
❖ In the below example, When an object of child class is created, then the
method inside the child class is called. This is because the method in the
parent class is overridden by the child class. Since the method is
overridden, this method has more priority than the parent method inside
the child class. So, the body inside the child class is executed.

62
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

63
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class A
{
void run()
{
[Link]("Hello");
}
}

class B extends A
{
void run()
{
[Link]("Hi");
}
}
class sam
{
public static void main(String args[])
{
B b1=new B();
[Link]();
}
}

64
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Compile Time Polymorphism Runtime polymorphism


1) This type of polymorphism is 1) This type of polymorphism is
known as Static binding or early known as dynamic binding or
binding late binding

2) It is achieved by method 2) It is achieved by method


overloading as operator overriding
overloading is not supported by
java

3) Inheritance is not used in this 3) Inheritance is used in this type of


type of inheritance polymorphism to achieve method
overrding.

MCQ
Sr Question Answer
No.
1 Compile time polymorphism is also Static binding
known as …….
2 Runtime polymorphism is also Dynamic Binding
known as....
3 Compile time polymorphism is Method overloading
achieved by …….
4 The methods with same name but Method overloading
different parameters is known as
……..
5 Operator overloading is supported False. Not supported
by java? (T/F)
6 Runtime polymorphism is achieved Method overriding
by …..
7 In …………., child class overwrites Method overriding
the method of parent class

65
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-4 Write a short note on Constructor.

Ans:

❖ A constructor is a special method which have same name as class name


❖ It is automatically called when object of class is created.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructor

❖ There are two types of constructors in Java:

1) Default constructor (no-arg constructor)


2) Parameterized constructor

66
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1) Default Constructor:
❖ A constructor with zero parameter or no argument is known as
default constructor.

Example:

class A
{
A()
{
[Link]("Default constructor");
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A();
}
}

2) Parameterised Constructor:
❖ A constructor with parameters is known as parameterised
constructor.

67
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class A
{
int roll;
A(int r)
{
roll=r;
}
void display()
{
[Link](roll);
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A(10);
[Link]();
}
}

MCQ
Sr Question Answer
No.
1 Which method have same name as Constructor
class name
2 Constructor does not have return True
type (T/F)
3 The constructor with no or 0 Default constructor
arguments is known as……
4 The constructor with parameters is Parameterized constructor
known as ……..
68
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5 When constructor is called? When object of class is


created.

Q-5 Write a short note on Constructor overloading

Ans:

❖ A constructor with same name but different parameters is known as


constructor overloading.

69
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class cons
{
int roll;
String name;
cons()
{
[Link]("Hello");
}
cons(int r)
{
roll=r;
}
cons(int r,String n)
{
roll=r;
name=n;
}
void display()
{
[Link](roll);
[Link](name);
}
}
class consoverload
{
public static void main(String args[])
{
cons c=new cons();
cons c1=new cons(10);
cons c2=new cons(10,"xyz");
[Link]();
[Link]();
}
}

70
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Constructor with same name but Constructor overloading
different parameters is known as
…..

Q-6 Write a short note on static and non-static members in java

Ans:

Static Variables:
❖ When a variable is declared as static, then a single copy of the variable
is created and shared among all objects at a class level. Static variables
are, essentially, global variables. All instances of the class share the
same static variable.
❖ We can create static variables at class-level only

71
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class test
{
static int a=20;
void display()
{
a++;
[Link](a);
}
}
class sample
{
public static void main(String args[])
{ Variables:
Non-Static
test t1=new test();
test t2=new test();
test t3=new test();
[Link]();
[Link]();
[Link]();
}
}

❖ When a variable is declared as non-static, then individual copy of the


variable is created for the different objects. Static variables are,
essentially, local variables. All object of the class share the different non-
static variable.

72
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class test
{
int a=20;
void display()
{

a++;
[Link](a);
}

}
class sample
{
public static void main(String args[])
{
test t1=new test();
test t2=new test();
test t3=new test();
[Link]();
[Link]();
[Link]();
}
}

73
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Static Members Non-static Members


1) Static members can be accessed 1) Non-static members can be
directly using classname accessed using object of class
2) Static variables can be accessed 2) Non-static variables cannot be
by static and non-static methods accessed inside static method
both
3) All the objects of class share 3) All the objects of the class have
same static variables its own non-static variable.
4) Static variables are like global 4) Non-static variables are like local
variables variables.
5) static keyword is used to declare 5) No keyword is required to
the static members. declare non-static members.

MCQ
Sr Question Answer
No.
1 In ……….variable, only 1 copy of static
variable is shared by all the objects
of the class
2 Which keyword is used to declare static
static variable?
3 In …..variable, all the objects have Non-static
their own copy of variable
4 Static variables can be accessed by static and non-static
both …….and …….methods
5 Static variables are like global
…….variables
6. Non-static variables are like local
……variables

74
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-7 Write a short note on varargs

Ans:

❖ The varrags allows the method to accept zero or multiple arguments.


❖ If we don't know how many argument we will have to pass in the method,
varargs is the better approach.
❖ The varargs uses ellipsis i.e. three dots after the data type. Syntax is as
follows:

Syntax:
return_type method_name(data_type... variableName)
{
}
Example:

class varg
{
static void display(int...values)
{
[Link]("hello");

for(int i:values)
[Link](i);
}
public static void main(String args[])
{
display();
display(1,2,3,4);
display(12,22);
}
}

75
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 If we don't know how many varargs
argument we will have to pass in
the method, …… is the better
approach
2 varargs uses …………. ellipsis (…)

Q-8 Write a short note on IIB block in java

Ans:

❖ IIB stands for instance initializer block


❖ Instance Initializer block is used to initialize the instance data member
❖ It run each time when object of the class is created.

76
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class iib
{
int age;
iib()
{
[Link](age);
}

{
age=10; IIB Block
}

class im
{
public static void main(String args[])
{
iib i=new iib();
iib i2=new iib();
}

MCQ
Sr Question Answer
No.
1 IIB stands for …… Instance Intializer Block
2 IIB runs each time the ……….is object of class
created

77
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Unit-2:- Inheritance and java packages

Q-1 Explain Universal class


Ans:
❖ The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
❖ Object class is present in java. Lang package. Every class in Java is
directly or indirectly derived from the Object class.
❖ If a class does not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
❖ Therefore the Object class methods are available to all Java classes.
❖ Hence object class acts as a root of inheritance hierarchy in any
Java Program.
❖ The Object class is beneficial if you want to refer any object whose
type you don't know.
❖ Following are the methods of object class.

Sr No. Method Name Description


1 toString() It is used to convert an object to string
Note: It is always recommended to override
toString() method to get our own string
representation.
2 hashcode() It returns a hashvalue that is used to
search the object in the collection
Note: For every object, JVM generates
unique number which is known as hascode.
3 equals It compares given object to “this” object
(the object on which method is called)
4 getClass() It returns the class of the object and is used
to get actual runtime class of the object.

78
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5 finalize() This method is called just before an object


is garbage collected. It is called on an
object when garbage collector determines
that there are no references to the object.
Note: finalize() is just called once on an
object
6 clone() It returns the new object that is exactly
same as this object
7 notify() wakes up single thread, waiting on object’s
monitor
8 notifyall() wakes up all thread, waiting on object’s
monitor
9 wait() Causes the current thread to wait for the
specified milliseconds until another thread
notifies.

MCQ
Sr Question Answer
No.
1 Which is the universal class in Object
java?
2 Object class is present in [Link]
……package
3 Which method of object class is hashcode()
used to return a hash value that is
used to search the object in
collection?
4 Which method of object class clone()
generates exactly same object as
this object?
5 Which method of object class is finalize()
called just before the object is
garbage collected?

79
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-2 Write a short note on Access Specifier


Ans:
❖ The access modifiers in Java specifies the accessibility or scope of a
field, method, constructor, or class. We can change the access level of
fields, constructors, methods, and class by applying the access modifier
on it.
❖ There are 4 types of java access modifiers

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class. A class cannot be private
except nested class.

80
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1. class A
2. {
private int data=40;
private void msg()
{
[Link]("Hello java");
}
3. }
4. class Simple
{
5. public static void main(String args[])
{
6. A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}
2. Default: The access level of a default modifier is only within the package.
It cannot be accessed from outside the package. If you do not specify any
access level, it will be the default.

81
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

//Save this with [Link] (Package 1)

package pack;
class A
{
void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}

Note:

❖ In the above example, the scope of class A and its method msg() is
default so it cannot be accessed from outside the package.

82
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3. Protected: The access level of a protected modifier is within the package


and outside the package through the inheritance. The protected access
modifier can be applied on the data member, method and constructor. It
cannot be applied on class.

//Save this with [Link] (Package 1)

package pack;
public class A
{
protected void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj=new B();
[Link]();
}
}

83
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

4. Public: The access level of a public modifier is everywhere. It can be


accessed from within the class, outside the class, within the package and
outside the package.

//Save this with [Link] (Package 1)

package pack;
public class A
{
public void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}

84
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 ……..modifier is accessible from public
everywhere
2 The access level of …………modifier protected
is within the package and outside the
package through inheritance
3 Which is the default access modifier? default

Q-3 Write a short note on Constructor in inheritance


Ans:
❖ A constructor in Java is similar to a method with a few differences.
Constructor has the same name as the class name. A constructor doesn't
have a return type.
❖ A Java program will automatically create a constructor if it is not already
defined in the program. It is executed when an instance of the class is
created.
❖ A constructor cannot be static, abstract, final or synchronized. It cannot
be overridden.
❖ When the constructor is used in inheritance, then the constructor of base
class is executed first and then constructor of child class is executed.

85
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Constructor in single level inheritance

class parent
{
parent()
{
[Link](“Parent class constructor”);
}
}
class child extends parent
{
child()
{
[Link](“Child class constructor”);
}
}
class sample
{
public static void main(String args[])
{
child c=new child();
}
}

Constructor in single level inheritance

class parent
{
parent()
{
[Link]("Parent class constructor");
}
}
class child extends parent
{
child()
{
[Link]("Child class constructor");
} 86
}
class child1 extends child
{
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 ……..modifier is accessible from public
everywhere
2 The access level of …………modifier protected
is within the package and outside the
package through inheritance
3 Which is the default access modifier? default

MCQ
Sr Question Answer
No.
1 In case of constructor in single parent class
inheritance, the order of execution of constructor
constructor will be …………. child class
constructor
2 In case of constructor in multilevel parent class
inheritance, the order of execution of constructor
constructor will be….. child class
constructor
child1 constructor

87
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-4 Write a short note on Interface


Ans:
❖ An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
❖ Interface in java is used to achieve abstraction and multiple inheritance
❖ Interface can only have abstract methods that is methods without body
❖ “Implements” keyword is used when the class implements interface.

Syntax:
interface interfacename
{
returntype methodname();
}

88
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

interface draw
{
void print();
}

class rectangle implements draw


{
public void print()
{
[Link]("draw rectangle");
}
}
class circle implements draw
{
public void print()
{
[Link]("draw circle");
Multiple} inheritance in java using interface:
} ❖ Multiple inheritance means multiple parent class and one child class.
class test
{ The child class inherits from multiple parent class.
public static void main(String args[])
{
circle c1=new circle();
[Link]();
rectangle r=new rectangle();
[Link]();
}
}

❖ Multiple inheritance is not supported by java. But through the


interface multiple inheritance is achieved in java.

89
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

interface a
{
void display();
}
interface b
{
void display1();
}
class mul implements a,b
{
public void display()
{
[Link]("hello");
}
public void display1()
{
[Link]("hi");
}
}

class multiple
{
public static void main(String args[])
{
sam s=new sam();
[Link]();
s.display1();
}
}

90
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 class ……………interface implements
2 Which keyword is used to declare the interface
interface?
3 interface can have only abstract
………………methods
4 Multiple inheritance in java is achieved interface
using ……..

Q-5 Write a short note on Object cloning


Ans:
❖ The object cloning is a way to create exact copy of an object.
❖ The clone() method of Object class is used to clone an object.
❖ The clone() method is defined in the Object class.
❖ Every class that implements clone() should call [Link]() to obtain
the cloned object reference.
❖ The class must also implement [Link] interface whose
object clone we want to create otherwise it will throw
CloneNotSupportedException when clone method is called on that
class’s object.

Syntax:
public Object clone() throws CloneNotSupportedException

91
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class stu implements Cloneable


{
int rollno;
String name;

stu(int r,String n)
{
[Link]=r;
[Link]=n;
}
public Object clone()throws CloneNotSupportedException
{
return [Link]();
}

public static void main(String args[])


{
try
{
stu s1=new stu(1,"xyz");
stu s2=(stu)[Link]();

[Link]([Link]);
[Link]([Link]);
}catch(CloneNotSupportedException c)
{

}
}
}

MCQ
Sr Question Answer
No.

92
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1 Which method is used to create exact clone()


copy of the object?
2 To use clone(), which interface class Cloneable
should implement?
3 Every class that implements clone() [Link]()
should call …….. to obtain the cloned
object reference.

Q-6 Write a short note on Nested and Inner Class

Ans:
❖ Java inner class or nested class is a class that is declared inside the class
or interface.
❖ We use inner classes to logically group classes and interfaces in one place
to be more readable and maintainable.
❖ Additionally, it can access all the members of the outer class, including
private data members and methods.

Syntax:
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}

93
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Types of Nested Classes:

Non-static Nested Class Static Nested Class

1) Non-Static Nested class:


❖ A non-static nested class is a class within another class. It has access to
members of the enclosing class (outer class). It is commonly known as
inner class
❖ As inner class exists inside outer class, the object of outer class must be
created in order to create object of inner class.

Example:
class outer
{
int x=10;
class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer o=new outer();
[Link] i=[Link] inner();
[Link](i.y);
[Link](o.x);
}
}
94
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Note:
Dot operator(.) is used to create the object of inner class using outer
class

2) Static Nested class:


❖ Static class inside another class is known as static nested class.
❖ Static nested class are not known as static inner class.
❖ The main difference between static nested class and inner class is that a
static nested class can not access member variables of the outer [Link]
is because the static nested class does not require you to create an object
of outer class.

Example:

class outer
{
int x=10;
static class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
**Difference between
[Link]
i=newand non-static nested class
[Link]();
[Link](i.y);
[Link](i.x);//will generate error
}
}

95
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Non-static nested class Static Nested Class


1) In non-static nested class, 1) In static nested class, static
static keyword is not used keyword is used

2) Non-static nested class is 2) Static nested class is not


known as inner class known as inner class

3) Non-static nested class 3) Static nested class does not


requires object of outer class require object of outer class

4) Non-static nested class can 4) Static nested class cannot


access the members of outer access members of the outer
class class

MCQ
Sr Question Answer
No.
1 Which keyword is used to declare static Static
nested class?
2 In …………., object of outer class is non-static
required
3 ………can access members of outer Non-static nested
class class

Q-6 Write a short note on abstract class and final class


Ans:
Abstract Class:
A class which is declared as abstract is known as an abstract class.
It can have abstract and non-abstract methods.
It needs to be extended and its method implemented.

96
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

It cannot be instantiated.

97
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:
abstract class bike
{
abstract void run();
void display()
{
[Link]("hello");
}
}

class honda extends bike


{
public void run()
{

[Link]("hi");
}
}

class sampe
{
public static void main(String args[])
{
honda h=new honda();
[Link]();
[Link]();
}
}

Final:

❖ The final keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
▪ Variable
▪ Method

98
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

▪ Class

❖ A class which cannot be inherited or extended is known as final class.

Example:

final class bike


{

class ja extends bike


{
void display()
{
[Link]("hi");
}
public static void main(String args[])
{
bike b=new bike();
[Link](); //Compile time error
}
}

99
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Which keyword is used to declare the abstract
class as abstract?
2 Can we create the object of abstract No
class?
3 Abstract class can contain non-abstract True
methods?
4 When final keyword is applied to the Inheritance
class it prevents ………

Q-7 Write a short note on normal import and static import


Ans:
Normal import:
❖ The import allows the java programmer to access classes of a package
without package qualification
❖ The import provides accessibility to classes and interface

class ke
{
public static void main(String args[])
{
[Link]([Link](25));
[Link]([Link](2,2));
}
}

100
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

static import:
❖ In Java, static import concept is introduced in 1.5 version.
❖ With the help of static import, we can access the static members of a
class directly without class name or any object.
❖ For Example: we always use sqrt() method of Math class by using Math
class i.e. [Link](), but by using static import we can access sqrt()
method directly.

import static [Link].*;

class ke
{
public static void main(String args[])
{
[Link](sqrt(25));
[Link](pow(2,2));
}
}

** Difference between normal import and static import


normal import Static import
1) The normal import provides 1) static import provides access
access to class and interface to the static members of the
class.

2) The normal import allows to 2) Static import feature allows to


access the class of the access the static members of a
package without package class without class qualification.
qualification

101
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 ……….import provides access to class normal
and interface
2 ……..import provides access to the static static
members of the class

Q-8 what is package? List out the packages in java


Ans:
❖ Package in Java is a mechanism to encapsulate a group of classes, sub
packages and interfaces. Packages are used for: Preventing naming
conflicts
❖ For example there can be two classes with name Employee in two
packages, [Link] and [Link]

❖ Following are the types of in built packages:

102
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Built-in Packages:
❖ These packages consist of a large number of classes which are a part of
Java API.
❖ Some of the commonly used built-in packages are:
o [Link]: Contains language support classes(e.g classed which
defines primitive data types, math operations). This package is
automatically imported.
o [Link]: Contains classed for supporting input / output operations.
o [Link]: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for Date / Time
operations.
o [Link]: Contains classes for creating Applets.
o [Link]: Contain the classes for implementing the
components of graphical user in [Link] terfaces like
button, menus etc.
o [Link]: Contain classes for supporting networking
operations.

103
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

java. lang Package


❖ Provides classes that are fundamental to the design of the Java
programming language.
❖ Following are few important classes of [Link] package
1. Math
2. Wrapper Classes
3. String
4. String Buffer
Math Class of [Link] package
❖ The [Link] class contains various methods for performing basic
numeric operations such as the logarithm, cube root, and trigonometric
functions etc. The various java math methods are as follows:
❖ All the methods of the Math class are static so it can be called by class name
❖ Basic Math methods
Method Descriptio n
[Link]( ) It will return the Absolute value of the given value.
[Link]( ) It returns the Largest of two values.
[Link]( ) It is used to return the Smallest of two values.
[Link]( ) It is used to round of the decimal numbers to the nearest value.
[Link]( ) It is used to return the square root of a number.
[Link]( ) It is used to return the cube root of a number.
[Link]( ) It returns the value of first argument raised to the power to
second argument.
[Link]( ) It is used to find the smallest integer value that is greater than
or equal to the argument or mathematical integer.
[Link]( ) It is used to find the largest integer value which is less than or
equal to the argument and is equal to the mathematical integer
of a double value.
[Link]( It returns a double value with a positive sign, greater than or
) equal to 0.0 and less than 1.0.
[Link]( ) Returns the trigonometric cosine of an angle.
[Link]( ) Returns the trigonometric sine of an angle.
104
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

[Link]( ) Returns the trigonometric tangent of an angle.


[Link]( ) Returns the natural logarithm (base e) of a double value.

MCQ
Sr Question Answer
No.
1 [Link] gives ………. Maximum round
value of floating
point number
2 [Link]() gives….. Square root of
number
3 Math class is included in ………… [Link]
4 ……….is the default package [Link]

Wrapper class in [Link] package


❖ The wrapper class in Java provides the mechanism to convert primitive
into object and object into primitive.
❖ autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an
object is known as autoboxing and vice-versa unboxing.
Primitive Wrapper Class Primitive Type Wrapper Class
Type
byte Byte float Float
boolean Boolean int Integer
char Character long Long
double Double short Short

105
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Autoboxing:
❖ The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.

Example:

class wrapper1
{
public static void main(String args[])
{
int a=20;
Integer j=a; //Converting primitive data type to Integer wrapper class
[Link](j);
}
}

Unboxing:
❖ The automatic conversion of wrapper type into its corresponding primitive
type is known as unboxing. It is the reverse process of unboxing.

class wrapper1
{
public static void main(String args[])
{
Integer a=new Integer(3);
int i=a; //Converting Wrapper class into primitive data type
[Link](i);
}
}

106
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 ……….Provides the mechanism to Wrapper Class
convert primitive into object and object
into primitive.
2 The process of converting primitive data autoboxing
type into object is known as ……
3 The process of converting object into unboxing
primitive data type is known as ….

String class in [Link] package

❖ The [Link] class represents character strings. All string literals in


Java programs, such as "abc", are implemented as instances of this
[Link] are constant, their values cannot be changed after they are
created.

Method Description
char charAt(int index) Returns char value for the particular index
int length() Returns string length
String substring(int Returns substring for given begin index.
beginIndex)
String substring(int Returns substring for given begin index and
beginIndex, int endIndex) end index.
boolean contains(Char Returns true or false after matching the
Sequences) sequence of char value.
boolean equals(Object another) Checks the equality of string with the given
object.
Boolean isEmpty() Checks if string is empty.
String concat(String str) Concatenates the specified string.

107
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

String replace(char old, char Replaces all occurrences of the specified char
new) value.
static String Compares another string. It doesn't check case.
equalsIgnoreCase(String
another)
int indexOf(int ch) Returns the specified char value index.
String toLowerCase() Returns a string in lowercase.
String toUpperCase() Returns a string in uppercase.
String trim() Removes beginning and ending spaces of this
string.
int compareTo(String) Compares this String to another specified
String if match then return zero(0) otherwise
not zero(0).
int Compares two strings lexicographically,
compareToIgnoreCase(String) ignoring case differences.

108
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

class stringfunctions
{
public static void main(String args[])
{
String s="hello";
String s1="hello";
String s3="karishma";
String s4="rupani";
String s5="hi";
String s6="Hi";
[Link]("Charat" +[Link](1));
[Link]("length" +[Link]());
[Link]("substring" +[Link](1));
[Link]("substring" +[Link](1,3));
[Link]("index" +[Link]("el"));
[Link]("Equality" +[Link](s1));
[Link]("Empty" +[Link]());
[Link]("Concate"+[Link](s4));
[Link]("replace"+[Link]('l','k'));
[Link]("Uppercase" +[Link]());
[Link]("Lowercase" +[Link]());
[Link]("IndexOf" +[Link]('o'));
[Link]("ignorecase" +[Link](s6));

}
}

MCQ
Sr Question Answer
No.
1 Which class contains the string String class
functions?

109
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2 substring(startind,endind) gives ……. Substring from start


index to end index.
3 Which function of string class is used to concat()
merge 2 strings?
4 Which function returns the index of the indexOf()
given character

StringBuffer class in [Link] package

❖ StringBuffer is a peer class of String that provides much of the


functionality of strings.
❖ The string represents fixed-length, immutable character sequences while
StringBuffer represents growable and writable character sequences
❖ StringBuffer may have characters and substrings inserted in the middle or
appended to the end.
❖ It will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for
growth.

Method Description
append(String s) Is used to append the specified string with this string.
insert(int offset, Is used to insert the specified string with this string at the
String s) specified position.
replace(intstartIndex, Is used to replace the string from specified startindex and
intendIndex, String endindex.
str)
delete(int startIndex, Is used to delete the string from specified startindex and
int endIndex) endindex.
reverse() Is used to reverse the string.
capacity() Is used to return the current capacity.
charAt(int index) Is used to return the character at the specified position.
length() Is used to return the length of the string i.e. Total number
of characters.

110
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

substring(int Is used to return the substring from the specified begin


beginIndex) index.
int returns the index within this string of the first occurrence
indexOf(String str) of the specified substring.

Example:
class stringfunctions
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("hello");
[Link]("Length" +[Link]());
[Link]("Specified" +[Link](2,"hi"));
[Link]("Replace" +[Link](1,3,"ee"));
[Link]("Deleting" +[Link](1,3));
[Link]("Reversing" +[Link]());
[Link]("Capacity" +[Link]());
[Link]("Charat" +[Link](2));
[Link]("Substring" +[Link](1));

MCQ
Sr Question Answer
No.
1 ……..is the peer class of the String class StringBuffer
2 ………is the growable sequence of StringBuffer
characters
3 Which method is used to add insert the insert()
string in the specified string?

[Link] Package
111
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ The [Link] packages provide support for the event model, collections
framework, date and time facilities, and contain various utility classes.
❖ Following are the classes in [Link] package
❖ Random
❖ Date
❖ GregorianCalendar
❖ Vector
❖ HashTable
❖ StringTokenizer
❖ Collections in Java : Linked List, SortedSet, Stack, Queue, Map

Random class in [Link] package

❖ Java Random class is used to generate a stream of pseudorandom


numbers
❖ This class provides various method calls to generate different random
data types such as float, double, int.

Methods Description
doubles() Returns an unlimited stream of pseudorandom double
values.
ints() Returns an unlimited stream of pseudorandom int values.
longs() Returns an unlimited stream of pseudorandom long values.
next() Generates the next pseudorandom number.
nextBoolean() Returns the next uniformly distributed pseudorandom
boolean value from the random number generator's sequence
nextByte() Generates random bytes and puts them into a specified byte
array.
nextDouble() Returns the next pseudorandom Double value between 0.0
and 1.0 from the random number generator's sequence
nextFloat() Returns the next uniformly distributed pseudorandom Float
value between 0.0 and 1.0 from this random number
generator's sequence

112
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

nextInt() Returns a uniformly distributed pseudorandom int value


generated from this random number generator's sequence
nextLong() Returns the next uniformly distributed pseudorandom long
value from the random number generator's sequence.

Example:
import [Link].*;
class randomn
{
public static void main(String args[])
{
Random r=new Random();
[Link]("Integer val" +[Link]());
[Link]("Next decimal" +[Link]());
}
}

MCQ
Sr Question Answer
No.
1 Random class comes in which package? [Link]
2 Which class generates pseudorandom Random()
numbers?

Date class in [Link] package

❖ The [Link] class represents date and time in java.

Method Description
boolean after(Date date) Tests if current date is after the given date.
boolean before(Date date) Tests if current date is before the given date.
int compareTo(Date date) Compares current date with given date.

113
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

boolean equals(Date date) Compares current date with given date for
equality.
long getTime() Returns the time represented by this date
object.
void setTime(long time) Changes the current date and time to given
time.

Example:

import [Link].*;

public class main1


{
public static void main(String[] args)
{
Date d=new Date();
Date d1=new Date(21-11-2010);
Date d2=new Date(25-6-2022);
// Creating date
[Link]("Current date: " +d);
[Link]("Checking"+[Link](d));
[Link]("after" +[Link](d2));
[Link]("Clone object" +[Link]());
[Link]("Compare" +[Link](d1));
[Link]("Equlas" +[Link](d1));
[Link]("Time" +[Link]());
[Link]("Hashcode" +[Link]());
}
}

114
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 Which class of [Link] package is used Date
to give date and time
2 Which method is used to check that before()
current date is before given date or not?
3 Which method of Date class is used to hashcode
generate unique ID of Date object

StringTokenizer class in [Link] package

❖ The [Link] class allows you to break a string into


tokens. It is simple way to break string.

115
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Method Description
booleanhasMoreTokens() Checks if there is more tokens available.
String nextToken() Returns the next token from the stringtokenizer
object.
String nextToken(String Returns the next token based on the delimeter.
delim)
booleanhasMoreElements() Same as hasmoretokens() method.
Object nextElement() Same as nexttoken() but its return type is
Object.
intcountTokens() Returns the total number of tokens.

Example:

import [Link].*;

public class main1


{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("my name is karishma");
[Link]("Total number of Tokens: "+[Link]());
while([Link]())
{
[Link]([Link]());
}

}
}

MCQ
Sr Question Answer
No.

116
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1 Which class of [Link] package allows StringToeknizer


you to break the string into tokens?
2 Which method is used to count total no. countTokens()
of tokens in the string?
3 Which method is used to print next nextToken()
token of the string?

Gregorian calendar class in [Link] package

❖ Gregorian calendar is a concrete subclass(one which has implementation


of all of its inherited members either from interface or abstract class) of
a Calendar.
❖ The major difference between Gregorian calendar and Calendar class are
that the Calendar class being an abstract class cannot be instantiated.
Calendar cal = [Link]();

❖ GregorianCalendar Class being a concrete class, can be instantiated.


So an object of the GregorianCalendar Class
GregorianCalendar gcal = new GregorianCalendar();
Example:

import [Link].*;
class greg
{
public static void main(String args[])
{
Calendar cal=[Link]();
GregorianCalendar c=new GregorianCalendar();
[Link]("Calendar date:"+[Link]());
[Link]("Greg" +[Link]());
}
}

117
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 …….is the subclass of Calendar Class Gregorian Calendar
2 We cannot create object of Calendar True
Class directly (T/F)?
3 Which method is used to create the getInstance()
object of calendar class?

Collection class in [Link] package


❖ The Collection interface is the root interface of the collections framework
hierarchy. A Collection represents a single unit of objects, i.e., a group.
❖ Java does not provide direct implementations of the Collection interface
but provides implementations of its sub interfaces like List, Set,
and Queue.
❖ Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
❖ Following are the collections in java:
▪ Vector
▪ HashTable
▪ Linked List
▪ Sorted Set
▪ Stack
▪ Queue
▪ Map

118
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Vector class in [Link] package


❖ Vector is like the dynamic array which can grow or shrink its size.
Unlike array, we can store n-number of elements in it as there is no size
limit.

void add(int index, Inserts the element at the given position.


Object element)
void add() Adds the elements in vector
void clear( ) Removes all of the elements from this.
int lastElement() Returns the last element of vector
int firstElement() Returns the first element of vector

int indexOf(Object element) Searches for the first occurrence of the


given argument.
boolean remove(Object o) Removes the first occurrence of the
specified element.
void Deletes the component at the specified
removeElementAt(int index) index.
void clone() Creates the clone of vetor.
int capacity() Returns the capacity of vector.
int size( ) Returns the number of components in this
vector.
boolean contains() Checks whether the element is contained in
vector or not.

119
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
class greg
{
public static void main(String args[])
{
Vector<Integer>ve=new Vector<Integer>(5);
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]("Elements of vector" +ve);
[Link]("Clone" +[Link]());
[Link]("Capacity" +[Link]());
[Link]("Size" +[Link]());
[Link]("Firstelement" +[Link]());
[Link]("Firstelement" +[Link]());
[Link]("Index" +[Link](20));
[Link]("Contains" +[Link](10));
[Link](0);
[Link]("Elements after removal" +ve);
}
}

Hashtable class in [Link] package

120
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ The Hashtable class implements a hash table, which maps keys to


values.

put(key,value) Maps the specified key to the specified


value in hashtable
remove(key) Removes the element specified at key in the
hashtable
size() Returns the number of keys in the hashtable
replace(key,value) Replaces the value at given key in the
hashtable
Boolean containsKey(key) Checks if hastable contains specified key or
not
Boolean Checks if hashtable contains specified value
containsValue(value) or not

import [Link].*;
class hash1
{
public static void main(String args[])
{
Hashtable<Integer,String> h=new Hashtable<Integer,String>();
[Link](1,"abc");
[Link](2,"xyz");
[Link]("Mapping" +h);
[Link](2,"ddd");
[Link]("Mapping" +h);
[Link](2);
[Link]("Mapping" +h);
[Link]("Check key:" +[Link](1));
[Link]("Check value: "+[Link]("abc"));
}
}

121
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Linked List class in [Link] package

❖ Linked List is a part of the Collection framework present in [Link]


package.
❖ This class is an implementation of the LinkedList data structure which is
a linear data structure where the elements are not stored in contiguous
locations and every element is a separate object with a data part and
address part.
❖ The elements are linked using pointers and addresses.
❖ Each element is known as a node.

add(ele) Adds the element in the linked list


addFirst(ele) Adds the element in the first node of the
linked list
addLast(ele) Adds the element in the last node of the
linked list
remove(ele) Removes the given element from the linked
list
removeFirst() Removes the first element from the linked
list
removeLast() Removes the last element from the linked
list

122
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
class linked
{
public static void main(String args[])
{
LinkedList<String>s=new LinkedList<String>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");
[Link](s);
[Link]("C");
[Link]();
[Link]();
[Link](s);
}
}

Stack class in [Link] package

❖ Java Collection framework provides a Stack class that models and


implements a Stack data structure.
❖ The class is based on the basic principle of last-in-first-out. In addition
to the basic push and pop operations, the class provides three more
functions of empty, search, and peek.

push(ele) Insert the element in the stack

123
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

pop() Removes the last element inserted in the


stack
search(ele) Searches the given element in the stack
peek() Returns the first element of the stack
empty() Returns the Boolean value after checking
whether the stack is empty or not

import [Link].*;
class stack
{
public static void main(String args[])
{
Stack<Integer> s=new Stack<Integer>();
[Link](10);
[Link](11);
[Link](12);
[Link](13);
[Link](14);
[Link](s);
[Link]();
[Link](s);
[Link]("Stack empty :"+[Link]());
[Link]("Search :"+[Link](11));
[Link]("Peek: "+[Link]());
}
}

124
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Queue class in [Link] package

❖ Java Collection framework provides a Queue class that models and


implements a Queue data structure.
❖ The class is based on the basic principle of First-in-first-out.

add(ele) It is used to insert the element in the queue


remove() Removes the head element from the queue
poll() Used to retrieve and removes the head of
queue
peek() Returns the head element of the stack

import [Link].*;
class que
{
public static void main(String args[])
{
PriorityQueue<String> p=new PriorityQueue<String>();
[Link]("abc");
[Link]("xyz");
[Link]("aaa");

[Link]("Queue ele: "+p);


[Link]();
[Link]("After removal: "+p);
[Link]("Poll: "+[Link]());
[Link]("After poll:" +p);
[Link]("Peek: "+[Link]());
}
}

125
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
Sr Question Answer
No.
1 ……….class allows to insert and remove Vector
the elements unlike array
2 ……….is the collection which represents Hashtable
element in key value form?
3 Which Class works on LIFO? Stack
4 To create the queue, ………….is used Priority Queue

Q-8 what is User define package? How to create the package


Ans:
❖ The package which is created by the user is known as User Define
Package.
❖ Following are the steps to create the package

Step 1: Create the notepad file

package mypackage;
public class Demo
{
public void display()
{
[Link]("hi");
}
}

Step 2: Create the folder named “mypackage” and save the above file with
[Link]

126
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Step 3: Create the file and import the created package


import mypackage.*;
public class sample
{

Demo d=new Demo();


[Link]();
}

Step 4: Save the file in the root directory outside the “mypackage” folder as
[Link]
Step 5: Compile Package (javac [Link])
Step 6: Compile the file in which you imported package (javac [Link])
Step 7: Run the File

127
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Unit-3
Exception Handling, Threading and Streams (Input and Output)

Q-1 what is Exception Handling?


Ans:
❖ The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can
be maintained.
❖ The core advantage of exception handling is to maintain the normal
flow of the application. An exception normally disrupts the normal flow
of the application; that is why we need to handle exceptions.

128
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Types of Java Exceptions

1) Checked Exception:
❖ The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.
2) UnChecked Exception:
❖ The classes that inherit the RuntimeException are known as unchecked
exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error:
❖ Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
129
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Java Exception Keywords

Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block
must be followed by either catch or finally.

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.

finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.

class exc
{
public static void main(String args[])
{
try
{
int a=5/0;
}catch(ArithmeticException e)
{
[Link](e);
}
finally
{
[Link]("hi");
}
}
}

130
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

** Difference between checked and unchecked exception


Checked Exception Unchecked Exception
1) Checked Exceptions are 1) Unchecked Exceptions are
declared at compile time declared at runtime

2) This class inherits Throwable 2) This class inherits Runtime


Class except Rutime Exception class
Exception
3) Example: IO Exception 3) Example: Arithmetic Exception

** Difference between throw and throws in java


throw Throws
1) throw keyword is used to throw 1) throws keyword is used to declare
the exception explicitly in the the exception in the method
code, inside the function or the signature
block of code.
2) It is followed by an instance of 2) It is followed by the class name of
the exception to be thrown exception to be thrown

3) Only 1 exception can be thrown 3) We can declare multiple


at a time exceptions using throws keyword.

131
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which is the superclass of all Throwable
the errors and exceptions?

2) Which keyword is used to Try


write the code that contains
error or exception?

3) Which keyword is used to Finally


write the code that must be
compulsory executed?

4) ………Exception is declared Checked Exception


at compile time

Q-2 what is User Defined Exception? How to create it


Ans:
❖ Creating our own Exception is known as custom exception or user-defined
exception. Basically, Java custom exceptions are used to customize the
exception according to user need.
❖ This can be done by extending the class Exception.

132
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class userdefinedexception
{
public static void main(String args[])
{
try
{
throw new myexception(400);
}
catch(myexception e)
{
[Link](e);
}
}
}

class myexception extends Exception


{
int n1;
myexception(int n2)
{
n1=n2;
}
public String toString()
{
return ("Status: " +n1);
}
}

133
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Creating the customized User defined exception
exception is known as ……..

2) User defined exception should Exception


extend ……………Class

Q-3 what is thread? Explain life cycle of thread


Ans:
❖ A thread is a single sequential flow of control within a program. A process
can have multiple threads, all executing at the same time.
❖ There can be more than one thread inside a process. Each thread of the
same process makes use of a separate program counter

❖ In Java, a thread always exists in any one of the following states. These
states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

134
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1) New:
❖ Whenever a new thread is created, it is always in the new state. For a
thread in the new state, the code has not been run yet and thus has not
begun its execution.
2) Active:
❖ When a thread invokes the start() method, it moves from the new state
to the active state. The active state contains two states within it: one
is runnable, and the other is running.

Runnable:
❖ A thread that is ready to run is then moved to the runnable
state. In the runnable state, the thread may be running or may
be ready to run at any given instant of time.
❖ It is the duty of the thread scheduler to provide the thread time
to run, i.e., moving the thread the running state.

135
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Running:
❖ When the thread gets the CPU, it moves from the runnable to the
running state

3) Blocked/Waiting:
❖ Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.
❖ For example, a thread (let's say its name is A) may want to print some
data from the printer. However, at the same time, the other thread
(let's say its name is B) is using the printer to print some data.
❖ Therefore, thread A has to wait for thread B to use the printer. Thus,
thread A is in the blocked state.

4) Timed Waiting:
❖ Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing
to leave that critical section.
❖ In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting
state is given to thread B.
❖ Thus, thread lies in the waiting state for a specific span of time, and
not forever.
❖ A real example of timed waiting is when we invoke the sleep()
method on a specific thread. The sleep() method puts the thread in
the timed wait state.
❖ After the time runs out, the thread wakes up and start its execution
from when it has left earlier.
5) Terminated:
❖ A thread reaches the termination state because of the following
reasons:
❖ When a thread has finished its job, then it exists or terminates
normally.

136
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ Abnormal termination: It occurs when some unusual events such


as an unhandled exception or segmentation fault.

MCQ
1) …………..is a sequential flow Thread
of the control within the
program

2) There can be more than one True


thread inside the process
(T/F)?

3) The active state of thread Runnable, Running


contains ……. and
………….states

4) Which process occurs when Abnormal Termination


some unusual events such as
an unhandled exception or
segmentation fault?

Q-4) what is Thread Class? Explain its methods.


Ans:
❖ Thread can be created using following methods:
o Extending Thread Class
o Implementing Runnable interface
o Explicitly creating thread object using Thread Class

137
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

1) Extending Thread Class:


❖ Thread class provide constructors and methods to create and perform
operations on a thread.
class m extends Thread
{
public void run()
{
[Link](“Running”);
}
public static void main(String args[])
{
m m1=new m();
[Link]();
}
}

2) Implementing Runnable Interface:


❖ The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread.
❖ Runnable interface have only one method named run().

138
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class m extends implements Runnable


{
public void run()
{
[Link](“Running”);
}
public static void main(String args[])
{
m m1=new m();
Thread t1=new Thread(m1);
[Link]();
}
}

3) Explicitly creating thread object using Thread Class:


❖ If we don’t extend the Thread class, then object of thread class is created
explicitly.

class m extends
{
public static void main(String args[])
{
Thread t1=new Thread(“First Thread”);
[Link]();
[Link](“Thread Name: “+[Link]());
}
}

139
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Methods of Thread Class:


Methods Description
void run() Used to perform action for thread
void start() Starts the execution of thread. JVM
calls run() on thread
public String getName() It is used to get the name of thread
public void It is used to change or set the name of
setName(String) the given thread.
public int getPriority() It is used to get the priority of the
thread
public int setPriority() It is used to set the priority of the
thread
public void suspend() It is used to suspend the given thread
public void resume() It is used to resume the suspended
thread
public void sleep(long Waits for a thread to die for the
milliseconds) specified milliseconds
public void yield() Causes currently executing thread
object to temporarily pause and allow
other threads to execute.
public Boolean Tests if the thread is daemon thread
isDaemon() or not

140
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class th
{

public static void main(String args[])


{
Thread t1=new Thread("First Thread");
[Link]("Thread Priority:
"+[Link]());
[Link](6);
[Link]();
[Link]("My Thread");
[Link]("Thread Name: "+[Link]());
[Link]("Thread Priority:
"+[Link]());
[Link]("Daemon Thread: "+[Link]());

}
}

141
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class th1 extends Thread


{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link](e);
}
[Link](i);
}
}

public static void main(String args[])


{
th1 t=new th1();
[Link]();

}
}

MCQ
1) Thread can be created by Runnable
implementing
…………interface

142
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2) Which method of thread class start()


moves the thread from new
state to active state?

3) Which method of thread class run()


is called on the start () of
thread?

4) Runnable interface have only run()


1 method. Which is that?

5) Which method causes yield()


currently executing thread
object to temporarily pause
and allow other threads to
execute

Q-5) Write a short note on Thread Synchronization? OR


Write a short note on Multithreading
Ans:

❖ Synchronization in Java is the capability to control the access of multiple


threads to any shared resource.
❖ Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
❖ Synchronization can be achieved by:
o Using Synchronized method
o Using Synchronized block
o Using Static Synchronization

Why use Synchronization?

❖ The synchronization is mainly used to

1. To prevent thread interference.

143
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2. To prevent consistency problem.

❖ Below example shows the scenario where synchronization is not there. In


the below example, thread t1 and thread t2 are not synchronized so thread
t1 prints table of 5 and simultaneously thread t2 prints table of 10. So in
this case, synchronization is required.

144
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class table
{
void printtable(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link](e);
}
}
}
}
class mythread1 extends Thread
{
table t;
mythread1(table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}
class mythread2 extends Thread
{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
[Link](10);
}
} 145
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new mythread1(o);
mythread2 t2=new mythread2(o);
[Link]();
[Link]();
}
}

146
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example with synchronization:

class table
{
synchronized void printtable(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](500);
}
catch(InterruptedException e)
{
[Link](e);
}
}
}
}

class mythread1 extends Thread


{
table t;
mythread1(table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

147
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class mythread2 extends Thread


{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new mythread1(o);
mythread2 t2=new mythread2(o);
[Link]();
[Link]();
}
}

MCQ
1) ……..is the capability to Synchronization
control the access of multiple
threads to any shared
resource.

2) What are the advantages of 1) To reduce conflicts among


Synchronization? threads
148
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2) To avoid interference among


threads

Q-6) Write a short note on Daemon and Non-Daemon Thread


Ans:
Daemon Thread:

❖ Damon thread in java is a low-priority thread that runs in the background


to perform tasks such as garbage collection.
❖ Daemon thread in java is also a service provider thread that provides
services to the user thread.

Non-Daemon Thread:

❖ Non-Damon thread in java is a thread that does not run in the background.
❖ Non-daemon thread in java are not service provider

Daemon Threads User Threads (Non-daemon)


Daemon threads are created by JVM User threads are created by an
application itself
JVM does not wait for its execution JVM waits until the execution
completes
Low Priority threads High priority threads
Used for background tasks(not Used for foreground tasks(critical)
critical)
Life is dependent on user threads Life is independent

149
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-7) what is Stream? Explain types


Ans:
❖ A stream is a sequence of data. In Java, a stream is composed of bytes.
It's called a stream
❖ Java uses the concept of a stream to make I/O operation fast. The [Link]
package contains all the classes required for input and output operations.
❖ In general, a Stream will be an input stream or, an output stream.

• InputStream − this is used to read data from a source.


• OutputStream − this is used to write data to a destination.
❖ Based on the data they handle there are two types of streams −

• Byte Streams − these handle data in bytes (8 bits) i.e., the byte
stream classes read/write data of 8 bits. Using these you can
store characters, videos, audios, images etc.
• Character Streams − these handle data in 16 bit Unicode.
Using these you can read and write text data only.

150
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

** Difference between byte stream and character stream:


Byte Stream Character Stream
Java Byte streams are used to perform Java Character streams are used to
input and output of 8-bit bytes perform input and output for 16-bit
Unicode.
Byte stream are not tied to any data Character stream are tied to data type.
type. Data of any data type can be Only string or character data type can
read be read.
Byte stream reads byte by byte Character stream reads character by
character
Byte stream are known as data Character streams are also known as
streams-Data input stream and Data reader and writer streams.
Output Stream

151
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) …….is sequence of data Stream

2) Which package contains all the [Link] package


class for input and output
operations?
3) Which streams are used to Byte Stream
perform input and output for 8-
bit bytes

4) Which stream are tied to data Character Stream


type?

Q-8) what is File Class?


Ans:
❖ The File class is an abstract representation of file and directory pathname.
❖ A pathname can be either absolute or relative.
❖ The File class have several methods for working with directories and files
such as creating new directories or files, deleting and renaming directories or
files, listing the contents of a directory etc.

152
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
class filedemo
{
public static void main(String args[])
{
File f=new File("d:\\[Link]");
if([Link]())
[Link]("\n File Exists");
else
[Link]("\n File does not exists");
}
}

153
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Creating a new file:


❖ Create a File operation is performed to create a new file.
❖ We use the createNewFile() method of file.
❖ The createNewFile() method returns true when it successfully creates a
new file and returns false when the file already exists.

Example:

import [Link].*;
import [Link];

class crf
{
public static void main(String args[])
{
try
{
File f=new File("D:\\[Link]");
if([Link]())
[Link]("Created");
else
[Link]("Not Created");
}
catch(IOException e)
{
[Link](e);
}
}

Getting the file information:


❖ The operation is performed to get the file information. We use several
methods to get the information about the file like name, absolute path, is
readable, is writable and length.

154
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
import [Link];

classExplain
Q-8) crf Random Access File?
{
public static void main(String args[])
{

File f=new File("D:\\[Link]");


if([Link]())
{
[Link]("Name of file: "+[Link]());
[Link]("Path of file:
"+[Link]());
[Link]("Path of file: "+[Link]());
}
else
{
[Link]("Does not exists");
}

Write into file:


❖ In order to write data into a file, we will use the FileWriter class and
its write() method together. We need to close the stream using
the close() method to retrieve the allocated resources.

Example:

155
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link];

class crf
{
public static void main(String args[])
{
try
{
FileWriter w=new FileWriter("d:\\[Link]");
[Link]("Hello");
[Link]();
}
Read from thecatch(IOException
file: e)
{
[Link](e);
}

❖ In order to write data into a file, we will use the Scanner class. Here, we
need to close the stream using the close() method.
❖ We will create an instance of the Scanner class and use
the hasNextLine() method nextLine() method to get data from the file.

Example:

156
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link];
import [Link].*;

class crf
{
public static void main(String args[])
{
try
{
File f=new File("D:\\[Link]");
Scanner s=new Scanner(f);
while([Link]())
{
String fd=[Link]();
[Link](fd);
}
[Link]();
}
catch(FileNotFoundException e)
{
[Link](e);
}

Delete from the file:


❖ In order to delete a file, we will use the delete() method of the file. We
don't need to close the stream using the close() method because for
deleting a file

Example:

157
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;

class del
{
public static void main(String args[])
{
File f=new File("D:\\[Link]");
if([Link]())
[Link]("Deleted");
else
[Link]("Not Deleted");
}
}

MCQ
1) Which method is used to create createNewFile()
the file?
2) createNewFile() must be used IOException
with ……..exception
3) In order to write the data into FileWriter
file, which class is used?
4) Which class is used to read the Scanner
data from the file?
5) hasnextLine() and nextLine() are Scanner
the methods of ……..class

6) ……….method is used to delete delete()


the file

158
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-9) what is Random Access File Class?


Ans:
❖ A sequential file structure is the common way where records are stored in
order by the record key field.
❖ Random file access is the superimposed mechanism implemented through
Java code to access individual records directly and quickly without
searching through records in the file
❖ The RandomAccessFile class allows you to write programs that can seek
to any location in a file and read or write data at that point.
❖ This type of functionality is very valuable in some programs.

Method Description
Void close() Close the file.
Long Returns the current position of the file pointer. This
getFilePointer() identifies the point at which the next byte is read or
written.
Long length() Returns the number of bytes in the file.
Int read() Reads and returns a byte from the file. Waits until
data is available.
Int read(byte Attempts to read size bytes from the file and places
buffer[], int index, these in buffer starting at position index. Returns the
int size) number of bytes actually read. Waits until data is
available.
Int read(byte Reads bytes form the file and places these in buffer.
buffer[]) Returns the number of bytes read. Waits until data
is available.
Void seek(long n) Positions the file pointer at n bytes form the
beginning of the file. The next read or write occurs
at this position.

159
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Int skipBytes(int n) Adds n to the file pointer. Returns the actual number
of bytes skipped. If n is negative, no bytes are
skipped.

Example

import [Link].*;
class Random1
{
public static void main(String args[])
{
try
{
RandomAccessFile f=new RandomAccessFile("[Link]","rw");
[Link](‘k’);
[Link](10);
[Link](10.2);
[Link](0);

[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](2);
[Link]([Link]());
[Link]();
}

catch(IOException e)
{
[Link](e);
}
}
}

160
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Random Access is used to read,write
perform ……and
………..operations both
simultaneously
2) In random access file, the file can seek()
be moved to any location using
………….method

Q-10) Write a short note on character stream class


Ans:
❖ The [Link] package provides character stream classes to overcome the
limitations of byte stream classes which can only handle 8 bit and is not
compatible to work directly with characters.
❖ Character stream classes are used to work with 16 bit.
❖ Generally, character stream classes are used to read the characters from
the source and write them into destination.

Classes of Character Stream


Class Description
Buffered This class provides the methods to read characters from
Reader buffer
FileReader This class provides the methods to read characters from
the file
BufferedWriter This class provides the methods to write the characters
to the buffer
FileWriter This class provides the methods to write the characters
to the file.

161
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

File Reader Class and File Writer Class:


❖ Java FileWriter and FileReader classes are used to write and read data
from text files
❖ Unlike FileOutputStream class, you don't need to convert string into
byte array because it provides method to write string directly.

Methods of File Reader and File Writer


Methods Description
int read() This method returns the integral representation of the
next character present in the input.
void write() This method is used to write the data to the output
stream
void flush() This method is used to flush the output stream
FileWriter This class provides the methods to write the characters
to the file.

Example of File Reader and File Writer

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new FileReader("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
} 162
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new FileWriter("D:\\[Link]");
[Link]("Hello");
Buffered Reader Class and Buffered Writer Class:
[Link]();

}
❖ The "BufferedWriter"
catch(IOExceptionclass
e) of java supports writing a chain of
❖ {
❖ [Link](e);
❖ }
}
}

❖ characters output stream (Text based) in an efficient way. The Chain-Of-


Characters can be Arrays, Strings etc. The "BufferedReader" class is
used to read stream of text from a character based input stream.
❖ The BufferedReader and BufferedWriter class provides support for
writing and reading

163
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example of Buffered Reader and Buffered Writer:

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new FileWriter("D:\\[Link]");
BufferedWriter b=new BufferedWriter(f);
[Link]("Hello");
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

164
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new FileReader("D:\\[Link]");
BufferedReader b=new BufferedReader(f);
int i;
while(i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

MCQ
1) Character Stream class works on 16
…….bits
2) BufferedReader inherits from FileReader
………

165
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-11) Write a short note on Byte stream class


Ans:
❖ Byte Stream classes are used to read bytes from the input stream and
write bytes to the output stream. In other words, we can say that Byte
Stream classes read/write the 8-bits.
❖ The Byte Stream classes are divided into two types of classes, i.e., Input
Stream and Output Stream.

InputStreamClass:
❖ The Input Stream class provides methods to read bytes from a file,
console or memory. It is an abstract class and can't be instantiated.
❖ The subclass of Input Stream class are:

SN Class Description

1 BufferedInputStream This class provides methods to read bytes from the


buffer.

2 ByteArrayInputStream This class provides methods to read bytes from the


byte array.

3 DataInputStream This class provides methods to read Java primitive


data types.

4 FileInputStream This class provides methods to read bytes from a file.

5 FilterInputStream This class contains methods to read bytes from the


other input streams, which are used as the primary
source of data.

6 ObjectInputStream This class provides methods to read objects.

166
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

7 PipedInputStream This class provides methods to read from a piped


output stream to which the piped input stream must be
connected.

Methods of File InputStream


Methods Description
int read() It is s used to read the byte from the current stream
void flush() This method is used to flush the input stream
void close() It is used to close the input stream

OutputStreamClass:
❖ The [Link] class is the superclass of all classes
representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.

SN Class Description

1 BufferedOutputStream This class provides methods to write bytes in the


buffer.

2 ByteArrayOutputStream This class provides methods to write bytes from the


byte array.

3 DataOutputStream This class provides methods to write Java primitive


data types.

4 FileOutputStream This class provides methods to write bytes in a file.

5 FilterOutputStream This class contains methods to write bytes in the


other input streams, which are used as the primary
source of data.

167
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

6 ObjectOutputStream This class provides methods to write objects.

7 PipedOutputStream This class provides methods to write in a piped


output stream to which the piped input stream must
be connected.

Methods of File OutputStream


Methods Description
int write() It is s used to write the byte in the current stream
void flush() This method is used to flush the output stream
void close() It is used to close the output stream

FileInputStreamClass
❖ Java FileInputStream class obtains input bytes from a file.
❖ It is used for reading byte-oriented data (streams of raw bytes) such as image
data, audio, video etc.

Methods of File Input Stream


Methods Description
int read() It is s used to read the byte from the current stream
void flush() This method is used to flush the input stream
void close() It is used to close the input stream

FileOutputStreamClass
❖ FileOutputStream is an output stream used for writing data to a file.
❖ If you have to write primitive values into a file, use FileOutputStream class.
❖ You can write byte-oriented as well as character-oriented data through
FileOutputStream class.

168
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Methods of File Output Stream


Methods Description
int write() It is s used to write the byte in the current stream
void flush() This method is used to flush the output stream
void close() It is used to close the output stream

Example of FileOutputStream and FileInputStream:


import [Link].*;

class inp
{
public static void main(String args[])
{
try
{
FileOutputStream f=new
FileOutputStream("D:\\[Link]");
[Link](10);
FileInputStream f1=new FileInputStream("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}
}
catch(IOException e)
{
[Link](e);
}
}
}

DataInputStreamClass and DataOutputStream Class:


❖ The DataInputStream class read primitive Java data types from an underlying
input stream in a machine-independent way. While
the DataOutputStream class write primitive Java data types to an output
stream in a portable way.
169
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example of DataInputStream and DataOutputStream:

import [Link].*;
class da
{
public static void main(String args[])throws IOException
{
FileOutputStream f=new
FileOutputStream("D:\\[Link]");
DataOutputStream f1=new DataOutputStream(f);
[Link](10);
FileInputStream f2=new FileInputStream("D:\\[Link]");
DataInputStream f3=new DataInputStream(f2);
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}

[Link]();
[Link]();
}
}

Program: Write a program to copy the data of one file into another file
import [Link].*;
class cop
{
public static void main(String args[])throws IOException
{
FileInputStream f=new FileInputStream("D:\\[Link]");
FileOutputStream f1=new
FileOutputStream("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();
[Link]();
}
} 170
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Byte stream class works on 8 ibts
…………bits
2) Which subclass of byte stream DataInputStream and
class is used to read and write the DataOutputStream
primitive data types

Q-12) Write a short note on Stream Tokenizer Class


Ans:
❖ The [Link] class takes an input stream and parses it into
"tokens", allowing the tokens to be read one at a time.
❖ The stream tokenizer can recognize identifiers, numbers, quoted strings, and
various comment styles.
❖ For StreamTokenizer, the source is a character stream, Reader.
❖ Following constant variables used to decide the type of the token:

int ttype When the nextToken() returns a token, this field can
be used to decide the type of the token.
int TT_EOF This field is used to know the end of file is reached.
int TT_EOL This field is used to know the end of line is reached.
int This field is used to decide the token returned by the
TT_NUMBER nextToken() method is a number or not.
int TT_WORD This field is used to decide the token returned by the
nextToken() method is a word or not.
String sval If the token is a word, this filed contains the word
that can be used in programming.
double nval If the token is a word, this filed contains the number
that can be used in programming.

171
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;

class stto
{
public static void main(String args[])throws IOException
{
FileReader r=new FileReader("D:\\[Link]");
StreamTokenizer st=new StreamTokenizer(r);
double sum=0;
int n=0;
while([Link]()!=st.TT_EOF)
{
if([Link]==StreamTokenizer.TT_NUMBER)
sum=sum+[Link];
else if([Link]==StreamTokenizer.TT_WORD)
n++;
}
[Link]("Sum:" +sum);
[Link]("Total Words: "+n);
}
}

MCQ
1) Which class takes an input stream Stream Tokenizer
and parses it in to tokens?
2) Which constant is used to ttype
indicate type of token?
3) TT_EOF indicates ……………. End of File

4) Which constant is used to check TT_NUMBER


whether the returned token is
number or not?
5) Which constant is used to check TT_WORD
whether the returned token is word
or not?

172
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-13) Write a short note on Piped Input and Output Stream


Ans:
❖ The PipedInputStream and PipedOutputStream classes can be used to
read and write data simultaneously.
❖ Both streams are connected with each other using the connect() method
of the PipedOutputStream class.

import [Link].*;

class pipe
{
public static void main(String args[])
{
PipedOutputStream out=new PipedOutputStream();
PipedInputStream in=new PipedInputStream();
try
{
[Link](out);
[Link](23);
[Link](24);
for(int i=0;i<2;i++)

[Link]([Link]());
}
catch(IOException e)
{
[Link](e);
}
}
}

173
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which method is used to connect connect()
piped input stream with piped
output stream
2) What is main Feature of piped Allows to read and write the data
stream? simultaneously

Q-14) Write a short note on Bridge Class


Ans:
InputStreamReader:
❖ An InputStreamReader is a bridge from byte streams to character streams:
It reads bytes and decodes them into characters using a specified charset.

import [Link].*;
class br
{
public static void main(String args[])throws IOException
{
FileInputStream f=new FileInputStream("D:\\[Link]");
InputStreamReader r=new InputStreamReader(f);
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
OutputStreamWriter:
}
[Link]();
}
}

❖ OutputStreamWriter is a which is used to convert character stream to


byte stream, the characters are encoded into byte using a specified

174
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

charset. write() method calls the encoding converter which converts the
character into bytes.

import [Link].*;
class br
{
public static void main(String args[])throws IOException
{
FileOutputStream f=new
FileOutputStream("D:\\[Link]");
OutputStreamWriter w=new OutputStreamWriter(f);
[Link]("hello world");
[Link]();
}
}
}

ObjectInputStream and ObjectOutputStream:


❖ The objectinputstream class is mainly used to deserialize the primitive
data and objects which are written by using ObjectOutputStream.

import [Link].*;
class br
{
public static void main(String args[])throws IOException
{
int i=10;
FileOutputStream f=new FileOutputStream("d:\\[Link]");
ObjectOutputStream o=new ObjectOutputStream(f);
[Link](i);

FileInputStream f1=new FileInputStream("d:\\[Link]");


ObjectInputStream o1=new ObjectInputStream(f1);
[Link]("Integer:" +[Link]());
;
[Link]();
[Link]();
}

}
175
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) ……..class is used to convert byte InputStreamReader
stream to character stream class?
2) Which class is used to convert OutputStreamWriter
character stream to byte stream
class?

176
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Unit-4

Applet and Layout Managers


Q-1 what is Applet? Explain life cycle of Applet
Ans:
❖ In Java, an applet is a special type of program embedded in the web page
to generate dynamic content.
❖ Applet is a class in java.
❖ Appletviewer is a program that can run applet
❖ In java, non-applet programs are called applications.
❖ The Applet package is the package that is specially designed for working
with applets.
Advantage:
1) It works at client side so less time
2) Secured
3) It can be executed by browsers running under many platforms,
including Linux, Mac OS etc

Java Application Applet


1) Java application contains main() 1) Applet does not contain main()
2) Does not require internet 2) Requires internet connection to
connection to execute execute
3) It is stand alone application 3) It is a part of web page.
4) Can be executed without browser 4) Requires compatible browser
5) Used for Console Programs 5) Used for GUI Interfaces

Applet Life Cycle:

❖ The applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of its
application. It basically has five core methods namely init(), start(), stop(),
paint() and destroy().These methods are invoked by the browser to execute.

177
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ Following are the methods that are executed during life cycle of an
applet.

1) init():
❖ It is used to initialize the applet
❖ It is invoked when applet is first loaded
❖ It is invoked only once
2) start():
❖ It is invoked after the init()
❖ It is invoked when the applet is started or restarted
3) paint():
❖ This method is invoked immediately after the start()
❖ It is called anytime when the applet needs to repaint itself in the browser.
4) stop():
❖ It is used to stop the applet
❖ It is invoked when the applet stop or browser is minimized
5) destroy():
❖ It is used to destroy the applet
❖ It is invoked only once
❖ It is invoked when the browser unloads the applet

178
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;
/*<applet code="ap" width=200 height=200>
</applet>*/
public class ap extends Applet {
String msg="";
public void init()
{
msg+="init()called";
}
public void start()
{
msg+="start() called";
}
public void paint(Graphics g)
{
[Link](msg,30,30);
}
public void stop()
{
msg+="stop() called";
}
public void destroy()
{
msg+="destroy called";
}
}

MCQ
1) An ……… is a special type of applet
program embedded in the web page
to generate dynamic content...
2) ……….method of the applet is init()
used to initialize the applet

179
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3) ……….method of the applet is paint()


used to repaint in the browser
4) ……….method of applet is used stop()
to stop the applet

Q-2 How to pass parameters in Applet.


Ans:
❖ To pass the parameters to the Applet we need to use the param attribute
of <applet> tag.
❖ To retrieve a parameter's value, we need to use
the getParameter() method of Applet class.

import [Link].*;
import [Link].*;
/*<applet code="par" width=200 height=100>
<param name="Stuname" value="xyz">
<param name="roll" value="12">
</applet>*/

public class par extends Applet


{
String name1;
String roll;
Font f1;
public void init()
{
f1=new Font("Arial",[Link],32);
name1=getParameter("Stuname");
roll=getParameter("roll");
}
public void paint(Graphics g)
{
[Link](f1);
[Link]("Name:"+ name1,50,20);
[Link]("Roll:" +roll,250,20);
}
}
180
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which method is used to get the getParameter()
parameter when the parameters
are passed in the applet

Q-3 Write a short note on graphics class


Ans:
❖ Following is the list of graphics class:
o Flow Laoyout
o Border Layout
o Card Layout
o Grid Layout
o GridBag Layout

Flow Layout
❖ The Java FlowLayout class is used to arrange the components in a line,
one after another (in a flow). It is the default layout of the applet or panel

import [Link].*;
import [Link].*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Label b1,b2,b3;
public void init()
{
setLayout(new FlowLayout());
b1=new Label("OK");
b2=new Label("Open");
b3=new Label("Close");
add(b1);
add(b2);
add(b3);

}
}
181
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Border Layout:

❖ The BorderLayout is used to arrange the components in five regions: north,


south, east, west, and center. Each region (area) may contain one
component only. It is the default layout of a frame or window. The
BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

import [Link].*;
import [Link].*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Button b1,b2,b3,b4,b5;
public void init()
{
setLayout(new BorderLayout());
b1=new Button("NORTH");
b2=new Button("SOUTH");
b3=new Button("EAST");
b4=new Button("WEST");
b5=new Button("CENTER");
add(b1,[Link]);
add(b2,[Link]);
add(b3,[Link]);
add(b4,[Link]);
add(b5,[Link]);

}
}

182
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Card Layout:
❖ The Java CardLayout class manages the components in such a manner
that only one component is visible at a time. It treats each component as a
card that is why it is known as CardLayout.

Example:

import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="card" width=200 height=200>


</applet>*/

public class card extends Applet


{
Button b1,b2,b3;
Font f;

public void init()


{
f=new Font("Arial", [Link],32);
setLayout(new CardLayout);
b1=new Button("OK");
Grid Layout: b2=new Button("Cancel");
❖ The Javab3=new Button("Close");
Grid Layout class is used to arrange the components in a
[Link](f);
rectangular grid. One component is displayed in each rectangle.
[Link](f);
[Link](f);
Example: add(b1);
add(b2);
add(b3);
}

183
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

/*<applet code="gri" width=200 height=200>


</applet>*/

public class gri extends Applet


{
Button b1,b2,b3,b4,b5;
Font f;
public void init()
{
setLayout(new GridLayout(3,3));
f=new Font("Arial",[Link],32);
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
Grid BagLayout: b5=new Button("5");
❖ The [Link](f);
GridBagLayout class is used to align components vertically,
[Link](f);
horizontally or along their baseline.
[Link](f);
❖ The components
[Link](f);
may not be of the same size. Each GridBagLayout
[Link](f);
object maintains a dynamic, rectangular grid of cells. Each component
add(b1);
occupiesadd(b2);
one or more cells known as its display area
add(b3);
add(b4);
add(b5);
}
}

184
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
import [Link].*;

/*<applet code="gri" width=200 height=200>


</applet>*/

public class gri extends Applet


{
Button b1,b2;
public void init()
{
setLayout(new GridBagLayout());
Button b1=new Button("Ok");
Button b2=new Button("Cancel");
Button b3=new Button("Close");
Button b4=new Button("Hi");
GridBagConstraints gc=new GridBagConstraints();
[Link]=[Link];
[Link]=0;
[Link]=0;
[Link](b1,gc);
[Link]=0;
[Link]=1;
[Link](b2,gc);
[Link]=1;
[Link]=0;
[Link](b3,gc);
[Link]=2;
[Link]=2;
[Link]=2;
[Link](b4,gc);
}
}

185
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which layout is used to FlowLayout
arrange the components line
by line?
2) Which layout can arrange the BorderLayout
components in different 5
areas?
3) In which layout only 1 Card Layout
component is displayed at one
time?
4) Which layout arranges the Grid Layout
components in row and
columns?

186
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Unit-5:

GUI using swing and Event Handling

Q-1 what is Awt? What is Swing?


Ans:
Awt:
❖ AWT and Swing are used to develop window-based applications in
Java.
❖ Awt is an abstract window toolkit that provides various component
classes like Label, Button, TextField, etc., to show window
components on the screen. All these classes are part of the [Link]
package.
Swing:
❖ On the other hand, Swing is the part of JFC (Java Foundation
Classes) built on the top of AWT and written entirely in Java. The
[Link] API provides all the component classes like JButton,
JTextField, JCheckbox, JMenu, etc.
❖ The components of Swing are platform-independent, i.e., swing
doesn't depend on the operating system to show the components.
Also, the Swing's components are lightweight.

MCQ
1) ……….is a window toolkit AWT
that provides various
components like babel,
button, textfield etc.
2) ………….is the part of JFC Swing
built on top of AWT and
written entirely in java

187
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3) JFC stands for ……….. Java Foundation Class

4) The components of swing are True


platform independent (T/F)?

Q-2 Differentiate Awt and Swing Components


Ans:
Difference between Awt and Swing Components:
Awt Components Swing Components
1) Awt components classes are 1) Swing components are provided by
provided by [Link] package [Link] package
2) The Components used in AWT are The Components used in Swing are
mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.
3) The AWT is heavyweight since it 3) The Swing is mostly lightweight
uses the resources of the operating since it doesn't need any Operating
system. system object for processing. The
Swing Components are built on the top
of AWT.
4) The Appearance of AWT 4) The Swing Components are
Components is mainly not configurable and mainly support
configurable. It generally depends on pluggable look and feel
the operating system's look and feels.
5) The Java AWT provides a smaller 5) Java Swing provides a greater
number of components in comparison number of components than AWT,
to Swing. such as list, scroll panes, tables, color
choosers, etc.
6) Java AWT has 21 peers There is one 6) Java Swing has only one peer in the
peer for each control Peers are form of OS's window object, which
provided by the operating system in provides the drawing surface used to
the form of widgets themselves. draw the Swing's widgets
7) Java AWT needs a higher amount 7) Java Swing needs less memory
of memory for the execution. space as compared to Java AWT.

188
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

8) Java AWT is slower than swing in 8) Java Swing is faster than the AWT.
terms of performance.

Q-3 Write a short note on Swing Components:


Ans:

1) Image Icon:

❖ The ImageIcon component creates an icon sized-image from an image


residing at the source URL.
Example:

ImageIcon homeIcon = new


ImageIcon(“src/images/[Link]”);
❖ This returns an icon of a home button. The string parameter is the path at
which the source image is present.

2) JButton:

❖ JButton class is used to create a push-button on the UI.


❖ The button can contain some display text or image.

189
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ It generates an event when clicked and double-clicked.


❖ A JButton can be implemented in the application by calling one of its
constructors.

Example:
JButton okBtn = new JButton(“Ok”);
❖ This constructor returns a button with text Ok on it.

JButton homeBtn = new JButton(homeIcon);


❖ It returns a button with a homeIcon on it.
JButton btn2 = new JButton(homeIcon, “Home”);

3) JLabel:

❖ JLabel class is used to render a read-only text label or images on the UI.
It does not generate any event.
Example:
JLabel textLbl = new JLabel(“This is a text label.”);
❖ This constructor returns a label with text.
JLabel imgLabel = new JLabel(homeIcon);
❖ It returns a label with a home icon.

4) JTextField:

❖ JTextField renders an editable single-line text box.


❖ A user can input non-formatted text in the box.
❖ To initialize the text field, call its constructor and pass an optional integer
parameter to it. This parameter sets the width of the box measured by the
number of columns.
❖ It does not limit the number of characters that can be input in the box.
Example:
JTextField txtBox = new JTextField(20);
❖ It renders a text box of 20 column width.

190
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5) JTextArea:

❖ JTextArea class renders a multi-line text box. Similar to the JTextField, a


user can input non-formatted text in the field.
❖ The constructor for JTextArea also expects two integer parameters which
define the height and width of the text-area in columns.
❖ It does not restrict the number of characters that the user can input in the
text-area.
Example:

JTextArea txtArea = new JTextArea(“This text is default text for text area.”, 5,
20);
❖ The above code renders a multi-line text-area of height 5 rows and width
20 columns, with default text initialized in the text-area.

6) JPasswordField:

❖ JPasswordField is a subclass of JTextField class. It renders a text-box that


masks the user input text with bullet points. This is used for inserting
passwords into the application.
Example:
JPasswordField pwdField = new JPasswordField(15);
var pwdValue = [Link]();
❖ It returns a password field of 15 column width. The getPassword method
gets the value entered by the user.

7) JCheckBox:

❖ JCheckBox renders a check-box with a label. The check-box has two


states – on/off. When selected, the state is on and a small tick is displayed
in the box.
Example:
CheckBox chkBox = new JCheckBox(“Show Help”, true);

191
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ It returns a checkbox with the label Show Help. The second parameter in
the constructor. It is a boolean value that indicates the default state of the
check-box. True means the check-box is defaulted to on state.

8) JRadioButton:

❖ JRadioButton is used to render a group of radio buttons in the UI. A user


can select one choice from the group.
Example:
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton rb1 = new JRadioButton(“Easy”, true);
JRadioButton rb2 = new JRadioButton(“Medium”);
JRadioButton rb3 = new JRadioButton(“Hard”);
[Link](rb1);
[Link](rb2);
[Link](rb3);
❖ The above code creates a button group and three radio button elements.
All three elements are then added to the group. This ensures that only one
option out of the available options in the group can be selected at a time.

9) JList:

❖ JList component renders a scrollable list of elements. A user can select a


value or multiple values from the list. This select behavior is defined in
the code by the developer.
Example:
DefaultListItem cityList = new DefaultListItem();
[Link](“Mumbai”):
[Link](“London”):
[Link](“New York”):
[Link](“Sydney”):
[Link](“Tokyo”):

192
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

JList cities = new JList(cityList);


[Link](ListSelectionModel.SINGLE_SELECTION);
❖ The above code renders a list of cities with 5 items in the list
❖ . The selection restriction is set to SINGLE_SELECTION. If multiple
selections is to be allowed, set the behaviour to
MULTIPLE_INTERVAL_SELECTION.

10) JComboBox:

❖ JComboBox class is used to render a dropdown of the list of options.


Example:
String[] cityStrings = { "Mumbai", "London", "New York", "Sydney",
"Tokyo" };
JComboBox cities = new JComboBox(cityList);
[Link](3);
❖ The default selected option can be specified through the setSelectedIndex
method. The above code sets Sydney as the default selected option.

11) JFileChooser

❖ JFileChooser class renders a file selection utility. This component lets a


user select a file from the local system.
Example:
JFileChooser fileChooser = new JFileChooser();
JButton fileDialogBtn = new JButton(“Select File”);
[Link](new ActionListner(){
[Link]();
})
var selectedFile = [Link]();
❖ The above code creates a file chooser dialog and attaches it to the button.
❖ The button click would open the file chooser dialog.
❖ The selected file is returned through the getSelectedFile method.

12) JTabbedPane:
193
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ JTabbedPane is another very useful component that lets the user switch
between tabs in an application. This is a highly useful utility as it lets the
user browse more content without navigating to different pages.
Example:
JTabbedPane tabbedPane = new JTabbedPane();
[Link](“Tab 1”, new JPanel());
[Link](“Tab 2”, new JPanel());
❖ The above code creates a two tabbed panel with headings Tab 1 and Tab
2.

13) JSlider:

❖ JSlider component displays a slider which the user can drag to change its
value. The constructor takes three arguments – minimum value,
maximum value, and initial value.
Example:
JSlider volumeSlider = new JSlider(0, 100, 50);
var volumeLevel = [Link]();

194
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Q-3 Write a short note on Event Delegation Model


Ans:

❖ It defines a standard and compatible mechanism to generate and process


events. In this model, a source generates an event and forwards it to one or
more listeners. The listener waits until it receives an event.
❖ Once it receives the event, it is processed by the listener and returns it. The
UI elements are able to delegate the processing of an event to a separate
function.
❖ The key advantage of the Delegation Event Model is that the application
logic is completely separated from the interface logic.
❖ In this model, the listener must be connected with a source to receive the
event notifications. Thus, the events will only be received by the listeners
who wish to receive them.
❖ Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

195
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Events

❖ The Events are the objects that define state change in a source.
❖ An event can be generated as a reaction of a user while interacting with
GUI elements. Some of the event generation activities are moving the
mouse pointer, clicking on a button, pressing the keyboard key etc

Event Sources

❖ A source is an object that causes and generates an event. It generates an


event when the internal state of the object is changed. The sources are
allowed to generate several different types of events.

Event Listeners

❖ An event listener is an object that is invoked when an event triggers.

The listeners require two things; first, it must be registered with a source;
however, it can be registered with several resources to receive notification about
the events. Second, it must implement the methods to receive and

196
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:

import [Link].*;
import [Link].*;

public class ac1 implements ActionListener


{
JTextField t;
ac1()
{
JFrame f=new JFrame();

JButton b1=new JButton("Submit");


[Link](80,200,80,30);
t=new JTextField();
[Link](80,250,80,30);

[Link](b1);
[Link](t);
[Link](this);
[Link](null);
[Link](300,300);
[Link](true);
}
public void actionPerformed(ActionEvent e)
{
[Link]("Hello World");
}
public static void main(String args[])
{
ac1 a=new ac1();
}

197
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which are components of event Event, Event Source, Event Listener
delegation model?
2) Event Listener must be True
registered with event source?
(T/F)?

Q-3 Write a short note on Event packages OR


Write a short note on Awt and swing Event Package
Ans:
❖ The [Link] package defines classes and interfaces used for event
handling in the AWT and Swing. The members of this package fall into
three categories:

Event Class:
❖ The classes with names ending in "Event" represent specific types of
events, generated by the AWT or by one of the AWT or Swing
components.

Listeners:
❖ The interfaces in this package are all event listeners; their names end with
"Listener". These interfaces define the methods that must be implemented
by any object that wants to be notified when a particular event occurs.
❖ There is a listener interface for each Event Class.

Adapters:
❖ Java adapter classes provide the default implementation of
listener interfaces. If you inherit the adapter class, you will not be forced
to provide the implementation of all the methods of listener interfaces. So
it saves code.

198
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

3) Action Event:
❖ The ActionEvent is generated when button is clicked or the item of a list
is double clicked.
❖ It is notified against ActionEvent.
❖ The ActionListener interface is found in [Link] package.
❖ It has only one method: actionPerformed().

actionPerformed():

❖ The actionPerformed() method is invoked automatically whenever you


click on the registered component.

199
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class buttoncli implements ActionListener


{
JFrame f;
JButton b;
JTextField t;
buttoncli()
{
f=new JFrame();
b=new JButton("Submit");
[Link](100,150,100,20);
t=new JTextField();
[Link](150,100,50,20);
[Link](this);
[Link](b);
[Link](t);
[Link](400,400);
4) Item Event: [Link](true);
[Link](null);
❖ The }
Java ItemListener is notified whenever you click on the checkbox. It
ispublic
notified
voidagainst ItemEvent.
actionPerformed(ActionEvent e)
❖ The { ItemListener interface is found in [Link] package.
❖ It has only [Link]("Hello
one method: World");
itemStateChanged().
}
itemStateChanged():
public static void main(String args[])
❖ The { itemStateChanged() method is invoked automatically whenever you
click or buttoncli
unclick c=new
on thebuttoncli();
registered checkbox component.
}

200
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class check implements ItemListener


{
JFrame f;
JCheckBox c1,c2;
JLabel l;
check()
{
f=new JFrame();
l=new JLabel();
[Link](50,100,50,50);
c1=new JCheckBox("C#");
[Link](100,150,50,50);
c2=new JCheckBox("Java");
[Link](100,250,50,50);
[Link](this);
[Link](this);
[Link](c1);
[Link](c2);
[Link](l);
[Link](null);
[Link](300,300);
[Link](true);
}
public void itemStateChanged(ItemEvent e)
{
if([Link]()==c1)
[Link]("Checkbox 1 checked");
else
[Link]("Checkbox 2 checked");
}

public static void main(String args[])


{ 201
check e=new check();
}
}
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5) Focus Event:
❖ A low-level event which indicates that a component has gained or lost
the input focus
❖ The ItemListener interface is found in [Link] package.
❖ It has only two methods: foucsGained() and focusLost()

foucsGained():
❖ This method is invoked automatically whenever any component gains the
focus.

focusLost()
❖ This method is invoked automatically when window is closed. The focus
is lost when the window is closed.

202
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class focus1 implements FocusListener


{
JFrame f;
JTextField tf;

focus1()
{
f=new JFrame();
tf=new JTextField();
[Link](80,150,80,80);
[Link](this);
[Link](tf);
[Link](null);
[Link](300,300);
[Link](true);
}
public void focusGained(FocusEvent e)
{
[Link]("Focus Gained");
}
public void focusLost(FocusEvent e)
{
[Link]("Focus Lost");
}

public static void main(String args[])


{
focus1 f=new focus1();
}
}

203
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

6) Adjustment Event:
❖ The adjustment event emitted by Adjustable objects like Scrollbar
and Scroll Pane.
❖ When the user changes the value of the scrolling component, it receives
an instance of Adjustment Event.
❖ It has only one method: adjustmentValueChanged()

adjustmentValueChanged():
❖ This method is invoked automatically to get the value of scrolling

204
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

❖ class adjus implements AdjustmentListener
public
{ ❖
❖ f;
JFrame

JScrollBar s;
JTextField tf;

❖ component
adjus()
{
f=new JFrame();
tf=new JTextField();
[Link](80,100,80,80);
s=new JScrollBar();
[Link](80,150,80,80);
[Link](this);

[Link](s);
[Link](tf);
[Link](null);
[Link](300,300);
[Link](true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
Integer i=[Link]();
[Link]([Link]());
}

public static void main(String args[])


{
adjus f=new adjus();
}
}

205
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

7) Window Event:
❖ A low-level event that indicates that a window has changed its status.
❖ This low-level event is generated by a Window object when it is opened,
closed, activated, deactivated, iconified, or deiconified, or when focus is
transfered into or out of the Window.
❖ It has only following methods:

windowOpened():
❖ This method is executed only the first time a window is made visible.

windowClosed():
❖ This method is executed when the window has been closed

WindowActivated():
❖ This event is delivered when the Window becomes the active window

WindowDeactivated():
❖ This event is delivered when the Window is no longer active window.

WindowClosing():
❖ This event is delivered when the user attempts to close the window from
the window's system menu

WindowIconified():
❖ This event is delivered when the window has been changed from a
normal to a minimized state

WindowDeiconified():
❖ This event is delivered when the window has been changed from a
minimized to a normal state.

Example:

206
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;
public class w1 implements WindowListener
{
JFrame f; w1(){
f=new JFrame();
[Link](this);
[Link](null);
[Link](300,300);
[Link](true); }
public void windowActivated(WindowEvent e)
{
[Link]("Activated"); }
public void windowDeactivated(WindowEvent e)
{
[Link]("Deactivated");
}
public void windowClosed(WindowEvent e)
{
[Link]("Closed");
}
public void windowOpened(WindowEvent e)
{
[Link]("Opened");
}
public void windowIconified(WindowEvent e)
8){ Mouse Event:
❖ The Java MouseListener is notified whenever you change the state of
[Link]("Iconified");
} mouse. It is notified against MouseEvent.
❖ The
public voidMouseListener
windowDeiconified(WindowEvent e) in [Link] package.
interface is found
{
❖ It has five methods.
[Link]("DeIconified");
}
Mouse
public void windowClosing(WindowEvent e)
{ 207
[Link]("Closing");
}
public static void main(String args[])
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Entered():
❖ This method is executed when the mouse cursor enters into specific
component.

mouseExited():
❖ This method is executed when the cursor leaves the specific component

mousePressed():
❖ This event is executed when the mouse is being pressed in the component
area

mouseReleased():
❖ This event is executed when the mouse is released from the component
area.

mouseClicked():
❖ This event is delivered when the mouse is clicked in the component area.

208
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

9) MouseWheel Event:

❖ An event which indicates that the mouse wheel was rotated in a


component.
❖ A wheel mouse is a mouse which has a wheel in place of the middle
button.
❖ This wheel can be rotated towards or away from the user.
❖ It has only one method: mouseWheelMoved()

mouseWheelMoved(): This method is executed when mouse wheel is rotated


or moved in the component.

209
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class w1 implements MouseWheelListener


{
JFrame f;
JTextField t;
w1(){
f=new JFrame();
t=new JTextField();
[Link](80,150,80,30);
[Link](this);
[Link](t);
[Link](null);
[Link](300,300);
[Link](true);
}
public void mouseWheelMoved(MouseWheelEvent e)
{
10) TextEvent: [Link](“Mouse Wheel Moved”);
}

public static void main(String args[])


{
w1 e=new w1();
}
}

❖ An event which indicates that an object’s text changed.


❖ It is generated by an object when its text changes.

210
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

❖ The event is passed to every Text Listener object which registered to


receive such events using the component's addTextListener method.
❖ It has only one method: textValueChanged()

textValueChanged(): This method is executed when object’s text changes.

import [Link].*;
import [Link].*;

public class w1 implements TextListener


{
JFrame f;
JTextField t;
w1(){
f=new JFrame();
t=new JTextField();
[Link](80,150,80,30);
[Link](this);
[Link](t);
[Link](null);
[Link](300,300);
[Link](true);
}
public void textValueChanged(TextEvent e)
{
[Link](“Text Changed”);
}

public static void main(String args[])


{
w1 e=new w1();
}
}

211
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) Which event is generated MouseWheelEvent
when mouse wheel is rotated?
2) ActionEvent have actionPerformed()
……..method.
3) Which event is generated to Adjustment Event
adjust the values of scrollbar
4) How many methods focusGained(), focusLost()
focusEvent have?
5) Which event is generated KeyEvent
when key is released or
pressed?

Q-4 Write a short note on Adapter Class


Ans:
❖ Java adapter classes provide the default implementation of
listener interfaces
❖ If you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.

Pros of using Adapter classes:


o It assists the unrelated classes to work combined.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

❖ The adapter classes are found in [Link], [Link] and


[Link] pacakges.

212
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Mouse Adapter:
❖ An abstract adapter class for receiving keyboard focus events.

import [Link].*;
import [Link].*;

public class mouse1 extends MouseAdapter


{
JFrame f;
JTextArea ta,ta1;
mouse1()
{
f=new JFrame();
ta=new JTextArea();
ta1=new JTextArea();
[Link](80,150,80,70);
[Link](this);
[Link](80,250,80,70);
[Link](this);
[Link](ta);
[Link](ta1);
[Link](null);
[Link](300,300);
[Link](true);
Focus Adapter: }
❖ An abstractpublic voidclass
adapter mouseClicked(MouseEvent e) focus events.
for receiving keyboard
{
[Link]("CLicked");
}

public static void main(String args[])


{
mouse1 k=new mouse1();
}
}

213
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class focus1 extends FocusAdapter


{
JFrame f;
JTextField tf;

focus1()
{
f=new JFrame();
tf=new JTextField();
[Link](80,150,80,80);
[Link](this);
[Link](tf);
[Link](null);
[Link](300,300);
[Link](true);
}
❖ Key public
Adapter:
void focusGained(FocusEvent e)
❖ An{ abstract adapter class for receiving keyboard events.
[Link]("Focus Gained");
}

public static void main(String args[])


{
focus1 f=new focus1();
}
}

214
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class key1 extends KeyAdapter


{
JFrame f;
JTextArea ta,ta1;
key1()
{
f=new JFrame();
ta=new JTextArea();
ta1=new JTextArea();
[Link](80,150,80,70);
[Link](this);
[Link](80,250,80,70);
[Link](this);
[Link](ta);
[Link](ta1);
[Link](null);
[Link](300,300);
[Link](true);
❖ Mouse Motion } Adapter:
❖ Mouse motion events
public void occur when a mouse
keyPressed(KeyEvent e) is moved or dragged. (Many
such events
{ will be generated in a normal program. To track clicks and
❖ [Link]("Pressed");
}

public static void main(String args[])
❖ {
❖ key1 k=new key1();
❖ }
}❖
❖ other mouse events, use the MouseAdapter.)

215
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class key1 extends MouseAdapter


{
JFrame f;
JTextArea ta,ta1;
key1()
{
f=new JFrame();
ta=new JTextArea();
ta1=new JTextArea();
[Link](80,150,80,70);
[Link](this);
[Link](80,250,80,70);
[Link](this);
[Link](ta);
[Link](ta1);
[Link](null);
[Link](300,300);
[Link](true);
}
public void mouseDragged(MouseEvent e)
{
[Link]("Dragged");
}
public static void main(String args[])
{
key1 k=new key1();
}
}\

216
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

MCQ
1) .............class provide the Adapter Class
default implementation of
listener interface
2) If you inherit adapter class, true
you will not need to include
implementation of all the
methods? (T/F)

217
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

UNIT-4 PENDING LAYOUT


MANAGERS
1) Box Layout:
❖ The BoxLayout class is used to arrange the components either vertically
(along Y-axis) or horizontally (along X-axis).

In BoxLayout class, the components are put either in a single row or a single
column

218
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Example:
import [Link].*;
import [Link].*;
public class box12
{
box12()
{
JFrame f=new JFrame();
JButton b1=new JButton("Button1");
JButton b2=new JButton("Button 2");
JButton b3=new JButton("Button 3");
JButton b4=new JButton("Button 4");
JButton b5=new JButton("Button 5");
JPanel p=new JPanel();
BoxLayout bo=new BoxLayout(p,BoxLayout.X_AXIS);
[Link](bo);
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
[Link](p);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
box12 b=new box12();
}
}

219
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

2) Group Layout:
❖ GroupLayout groups its components and places them in a Container
hierarchically. The grouping is done by instances of the Group class.
❖ Group is an abstract class, and two concrete classes which implement
this Group class are SequentialGroup and ParallelGroup.
❖ SequentialGroup positions its child sequentially one after another
whereas ParallelGroup aligns its child on top of each other.
❖ The GroupLayout class provides methods such as createParallelGroup()
and createSequentialGroup() to create groups.
❖ GroupLayout treats each axis independently. That is, there is a group
representing the horizontal axis, and a group representing the vertical
axis. Each component must exist in both a horizontal and vertical group,
otherwise an IllegalStateException is thrown during layout or when the
minimum, preferred, or maximum size is requested.

Example:

220
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645
import [Link].*;
import [Link].*;
public class group1
{
JFrame f;
JButton b1,b2,b3,b4,b5,b6;
group1()
{
f=new JFrame();
Container c=[Link]();
GroupLayout g=new GroupLayout(c);
[Link](g);
b1=new JButton("Button 1");
b2=new JButton("Button 2");
b3=new JButton("Button 3");
b4=new JButton("Button 4");
b5=new JButton("Button 5");
b6=new JButton("Button 6");
[Link](
[Link]()
.addComponent(b1)
.addComponent(b2)
.addComponent(b3)
.addComponent(b4)
.addComponent(b5)
.addComponent(b6));
[Link](
[Link]([Link])
.addComponent(b1)
.addComponent(b2)
.addComponent(b3)
.addComponent(b4)
.addComponent(b5)
.addComponent(b6));
[Link]();
[Link](true);

221
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

3) Spring Layout:
❖ A SpringLayout arranges the children of its associated container
according to a set of constraints.
❖ Constraints are nothing but horizontal and vertical distance between two-
component edges.
❖ Every constraint is represented by a [Link] object.
❖ Each child of a SpringLayout container, as well as the container itself, has
exactly one set of constraints associated with them.
❖ Each edge position is dependent on the position of the other edge. If a
constraint is added to create a new edge, than the previous binding is
discarded. SpringLayout doesn't automatically set the location of the
components it manages.

222
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

import [Link].*;
import [Link].*;

public class spr


{
JFrame f;
JLabel l;
JButton b;
JTextField t;
spr()
{
f=new JFrame();
SpringLayout s=new SpringLayout();
l=new JLabel("heading");
t=new JTextField("my textbox",15);
b=new JButton("Submit");
[Link](l);
[Link](t);
[Link](b);
[Link](s);
[Link]([Link],l,6,[Link],f);
[Link]([Link],t,6,[Link],l);
[Link]([Link],b,80,[Link],f);
[Link]();
[Link](true);
[Link](300,300);
}
public static void main(String args[])
{
spr s1=new spr();
}
}

223
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Ch-1

1) Write a program to print hello

class hello
{
public static void main(String args[])
{
[Link](“Hello”);
}
}

Output: Hello

2) Write a program to demonstrate use of arithmetic operator

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Addition=” +(a+b));
[Link](“Sub is” +(a-b));
[Link](“Mul is” +(a*b));
[Link](“Div is”+(a/b));
[Link](“Modulas is” +(a%b));
}
}
224
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Output:
Enter a 10
Enter b 5
Addition=15
Sub is 5
Mul is 50
Div is 2
3) Write a program to demonstrate use of relational operator

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“> than” +(a>b));
[Link](“< than” +(a<b));
[Link](“>= is” +(a>=b));
[Link](“<=”+(a<=b));
[Link](“== is” +(a==b));
[Link](“!= is” +(a!=b));
}
}

Output:
Enter a 10
Enter b 5
1

225
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

0
1
0
0
1

4) Write a program to demonstrate use of logical operator

import [Link].*;
class arithmetic
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();
if(a>b && a>c)
[Link](“a is max”);
else if(b>c && b>a)
[Link](“b is max”);
else
[Link](“c is max”);
}
}

Output:
Enter a 10
Enter b 5
Enter c 2
a is max

226
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

5) Write a program to demonstrate use of decision control structure (if)

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
if(a==b)
[Link](“Equal”);
}
}

Output:
Enter a 10
Enter b 10

Equal

227
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

6) Write a program to demonstrate use of decision control structure (if-


else)

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
if(a==b)
[Link](“Equal”);
else
[Link],println(“Not Equal”);
}
}

Output:
Enter a 10
Enter b 11
Not Equal

228
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

7) Write a program to demonstrate use of decision control structure


(Nested if)

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();

if(a>b)
{
if(a>c)
[Link](“a is max”);
else
[Link],println(“c is max”);
}
else
{
if(b>c)
[Link](“b is max”);
else
[Link](“c is max”);
}
}
}

Output:
Enter a 10

229
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Enter b 11
Enter c 50
c is max

8) Write a program to demonstrate use of decision control structure (else-if


ladder)

import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,c;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter c”);
c=[Link]();

if(a>b && a>c)


[Link](“a is max”);
else if(b>c && b>a)
[Link](“b is max”);
else
[Link](“c is max”);

}
}
Output:
Enter a 10
Enter b 11
Enter c 50
c is max

230
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

9) Write a program to demonstrate use of decision control structure


(switch case)
import [Link].*;
class dc
{
public static void main(String args[])
{
int a,b,ch;
Scanner sc=new Scanner([Link]);
[Link](“Enter a”);
a=[Link]();
[Link](“Enter b”);
b=[Link]();
[Link](“Enter [Link] [Link] [Link] [Link]”);
ch=[Link]();
switch(ch)
{
case 1: [Link](a+b);
break;

case 2: [Link](a-b);
break;

case 3: [Link](a*b);
break;

case 4: [Link](a/b);
break;
Output: default: [Link](“Invalid”);
Enter a 10 break;
} b 11
Enter
Enter [Link] [Link] [Link] [Link] 3
} 110
}

231
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

10) Write a program to demonstrate use of for loop

class loop
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
[Link](i);
}
}

Output:
1
2
3
4
5

232
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

11) Write a program to demonstrate use of while loop

class loop
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
[Link](i);
i++;
}
}

Output:
1
2
3
4
5

12) Write a program to demonstrate use of do-while loop


class loop
{
public static void main(String args[])
{
int i=1;
do
{
[Link](i);
i++;
}while(i<=5);
}

233
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Output:
1
2
3
4
5

13) Write a program to demonstrate use of jumping statements (break)

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
break;
[Link](i);
}
}

Output:
1
2

234
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

14) Write a program to demonstrate use of jumping statements


(continue)

class jm
{
public static void main(String args[])
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
[Link](i);
}
}

Output:
1
2
4
5

15) Write a program to demonstrate use of type casting

class exp1
{
public static void main(String args[])
{
int x;
double f=2.5;
Output: x=(int)f;
2 [Link](x);
}
} Write a program to demonstrate use of 1 dimensional array
16)

235
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class exp1
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
a[0]=10;
a[1]=11;
a[2]=12;
a[3]=13;
a[4]=14;
for(i=0;i<[Link];i++)
[Link](a[i]);
}
}

Output:
10
11
12
13
14

236
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

17) Write a program to demonstrate use of 1 dimensional array


(inputting the values from the user)

import [Link].*;
class arr
{
public static void main(String args[])
{
int i;
int a[]=new int[5];
Scanner sc=new Scanner([Link]);
for(i=0;i<5;i++)
{
[Link]("Enter array elements");
a[i]=[Link]();
}
for(i=0;i<5;i++)
{
[Link]("Array ele" +a[i]);
}
}
}

Output:
Enter array elements Array ele
10 10
11 11
12 12
13 13
14 14

237
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

18) Write a program to demonstrate use of multi-dimensional array


(inputting the values from the user)

import [Link].*;
class arr
{
public static void main(String args[])
{
int i,j;
int a[][]=new int[2][3];
Scanner sc=new Scanner([Link]);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
[Link]("Enter array elements");
a[i][j]=[Link]();
}

}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
[Link]("Array ele" +a[i][j]);
}
}
}
}

238
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Output:
Enter array elements Array ele
10 10
11 11
12 12
13 13
14 14

19) Write a program to print hello using command line arguments

class cmd1
{
public static void main(String args[])
{
[Link](args[0]);
}
}
Output:
hello

20) Write a program to print value using command line arguments


class cmd1
{
public static void main(String args[])
{
int i;
for(i=0;i<[Link];i++)
{
[Link](args[i]);
}
}
}

239
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Output:
10

21) Write a program to demonstrate use of class and object

class student
{
int roll;
String name;
}
class sample
{
public static void main(String args[])
{
student s=new student();
[Link]=1;
[Link]="xyz";
[Link]([Link]);
[Link]([Link]);
}
}

Output:
1
xyz

240
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

22) Write a program to demonstrate use of encapsulation

class test
{
private int age;
public void get()
{
[Link](age);
}
public void set(int age)
{
[Link]=age;
}
}

class enc
{
public static void main(String args[])
{
test t=new test();
[Link](1);
[Link]();
}
}
Output:
1

241
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

23) Write a program to demonstrate use of single level inheritance

class Animal
{
void eat()
{
[Link]("Eating");
}
}

class Dog extends Animal


{
void bark()
{
[Link]("Barking");
}
}

class single
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}

Output:
Eating
Barking

242
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

24) Write a program to demonstrate use of multi level inheritance


class Animal
{
void eat()
{
[Link]("Eating");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barking");
}
}
class BabyDog extends Dog
{
void sleep()
{
[Link](“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
BabyDog bd=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
Eating
Barking
Sleeping

243
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

25) Write a program to demonstrate use of hierarchical inheritance


class Animal
{
void eat()
{
[Link]("Eating");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Barking");
}
}
class cat extends Animal
{
void sleep()
{
[Link](“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
cat c=new cat();
[Link]();
[Link]();
Output: Dog d=new Dog();
Eating [Link]();
Barking [Link]();
Eating
Sleeping }
}
244
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

26) Write a program to demonstrate use of multiple inheritance

class A
{
void msg()
{
[Link](“Hello”);
}
}
class B
{
void msg()
{
[Link](“Hi”);
}
}
class C extends A,B
{
public static void main(String args[])
{
C c1=new C();
[Link]();//Which msg() method will be called?
}
}

Will generate compile time error

Output:
Error

245
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

27) Write a program to demonstrate use of hybrid inheritance


class Animal
{
void eat()
{
[Link]("Eating");
}
}
class Dog extends Animal //Single level inheritance
{
void bark()
{
[Link]("Barking");
}
}
class cat extends Animal //Multilevel inheritance
{
void sleep()
{
[Link](“Sleeping”);
}
}
class single
{
public static void main(String args[])
{
cat c=new cat();
[Link]();
Output: [Link]();
Eating Dog d=new Dog();
Sleeping [Link]();
Eating [Link]();
Barking}
}
28) Write a program to demonstrate use of compile time polymorphism

246
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class overload
{
void add(int a,int b,int c)
{
[Link](a+b+c);
}
void add(int a,int b)
{
[Link](a+b);
}
}
class method1
{
public static void main(String args[])
{
overload o1=new overload();
[Link](2,3,4);
[Link](1,2);
}
}

Output:
9
3

247
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

29) Write a program to demonstrate use of run time polymorphism

class A
{
void run()
{
[Link]("Hello");
}
}

class B extends A
{
void run()
{
[Link]("Hi");
}
}
class sam
{
public static void main(String args[])
{
B b1=new B();
[Link]();
}
}

Output: Hi

248
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

30) Write a program to demonstrate use of default constructor

class A
{
A()
{
[Link]("Default constructor");
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A();
}
}

Output: Default constructor

249
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

31) Write a program to demonstrate use of constructor overloading

class Aint roll;


A(int r)
{
roll=r;
}
void display()
{
[Link](roll);
}
}

class inhe
{
public static void main(String args[])
{
A a1=new A(10);
[Link]();
}
}

Output:
10

32) Write a program to demonstrate use of constructor overloading

250
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class cons
{
int roll;
String name;
cons()
{
[Link]("Hello");
}
cons(int r)
{
roll=r;
}
cons(int r,String n)
{
roll=r;
name=n;
}
void display()
{
[Link](roll);
[Link](name);
}
}
class consoverload
{
public static void main(String args[])
{
cons c=new cons();
cons c1=new cons(10);
cons c2=new cons(10,"xyz");
[Link]();
[Link]();
}
}

Output:

251
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Hello
10
10, xyz

33) Write a program to demonstrate use of static and non-static data


members

class test
{
static int a=20;
void display()
{

a++;
[Link](a);
}

}
class sample
{
public static void main(String args[])
{
test t1=new test();
test t2=new test();
test t3=new test();
[Link](); Output: 21,22,23
[Link]();
[Link]();
}
}

252
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Non-static

class test
{
int a=20;
void display()
{

a++;
[Link](a);
}

}
class sample
{
public static void main(String args[])
{
test t1=new test();
test t2=new test();
test t3=new test();
[Link](); Output: 21,21,21
[Link]();
[Link]();
}
}

253
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

34) Write a program to demonstrate use of vargs

class varg
{
static void display(int...values)
{
[Link]("hello");

for(int i:values)
[Link](i);
}
public static void main(String args[])
{
display();
display(1,2,3,4);
display(12,22);
}
}

254
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

35) Write a program to demonstrate use of private access specifier

7. class A
8. {
private int data=40;
private void msg()
{
[Link]("Hello java");
}
9. }
[Link] Simple
{
11. public static void main(String args[])
{
12. A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
}

Output:
Error

255
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

36) Write a program to demonstrate use of default access specifier

//Save this with [Link] (Package 1)

package pack;
class A
{
void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}

Output:
Cannot be accessed outside the package

256
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

37) Write a program to demonstrate use of protected access specifier

//Save this with [Link] (Package 1)

package pack;
public class A
{
protected void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj=new B();
[Link]();
}
}

257
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

38) Write a program to demonstrate use of public access specifier

//Save this with [Link] (Package 1)

package pack;
public class A
{
public void display()
{
[Link](“Hello”);
}
}

//Save this with [Link] (Package 2)

package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
[Link]();
}
}

258
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

39) Write a program to demonstrate use of constructor in single level


inheritance

class parent
{
parent()
{
[Link]("Parent class constructor");
}
}
class child extends parent
{
child()
{
[Link]("Child class constructor");
}
}
class child1 extends child
{

child1()
{
[Link]("Child1 constructor");
}
}
class sample
{
public static void main(String args[])
{
child1 c=new child1();
Output:}
parent
} class constructor
child class constructor
child1 class constructor

259
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

40) Write a program to demonstrate use of interface

interface draw
{
void print();
}

class rectangle implements draw


{
public void print()
{
[Link]("draw rectangle");
}
}
class circle implements draw
{
public void print()
{
[Link]("draw circle");
}
}
class test
{
public static void main(String args[])
{
circle c1=new circle();
[Link]();
rectangle r=new rectangle();
[Link]();
}
}

Output:
draw circle
draw rectangle

260
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

41) Write a program to demonstrate use of multiple inheritance in java


using interface

interface a
{
void display();
}
interface b
{
void display1();
}
class mul implements a,b
{
public void display()
{
[Link]("hello");
}
public void display1()
{
[Link]("hi");
}
}

class multiple
{
public static void main(String args[])
Output:
{
sam s=new sam();
[Link]();
s.display1();
}
}
Hello
Hi

42) Write a program to demonstrate use of object cloning

261
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

class stu implements Cloneable


{
int rollno;
String name;

stu(int r,String n)
{
[Link]=r;
[Link]=n;
}
public Object clone()throws CloneNotSupportedException
{
return [Link]();
}

public static void main(String args[])


{
try
{
stu s1=new stu(1,"xyz");
stu s2=(stu)[Link]();

[Link]([Link]);
[Link]([Link]);
}catch(CloneNotSupportedException c)
{

}
}
}

Output:
1
xyz

262
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

43) Write a program to demonstrate use of non-static nested class

class outer
{
int x=10;
class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
outer o=new outer();
[Link] i=[Link] inner();
[Link](i.y);
[Link](o.x);
}
}

Output:
4
10

263
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

44) Write a program to demonstrate use of static nested class

class outer
{
int x=10;
static class inner
{
int y=4;
}
}

class nested
{
public static void main(String args[])
{
[Link] i=new [Link]();
[Link](i.y);
[Link](i.x);//will generate error
}
}
Output:
4
will generate error

264
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

45) Write a program to demonstrate use of abstract class

abstract class bike


{
abstract void run();
void display()
{
[Link]("hello");
}
}

class honda extends bike


{
public void run()
{

[Link]("hi");
}
}

class sampe
{
public static void main(String args[])
{
honda h=new honda();
[Link]();
[Link]();
}
}

Output:
hello
hi

265
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

46) Write a program to demonstrate use of final keyword

final class bike


{

class ja extends bike


{
void display()
{
[Link]("hi");
}
public static void main(String args[])
{
bike b=new bike();
[Link](); //Compile time error
}
}

Output:
Compile time error

266
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

47) Write a program to demonstrate use of normal import

class ke
{
public static void main(String args[])
{
[Link]([Link](25));
[Link]([Link](2,2));
}
}

Output:
5
4

48) Write a program to demonstrate use of static import

import static [Link].*;

class ke
{
public static void main(String args[])
{
[Link](sqrt(25));
[Link](pow(2,2));
}
}

Output:
5
4

267
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

49) Write a program to demonstrate use of Wrapper class (Autoboxing)

class wrapper1
{
public static void main(String args[])
{
int a=20;
Integer j=a; //Converting primitive data type to Integer
wrapper class
[Link](j);
}
}

Output:
20

50) Write a program to demonstrate use of Wrapper class (Unboxing)

class wrapper1
{
public static void main(String args[])
{
int a=20;
Integer j=a; //Converting primitive data type to Integer wrapper class
[Link](j);
}
}

Output:
20

268
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

51) Write a program to demonstrate use of String class ([Link])

class stringfunctions
{
public static void main(String args[])
{
String s="hello";
String s1="hello";
String s3="karishma";
String s4="rupani";
String s5="hi";
String s6="Hi";
[Link]("Charat" +[Link](1));
[Link]("length" +[Link]());
[Link]("substring" +[Link](1));
[Link]("substring" +[Link](1,3));
[Link]("index" +[Link]("el"));
[Link]("Equality" +[Link](s1));
[Link]("Empty" +[Link]());
[Link]("Concate"+[Link](s4));
[Link]("replace"+[Link]('l','k'));
[Link]("Uppercase" +[Link]());
[Link]("Lowercase" +[Link]());
[Link]("IndexOf" +[Link]('o'));
[Link]("ignorecase" +[Link](s6));

}
}

Output:
e
5
ello

269
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

ell
1
1
0
karishmrupani
hekko
KARISHMA
Karishma
4
1

52) Write a program to demonstrate use of StringBuffer class ([Link])

class stringfunctions
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer("hello");
[Link]("Length" +[Link]());
[Link]("Specified" +[Link](2,"hi"));
[Link]("Replace" +[Link](1,3,"ee"));
[Link]("Deleting" +[Link](1,3));
[Link]("Reversing" +[Link]());
[Link]("Capacity" +[Link]());
[Link]("Charat" +[Link](2));
[Link]("Substring" +[Link](1));

270
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

53) Write a program to demonstrate use of random class

import [Link].*;
class randomn
{
public static void main(String args[])
{
Random r=new Random();
[Link]("Integer val" +[Link]());
[Link]("Next decimal" +[Link]());
}
}

54) Write a program to demonstrate use of Date class

import [Link].*;

public class main1


{
public static void main(String[] args)
{
Date d=new Date();
Date d1=new Date(21-11-2010);
Date d2=new Date(25-6-2022);
// Creating date
[Link]("Current date: " +d);
[Link]("Checking"+[Link](d));
[Link]("after" +[Link](d2));
[Link]("Clone object" +[Link]());
[Link]("Compare" +[Link](d1));
[Link]("Equlas" +[Link](d1));
[Link]("Time" +[Link]());
[Link]("Hashcode" +[Link]());
}
}

271
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

55) Write a program to demonstrate use of StringTokenizer class

import [Link].*;

public class main1


{
public static void main(String[] args)
{
StringTokenizer st=new StringTokenizer("my name is karishma");
[Link]("Total number of Tokens: "+[Link]());
while([Link]())
{
[Link]([Link]());
}

}
}

56) Write a program to demonstrate use of Gregorian Calendar class

import [Link].*;
class greg
{
public static void main(String args[])
{
Calendar cal=[Link]();
GregorianCalendar c=new GregorianCalendar();
[Link]("Calendar date:"+[Link]());
[Link]("Greg" +[Link]());
}
}

272
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

57) Write a program to demonstrate use of Collection class

import [Link].*;
class greg
{
public static void main(String args[])
{
Vector<Integer>ve=new Vector<Integer>(5);
[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link]("Elements of vector" +ve);
[Link]("Clone" +[Link]());
[Link]("Capacity" +[Link]());
[Link]("Size" +[Link]());
[Link]("Firstelement" +[Link]());
[Link]("Firstelement" +[Link]());
[Link]("Index" +[Link](20));
[Link]("Contains" +[Link](10));
[Link](0);
[Link]("Elements after removal" +ve);
}
}

273
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

58) Write a program to demonstrate use of Hashtable class

import [Link].*;
class hash1
{
public static void main(String args[])
{
Hashtable<Integer,String> h=new Hashtable<Integer,String>();
[Link](1,"abc");
[Link](2,"xyz");
[Link]("Mapping" +h);
[Link](2,"ddd");
[Link]("Mapping" +h);
[Link](2);
[Link]("Mapping" +h);
[Link]("Check key:" +[Link](1));
[Link]("Check value: "+[Link]("abc"));
}
}

274
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

59) Write a program to demonstrate use of linked list class

import [Link].*;
class linked
{
public static void main(String args[])
{
LinkedList<String>s=new LinkedList<String>();
[Link]("A");
[Link]("B");
[Link]("C");
[Link]("D");
[Link]("E");
[Link](s);
[Link]("C");
[Link]();
[Link]();
[Link](s);
}
}

275
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

60) Write a program to demonstrate use of Stack class

import [Link].*;
class stack
{
public static void main(String args[])
{
Stack<Integer> s=new Stack<Integer>();
[Link](10);
[Link](11);
[Link](12);
[Link](13);
[Link](14);
[Link](s);
[Link]();
[Link](s);
[Link]("Stack empty :"+[Link]());
[Link]("Search :"+[Link](11));
[Link]("Peek: "+[Link]());
}
}

276
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

61) Write a program to demonstrate use of Queue class

import [Link].*;
class que
{
public static void main(String args[])
{
PriorityQueue<String> p=new PriorityQueue<String>();
[Link]("abc");
[Link]("xyz");
[Link]("aaa");

[Link]("Queue ele: "+p);


[Link]();
[Link]("After removal: "+p);
[Link]("Poll: "+[Link]());
[Link]("After poll:" +p);
[Link]("Peek: "+[Link]());
}
}

277
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

62) Write a program to demonstrate use of exception handling

class exc
{
public static void main(String args[])
{
try
{
int a=5/0;
}catch(ArithmeticException e)
{
[Link](e);
}
finally
{
[Link]("hi");
}
}
}

Output:
hi

278
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

63) Write a program to demonstrate use of user defined exception

class userdefinedexception
{
public static void main(String args[])
{
try
{
throw new myexception(400);
}
catch(myexception e)
{
[Link](e);
}
}
}

class myexception extends Exception


{
int n1;
myexception(int n2)
{
n1=n2;
}
public String toString()
{
return ("Status: " +n1);
}
}

279
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Output:
400

64) Write a program to demonstrate use of Thread Class

class m extends Thread


{
public void run()
{
[Link](“Running”);
}
public static void main(String args[])
{
m m1=new m();
[Link]();
}
}

Output:
Running

280
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

65) Write a program to demonstrate use of Thread Class using Runnable


interface
class m extends implements Runnable
{
public void run()
{
[Link](“Running”);
}
public static void main(String args[])
{
m m1=new m();
Thread t1=new Thread(m1);
[Link]();
}
}

Output:
Running

281
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

66) Write a program to demonstrate use of Thread Class properties

class th
{

public static void main(String args[])


{
Thread t1=new Thread("First Thread");
[Link]("Thread Priority: "+[Link]());
[Link](6);
[Link]();
[Link]("My Thread");
[Link]("Thread Name: "+[Link]());
[Link]("Thread Priority: "+[Link]());
[Link]("Daemon Thread: "+[Link]());
}
}

Output:
Thread Name: My Thread
Thread Priority: 6
Daemon Thread: 0

282
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

67) Write a program to demonstrate use of Thread Synchronization

class mythread2 extends Thread


{
table t;
mythread2(table t)
{
this.t=t;
}
public void run()
{
[Link](5);
}
}

class synch
{
public static void main(String args[])
{
table o=new table();
mythread1 t1=new mythread1(o);
mythread2 t2=new mythread2(o);
[Link]();
[Link]();
}
}

283
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

68) Write a program to demonstrate use of File Class


import [Link].*;
class filedemo
{
public static void main(String args[])
{
File f=new File("d:\\[Link]");
if([Link]())
[Link]("\n File Exists");
else
[Link]("\n File does not exists");
}
}

284
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

69) Write a program to demonstrate use of new file creation

import [Link].*;
import [Link];
class crf
{
public static void main(String args[])
{
try
{
File f=new File("D:\\[Link]");
if([Link]())
[Link]("Created");
else
[Link]("Not Created");
}
catch(IOException e)
{
[Link](e);
}
}

285
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

70) Write a program to demonstrate use of file information

import [Link].*;
import [Link];

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

File f=new File("D:\\[Link]");


if([Link]())
{
[Link]("Name of file: "+[Link]());
[Link]("Path of file:
"+[Link]());
[Link]("Path of file: "+[Link]());
}
else
{
[Link]("Does not exists");
}
}

286
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

71) Write a program to demonstrate writing into file

import [Link].*;
import [Link];

class crf
{
public static void main(String args[])
{
try
{
FileWriter w=new FileWriter("d:\\[Link]");
[Link]("Hello");
[Link]();
}
catch(IOException e)
{
[Link](e);
}

}
}

287
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

72) Write a program to demonstrate reading from file

import [Link].*;
import [Link];
import [Link].*;

class crf
{
public static void main(String args[])
{
try
{
File f=new File("D:\\[Link]");
Scanner s=new Scanner(f);
while([Link]())
{
String fd=[Link]();
[Link](fd);
}
[Link]();
}
catch(FileNotFoundException e)
{
[Link](e);
}
}
}

288
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

73) Write a program to demonstrate deleting from file

import [Link].*;

class del
{
public static void main(String args[])
{
File f=new File("D:\\[Link]");
if([Link]())
[Link]("Deleted");
else
[Link]("Not Deleted");
}
}

289
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

74) Write a program to demonstrate use of random access file

import [Link].*;
class Random1
{
public static void main(String args[])
{
try
{
RandomAccessFile f=new
RandomAccessFile("[Link]","rw");
[Link](‘k’);
[Link](10);
[Link](10.2);
[Link](0);

[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link](2);
[Link]([Link]());
[Link]();
}
catch(IOException e)
{
[Link](e);
}
}
}

290
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

75) Write a program to demonstrate use of Character Stream Class


(FileReader Class)

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new FileReader("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
[Link]((char)i);
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

291
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

76) Write a program to demonstrate use of Character Stream Class


(FileWriter Class)

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new FileWriter("D:\\[Link]");
[Link]("Hello");
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

292
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

77) Write a program to demonstrate use of Buffered Writer Class

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileWriter f=new FileWriter("D:\\[Link]");
BufferedWriter b=new BufferedWriter(f);
[Link]("Hello");
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

293
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

78) Write a program to demonstrate use of Buffered Reader Class

import [Link].*;
import [Link];

class ch1
{
public static void main(String args[])
{
try
{
FileReader f=new FileReader("D:\\[Link]");
BufferedReader b=new BufferedReader(f);
int i;
while(i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();

}
catch(IOException e)
{
[Link](e);
}
}
}

294
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

79) Write a program to demonstrate use of FileOutputStream and File


InputStream Class

import [Link].*;

class inp
{
public static void main(String args[])
{
try
{
FileOutputStream f=new FileOutputStream("D:\\[Link]");
[Link](10);
FileInputStream f1=new FileInputStream("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}
}
catch(IOException e)
{
[Link](e);
}
}
}

295
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

80) Write a program to demonstrate use of DataOutputStream and Data


InputStream Class

import [Link].*;
class da
{
public static void main(String args[])throws IOException
{
FileOutputStream f=new FileOutputStream("D:\\[Link]");
DataOutputStream f1=new DataOutputStream(f);
[Link](10);
FileInputStream f2=new FileInputStream("D:\\[Link]");
DataInputStream f3=new DataInputStream(f2);
int i;
while((i=[Link]())!=-1)
{
[Link](i);
}

[Link]();
[Link]();
}
}

296
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

81) Write a program to copy the data of one file into another file

import [Link].*;
class cop
{
public static void main(String args[])throws IOException
{
FileInputStream f=new FileInputStream("D:\\[Link]");
FileOutputStream f1=new
FileOutputStream("D:\\[Link]");
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();
[Link]();
}
}

297
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

82) Write a program to demonstrate use of StreamTokenizer class

import [Link].*;

class stto
{
public static void main(String args[])throws IOException
{
FileReader r=new FileReader("D:\\[Link]");
StreamTokenizer st=new StreamTokenizer(r);
double sum=0;
int n=0;
while([Link]()!=st.TT_EOF)
{
if([Link]==StreamTokenizer.TT_NUMBER)
sum=sum+[Link];
else if([Link]==StreamTokenizer.TT_WORD)
83) Write a programn++; to demonstrate use of StreamTokenizer class
}
[Link]("Sum:" +sum);
[Link]("Total Words: "+n);
}
}

298
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

84) Write a program to demonstrate use of pipedInputStream and


PipedOutputStream

import [Link].*;

class pipe
{
public static void main(String args[])
{
PipedOutputStream out=new PipedOutputStream();
PipedInputStream in=new PipedInputStream();
try
{
[Link](out);
[Link](23);
[Link](24);
for(int i=0;i<2;i++)

[Link]([Link]());
}
catch(IOException e)
{
[Link](e);
}
}
}

299
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

85) Write a program to demonstrate use of Bridge Class


(InputStreamReader class)

import [Link].*;
class br
{
public static void main(String args[])throws IOException
{
FileInputStream f=new
FileInputStream("D:\\[Link]");
InputStreamReader r=new InputStreamReader(f);
int i;
while((i=[Link]())!=-1)
{
[Link]((char)i);
}
[Link]();
}
}

300
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

86) Write a program to demonstrate use of Bridge Class


(OutputStreamWriter class)

import [Link].*;
class br
{
public static void main(String args[])throws
IOException
{
FileOutputStream f=new
FileOutputStream("D:\\[Link]");
OutputStreamWriter w=new
OutputStreamWriter(f);
[Link]("hello world");
[Link]();
}
}
}

301
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

87) Write a program to demonstrate use of Bridge Class


(ObjectInputStream and ObjectOutputStream class)

import [Link].*;
class br
{
public static void main(String args[])throws IOException
{
int i=10;
FileOutputStream f=new
FileOutputStream("d:\\[Link]");
ObjectOutputStream o=new ObjectOutputStream(f);
[Link](i);

FileInputStream f1=new FileInputStream("d:\\[Link]");


ObjectInputStream o1=new ObjectInputStream(f1);
[Link]("Integer:" +[Link]());
;
[Link]();
[Link]();
}
}

302
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

Write a program which demonstrate life cycle of thread

import [Link].*;
import [Link].*;
/*<applet code="ap" width=200 height=200>
</applet>*/
public class ap extends Applet {
String msg="";
public void init()
{
msg+="init()called";
}
public void start()
{
msg+="start() called";
}
public void paint(Graphics g)
{
[Link](msg,30,30);
}
public void stop()
{
msg+="stop() called";
}
public void destroy()
{
msg+="destroy called";
}
}

303
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

88) Write a program that demonstrate use of parameterized applet

import [Link].*;
import [Link].*;
/*<applet code="par" width=200 height=100>
<param name="Stuname" value="xyz">
<param name="roll" value="12">
</applet>*/

public class par extends Applet


{
String name1;
String roll;
Font f1;
public void init()
{
f1=new Font("Arial",[Link],32);
name1=getParameter("Stuname");
roll=getParameter("roll");
}
public void paint(Graphics g)
{
[Link](f1);
[Link]("Name:"+ name1,50,20);
[Link]("Roll:" +roll,250,20);
}
}

304
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

89) Write a program that demonstrate use of flow layout

import [Link].*;
import [Link].*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Label b1,b2,b3;
public void init()
{
setLayout(new FlowLayout());
b1=new Label("OK");
b2=new Label("Open");
b3=new Label("Close");
add(b1);
add(b2);
add(b3);
}
}

305
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

90) Write a program that demonstrate use of Border layout

import [Link].*;
import [Link].*;
/*<applet code="flowl" width=200 height=200>
</applet>*/

public class flowl extends Applet


{
Button b1,b2,b3,b4,b5;
public void init()
{
setLayout(new BorderLayout());
b1=new Button("NORTH");
b2=new Button("SOUTH");
b3=new Button("EAST");
b4=new Button("WEST");
b5=new Button("CENTER");
add(b1,[Link]);
add(b2,[Link]);
add(b3,[Link]);
add(b4,[Link]);
add(b5,[Link]);
}
}

306
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

91) Write a program that demonstrate use of Card layout

import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="card" width=200 height=200>


</applet>*/

public class card extends Applet


{
Button b1,b2,b3;
Font f;

public void init()


{
f=new Font("Arial", [Link],32);
setLayout(new CardLayout);
b1=new Button("OK");
b2=new Button("Cancel");
b3=new Button("Close");
[Link](f);
[Link](f);
[Link](f);
add(b1);
add(b2);
add(b3);
}

307
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

92) Write a program that demonstrate use of Grid layout

import [Link].*;
import [Link].*;

/*<applet code="gri" width=200 height=200>


</applet>*/

public class gri extends Applet


{
Button b1,b2,b3,b4,b5;
Font f;
public void init()
{
setLayout(new GridLayout(3,3));
f=new Font("Arial",[Link],32);
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
[Link](f);
[Link](f);
[Link](f);
[Link](f);
[Link](f);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
}
}

308
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

93) Write a program that demonstrate use of Grid Bag layout

import [Link].*;
import [Link].*;

/*<applet code="gri" width=200 height=200>


</applet>*/

publ
ic class gri extends Applet
{
Button b1,b2;
public void init()
{
setLayout(new GridBagLayout());
Button b1=new Button("Ok");
Button b2=new Button("Cancel");
Button b3=new Button("Close");
Button b4=new Button("Hi");
GridBagConstraints gc=new GridBagConstraints();
[Link]=[Link];
[Link]=0;
[Link]=0;
[Link](b1,gc);
[Link]=0;
[Link]=1;
[Link](b2,gc);
[Link]=1;
[Link]=0;
[Link](b3,gc);
[Link]=2;
[Link]=2;
[Link]=2;
[Link](b4,gc);
}
}

309
SHREE H. N. SHUKLA COLLEGE OF I.T. & MGMT.
(AFFILIATED TO SAURASHTRA UNIVERSITY)
2 – Vaishali nagar 3 – Vaishali nagar
Nr. Amrapali Under Bridge Nr. Amrapali Under Bridge
Raiya Road Raiya Road
Rajkot – 360001 Rajkot - 360001
[Link]–(0281)2440478,2472590 [Link]–(0281)2471645

94) Write a program which demonstrate use of Mouse Motion Adapter

import [Link].*;
import [Link].*;

public class key1 extends MouseAdapter


{
JFrame f;
JTextArea ta,ta1;
key1()
{
f=new JFrame();
ta=new JTextArea();
ta1=new JTextArea();
[Link](80,150,80,70);
[Link](this);
[Link](80,250,80,70);
[Link](this);
[Link](ta);
[Link](ta1);
[Link](null);
[Link](300,300);
[Link](true);
}
public void mouseDragged(MouseEvent e)
{
[Link]("Dragged");
}
public static void main(String args[])
{
key1 k=new key1();
}
}

310

You might also like