0% found this document useful (0 votes)
1K views166 pages

Java Programming For MSBTE I Scheme (IV - Comp. - 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
1K views166 pages

Java Programming For MSBTE I Scheme (IV - Comp. - 2

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 166

Preface

The importance of Java Programming is well known in various engineering fields.


Overwhelming response to our books on various subjects inspired us to write this book.
The book is structured to cover the key aspects of the subject Java Programming.

The book uses plain, lucid language to explain fundamentals of this subject. The book
provides logical method of explaining various complicated concepts and stepwise
methods to explain the important topics. Each chapter is well supported with necessary
illustrations, practical examples and solved problems. All chapters in this book are
arranged in a proper sequence that permits each topic to build upon earlier studies. All
care has been taken to make students comfortable in understanding the basic concepts
of this subject.

Representative questions have been added at the end of each section to help the
students in picking important points from that section.

The book not only covers the entire scope of the subject but explains the philosophy of
the subject. This makes the understanding of this subject more clear and makes it more
interesting. The book will be very useful not only to the students but also to the subject
teachers. The students have to omit nothing and possibly have to cover nothing more.

We wish to express our profound thanks to all those who helped in making this book a
reality. Much needed moral support and encouragement is provided on numerous
occasions by our whole family. We wish to thank the Publisher and the entire team of
Technical Publications who have taken immense pain to get this book in time with
quality printing.

Any suggestion for the improvement of the book will be acknowledged and well
appreciated.

Authors
A. A. Puntambekar
Prashant P. Sawant
Swati T. Ghorsad

Dedicated to God.

(iii)
Syllabus
Java Programming (22412)
Teaching Credit Examination Scheme
Scheme (L+T+P)
L T P Theory Practical

Paper ESE PA Total ESE PA Total


Hrs.
Max Min Max Min Max Min Max Min Max Min Max Min

3 - 4 7 3 70 28 30* 00 100 40 50# 20 50 20 100 40

Unit Unit Outcomes (UOs) Topics and Sub - topics Marks


(in cognitive domain)
Unit - I 1a. Write programs to 1.1 Java Features and the Java 10
Basic create classes and Programming Environment, Object
Syntactical objects for the given Oriented, Compiled, Interpreted,
Constructs problem. Platform independent, Portable, Robust
in Java 1b. Explain the and Secure, Dynamic.
characteristics of the l.2 Defining a class. creating object,
given Java token. accessing class members
1c. Explain the function of 1.3 Java Tokens and Data types, Constants
the given operator with and Symbolic Constants, variables,
example. dynamic initialization, data types, array
1d. Construct the and string, scope of variable,
expressions using typecasting, and standard default
implicit and explicit values.
type conversions to 1.4 Operators and Expressions, Arithmetic
solve the given Operators, Relational Operators, Logical
problem. Operators, Increment and Decrement,
1e. Develop the programs Conditional Operators, Bit wise
using relevant control Operators, Instance of Operators, Dot
structure to solve the Operators, Operator precedence and
given problem. associativity, Evaluation of Expressions,
Type conversions in expressions,
Mathematical Functions - min(),max(),
sqrt(), pow(), exp(), round(), abs().
1.5 Decision making and looping: If
statement, if else statement, nested if
else statement, if else if ladder, the
switch statement, nested switch
statement, The ?: operator, The while
statement, the Do while statement, the
'for' statement, break, continue and
return statement, nested loops, labeled
loops, for-each version of the for loop.

(iv)
Unit - II 2a. Use Constructors for 2.1 Constructors and methods, types of 18
Derived the given programming constructors, nesting of methods,
Syntactical problem. argument passing the 'this' keyword,
Constructs 2b. Identify scope and command line arguments, varargs:
in Java lifetime of a variable in variable-length arguments, garbage
the given program collection, finalize() method, the object
code. class.

2c. Describe the given 2.2 Visibility control public, Private


visibility control with Protected default, friendly private
example. Protected access.

2d. Write the programs by 2.3 Arrays and Strings: Types of arrays.
implementing arrays to creating an array, strings, string classes
solve the given and string buffer, vectors, wrapper
problem. classes, enumerated types.

2c. Develop programs using


vectors and wrapper
classes for the given
problem.
Unit - III 3a. Apply the identified 3.1 Inheritance: concept of inheritance, 12
Inheritance, type of inheritance for Types of Inheritance
Interface the given programming 3.2 Single Inheritance. multilevel
and problem. Inheritance. Hierarchical Inheritance.
Package 3b. Differentiate between method and constructor overloading
overloading and and overriding. dynamic method
overriding for the given dispatch, final variables, final methods,
example. use of super, abstract methods and
3c. Develop program using classes, static members.
the specified interface. 3.3 Interfaces: Define Interface,
3d. Create user defined implementing interface, accessing
package for the given interface, variables and methods,
problem. extending interfaces, interface
references, nested interfaces
3e. Add class and interface
to the given package 3.4 Package: Define package, type of
package naming and creating packages,
accessing package, import statement,
static import, adding class and
interfaces to a package.

(v)
Unit - IV 4a. Distinguish the errors 4.1 Errors and Exception : Types of errors, 12
Exception and exceptions (if any) exceptions, try and catch statement,
Handling in the given example. nested try statement, throws and Finally
and 4b. Develop program for statement, build-in exceptions, chained
Multithread handling the given exceptions, creating own exception
-ing exception. (throw clause), subclasses.

4c. Create threads to run 4.2 Multithreaded Programming Creating a


the given multiple Thread : By extending to thread class
processes in the given and by implementing runnable
program. Interface, Life cycle of thread : Thread
Methods : wait(), sleep(), notify(),
4d. Explain the function of resume(), suspend(), stop(). Thread
the specified phase in exceptions. thread priority and methods,
thread life cycle using synchronization, interthread
the given example. communication, deadlock.
Unit - V 5a. Describe the given 5.1 Introduction to applets : Applet, Applet 10
Java phase of applet life life cycle (skeleton), Applet tag,
Applets and cycle using a typical Adding Applet to HTML file, passing
Graphics example. parameter to applet, embedding
Programm 5b. Develop programs <applet> tags in java code, adding
-ing using applet controls to applets.
implementation for the 5.2 Graphics Programming : Graphics
given problem. classes, lines, rectangles, ellipse, circle,
5c. Develop program for arcs. polygons, color and fonts,
implementing the given setColor(). getColor(), setForeGround(),
geometric shape. setBackGround(), font class, Variable
defined by font class : name, pointSize
5d. Develop program for size, style, font methods : getFamily().
implementing the given getFont(), getFontname (), getSize().
font settings. getStyle(), getAllFonts() and get
available font family name() of the
graphics environment class.
Unit - VI 6a. Use I/O stream classes 6.1 Introduction and Concept of Streams. 08
in a program to solve
Mananging 6.2 Stream Classes.
the given problem.
Input /
Ouput / 6b. Write programs for 6.3 Byte Stream Classes : Input Stream
Files in reading and writing Classes, Output Stream Classes.
Java character streams to 6.4 Character Stream Classes. Using
and from the given streams.
files.
6c. Write programs for 6.5 Using File Class : I/O Exceptions,
reading and writing Creation of Files, Reading/Writing
bytes to and from the characters, Reading/Writing Bytes,
given files. Handling Primitive data types.
6d. Write program to
demonstrate use of
primitive data types
with the specified
stream.
Total Marks 70

(vi)
Table of Contents
1.8.3 Nested if-else Statement . . . . . . . . . . . . . . 1 - 21
Unit - I
1.8.4 If-else-if Ladder . . . . . . . . . . . . . . . . . . . . 1 - 21
1.8.5 Switch Statement. . . . . . . . . . . . . . . . . . . . 1 - 21
Chapter - 1 Basic Syntactical Constructs in
Java (1 - 1) to (1 - 30) 1.8.6 Nested Switch Statement . . . . . . . . . . . . . 1 - 22
1.8.7 The while Statement . . . . . . . . . . . . . . . . . 1 - 22
1.1 Java Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 1
1.8.8 The do while Statement. . . . . . . . . . . . . . . 1 - 24
1.2 Java Programming Environment . . . . . . . . . . . . 1 - 2
1.2.1 Java Development Kit (JDK) . . . . . . . . . . . 1 - 2 1.8.9 The for Statement . . . . . . . . . . . . . . . . . . . 1 - 24

1.2.2 Java Virtual Machine (JVM). . . . . . . . . . . . 1 - 3 1.8.10 The Break Statement. . . . . . . . . . . . . . . . . 1 - 25

1.3 Difference between Java 1.8.11 The continue Statement. . . . . . . . . . . . . . . 1 - 25


and other Programming Languages . . . . . . . . . 1 - 4 1.8.12 The return Statement. . . . . . . . . . . . . . . . . 1 - 26
1.4 How to Write and Execute Java Program . . . . . 1 - 4 1.8.13 The nested Loops . . . . . . . . . . . . . . . . . . . 1 - 26
1.5 Class and Object . . . . . . . . . . . . . . . . . . . . . . . . 1 - 6 1.8.14 The Labeled Loops . . . . . . . . . . . . . . . . . . 1 - 28
1.6 Java Tokens . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 8 1.8.15 The for-Each Version of the for Loop . . . 1 - 29
1.6.1 Variable. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 9
1.6.2 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 1 - 9
Unit - II
1.6.3 Constants and Symbolic Constants . . . . . . 1 - 11
Chapter - 2 Derived Syntactical Constructs
1.6.4 Dynamic Initialization. . . . . . . . . . . . . . . . 1 - 12
in Java (2 - 1) to (2 - 18)
1.6.5 Scope of Variable . . . . . . . . . . . . . . . . . . . 1 - 12
2.1 Constructors and Method. . . . . . . . . . . . . . . . . . 2 - 1
1.6.6 Typecasting . . . . . . . . . . . . . . . . . . . . . . . . 1 - 13
2.2 Types of Constructors . . . . . . . . . . . . . . . . . . . . 2 - 1
1.6.7 Standar defult value . . . . . . . . . . . . . . . . . 1 - 14
2.3 Nesting of Methods . . . . . . . . . . . . . . . . . . . . . . 2 - 2
1.7 Operators and Expression . . . . . . . . . . . . . . . . 1 - 14
1.7.1 Arithmetic Operators. . . . . . . . . . . . . . . . . 1 - 14
2.4 Argument Passing . . . . . . . . . . . . . . . . . . . . . . . 2 - 3
2.5 The this Keyword. . . . . . . . . . . . . . . . . . . . . . . . 2 - 4
1.7.2 Relational Operators . . . . . . . . . . . . . . . . . 1 - 15
2.6 Command Line Arguments . . . . . . . . . . . . . . . . 2 - 4
1.7.3 Logical Operators . . . . . . . . . . . . . . . . . . . 1 - 15
2.7 Varargs : Variable Length Arguments. . . . . . . . 2 - 5
1.7.4 Increment and Decrement . . . . . . . . . . . . . 1 - 16
2.8 Garbage Collection and Finalize Method . . . . . 2 - 6
1.7.5 Conditional Operators . . . . . . . . . . . . . . . . 1 - 16 2.9 The Object Class . . . . . . . . . . . . . . . . . . . . . . . . 2 - 6
1.7.6 Bitwise Operators . . . . . . . . . . . . . . . . . . . 1 - 16 2.10 Visibility Control . . . . . . . . . . . . . . . . . . . . . . . . 2 - 6
1.7.7 Instance of Operators and Dot Operators. 1 - 18 2.11 Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 7
2.11.1 Types of Arrays with their Creation . . . . . . 2 - 7
1.7.8 Operator Precedence and Associativity . . 1 - 18
2.12 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 9
1.7.9 Evaluation of Expression . . . . . . . . . . . . . 1 - 19
2.12.1 String Classes . . . . . . . . . . . . . . . . . . . . . . . 2 - 9
1.7.10 Mathematical Functions . . . . . . . . . . . . . . 1 - 19
2.12.2 String Buffer . . . . . . . . . . . . . . . . . . . . . . . 2 - 11
1.8 Decision Making and Looping. . . . . . . . . . . . . 1 - 20
2.13 Vector. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 14
1.8.1 If Statement . . . . . . . . . . . . . . . . . . . . . . . . 1 - 20
2.14 Wrapper Classes. . . . . . . . . . . . . . . . . . . . . . . . 2 - 16
1.8.2 if else Statement . . . . . . . . . . . . . . . . . . . . 1 - 20
2.15 Enumerated Types . . . . . . . . . . . . . . . . . . . . . . 2 - 17
®
(vii)
TECHNICAL PUBLICATIONS
TM

- An up thrust for knowledge


(viii)

Unit - III Unit - IV

Chapter - 3 Inheritance, Interface Chapter - 4 Exception Handling


and Package (3 - 1) to (3 - 26) and Multithreading
(4 - 1) to (4 - 20)
Part - I : Inheritance
Part - I : Exception Handling
3.1 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 1
4.1 Errors and Exception . . . . . . . . . . . . . . . . . . . . . 4 - 1
3.2 Types of Inheritance . . . . . . . . . . . . . . . . . . . . . 3 - 1
4.2 Types of Errors . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 1
3.3 Method Overloading . . . . . . . . . . . . . . . . . . . . . 3 - 5
4.3 Concept of Exception. . . . . . . . . . . . . . . . . . . . . 4 - 2
3.4 Constructor Overloading . . . . . . . . . . . . . . . . . . 3 - 6
4.4 try-catch Statement . . . . . . . . . . . . . . . . . . . . . . 4 - 2
3.5 Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 8
4.5 Nested try Statement . . . . . . . . . . . . . . . . . . . . . 4 - 3
3.6 Dynamic Method Dispatch . . . . . . . . . . . . . . . . 3 - 9
4.6 Throws Statement . . . . . . . . . . . . . . . . . . . . . . . 4 - 4
3.7 Final Variables and Final Methods . . . . . . . . . 3 - 10
4.7 Using Throw . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5
3.8 Use of Super. . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 10
4.8 finally Statement . . . . . . . . . . . . . . . . . . . . . . . . 4 - 5
3.9 Abstract Methods and Classes . . . . . . . . . . . . . 3 - 12
4.9 Built in Exception . . . . . . . . . . . . . . . . . . . . . . . 4 - 6
3.10 Static Members . . . . . . . . . . . . . . . . . . . . . . . . 3 - 13
4.10 Chained Exception . . . . . . . . . . . . . . . . . . . . . . . 4 - 7
Part - II : Interface
4.11 Creating Own Exception Subclasses . . . . . . . . . 4 - 7
3.11 Definition of Interface . . . . . . . . . . . . . . . . . . . 3 - 14
Part - II : Multithreading
3.12 Implementing Interface . . . . . . . . . . . . . . . . . . 3 - 15
4.12 Concept of Multithreading. . . . . . . . . . . . . . . . 4 - 10
3.13 Accessing Interface . . . . . . . . . . . . . . . . . . . . . 3 - 16
4.13 Creating a Thread. . . . . . . . . . . . . . . . . . . . . . . 4 - 10
3.14 Variables and Methods Interfaces . . . . . . . . . . 3 - 17
4.14 Life Cycle of Thread . . . . . . . . . . . . . . . . . . . . 4 - 13
3.15 Extending Interfaces . . . . . . . . . . . . . . . . . . . . 3 - 17
4.15 Thread Exceptions . . . . . . . . . . . . . . . . . . . . . . 4 - 14
3.16 Interface References. . . . . . . . . . . . . . . . . . . . . 3 - 19
4.16 Thread Priority and Methods . . . . . . . . . . . . . . 4 - 14
3.17 Nested Interfaces . . . . . . . . . . . . . . . . . . . . . . . 3 - 20
4.17 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . 4 - 15
Part - III : Package
4.18 Interthread Communication . . . . . . . . . . . . . . . 4 - 17
3.18 Definition of Packages. . . . . . . . . . . . . . . . . . . 3 - 21 4.19 Deadlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 - 18
3.19 Built-in Java Packages . . . . . . . . . . . . . . . . . . . 3 - 21
Unit - V
3.20 Type of Package Naming. . . . . . . . . . . . . . . . . 3 - 21
3.21 Creating Packages . . . . . . . . . . . . . . . . . . . . . . 3 - 22
Chapter - 5 Java Applets and Graphics
3.22 Accessing Package. . . . . . . . . . . . . . . . . . . . . . 3 - 23 Programming (5 - 1) to (5 - 20)
3.23 Import Statement . . . . . . . . . . . . . . . . . . . . . . . 3 - 24
Part - I : Java Applets
3.24 Static Import. . . . . . . . . . . . . . . . . . . . . . . . . . . 3 - 25
5.1 Concept of Applet . . . . . . . . . . . . . . . . . . . . . . . 5 - 1
3.25 Adding Class and Interfaces to a Package . . . . 3 - 26
®
TM

TECHNICAL PUBLICATIONS - An up thrust for knowledge


(ix)

5.2 Applet Life Cycle. . . . . . . . . . . . . . . . . . . . . . . . 5 - 2


Unit - VI
5.3 Applet Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 3
5.4 Creating Applet . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 3 Chapter - 6 Managing Input, Output Files
5.5 Executing Applet Code . . . . . . . . . . . . . . . . . . . 5 - 4 in Java (6 - 1) to (6 - 10)
5.5.1 Adding Applet to HTML File . . . . . . . . . . . 5 - 4
6.1 Introduction and Concept of Stream . . . . . . . . . 6 - 1
5.5.2 Embedding Applet Code in Java. . . . . . . . . 5 - 5
6.2 Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 6 - 1
5.6 Passing Parameter to Applet . . . . . . . . . . . . . . . 5 - 6
6.3 Byte Stream Classes. . . . . . . . . . . . . . . . . . . . . . 6 - 2
5.7 Adding Controls to Applets . . . . . . . . . . . . . . . . 5 - 8
6.4 Character Stream Classes. . . . . . . . . . . . . . . . . . 6 - 2
Part - II : Graphics Programming
6.5 Using File Class . . . . . . . . . . . . . . . . . . . . . . . . . 6 - 3
5.8 Introduction to Graphics Programming . . . . . . 5 - 10 6.6 I/O Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 - 3
5.8.1 Graphics Classes . . . . . . . . . . . . . . . . . . . . 5 - 10
6.7 Creation of Files. . . . . . . . . . . . . . . . . . . . . . . . . 6 - 4
5.8.2 Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 11
6.8 Reading/Writing Characters. . . . . . . . . . . . . . . . 6 - 4
5.8.3 Rectangles . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 12
6.9 Reading/ Writing Bytes . . . . . . . . . . . . . . . . . . . 6 - 6
5.8.4 Ellipse and Circle . . . . . . . . . . . . . . . . . . . 5 - 13
6.9.1 Handling Primitive Data Types. . . . . . . . . . 6 - 9
5.8.5 Arcs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 14
5.8.6 Polygons . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 15 Java Programming Laboratory (L - 1) to (L - 8)
5.9 Colors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 16
Solved Model Question Paper (M - 1) to (M - 2)
5.10 Fonts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 18

Solved Board Question Papers


(S - 1) to (S - 12)

®
TM

TECHNICAL PUBLICATIONS - An up thrust for knowledge


(x)

®
TM

TECHNICAL PUBLICATIONS - An up thrust for knowledge


Java Programming 1-1 Basic Syntactical Constructs in Java

UNIT - I

1 Basic Syntactical Constructs in Java

That means user allocates or deallocates the


memory. Whereas in java its automatically done
1.1 Java Features
MSBTE : Winter 15, Summer 17,18, Marks 4
using garbage collection. Thus user can not
perform the memory management directly.
Java is getting popular because of its features. Following
4. If an applet is executing in some browser then it is
is a list of buzzwords that makes Java a popular
not allowed to access the file system of local
programming language.
machine.
1. Java is simple and small programming language
3. Java is a platform independent and portable
 Java is a simple programming language. Even
programming language
though you have no programming background you
can learn this language comfortably.  Platform independence is the most exciting feature
of Java program. That means programs in Java can
 The programmers who worked on C or C++ can
be executed on variety of platforms. This feature is
learn this language more efficiently because the
based on the goal - write once, run anywhere and
syntax of Java resembles with C and C++.
at anytime forever.
 In fact Java is made more clear and adaptable than
 Java supports portability in 2 ways - Java compiler
C++. generates the byte code which can be further used to
2. Java is robust and secure obtain the corresponding machine code. Secondly
 Following are reasons that make Java more secured the primitive data types used in Java are machine
independent.
than other programming languages -
1. Java does not support the concept of pointers 4. Java is known as object oriented programming language

directly. This makes it impossible to accidentally  Java is popularly recognised as an object oriented
reference memory that belongs to other programs programming language.
or the kernel.  It supports various object oriented features such as
2. The output of Java compiler is not executable code data encapsulation, inheritance, polymorphism
but it is a bytecode. The instructions of bytecode is and dynamic binding.
executed by the Java Virtual Machine (JVM). That  Everything in Java is an object. The object
means JVM converts the bytecode to machine oriented model of Java is simple and can be
readable form. JVM understand only the bytecode extended easily.
and therefore any infectious code can not be 5. Java is multithreaded and interactive language
executed by JVM. No virus can infect bytecode.  Java supports multithreaded programming which
Hence it is difficult to trap the internet and network
allows a programmer to write such a program that
based applications by the hackers.
can perform many tasks simultaneously.
3 In programming languages like C or C++ the
 This ultimately helps the developer to develop more
memory management is done explicitly by the user.
interactive code.
TM
Technical Publications
(1 --An
1) up thrust for knowledge
Java Programming 1-2 Basic Syntactical Constructs in Java

6. Java can be compiled and interpreted Board Questions


 Normally programming languages can be either 1. State and explain any four features of Java.
MSBTE : Winter 15, Summer 17,18, Marks 4
compiled or interpreted but Java is a language which
can be compiled as well as interpreted. 2. Why java became platform independent language ?
Explain.
 First, Java compiler translates the Java source MSBTE : Winter 17, Marks 4
program into a special code called bytecode. Then
Java interpreter interprets this bytecode to obtain 1.2 Java Programming Environment
MSBTE : Summer 15, Winter 15, Marks 4
the equivalent machine code.
 The Java environment is made up of three things-
 This machine code is then directly executed to
development tools, classes and methods and java
obtain the output.
runtime environment.
7. Java is known for its high performance, scalability,  The java development tools constitute Java
monitoring and manageability Development Kit (JDK).
 Due to the use of bytecode the Java has high  The classes and methods are called Application
performance. The use of multi-threading also helps Programming Interface (API) which forms a library
to improve the performance of the Java. called Java Standard Library (JSL)
 The J2SE helps to increase the scalability in Java.  The java runtime environment is supported by Java
For monitoring and management Java has large Virtual Machine (JVM).
number of Application Programming Interfaces
1.2.1 Java Development Kit (JDK)
(API).
 There are tools available for monitoring and  The Java Development Kit is nothing but a collection
tracking the information at the application level. of tools that are used for development and runtime
programs.
8. Java is a dynamic and extensible language
 It consists of -
 This language is capable of dynamically linking new 1. javac - The Java compiler which translates the
class libraries, methods and objects. source code to the bytecode form and stores it in a
 Java also supports the functions written in C and separate class file.
C++. These functions are called native methods. 2. java - The Java interpreter, which interprets the
9. Java is a designed for distributed systems bytecode stored in the class file and executes the
 This feature is very much useful in networking program to generate output.
environment. 3. javadoc - For creating the HTML document for
 In Java, two different objects on different documentation from source code file.
computers can communicate with each other. 4. javah - It produces header files for the use of
 This can be achieved by Remote Method native methods.
Invocation (RMI). This feature is very much useful 5. jdb - The Java debugger which helps to find the
in Client-Server communication. errors in the program.
6. appletviewer - For executing the Java applet.
10. Java can be developed with ease
7. javap - Java disassembler, which helps in
There are various features of Java such as Generics, static
converting byte code files into program description.
import, annotations and so on which help the Java
programmer to create a error free reusable code.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-3 Basic Syntactical Constructs in Java

 Following are the steps that illustrate execution  As the name suggests, it is a virtual computer that
process of the application program - resides in the real computer. Java can achieve its
1. The user creates the Java source code in the text platform independence feature due to Java Virtual
editor. Machine.
2. The source code is compiled using the javac  The execution of any Java program is carried out as
command. shown in Fig. 1.2.2
3. The javadoc tool can be used to create the HTML
files that document the source program.
4. On compiling the source program a class file gets
generated which consists of the byte code.
5. The developer may use javah tool for generating
the required header files.
6. The class file produced by javac can be interpreted
using java in order to produce an executable.

Fig. 1.2.2 Execution of Java program

 When we want to write any Java program, we write the


source code and store it in a file with extension .java.
 This .java file is compiled using javac and a class file
gets created. This class file is actually a byte code. The
name byte code is given because of the instruction set
of Java program.
 The Java Virtual Machine takes byte code as an input,
reads it, interprets it and then executes it.
 The Java Virtual machine can generate an output
corresponding to the underlying platform (operating
system).

Fig. 1.2.1 Execution process of application program Board Questions


1. What is JVM ? What is byte code ?
1.2.2 Java Virtual Machine (JVM) MSBTE : Summer 15, Marks 4
 Java Virtual Machine is a set of software and program 2. What is byte code ? Explain any two tools
components. available in JDK.
MSBTE : Winter 15, Marks 4

TM
Technical Publications - An up thrust for knowledge
Java Programming 1-4 Basic Syntactical Constructs in Java

3. Define JDK. List the tools available in JDK programming language. object oriented
explain any one in detail.
language. programming
MSBTE : Summer 15, Marks 4
language.
1.3 Difference between Java and other
Programming Languages 7. In C we can use In C++ we can In Java there is
MSBTE : Winter 16, Marks 4 the pointers. use the no concept of
pointers. pointers.
Sr. C C++ Java
No. 8. In C there is no In C++ we can In Java, there
class. The write a program must be at least
1. C is a language The C++ is a The Java is a structure is used without a class. one class
that needs to be language that language that instead of that. present.
compiled. needs to be gets interpreted
compiled. and compiled. Board Question
1. How java is different than other programming
2. C is platform C++ is platform Java is a language ?
dependent. dependent. platform MSBTE : Winter 16, Marks 4
independent.
1.4 How to Write and Execute Java Program
3. C does not C++ does not Java supports  Java programs are always stored by filename extension
support multi- support multi- multi- java.
threading threading threading.  The name of the Java program must be similar to its
programming. programming. class.
4. C does not C++ does not Using Java, one  These java programs can be written using simple
have facility to have facility to can design very notepad file and executed on command prompt.
create and create and interactive and  The structure of Java program is as follows -
implement the implement the user friendly Documentation section
graphical user graphical user graphical user
Package statements section
interface. interface. interface.
Import statements section
5. C does not have C++ has Java has Class definition
any exception exception exception
Main Method class
handling handling handling {
mechanism. mechanism mechanism public static void main(String[] args)
using try-catch using try-catch {
//main method definition
block. and throw.
}
}
6. C does not C++ supports Java does not
supports any multiple support Documentation section : The documentation section
object oriented inheritance. It multiple provides the information about the source program. This
programming is an object inheritance section contains the information which is not compiled by
concept. It is a oriented however it the Java. Everything written in this section is written as
procedure programming makes use of comment.
oriented interface.It is an
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-5 Basic Syntactical Constructs in Java

Package section : It consists of the name of the package by using the keyword package. When we use the
classes from this package in out program then it is necessary to write the package statement in the beginning of
the program.
Import statement section : All the required java API can be imported by the import statement. There are
some core packages present in the java. These packages include the classes and method required for java
programming. These packages can be imported in the program in order to use the classes and methods of the
program.
Class definition section : The class definition section contains the definition of the class. This class normally
contains the data and the methods manipulating the data.
Main method class : This is called the main method class because it contains the main() function. This class
can access the methods defined in other classes.
Note that we can write the
Example of My First Java Program program in simple Notepad.
Java Program[Firstprog.java]

Note that the name of the program and


class name should be same

How to Execute?
The output of this program can be generated on the command prompt using the commands.
Open command prompt and type javac command. The syntax of execution of Java program is
javac filename.java
java filename
Here is illustration -

TM
Technical Publications - An up thrust for knowledge
Java Programming 1-6 Basic Syntactical Constructs in Java

Program explanation  Thus the state of an object is represented using data


 In our first Java program, on the first line we have fields (data members) and behaviour of an object is
written a comment statement as represented by set of methods (member functions).
/* The class template can be represented by following
This is my First Java Program Fig. 1.5.1.
*/
This is a multi-line comment. Even a single line comment
like C++ is also allowed in Java. Hence if the statement
would be

//This is my First Java Program


Fig. 1.5.1 Class template
Is perfectly allowed in Java.  The Java Class can written as follows
 Then actual program starts with class Customer {

class Firstprog int ID;


int Age; Data
String Name;
Here class is a keyword and Firstprog is a variable name
of class. Note that the name of the class and name of Customer() {
your Java program should be the same. The class }
Constructor
definition should be within the curly brackets. Customer(int ID) {
}
 Then comes
public static void main(String args[]) double withdraw_money() {
This line is for a function void main(). The main is of …
Method
type public static void. …
}
The public is a access mode of the main() by which the
 Encapsulation means binding of data and method
class visibility can be defined. Typically main must be
together in a single entity called class. Thus a class is
declared as public.
used to achieve an encapsulation property.
The parameter which is passed to main is String args[].
 This class is not having the main function. The class
Here String is a class name and args[] is an array which
that contains main function is called main class.
receives the command line arguments when the program
runs. Concept of Object
 Then display the message on command prompt  Definition of object : Object is an instance of a class.
window we write following code -  Objects are basic run-time entities in object oriented
System.out.println("This is my first java program"); programming.
1.5 Class and Object  For example - If the class is country then the objects
MSBTE : Summer 16, 18, Winter 16, Marks 8 can be India, China, Japan, U.S.A and so on.

Concept of Class
 A single class can create any number of objects.

Definition of Class : Each class is a collection of data  Declaring objects -


and the functions that manipulate the data. The data The syntax for declaring object is -
components of the class are called data fields and the Class_Name Object_Name=new class_Name();
function components of the class are called member
functions or methods.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-7 Basic Syntactical Constructs in Java

 Example Program Explanation


Fruit f1=new Fruit()  In above program we have declared one simple class.
For the class Fruit the object f1 can be created. This class displays small database of the students. The
The new operator is used to create an object. Using new data members of this class are name,roll and marks.
operator memory is allocated for the object. There is one member function named display which is
for displaying the data members. In the main function
Example of Class and Object we have created three objects obj1,obj2 and obj3.
 Following is a simple Java program that illustrates the These objects represent the real world entities. These
use of class entities are actually the instances of the class. The class
import java.io.*; representation of the above program can be as
import java.lang.*; follows -
import java.math.*;
public class MyClass
{
String name;
Data
int roll;
members
double marks;
public void display(String n,int r,double m)
{
Members
System.out.println(); function
System.out.println("Name: "+n); is defined
System.out.println("Roll number: "+r); here
System.out.println("Marks: "+m); Fig. 1.5.2

Example 1.5.1 : Define a class item having data member


} code and price. Accept data for one object and display it.
public static void main(String args[]) MSBTE : Summer 16, Marks 4
{ Solution :
int a,b;
MyClass.java
MyClass obj1=new MyClass();
import java.io.*;
MyClass obj2=new MyClass();
import java.lang.*;
MyClass obj3=new MyClass();
import java.math.*;
obj1.display("Amar",10,76.65);
public class MyClass
obj2.display("Akbar",20,87.33);
{
obj3.display("Anthony",30,96.07);
int code;
}
double price;
}
public void display(int c,double p)
Output {
Name: Amar
Roll number: 10 System.out.println();
Marks: 76.65 System.out.println("Code: "+c);
System.out.println("Price: "+p);
Name: Akbar }
Roll number: 20 public static void main(String args[])
Marks: 87.33 {
MyClass obj1=new MyClass();
Name: Anthony obj1.display(101,76.50);
Roll number: 30 }
Marks: 96.07 }

TM
Technical Publications - An up thrust for knowledge
Java Programming 1-8 Basic Syntactical Constructs in Java

Example 1.5.2 : Write a program to create a class account 1.6 Java Tokens
having variable accno, accname and balance. Define deposite MSBTE : Winter 16, Summer 17, 18, Marks 4
( ) and withdraw ( ) methods. Create one object of class and
perform the operation. The smallest individual and logical unit of the java
MSBTE : Winter 16, Marks 8 statements are called tokens. In Java there are five types
Solution : of tokens used. These tokens are -
public class Account 1. Reserved keywords 2. Identifiers
{
private double balance; 3. Literals 4. Operators
public void initialize() 5. Separators
{
Reserved keywords
balance=1000;
} Keywords are the reserved words which are enlisted as
public void deposit(double amount) below-
{
balance = balance + amount; abstract default int super
}
assert double interface switch
public void withdraw(double amount) boolean else long this
{
balance = balance - amount; byte extends native throw
}
break final new throws
public double getBalance()
{ case for package transient
return balance;
} catch float private try
public static void main(String args[])
{ char goto protected void
Account ac=new Account();
class if public volatile
ac.initialize();
System.out.println("Depositing some amount"); const implements return while
ac.deposit(100);
System.out.println("Total Balance is: "); continue import short true
ac.balance();
do instanceof static false
System.out.println("Withdrawing some amount");
ac.withdraw(200); null
System.out.println("Total Balance is: ");
ac.balance(); Identifiers
} Identifiers are the kind of tokens defined by the
}
programmer. They are used for naming the classes,
Board Questions methods, objects, variables, interfaces and packages in
1. Define a class and object. Write syntax to create the program.
class and object with an example. Following are the rules to be followed for the identifiers-
MSBTE : Summer 18, Marks 4
1. The identifiers can be written using alphabets, digits,
2. What is the use of new operator ? Is it necessary to
be used whenever object of the class is created ? underscore and dollar sign.
Why ? 2. They should not contain any other special character
MSBTE : Winter 16, Marks 4 within them.
3. There should not be a space within them.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1-9 Basic Syntactical Constructs in Java

4. The identifier must not start with a digit, it should


; Used to terminate the statement
always start with alphabet.
5. The identifiers are case-sensitive. For example - , Commas are used to separate the contents.
int a;
. Period is used to separate the package
int A;
In above code a and A are treated as two different name from subpackages.
identifiers.
1.6.1 Variable
6. The identifiers can be of any length.
A variable is an identifier that denotes the storage
Literals location.
Literals are the kind of variables that store the
Variable is a fundamental unit of storage in Java. The
sequence of characters for representing the constant
variables are used in combination with identifiers, data
values. Five types of literals are -
types, operators and some value for initialization. The
1. Integer literal 2. Floating point literal
variables must be declared before its use. The syntax of
3. Boolean literal 4. Character literal
variable declaration will be -
5. String literal
data_type name_of_variable[=initialization][,=initialization][,…];
As the name suggests the corresponding data type
Following are some rules for variable declaration -
constants can be stored within these literals.
 The variable name should not begin with digits.
Operators  No special character is allowed in identifier except
Operators are the symbols used in the expression for underscore.
evaluating them.  There should not be any blank space with the identifier
name.
Separators
 The identifier name should not be a keyword.
For dividing the group of code and arranging them
systematically certain symbols are used, which are known  The identifier name should be meaningful.
as separators. Following table describes various For Example :
separators. int a,b;
char m=’a’;
Name of the Description byte k=12,p,t=22;

Separator
The variables have a scope which defines their visibility
and a lifetime.
() Parenthesis are used to - enclose the
1.6.2 Data Types
arguments passed to it to define precedence
Various data types used in Java are byte, short, int, long,
in the expression. For surrounding cast char, float, double and boolean.
type
byte
{} Curly brackets are used for - initialising This is in fact smallest integer type of data type. Its width
array for defining the block is of 8-bits with the range –128 to 127. The variable can
be declared as byte type as -
[] Square brackets are used for - declaring byte i,j;
array types dereferencing array values

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 10 Basic Syntactical Constructs in Java

short using + [In C we use comma in printf statement but in


This data type is also used for defining the signed Java + is used for this purpose]
numerical variables with a width of 16 bits and having a
Java Program [DatatypeDemo.java]
range from –32,768 to 32,767. The variable can be
/*
declared as short as - This program introduces use of various data type
short a,b;
in the program

int */
class DatatypeDemo
This is the most commonly used data type for defining the
{
numerical data. The width of this data type is 32-bit
public static void main(String args[])
having a range 2,147,483,648 to 2,147,483,647. The
{
declaration can be -
byte a=10;
int p,q;
short b=10*128;
long int c=10000* 128;
long d=10000*1000*128;
Sometimes when int is not sufficient for declaring some
double e=99.9998;
data then long is used. The range of long is really very
char f='a';
long and it is –9,223,372,036,854,775,808 to
boolean g=true; dynamic initialization
9,223,372,036,854,775,807. The declaration can be -
boolean h=false;
long x,y;
System.out.println("The value of a=: "+a);
float System.out.println("The value of b=: "+b);

To represent the real number (i.e. number that may have System.out.println("The value of c=: "+c);
System.out.println("The value of d=: "+d);
decimal point) float data type can be used. The width is
System.out.println("The value of e=: "+e);
32-bit and range of this data type is 1.4e – 045 to
System.out.println("The value of f=: "+f);
3.4e+038.
f++;
double System.out.println("The value of f after increment=: "+f);

To represent the real numbers of large range the double System.out.println("The value of g=: "+g);
System.out.println("The value of h=: "+h);
data type is used. Its width is 64-bit having the range
}
4.9e–324 to 1.8e+308.
}
Char
Output
This data type is used to represent the character type of
The value of a=: 10
data. The width of this data type is 16-bit and its range is
0 to 65,536. The value of b=: 1280
The value of c=: 1280000
Let us see one simple Java program which makes use of
various data types. The value of d=: 1280000000
The value of e=: 99.9998
boolean
The value of f=: a
Boolean is a simple data type which denotes a value to be The value of f after increment=: b
either true or false. The value of g=: true

Java Program The value of h=: false

Note that for displaying the value of variable, in the


println statement the variable is appended to the message
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 11 Basic Syntactical Constructs in Java

1.6.3 Constants and Symbolic Constants

Constants
Constants mean the fixed values that do not change during the execution of a program.
In Java various types of constants are used and these are as shown in following Fig. 1.6.1.

Fig. 1.6.1 Types of constants

Numeric constants
Numeric constants are used for representing the numerical values. The numeric values can be integer or real
type. Hence there exists the integer and real constants.

Integer constants
Integers mean sequence of digits. There are three types of integers -
Decimal integer : The decimal integers consist of a set of digits 0 through 9. These numbers can be unary
numbers. That means these can be preceded by unary minus. For example - 111, – 200, 455
Octal integer : The octal integer constants consists of set of 0 to 7 having a zero at the beginning.
For example - 033, 0431, 0633
Hexadecimal integer : Along with the 0 to 9 digits, it also consists of the letters A to F.
Real constants : The real constants contain the floating point parts. For example - 0.045, 0.567, 0.3211
Character constants : A single character constant is enclosed within a pair of single quotes.
For example - ‘a’, ’T’, ‘1’
String constant : A string is a collection of characters enclosed between double quotes. The characters can be
alphabets, numbers, white spaces or special characters.
For example - “India” ,”Best10”, “s?ss”

Symbolic Constants
 There are two problems that are associated with the constants and those are-
1. Modifiability : The constants may need to be modified during the program. For example : The value of
pi may be 3.14 at one place in the program and it may be required as 3.14159 at some other place in the
same program for the accuracy.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 12 Basic Syntactical Constructs in Java

2. Understandability : The purpose of each constant Example of Static Variable


need to be remembered. For example : The class Test
constant INDEX may be required to store the {
public void setA()
index, the constant COUNT may keep track of
{
some count or there may be some constant for int A=10;//local variable
SIZE. {
System.out.println("Block A: "+A);
 To overcome these problems there is a use of symbolic
}//scope of A=10 ends here
constants. The keyword final is used to declare the {
symbolic constants. A=20;//scope of A=20 starts here
 The syntax for declaring the symbolic constants is - System.out.println("Block A: "+A);
}//scope of A=20 ends here
final datatype variable_name=value
}
 For example - }//scope of all the variables end here
final int INDEX=1; public class VarScopeDemo
final int SIZE=10; {
 Conventions : Following are the conventions that are public static void main(String args[])
{
associated with the symbolic names -
Test obj=new Test();
1. Symbolic names must be written in capital letters. obj.setA();
2. After declaring the symbolic name one must not }
}
modify it.
3. The symbolic constants are declared for types. Output
Block A:10
4. The symbolic constants can not be declared inside Block A:20
a method. They should be used only as class data
 The local variables are not accessible to the method
members in the beginning of the class.
outside the method because their scope is limited
1.6.4 Dynamic Initialization within the { and }(i.e. scope of the local method)
 Java is a flexible programming language which allows  The area in which the variables are accessible is called
the dynamic initialization of variables. scope.
 In other words, at the time of declaration one can  The program blocks can be nesting , i.e. one block can
initialize the variables (note that in the above program be defined within another block.
we have done dynamic initialization).  When the objects are instantiated at that time the
 In Java we can declare the variable at any place before instance variables are created. The instance variables
it is used. are associated with objects. Hence with each different
object there is different value associated each instance
1.6.5 Scope of Variable
variable.
 There are three types of variables -
 Example of Instance Variable
1. Instance variable class Test
2. Class variable {
public int A;//instance variable
3. Local variable
public void setA()
 Instance and class variables are declared inside the {
class. A=10;
}
 The local variables are declared inside the method.
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 13 Basic Syntactical Constructs in Java

public class VarScopeDemo


For example:
{
public static void main(String args[]) int a=5;
{ long b;
Test obj=new Test();//instance of class is created
obj.setA();//accessing the variable using instance of the
b=a;
class  For incompatible data types we have to do explicit
System.out.println("A= "+obj.A);
type conversion. This mechanism is called casting.
}
} Hence

Output Defintition:
A= 10
Type casting means explicit conversion between
 The class variables are global to the corresponding incompatible data types.
class. This variable can be accessed by the objects of For casting the values we use following syntax:
that class.
(type) variable
 Example of class variable
class VarScopeDemo Example:
{ double a;
private static int A;//class or static variable int b;
public static void main(String args[]) b=(int) a;
{ In the following Java program, we use the type casting
A=10;
System.out.println("A = "+A); Java Program[TypeCastProg.java]
} public class TypeCastProg
} {
Output public static void main(String[] args)
A= 10 {
double x;
1.6.6 Typecasting int y;
x=25.50;
 Java allows the automatic conversion between these
System.out.println("Value of [double] x: "+x);
data types. System.out.println("Conversion of double to integer");
 But Java performs type conversion between the y=(int)x;
compatible data type elements. System.out.println("Value of [integer] y: "+y);
int m;
 For instance: If we assign an integer value to a float double n;
type element then Java automatically makes this m=10;
conversion. However, this automatic conversion can n=(double)m;
System.out.println("Value of [integer] m: "+m);
not be done between any data type, rather such a
System.out.println("Conversion of integer to double");
conversion is done with the compatible data type System.out.println("Value of [double] n: "+n);
elements.
}
Conditions in which Java allows automatic conversion
}
 When two data types are compatible to each other.
 When the target data type element is larger than the Output
source data type Value of [double] x: 25.5
Conversion of double to integer

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 14 Basic Syntactical Constructs in Java

Value of [integer] y: 25 Board Questions


Value of [integer] m: 10
1. State and explain scope of variable with an
Conversion of integer to double example. MSBTE : Summer 18, Marks 4
Value of [double] n: 10.0
2. What is scope of variable ? Give example of class
Program Explanation variable, instance variable and local variable.
In above program, MSBTE : Winter 16, Marks 4
3. What is type casting ? Explain its types with proper
1) We have made the type casting of-
syntax and example. MSBTE : Summer 18, Marks 4
Integer to double, double to integer 4. Write all primitive data types available in Java
2) When a double value is converted to an integer the with their storage sizes in bytes.
fractional parts is lost. This is called truncation. But MSBTE : Summer 17, Marks 4

when an integer gets converted to double then


fractional part is padded 1.7 Operators and Expression
Following table shows the possible type casting without MSBTE : Summer 15, 16, 17, 18, Winter 15, Marks 4

loss of information- Various types operators used in Java are -


1. Arithmetic operators
From To
2. Relational operators
byte short, char, int, long, float, double 3. Logical operators
short int, long, float, double 4. Increment and decrement operator

1.7.1 Arithmetic Operators


char int, long, float, double
Type Operator Meaning Example
int long, float, double
Arithmetic + Addition or unary plus c=a+b
long double , float – Subtraction or unary d= –a
minus
float double
* Multiplication c=a*b
1.6.7 Standard Default Values / Division c=a/b
Java provides default values to the variables if we don’t % Mod c=a%b
initialise them. The standard default values for the
Program demonstrating arithmetic operators
variables of different data types are enlisted below-
class ArithOperDemo
Data type of the variable Default value
{
byte 0 public static void main(String[] args)
short 0 {

int 0 System.out.println("\n Performing arithmetic operations ");


int a=10,b=20,c;
long 0L
System.out.println("a= "+a);
float 0.0f System.out.println("b= "+b);
double 0.0d c=a+b;
char null character System.out.println("\n Addition of two numbers is "+c);
c=a-b;
Boolean false
System.out.println("\n Subtraction of two numbers is "+c);
reference null
c=a*b;
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 15 Basic Syntactical Constructs in Java

System.out.println("\n Multiplication of two numbers is "+c); System.out.println("\n The a!=b is "+(a!=b));


c=a/b;
System.out.println("\n Division of two numbers is "+c); }
} }
}

Output Output
Performing arithmetic operations
a= 10 Performing Relational operations

b= 20 a= 10
b= 20
Addition of two numbers is 30
The a<b is true

Subtraction of two numbers is -10


The a>b is false

Multiplication of two numbers is 200


The a==c is true

Division of two numbers is 0


The a<=b is true
1.7.2 Relational Operators

Type Operator Meaning Example The a>=c is true

Relational < Less than a<4


The a!=b is true
> Greater than b>10
1.7.3 Logical Operators
<= Less than equal to b<=10
Type Operator Meaning Example
>= Greater than equal to a>=5
Logical && And operator 0&&1
== Equal to x==100
|| Or operator 0 ||1
!= Not equal to m!=8
Program Demonstrating Logical Operators
Program Demonstrating Relational Operators
import java.io.*;
class RelOperDemo
import java.lang.*;
{
public class LogicalOper
public static void main(String[] args)
{
{
public static void main(String args[])throws IOException
System.out.println("\n Performing Relational operations ");
{
int a=10,b=20,c=10;
boolean oper1,oper2;
System.out.println("a= "+a);
oper1=true;
System.out.println("b= "+b);
oper2=false;
System.out.println("\n The a<b is "+(a<b));
boolean ans1,ans2;
System.out.println("\n The a>b is "+(a>b));
ans1=oper1&oper2;
System.out.println("\n The a==c is "+(a==c));
ans2=oper1|oper2;
System.out.println("\n The a<=b is "+(a<=b));
System.out.println("The oper1 is: "+oper1);
System.out.println("\n The a>=c is "+(a>=c));
System.out.println("The oper2 is: "+oper2);
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 16 Basic Syntactical Constructs in Java

System.out.println("The oper1&oper2 is: "+ans1);


System.out.println("The oper1|oper2 is: "+ans2); PostIncrementing b 22
}
After this statement the value of b is 23
}
1.7.5 Conditional Operators
Output
The conditional operator is “?” The syntax of
The oper1 is: true
conditional operator is -
The oper2 is: false
Condition?expression1:expression2
The oper1&oper2 is: false
The oper1|oper2 is: true Where expression1 denotes the true condition and
expression2 denotes false condition.

1.7.4 Increment and Decrement For example:


a>b?true:false
This means that if a is greater than b then the expression
Type Operator Meaning Example
will return the value true otherwise it will return false.
Increment ++ Increment by one ++i or i++
Program Demonstrating Conditional Operator
Decrement –– Decrement by one – – k or k– – class Test
{
Program Demonstrating Increment and Decrement Operator
public static void main(String args[])
class IncrDecrOperDemo
{
{
int a,b,c;
public static void main(String[] args)
a=10;
{
b=20;
System.out.println("\n Performing increment and decrement System.out.println("a = "+a);
operations ");
System.out.println("b = "+b);
int a=11,b=22;
c=a>b?a:b;
System.out.println("a= "+a); System.out.println(c+" is greatest");
System.out.println("b= "+b); }
System.out.println("\n PreIncrementing a "+ ++a); }
System.out.println("\n PostIncrementing b "+ b++);
Output
System.out.println("\n After this statement the value of b is a = 10
"+ b);
b = 20
}
20 is greatest
}
1.7.6 Bitwise Operators
Output
Assume A=35 i.e. in binary form 00100011 and B = 14
Performing increment and decrement operations
i.e. in binary form 00001110
a= 11
b= 22

PreIncrementing a 12

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 17 Basic Syntactical Constructs in Java

Type Operator Meaning Example

bitwise and & Binary AND Operator copies a bit to the result if it exists in both A&B=00100011 &
operands. 00001110= 00000010
Truth Table

A B Output

0 0 0

0 1 0

1 0 0

1 1 1

bitwise or | Binary OR Operator copies a bit if it exists in either operand. A|B


Truth Table =

A B Output 00100011 | 00001110

0 0 0 = 00101111 i.e. 47

0 1 1

1 0 1

1 1 0

bitwise XOR ^ Binary XOR Operator copies the bit if it is set in one operand but A^B
not both. =
Truth Table 00100011 ^ 00001110
A B Output =00101101

0 0 0 i.e. 45

0 1 1

1 0 1

1 1 0

bitwise complement ~ Binary ones complement operator is unary and it has effect of ~A=11011100 = ~36
flipping bits.

Left shift << The left operands value is moved left by the number of bits 00100011<<2
specified by the right operand. =1000 1100

Right shift >> The left operands value is moved right by the number of bits 00100011>>2
specified by the right operand. =0000 1000

Zero fill right shift >>> The left operands value is moved right by the number of bits 00100011>>>2
specified by the right operand and shifted values are filled up == 0000 1000
with zeros.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 18 Basic Syntactical Constructs in Java

1.7.8 Operator Precedence and Associativity


Program Demonstrating Bitwise Operator
 Precedence : The precedence relation specifies which
public class Test {
operation must be done first during the expression
public static void main(String args[]) { evaluation.
int a = 35; /* 35 = 00100011 */  Associativity : Associativity tells the direction of
int b = 14; /* 14 = 00001110 */
execution of operators that can be either left to right or
int c = 0;
right to left. For example, in expression a = b = c = 10
c = a & b; /* 2 = 0000 0010 */ the assignment operator is executed from right to left
System.out.println("a & b = " + c ); that means c will be assigned by 10, then b will be
assigned by c and finally a will be assigned by b.
c = a | b; /* 47 = 00101111 */
System.out.println("a | b = " + c );  Following table denotes the precedence relation and
associativity. The operators are arranged from Highest
c = a ^ b; /* 45 = 00101101 */ priority to lowest priority. The operators in the same
System.out.println("a ^ b = " + c );
row indicate the equal precedence.
c = ~a; /*-36 */ Associativity
Precedence Operator Description
System.out.println("~a = " + c );

1 [] Array index Left -> Right


c = a << 2; /* 140 = 1000 1100 */
System.out.println("a << 2 = " + c ); () Method call
. Member access
c = a >> 2; /* 8 = 0000 1000 */
System.out.println("a >> 2 = " + c ); 2 ++ Pre or postfix increment Right -> Left
-- Pre or postfix decrement
c = a >>> 2; /* 8 = 0000 1000 */ +- Unary plus, minus
System.out.println("a >>> 2 = " + c ); ~ Bitwise NOT
}
! Logical NOT
}

1.7.7 Instance of Operators and Dot Operators 3 (type type cast Right -> Left
cast) object creation
 There are two special operators used in Java- new
instanceof and dot operators.
 For determining whether the object belongs to 4 * multiplication Left -> Right
particular class or not an instanceof operator is used. / division
% modulus (remainder)
For example -
Ganga instanceof River 5 +- addition, subtraction Left -> Right
If the object Ganga is an object of class River then it + String concatenation
returns true otherwise false.
6 << Left shift Left -> Right
 The dot operator is used to access the instance variable
>> Signed right shift
and methods of class objects. >>> Unsigned or zero-fill
For example - Right shift
Customer.name //for accessing the name of the
7 < Less than Left -> Right
customer
<= Less than or equal to
Customer.ID //for accessing the ID of the customer > Greater than
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 19 Basic Syntactical Constructs in Java

>= Greater than or equal to than addition. So we perform multiplication operation


instanceof reference test first and then addition.

8 == Equal to Left -> Right 1.7.10 Mathematical Functions


!= Not equal to  Java provides a support for performing mathematical
operations by means of mathematical functions.
9 & Bitwise AND Left -> Right
 The basic mathematical functions are defined in the
10 ^ Bitwise XOR Left -> Right Math class defined in java.lang package. Various
mathematical functions are -
11 | Bitwise OR Left -> Right
sin( double angle) Returns the sine of angle in radians
12 && Logical AND Left -> Right
cos(double angle) Returns the cosine of angle in radians
13 || Logical OR Left -> Right
tan (double angle) Returns the tan of angle in radians
14 ?: Conditional (ternary) Right -> Left asin(double val) Returns the angle whose sine is val

15 = Assignment and short Right -> Left acos(double val) Returns the angle whose cosine is val
+= hand assignment atan(double val) Returns the angle whose tan is val
-= operators
b
*= pow(double a, It computes a
/= double y)
%= exp(double a) It computes e
a

&=
^= sqrt(double a) It computes square root of a
|= max(a,b) It computes the maximum of a and b
<< =
>> = min(a,b) It computes the minimum of a and b
>>> = log(val) It computes the logarithmic values of
val
1.7.9 Evaluation of Expression
abs(val) It computes the absolute value of val
 Expression is a combination of operators and operands
in specific manner. ceil(val) It returns the smallest whole number
which is greater than or equal to val
 For example
floor(val) It returns the largest whole number
c=a+b*c; // Expression with arithmetic operators
which is lesser than or equal to val.
(a>b)&&(b<c)// Expression with logical operators and
relational operators Following is an example of Java program which makes
use of mathematical function -
 The evaluation of expression is an order of evaluating
the expression using precedence and associativity Example 1.7.1 : Write a simple Java program to illustrate use
of mathematical function.
rules. Solution :
 For example -
Java Program[MathDemo.java]
To evaluate 2+3*4 we will first perform 3*4=12, then
class MathDemo
add 2 to 12 and the result of this expression will be 14. {
This is because multiplication has higher precedence public static void main(String[] args)
{

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 20 Basic Syntactical Constructs in Java

double val; i) Simple if statement : The if statement in which only


val=25;
one statement is followed by that is statement.
System.out.println("\n The square root of "+val+" is
"+Math.sqrt(val));
Syntax
int a=10,b=20;
if(apply some condition)
System.out.println("\n The maximum of "+a+" and "+b+" is
statement
"+Math.max(a,b));
System.out.println("\n The minimum of "+a+" and "+b+" is
For example
"+Math.min(a,b));
if(a>b)
System.out.println("\n The sin of "+val+" is
"+Math.sin(val)); System.out.println(“a is Biiiiig!”);
System.out.println("\n The cos of "+val+" is ii) Compound if statement : If there are more than one
"+Math.cos(val)); statement that can be executed when if condition is
}
}
true. Then it is called compound if statement. All
these executable statements are placed in curly
Output
brackets.
The square root of 25.0 is 5.0

Syntax
The maximum of 10 and 20 is 20
if(apply some condition)
{
The minimum of 10 and 20 is 10
statement 1
statement 2
The sin of 25.0 is -0.13235175009777303
.
.
The cos of 25.0 is 0.9912028118634736
.
statement n
Board Questions
}
1. Describe any two relational and any two logical
operators in Java with simple example. 1.8.2 if else Statement
MSBTE : Summer 16, Marks 4
The syntax for if…else statement will be -
2. Explain any two relational operators in Java with if(condition)
example. statement
MSBTE : Summer 17, Marks 4 else
3. ‘? :’ What this operator is called ? Explain with statement
suitable example.
MSBTE : Summer 15, Winter 15, Marks 4 For example

4. Explain any two bit-wise operators with example. if(a>b)


MSBTE : Winter 15, Marks 4 System.out.println(“a is big”)
else
5. Explain following bitwise operator with an
System.out.println(“b :big brother”)
example :
The if…else statement can be of compound type even.
(1) Left shift operator (2) Right shift operator
MSBTE : Summer 18, Marks 4 For example,
if(raining==true)
{
1.8 Decision Making and Looping System.out.println(“I won’t go out”);
MSBTE : Winter 15,16, 17, Summer 15,16, 17, 18, Marks 8 System.out.println(“I will watch T.V. Serial”);
System.out.println(“Also will enjoy coffee”);
1.8.1 If Statement }
The if statement is of two types - else

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 21 Basic Syntactical Constructs in Java

{ System.out.println(First Class");
System.out.println(“I will go out”); else
System.out.println(“And will meet my friend”); System.out.println(" Distinction!!!.");
System.out.println(“we will go for a movie”); }
System.out.println(“Any how I will enjoy my life”); }
}
Output
1.8.3 Nested if-else Statement First Class

The syntax of if…else if statement is


1.8.5 Switch Statement
if(is condition true?)
statement Using switch statement we can make a choice from a list
else if(another condition) of values. Each value in switch statement is considered as
statement
case. A variable is used in switch statement to match the
else if(another condition)
statement
desired case.
else The Syntax of switch statement is
statement switch(expression)
{
For example case value:
if(age==1) statements
System.out.println(“You are an infant”); break;
else if(age==10) case value:
System.out.println(“You are a kid”); statements
else if(age==20) break;
System.out.println(“You are grown up now”); …
else default: //optional
System.out.println(“You are an adult”); //statements
}
1.8.4 If-else-if Ladder
For example
 The control flow statements are evaluated from top to switch(ch)
bottom. Hence the if-else-if ladder will be evaluated {
case 1: System.out.println("Monday");
from top to bottom.
break
 As soon as an if statement from the ladder evaluates to case 2: System.out.println("Tuesday");
true, the statements associated with that if are executed break;
and the remaining part of the ladder is bypassed. case 3: System.out.println("Wednesday");
break
 The last most else is executed only when no condition case 4: System.out.println("Thursday");
in the whole ladder returns true. break;
case 5: System.out.println("Friday");
 Example Program
break
public class Test
case 6: System.out.println("Saturday");
{
break;
public static void main(String[] args)
case 7: System.out.println("Sunday");
{
break;
char marks=69;
}

if (marks<50) Example 1.8.1 : In what ways does a switch statement differ


System.out.println("You are Fail"); from an if statements ? MSBTE : Winter 16, Marks 4
else if (marks >=50 && marks<60)
System.out.println("Second class is ");
else if (marks>60 && marks<70)
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 22 Basic Syntactical Constructs in Java

Solution : break;
}
Sr. if statement switch statement }
No. }
1 if-else statement test for switch statement tests Output
equality as well as for only for equality. PHP
logical expression.
Program Explanation : In above Program,
2 The if statement evaluates The switch statement
As value of a=1, the control will enter in the outer switch
integer, character pointer, evaluates only character
with case 1.
floating point or boolean or integer value.
values. As value of b=2,the control will enter in the inner switch
3 The if-else statement uses switch statement uses
with case 2.
multiple statements for single expression for Hence the output is “PHP”.
multiple choices. multiple choices.
1.8.7 The while Statement
4 Either if statement will be Switch statements
 This is one form of statement which is used to have
executed or else statement executes one case after
will be executed. other until it reads break iteration of the statement for the any number of times.
statement.  The syntax is,
while(condition)
1.8.6 Nested Switch Statement {
Nested Switch statement is a switch statement inside statement 1;
statement 2;
another switch statement.
statement 3;
For example - Consider following Java program …
public class Test statement n;
{ }
public static void main(String[] args)
{ For example
int a,b; int count=1;
a=1;b=2; while(count<=5)
switch(a) {
{ System.out.println(“I am on line number “+count);
case 1: count++;
switch(b) }
{ Let us see a simple Java program which makes the use of
case 1:System.out.println("Java");
while construct.
break;
case 2:System.out.println("PHP");
Java Program [whiledemo.java]
break;
/*
}
This is java program which illustrates
break;
while statement
case 2:
*/
switch(b)
class whiledemo
{
{
case 1:System.out.println("HTML");
public static void main(String args[])
break;
{
case 2:System.out.println("XML");
int count=1,i=0;
break;
while(count<=5)
}
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 23 Basic Syntactical Constructs in Java

i=i+1; Solution :
System.out.println("The value of i= "+i);
public class DigitSum
count++;
{
}
int num;
}
public void initialize()
}
{
Output num=123;
The value of i= 1 System.out.println("The number is: "+num);
The value of i= 2 }
The value of i= 3 public void display()
The value of i= 4 {
The value of i= 5 int sum=0;
while(num > 0)
Example 1.8.2 : Define a class having one 3 digit number,
num as data member, initialize and display reverse of that {
number. sum = sum + (num % 10);
MSBTE : Summer 15,16, Marks 4 num = num / 10;
Solution : }
System.out.println("The sum of digits is: "+sum);
public class NumReverse
}
{
public static void main(String[] args)
int num;
{
public void initialize()
DigitSum obj=new DigitSum();
{
obj.initialize();
num=123;
obj.display();
System.out.println("The number is: "+num);
}
}
}
public void display()
{ Output
int rev=0; The number is: 123
System.out.print("Reverse of number is: "); The sum of digits is: 6
while(num > 0)
Example 1.8.4 : Write a program to find the number of and
{
sum of all integers greater than 100 and less than 200 that are
rev = rev * 10 + (num % 10); divisible by 7. MSBTE : Winter 16, Marks 4
num=num/10; Solution :
}
System.out.println(rev); public class DigitRange
} {
public static void main(String[] args) public static void main(String[] args)
{ {
NumReverse obj=new NumReverse(); int sum=0;
obj.initialize();
System.out.println("\n Numbers between 100 to 200
obj.display(); which is divisible by 7");
}
for(int i=101;i<200;i++)
}
{
Output if(i%7==0)
The number is: 123
{
Reverse of number is: 321
System.out.print(" "+i);
Example 1.8.3 : Write a program to find sum of digit of sum= sum + i;
number entered by user.
MSBTE : Winter 16, Summer 17, Marks 4 }
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 24 Basic Syntactical Constructs in Java

System.out.println("\n sum = "+sum); i=i+1;


} System.out.println("The value of i= "+i);
count++;
}
}while(count<=5);
Output }
Numbers between 100 to 200 which is divisible by 7 }
105 112 119 126 133 140 147 154 161 168 175
182 189 196 Output
sum = 2107 The value of i= 1
The value of i= 2
1.8.8 The do while Statement The value of i= 3
The value of i= 4
 This is similar to while statement but the only The value of i= 5
difference between the two is that in case of do…while
statement the statements inside the do…while must be 1.8.9 The for Statement

executed at least once. for is a keyword used to apply loops in the program. Like
 This means that - other control statements for loop can be categorized in
o The statement inside the do…while body gets simple for loop and compound for loop.
executed first and then the while condition is Simple for loop :
checked for next execution of the statement. for (statement 1;statement 2;statement 3)
o Whereas in the while statement first of all the execute this statement;

condition given in the while is checked first and Compound for loop :
then the statements inside the while body get for(statement 1;statement 2; statement 3)
executed when the condition is true. {
execute this statement;
Syntax execute this statement;
do execute this statement;
{ that’s all;
}
statement 1;
Here
statement 2;
… Statement 1 is always for initialization of conditional
statement n; variables,
}while(condition); Statement 2 is always for terminating condition of the for
loop,
For example
Statement 3 is for representing the stepping for the next
Java Program [dowhiledemo.java] condition.
/*
For example :
This is java program which illustrates
for(int i=1;i<=5;i++)
do…while statement
{
*/
System.out.println(“Java is an interesting language”);
class dowhiledemo
System.out.println(“Java is a wonderful language”);
{
System.out.println(“And simplicity is its beauty”);
public static void main(String args[])
}
{
int count=1,i=0; Let us see a simple Java program which makes use of for
do loop.
{

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 25 Basic Syntactical Constructs in Java

Java Program [forloop.java] 1.8.10 The Break Statement


/* When a break statement is encountered in a loop then the
This program shows the use of for loop loop is terminated and the control resumes the next
*/
statement following the loop. For example
class forloop
{
Java Program
public static void main(String args[])
public class breakDemo
{
{
for(int i=0;i<=5;i++)
public static void main(String[] args)
System.out.println("The value of i: "+i);
{
}
for (int i = 1; i <= 10; i++)
}
{
Output if (i == 5)
The value of i: 0 {
The value of i: 1 break; // terminate loop if i is 5
The value of i: 2 }
The value of i: 3 System.out.print(i + " ");
The value of i: 4 }
The value of i: 5 System.out.println("Loop is terminated using break!!");
}
Example 1.8.5 : Write a program to generate Fibonacci series
1 1 2 3 5 8 13 21 34 55 89. }
MSBTE : Summer 17, Marks 4
Output
Solution : 1 2 3 4 Loop is terminated using break!!
class Fibonacci Program Explanation : In above program,
{
public static void main(String args[]) 1) The for loop is executed for i=1 to i=10.
{ 2) But when i value reaches to 5, the break statement is
int a,b, c, n;
encountered.
a=b=1;
for(n=1;n<=10;n++) 3) Due to this, the control terminates the for loop and the
{ System.out.println statement outside the for loop will
System.out.print(" "+a);
be executed. Hence is the output.
c=a+b;
a=b; 1.8.11 The continue Statement
b=c;
} When a continue statement is encountered inside the body
} of a loop, remaining statements are skipped and loop
}
proceeds with the next iteration. For example -
Output
Java Program
public class continueDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
continue;
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 26 Basic Syntactical Constructs in Java

System.out.print(i + " "); 1.8.12 The return Statement


}
 The return statement is used to return from a function.
} That means using return statement the control goes
} back to the caller function.
Output  At any time the return statement can be used to
1 2 3 4 6 7 8 9 10 transfer back the control to the caller function.
Program Explanation : In above program,  The return statement causes to terminate the function
1) When the value of i = 5 then it is skipped and loop immediately.
proceeds with further remaining values of i. Hence is  Example Program
the output. class ReturnProg
{
2) Note that : You cannot use break to transfer control to
public static void main(String args[])
a block of code that does not enclose the break {
statement. int a=10;
System.out.println("This statement is before execution of
Example 1.8.6 : Write a program to check whether an entered
return");
number is prime or not.
MSBTE : Winter 15,17, Summer 16, Marks 4 if(a==10)
Solution : return;
System.out.println("This statement will not be
class PrimeNumberDemo excuted!!!");
{ }
public static void main(String args[]) { }
int n = Integer.parseInt(args[0]);
boolean flag = true; Output
if(n < 2) This statement is before execution of return
flag = false;
1.8.13 The nested Loops
else
{ When one loop is present inside the other loop then that
for(int i=2; i<=n/2; i++) structure is called nested loop.
{
if(n % i == 0)
The outer loop takes control of the number of complete
{ repetitions of the inner loop.
flag = false;
break;
}
Example Program
flag = true;
} class NestedLoops
} {
if(flag == true) public static void main(String args[])
System.out.println(n + " is a prime number"); {
else int i,j;
System.out.println(n + " is not a prime number"); for(i=1;i<=3;i++)//outer loop
} {
} System.out.println(" i = "+i);
for(j=1;j<=3;j++)//inner loop
Output
D:\MSBTE_JAVA _Programs> javac {
PrimeNumberDemo.java System.out.print(" j = "+j);
D:\MSBTE_JAVA _Programs> java PrimeNumberDemo 15 }
15 is not a prime number System.out.println("\n------------------");
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 27 Basic Syntactical Constructs in Java

} System.out.println("The odd numbers are: ");


} for(int i=1;i<=30;i++)
{
Output
if(i%2!=0)
i=1
System.out.print(" "+i);
j=1j=2j=3
}
---------------------
}
i=2
}
j=1j=2j=3
--------------------- Output
i=3 The odd numbers are:
j=1j=2j=3 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
--------------------
Example 1.8.9 : Write a Java program to display following
Example 1.8.7 : Write a program to print the following output pattern.
:
11111 *
2222 ***
333
44 *****
5 *******
MSBTE : Winter 17, Marks 4
Solution : *********

class Test Solution :


{
class TriangleDisplay
public static void main(String args[])
{
{
int i,j; public static void main(String[] args)
for(i=1;i<=5;i++) {
{ int i,j,k;
for(j=5;j>=i;j--) for(i=1; i<=5; i++)
{ {
System.out.print(" "+i);
for(j=4; j>=i; j--)
}
{
System.out.println("");
} System.out.print(" ");
} }
} for(k=1; k<=(2*i-1); k++)

Output {
1 1 1 1 1 System.out.print("*");
2 2 2 2 }
3 3 3 System.out.println("");
4 4
}
5
}
Example 1.8.8 : Write a java program to display all the odd }
numbers between 1 to 30 using for loop and if statement.
MSBTE : Summer 18, Marks 8 Output
Solution : *
***
public class Test
*****
{
*******
public static void main(String[] args)
*********
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 28 Basic Syntactical Constructs in Java

Example 1.8.10 : Write a Java program to display following label is the name of the block which need to be
number pattern
1 skipped.
1 2  Following program demonstrates the use of labeled
1 2 3
1 2 3 4
break.
1 2 3 4 5
Example Program
Solution :
class breakLblDemo
class NumberPatternDisplay {
{ public static void main(String args[])
public static void main(String[] args) {
{ int i=5;
first:
int i,j;
{
for(i=1; i<=5; i++)
second:
{ {
for(j=1; j<=i; j++) third:
{ {
System.out.print(j+" "); System.out.println("Before the break.");
if(i==5)
}
break second; // break out of second block
System.out.println("");
System.out.println("Inside third block.");
} }
} System.out.println("Inside second block.");
} }
System.out.println("Inside first block.");
Output
}
}
}

Output
Before the break.
Inside first block.

Program Explanation : In above program,


1) We have created three blocks, by labeling them as
first, second and third.
2) Inside the third block the labeled break statement is
written to break the second block.
1.8.14 The Labeled Loops 3) Hence the control skips execution of second and third
block and reaches to the first block. So is the output.
1) labelled break
 Sometimes the control needs to be transferred to a 2) labelled Continue

specific instruction. This can be done using the  The labelled continue is basically a continue statement
statements like goto. with label.
 Java provides the support for jump statement using  The syntax is
labeled break. continue label;
 The syntax for labelled break is  Example Program : Following java program,
break label; illustrates the labeled continue statement.
TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 29 Basic Syntactical Constructs in Java

class continueLblDemo  Syntax


{
for(data_type variable_name:arry_name)
public static void main(String args[])
{
{
}
Label1: for(int i=0;i<10;i++)
{  Example Program
if(i%2==0) class ForEachProg
{ {
System.out.println("Even value: = "+i); public static void main(String args[])
continue Label1; {
} int array[]={10,20,30,40};
System.out.println("Odd value: = "+i); System.out.println("The elements in array are ...");
}
for(int i:array)
}
System.out.println(i);
}
}
Output }
Even value: = 0
Output
Odd value: = 1
The elements in array are ...
Even value: = 2
10
Odd value: = 3
20
Even value: = 4
30
Odd value: = 5
40
Even value: = 6
Odd value: = 7
Board Questions
Even value: = 8
Odd value: = 9
1. Write general syntax of any two decision making
statements and also give its examples.
1.8.15 The for-Each Version of the for Loop MSBTE : Summer 16, Marks 4

 The for-each element is used to access each element of 2. Explain break and continue statements with
example. MSBTE : Summer 16, Marks 4
an array.
3. State syntax and describe working of ‘for each’
 There are two advantages of for-each statement - version of for loop with one example.
i) It eliminates the possibility of bug. MSBTE : Summer 16, Marks 4

ii) It makes the code more readable and 4. Illustrate with example the use of switch case
statement. MSBTE : Winter 17, Marks 4
understandable.
5. Describe break and continue statement with
example. MSBTE : Winter 15, Marks 4



TM
Technical Publications - An up thrust for knowledge
Java Programming 1 - 30 Basic Syntactical Constructs in Java

Notes

TM
Technical Publications - An up thrust for knowledge
Java Programming 2-1 Derived Syntactical Constructs in Java

UNIT - II

2 Derived Syntactical
Constructs in Java
7. When we declare the constructor explicitly then we
2.1 Constructors and Method must declare the object of that class.

 Definition : The constructor is a specialized method Difference between Constructor and Method
for initializing objects.
Sr. Constructor Method
 Name of the constructor is same as that of its class No.
name. In other words, the name of the constructor and
1. The name of the The name of the method
class name is same.
constructor must be should not be the class
Class Test same as the class name.
{ Class Name name.

2. It does not return It can return and hence it


Test() Constructor
{ anything hence no has a return type. If method
//body of constructor return type. does not return anything
} then the return type is void.
}
3. The purpose of The method is defined to
 Whenever an object of its associated class is created,
constructor is to execute the core logic of
the constructor is invoked automatically.
initialize the data the class.
 The constructor is called constructor because it creates
members of the class.
values for data fields of class.
4. The constructor is The method must be called
Properties of Constructor invoked implicitly at explicitly using the object
1. Name of constructor must be the same as the name of the time of object name and dot operator.
the class for which it is being used. creation.
2. The constructor must be declared in the public mode.
2.2 Types of Constructors
3. The constructor gets invoked automatically when an
MSBTE : Winter 15, Summer 16, 18, Marks 4
object gets created.
Various types of constructors are –
4. The constructor should not have any return type. Even
1. Default constructor 2. Parameterized constructor
a void data type should not be written for the
Let us discuss them in detail –
constructor.
5. Constructor can make use of new or delete operators 1) Default Constructor
for allocating or releasing memory respectively.  The default constructor is a simple constructor in
6. Multiple constructors can be used by the same class. which no parameter is passed to the constructor
function.

TM
Technical Publications (2 --An
1) up thrust for knowledge
Java Programming 2-2 Derived Syntactical Constructs in Java

 This constructor is automatically called when the Program Explanation : In above program,
object of the class is created. 1) We have created parameterized constructor by passing
 Example Program the parameters id and Name. Note that these
class Test constructors will be called at the time of creation of
{ objects p1 and p2.
Test() <-- This is default constructor
{ 2) Then using these objects we can invoke the method
System.out.print("This message is from constructor"); display().
}
public static void main(String args[]) Board Questions
{ 1. What is constructor? Describe the use of
Test t=new Test(); parameterized constructor with suitable example.
} MSBTE : Winter 15, Marks 4
}
2. Define constructor. Explain parameterized
Output constructor with example.
MSBTE : Summer 16, Marks 4
This message is from constructor
3. Enlist types of constructor. Explain any two with
2) Parameterized Constructor example. MSBTE : Summer 18, Marks 4

Parameterized constructor is a constructor in which the 2.3 Nesting of Methods


parameters are passed to the constructor function.
 Any method belonging to a class can be invoked using
Example Program the object of that class but sometimes we can invoke
class Person that method by simply using the name of it. This is
{ called nesting of methods.
int id;
String city;  Following is a simple Java program which explains the
Person(int i,String c) idea of nesting of method -
{  Example : Java Program[NestingDemo.java]
id=i;
class NestingDemo
city=c;
{
}
void FirstMethod()
void display()
{
{
System.out.println("In the First method");
System.out.print("ID: "+id);
}
System.out.println(" City: "+city);
void SecondMethod()
}
{
public static void main(String args[])
FirstMethod();
{
System.out.println("\nNow, In the Second method");
Person p1=new Person(10,"Ankita");
}
Person p2=new Person(20,"Prajka");
}
p1.display();
class NestingTest
p2.display();
{
}
public static void main(String[] args)
}
{
Output NestingDemo obj=new NestingDemo();
ID: 10 City: Ankita obj.SecondMethod();
ID: 20 City: Prajka }
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 2-3 Derived Syntactical Constructs in Java

Output System.out.println("The values of a and b before function


D:\>javac NestingDemo.java call");
D:\>java NestingTest System.out.println("a= "+a);
System.out.println("b= "+b);
In the First method obj1.Fun(a,b);
System.out.println("The values of a and b after function
call");
Now, In the Second method
System.out.println("a= "+a);
System.out.println("b= "+b);
Program Explanation
In the above program,
}
1) We have created two methods namely FirstMethod }

and SecondMethod. Output


2) In the main function, we invoke the SecondMethod The values of a and b before function call
a= 10
using object of class NestingDemo.
b= 20
3) The FirstMethod can be invoked in the The values of a and b after function call
SecondMethod by simply using its name. There is no a= 10
b= 20
need to make use of the object to invoke the
FirstMethod from the SecondMethod. This is called Program Explanation
nesting of methods.
 The above Java program makes use of the parameter
2.4 Argument Passing passing by value. By this approach of parameter
 Argument or Parameter can be passed to the function passing we are passing the actual values of variables a
by two ways - and b.

1. Call by value 2. Call by reference  In the function Fun we are changing the values of a
and b by adding 5 to them. But these incremented
 In the call by value method the value of the actual
values will remain in the function definition body only.
argument is assigned to the formal parameter. If any
After returning from this function these values will not
change is made in the formal parameter in the
get preserved. Hence we get the same values of a and b
subroutine definition then that change does not reflect
before and after the function call.
the actual parameters.
 On the contrary the parameter passing by reference
 Following Java program shows the use of parameter
allows to change the values after the function call. But
passing by value -
use of variables as a parameter does not allow to pass
 Example : Java Program
the parameter by reference.
public class ParameterByVal
{  For passing the parameter by reference we pass the
void Fun(int a,int b) object of the class as a parameter.
{
 Creating a variable of class type means creating
a=a+5;
b=b+5; reference to the object. If any changes are made in the
} object made inside the method then those changes get
public static void main(String args[]) preserved and we can get the changed values after the
{
function call.
ParameterByVal obj1=new ParameterByVal();
int a,b;
a=10;b=20;

TM
Technical Publications - An up thrust for knowledge
Java Programming 2-4 Derived Syntactical Constructs in Java

2.5 The this Keyword Program Explanation


 The this keyword is used by a method to refer the In above program,
object which invoked that method. (1) We have created two objects for the class - obj1 and
 this keyword is used inside the method definition to obj2.
refer the current object. That means this is a (2) The value of a is assigned to be 10 and value of b as
reference to the object which is used to invoke it. 20 for the object obj1 using the keyword this.
 Following is a Java program in which the method uses Similarly the obj2 posses the values of a and b as 40
the keyword this and 50 respectively.
(3) Note that the keyword this is useful to refer the
 Example Program
import java.io.*;
current object.
import java.lang.*;

public class thisDemo


{
int a,b;
public void Sum(int a,int b)
{
this.a=a;
this.b=b;
} 2.6 Command Line Arguments
public void display() MSBTE : Summer 15, 17, Winter 17, Marks 4
{
 Definition : In Java, the command line argument is the
int c=a+b;
System.out.println("a= "+a); argument which is passed at the time of running the
System.out.println("b= "+b); Java program.
System.out.println("Sum= "+c);  The argument is passed to the main() method as
System.out.println();
parameter. Following program illustrates the use of
}
public static void main(String args[]) command line parameter.
{  Example Program
thisDemo obj1=new thisDemo(); class CommandLineDemo
thisDemo obj2=new thisDemo(); {
obj1.Sum(10,20); public static void main(String args[])
obj1.display(); {
obj2.Sum(40,50); for(int i=0;i<args.length;i++)
obj2.display(); System.out.println(args[i]);
} }
} }
Output Output Command line
a= 10 arguments
D:\>javac CommandLineDemo.java
b= 20
Sum= 30 D:\>java CommandLineDemo Hello My Friend
Hello
a= 40 My
b= 50 Friend
Sum= 90
Example 2.6.1 : Write a program to accept a number as
command line argument and print the number is even or odd.
MSBTE : Summer 15, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-5 Derived Syntactical Constructs in Java

Solution : Output
class CommandLineDemo D:\MSBTE_JAVA _Programs> javac
{ CommandLineDemo.java
public static void main(String args[]) D:\MSBTE_JAVA _Programs> java CommandLineDemo 25
{ The square root is: 5.0
int num=Integer.parseInt(args[0]);
if(num%2==0) 2.7 Varargs : Variable Length Arguments
System.out.print("The number is even");
 If we want to pass variable length arguments to the
else
System.out.print("The number is odd");
method then varargs is used.
}  Syntax : Following is the syntax of using Varargs -
} access_specifier static void method name(object
…arguments)
Output
{
D:\MSBTE_JAVA _Programs> javac
//Method body
CommandLineDemo.java
}
D:\MSBTE_JAVA _Programs> java CommandLineDemo 5
The number is odd  The ellipsis (…) is used while representing the
Example 2.6.2 : Write a program to accept two numbers as varargs.
command line arguments and print the addition of those  Thus with the help of three dots one can specify
numbers. MSBTE : Summer 17, Marks 4
variable length arguments for a particular method.
Solution :
class CommandLineDemo  Following simple Java program makes use of varargs.
{
public static void main(String args[]) Java Program [varargsDemo.java]
{ public class varargsDemo
int num1=Integer.parseInt(args[0]); {
int num2=Integer.parseInt(args[1]); public static void main(String[] args)
int result=num1+num2; {
System.out.print("The addition is: "+result); test("Archana","Supriya");
Method uses varargs
} test("Jayashri","Snehal","Rohini");
} }
public static void test(String...Student)
Output {
D:\MSBTE_JAVA _Programs> javac for(String name:Student)
CommandLineDemo.java
System.out.println("Welcome "+name);
D:\MSBTE_JAVA _Programs> java CommandLineDemo 5
}
10
}
The addition is: 15
Output
Example 2.6.3 : Write a program to accept number from
Welcome Archana
command line and print square root of the number.
MSBTE : Winter 17, Marks 4 Welcome Supriya
Solution : Welcome Jayashri
Welcome Snehal
class CommandLineDemo
Welcome Rohini
{
public static void main(String args[])
Program Explanation :
{
int num=Integer.parseInt(args[0]); In above program,
double result=Math.sqrt(num); 1) We have used two methods(named test) - To the first
System.out.print("The square root is: "+result);
method two arguments are passed and to the second
}
} method three arguments are passed.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-6 Derived Syntactical Constructs in Java

2) While defining the method test we have used three 2.9 The Object Class
dots and a collection which is named as Student. That Winter 16, 17, Marks 6
means in the collection(sort of array) Student , all the  In Java there is a special class named Object.
declared strings can be stored.  Object is a superclass of all other classes by default.
3) Hence we get the output as names of all the students  The object can be obtained using getObject() method.
which are passed to the method as variable length
For example –
arguments. Object obj=getObject();

2.8 Garbage Collection and Finalize Method 2.10 Visibility Control


MSBTE : Winter 16, Summer 17, Marks 6
MSBTE : Winter 16, 17, Marks 6
 Garbage collection is a method of automatic memory  Visibility control or Access control is a mechanism by
management.
which precisely controlled access to various members
 It works as follows -
of class is possible.
1. When an application needs some free space to
 The access control mechanism makes use of access
allocate the nodes and if there is no free space
specifiers for controlling the access to data members of
available to allocate the memory for these objects
class.
then a system routine called garbage collector is
called.  Java has three commonly used access specifies –
2. This routine then searches the system for the free public, private and protected. Java also defines
space. The free space is then made available for default access level.
reuse.  The protected access specifier is used only during
 Java used finalize() method for garbage collection. inheritance.
 To add finalizer to a class simply define the finalize  Public allows classes, methods and data fields
method. The syntax to finalize() the code is - accessible from any class.
void finalize()  Private allows classes, methods and data fields
{
accessible only from within own class.
finalization code
}  If public or private access is not mentioned then that
 Even though we allocate the memory and then forget member uses default access which is just similar to
to deallocate it then the objects that are no longer is public.
used get freed. Inside the finalize() method you will class AccessControl
specify those actions that must be performed before an {
int a;
object is destroyed. The garbage collector runs
public int b;
periodically checking for objects that are no longer
private int c;
referenced by any running state or indirectly though
other referenced objects. void fun(int val)
 Note that finalize() method is called just before the {
garbage collection. c=val;
}
Board Questions void display()
{
1. How garbage collection is done in Java ? Which
System.out.println("c = "+c);
methods are used for it ? MSBTE : Winter 16, Marks 4
}
2. What is garbage collection in Java ? Explain }
finalize method in Java. MSBTE : Summer 17, Marks 6
class test
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-7 Derived Syntactical Constructs in Java

public static void main(String args[]) array_name=new data_type[size];


{ where array_name represent name of the array, new is a
AccessControl obj=new AccessControl();
keyword used to allocate the memory for arrays,
obj.a=100;//Valid
obj.b=200;//Valid
data_type specifies the data type of array elements and
obj.c=300;//Error: Private access size represent the size of an array. For example :
obj.fun(300);//Valid a=new int[10];
obj.display();//Valid After this declaration the array a will be created as
}
follows
}
Array a[10]
Program Explanation :
 We have defined two classes AccessControl and test. 0 0 0 0 0 0 0 0 0 0
 Inside Access Control class we have declared three That means after the above mentioned declaration of
data members – a, b and c. The variable a is declared array, all the elements of array will get initialized to zero.
as default, b is declared as public and c is declared as Note that, always, while declaring the array in Java, we
private. make use of the keyword new, and thus we actually make
 Inside class test we have created an instance (i.e. use of dynamic memory allocation.
object) of class AccessControl. Using this object we 2.11.1 Types of Arrays with their Creation
assign values directly to variables a, b and c. Note that There are two types of arrays - One dimensional array
assigning value to variable c will cause error because c and two dimensional array.
has private access specifier.
One Dimensional Arrays
 Note that only way to access the private variable is
through method. The method fun can access variable The one dimensional arrays. The one dimensional array
c inside it. Note that this method should be present can be represented as -
within the same class. Array a[10]
 The protected access specifier allows accessing the
10 20 30 40 50 60 70 80 90 1000
members of all the classes and subclasses in the same
package. Example Program:
/*
Board Questions
This is a Java program which makes use of arrays
1. What are the access control parameters ? Explain */
the concept with suitable example. class SampleArray
MSBTE : Winter 16, Marks 6 {
2. Describe access control specifiers with example. public static void main(String args[])
MSBTE : Winter 17, Marks 4 {
int a[]=new int[10];
2.11 Arrays System.out.println("\tStoring the numbers in array");
MSBTE : Summer 15, Marks 6 a[0]=1;
 Array is a collection of similar type of elements. Thus a[1]=2;
grouping of similar kind of elements is possible using a[2]=3;
a[3]=4;
arrays. Typically arrays are written along with the size
a[4]=5;
of them. The syntax of declaring array is -
a[5]=6;
data_type array_name[ ]; a[6]=7;
 To allocate the memory the syntax is a[7]=8;
a[8]=9;
TM
Technical Publications - An up thrust for knowledge
Java Programming 2-8 Derived Syntactical Constructs in Java

a[9]=10; a[i][j]=k+10;
System.out.println("The element at a[5] is: "+a[5]); k=k+10;
} }
} }
When you run this program you will get a[5] to be 6. System.out.println("You have stored...");
Another way of initialization of array is for(int i=0;i<3;i++)
int a[ ]= {1,2,3,4,5,6,7,8,9,10}; {
for(int j=0;j<3;j++)
Two Dimensional Arrays {
The two dimensional arrays are the arrays in which System.out.print(" "+a[i][j]);
}
elements are stored in rows as well as in columns. For
System.out.println();
example
}
}
}

Output
Storing the numbers in array
You have stored...
10 20 30
The two array can be declared and initialized as follows 40 50 60
70 80 90
Syntax
data_type array_name=new data_type[size];
The typical application of two dimensional arrays is
performing matrix operations.
For example
Example 2.11.1 : Define a class ‘employee’ with data
members empid, name and salary.
int a=new int[10]; Accept data for five objects using array of objects and print it.
MSBTE : Summer 15, Marks 6

Let us straight away write a java program that is using Solution :


import java.util.*;
two dimensional arrays - class Employee
{
Java Program [Sample2DArray.java]
int empid;
/*
String name;
This is a Java program which makes use of 2D arrays double salary;
*/ void accept_data()
class Sample2DArray {
{ Scanner in=new Scanner(System.in);
public static void main(String args[]) System.out.print("Enter EmpID: ");
{ empid=in.nextInt();
System.out.print("Enter Name: ");
int a[][]=new int[3][3]; name=in.next();
int k=0; System.out.print("Enter Salary: ");
salary=in.nextDouble();
System.out.println("\tStoring the numbers in array");
}
for(int i=0;i<3;i++)
void display()
{
{
for(int j=0;j<3;j++)
System.out.println(empid+"\t"+name+"\t"+salary);
{ }

TM
Technical Publications - An up thrust for knowledge
Java Programming 2-9 Derived Syntactical Constructs in Java

} 2.12.1 String Classes


class EmpDataBase
 The syntax of String class is
{
String string_variable;
public static void main(String args[])
{  Example Program
Employee E[]=new Employee[5]; class StringDemo
int i; {
System.out.println("Enter Employee Data"); public static void main(String args[])
for(i=0;i<5;i++) {
{ String s="Hello, How are You?";
E[i] = new Employee(); System.out.println(s);
E[i].accept_data(); }
} }
System.out.println("Employee Data is as follows...");
Output
for(i=0;i<5;i++)
Hello, How are You?
E[i].display();
} Operations on Strings using String Class
}
Following are some commonly defined methods by a
Output
Enter Employee Data
string class -
Enter EmpID: 101
Method Description
Enter Name: AAA
Enter Salary: 1000 s1.CharAt(position) Returns the character present at the
Enter EmpID: 102
index position.
Enter Name: BBB
Enter Salary: 2000 s1.compareTo(s2) If s1<s2 then it returns positive, if
Enter EmpID: 103
Enter Name: CCC s1>s2 then it returns negative and
Enter Salary: 3000 if s1=s2 then it returns zero.
Enter EmpID: 104
Enter Name: DDD s1.concat(s2) It returns the concatenated string of
Enter Salary: 4000 s1 and s2.
Enter EmpID: 105
Enter Name: EEE s1.equals(s2) If s1 and s2 are both equal then it
Enter Salary: 5000 returns true.
Employee Data is as follows...
101 AAA 1000.0 s1.equalsIgnoreCase(s2) By ignoring case, if s1 and s2 are
102 BBB 2000.0
equal then it returns true.
103 CCC 3000.0
104 DDD 4000.0 s1.indexof('c') It returns the first occurrence of
105 EEE 5000.0
character 'c' in the string s1.
2.12 Strings
s1.indexof('c',n) It returns the position of 'c' that
MSBTE : Winter 15, 16, 17, Summer 15, 16, 17, 18, Marks 6
occur at after nth position in string
Definition : String is a collection of characters.
s1.
In Java, the string can be defined using two commonly
used methods – s1.length() It gives the length of string s1.

1) Using String Class String.valueof(var) Converts the value of the variable


2) Using StringBufferClass passed to it into String type.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 10 Derived Syntactical Constructs in Java

1) The length() function {


class Str_lengthDemo String s1="Java";
{ String s2="Java";
public static void main(String[] args) String s3="Programming";
{ String s4="Software";
String S=new String(“PROGRAM”); System.out.println(s1.compareTo(s2));//it will return 0
System.out.println("The string S is "+S); System.out.println(s1.compareTo(s3));//it will return –ve

System.out.println("The length of string is "+S.length()); number as J<P

} System.out.println(s4.compareTo(s3)); //it will return


+ve number as S>P
}
}
Output
}
The string S is PROGRAM
The length of string is 7 Output
0
2) The charAt() -6
3
There is a method called charAt(index) with the help of
which we can extract the character denoted by some index 4) The equal operation

in the array. Sometimes we need to know whether two strings are

Example Program
equal or not. We use method equals() for that purpose.
class charAtProg This method is of Boolean type. That is, if two strings are
{ equal then it returns true otherwise it returns false.
public static void main(String args[]) The syntax is –
{ boolean equals(String Str);
String fruit=new String("mango");
Let us see one illustrative program –
char ch;
ch=fruit.charAt(2); //It will output character n Example program
System.out.println(ch); class StringCompareDemo
} {
} public static void main(String[] args)
{
3) The compareTo()
String str1=new String(“INDIA”);
The java string compareTo() method compares the given String str2=new String(“india”);
string with current string lexicographically. It returns if(str1.equals(str2)==true)
System.out.println(“\n The two strings are equal”);
positive number, negative number or 0.
else
If s1>s2 it returns positive number
System.out.println(“\n The two strings are not equal”);
If s1<s2 it returns negative number }
If s1==s2 It returns 0 }

Example Program
class cmpareTo
{
public static void main(String args[])

TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 11 Derived Syntactical Constructs in Java

public static void main(String args[])


Output
D:\>javac StringCompareDemo.java {
String s1="Java";
D:\> java StringCompareDemo String s2=" Programming";
The two strings are not equal s1.concat(s2);
System.out.println("The resultant string is: "+s1);
The above program will generate the message “The two s1=s1.concat(s2);
strings are not equal” if str1 and str2 are not equal but if System.out.println("The resultant string is: "+s1);
}
we write same str1 and str2 then naturally the output will
}
be “The two strings are equal”. This string comparison is
Output
case sensitive. The resultant string is: Java
The resultant string is: Java Programming
5) Searching for the substring

We can look for the desired substring from the given 5) The equalsIgnoreCase()

string using a method substring(). The syntax of method It returns true if characters of both strings are equal
substring() is as follows – ignoring case otherwise it returns false.
String substring(int start_index,int end_index)
Example Program
Example program class Test
class SubstringDemo {
{ public static void main(String args[])
public static void main(String[] args) {
{ String s1="java";
String str1=new String(“I love my country very much”); String s2="JAVA";
System.out.println(“\n One substring from the given String s3="PHP";
sentence is:”+str1.substring(2,6)); System.out.println(s1.equalsIgnoreCase(s2));//returns
System.out.println(“\n And another substring //true
is:”+str1.substring(18)); System.out.println(s2.equalsIgnoreCase(s3));//returns
} //false
} }
}

Output 2.12.2 String Buffer


D:\>javac SubstringDemo.java
 The StringBuffer is a class which is alternative to the
D:\>java SubstringDemo String class. But StringBuffer class is more flexible
One substring from the given sentence is:love to use than the String class.
And another substring is:very much  That means, using StringBuffer we can insert some
6) Concatenation Operation components to the existing string or modify the
existing string but in case of String class once the
The string concatenation means combining one string at
string is defined then it remains fixed.
the end of the other string.
 Following are some simple methods used for
Example Program
StringBuffer –
class concateProg
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 12 Derived Syntactical Constructs in Java

Name of method Description

append(String str) Appends the string to the buffer

capacity() It returns the capacity of the string buffer

charAt(int index) It returns a specific character from the sequence which is specified by the index.

delete(int start,int end) It deletes the characters from the string specified by the starting and ending index.

insert(int offset,char ch) It inserts the character at the position specified by the offset.

length() It returns the length of the string buffer.

setCharAt(int index,char ch) The character specified by the index from the stringbuffer is set to ch.

setLength(int new_len) It sets the length of the string buffer.

toString() It converts the string representing data in this string buffer.

replace(int start,int end,String str) It replaces the characters specified by the new string

reverse() The character sequence is reversed.

Difference between String and StringBuffer

Sr. No. String StringBuffer

1. The length of string object is fixed. The length of stringBuffer can be increased.

2. The String object is immutable, that means we can not The stringBuffer class is immutable.
modify the string once created.

3. It is slower in performance. It is faster in performance.

4. It consumes more memory. It consumes less memory.

Example 2.12.1 : Write a JavaProgram illustrating the difference between the capacity and length function of StringBuffer
Solution :
public class StringBuffDemo{
public static void main(String args[]) creating string buffer in str
{
StringBuffer str=new StringBuffer("Java");
Finding length of str
System.out.println("The String Buffer is "+str);
System.out.println("The length is "+str.length());
System.out.println("The capacity is "+str.capacity());
Finding capacity of str
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 13 Derived Syntactical Constructs in Java

Example 2.12.3 : Write a simple Java Program to check the


Output
palindrome of the given string
The String Buffer is Java
Solution :
The length is 4
The capacity is 20 public class StringBuffDemo{
public static void main(String args[])
Program Explanation {
Using the StringBuffer/StringBuilder class, we can create String str1=new String("Java");
StringBuffer str2=new StringBuffer(str1);
a buffer of characters. The length function returns the
str2.reverse();
number of characters in the string and the capacity System.out.println("Initially the String is: "+str1);
function returns the number of characters in the string +16 System.out.println("Reversed String is: "+str2);
additional characters. if(str1.equals(str2.toString())) //checks if str1=str2
System.out.println("This string is palindrome ");
Example 2.12.2 : Perform following string / string buffer
else
operations, write java program.
System.out.println("This string is not palindrome ");
i) Accept a password from user
ii) Check if password is correct then display “Good”, else
display “Wrong” }
iii) Display the password in reverse order. }
iv) Append password with “welcome”.
MSBTE : Winter 16, Marks 4 Output
Solution :
Initially the String is: Java
import java.util.*; Reversed String is: avaJ
class PasswordDemo This string is not palindrome
{
public static void main(String[] args) Board Questions
{
1. Describe the following string class methods with
String str="mypassword";
examples :
Scanner in=new Scanner(System.in);
System.out.println("Enter Password: "); i) length( ) ii) charAt( ) iii) CompareTo( )
String pwd=in.nextLine(); MSBTE : Winter 15, Marks 6
if(str.compareTo(pwd)==0) 2. Compare string class and StringBuffer class with
System.out.println("Good"); any four points.
else MSBTE : Summer 15, Marks 4
System.out.println("Wrong Password"); 3. Explain following methods of string class with
StringBuffer new_str1 = new StringBuffer(pwd); their syntax and suitable example.
new_str1= new_str1.reverse();
i) substring () ii) replace ()
System.out.println("The reversed String is: "+new_str1);
MSBTE : Summer 16, Marks 6, Summer 17, Marks 4
StringBuffer new_str2=new StringBuffer(pwd);
new_str2=new_str2.append("Welcome");
System.out.println(new_str2); 3. Describe following string class method with
} example :
} i) compareTo( ) ii) equalsIgnoreCase( )
MSBTE : Winter 17, Marks 4
Output
Enter Password: 4. Write a java program to implement following
mypassword functions of string :
mypassword 1) Calculate length of string
Good
2) Compare between strings
The reversed String is: drowssapym
mypasswordWelcome 3) Concatenating strings
MSBTE : Summer 18, Marks 6

TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 14 Derived Syntactical Constructs in Java

2.13 Vector
void insertElementAt(object For inserting the element in
MSBTE : Winter 15, 16, Summer 15, 16, 17, Marks 8
obj,int pos) the vector specified by its
 Vector is a class in Java that implement the dynamic
position.
array. This class stores any number of objects of any
data type. boolean removeElement This method removes the
 This class is defined by java.util package. (object ele) specified element.
 In vector one can store the elements of any data type.
That means in a single vector you store integer, string, void removeAllElements() This method is for removing
double or any other data type elements altogether. all the elements from the
 Vector can be created like this - vector
vector myvector=new vector(); //declaring vector
void removeElementAt(int The element specified by its
without size
pos) position gets deleted from the
vector yourvector= new vector(5);//declaring vector
with size. vector.

int capacity() It returns the capacity of the


Difference between Array and Vector
vector.
Arrays Vectors
int size() It returns the total number of
Array contains all the Vector contains the elements that
elements present in the vector.
elements of similar data may be of varying data type.
type. boolean isEmpty() It returns true if the vector is
The size of array is fixed. The size of array is varying. We empty.
can change the size of the vector
object firstElement() Returns the first element of
whenever is required.
the vector
We can store the simple We can not store the simple
elements directly in the object in the database. int indexOf(object ele) It returns the index of
arrays. corresponding element in the

We can directly add the We can not directly add the vector.
simple data type element in simple data type element in the void setSize(int size) This method is for setting the
the array. vector we need to add an object. size of the vector.

Advantages of vectors over array Example 2.13.1 : Write a program to create a vector with
1. Vectors contain elements of varying data types. seven elements as (10, 30, 50, 20, 40,10, 20). Remove element
at 3rd and 4th position. Insert new element at 3rd position.
2. The size of vector can be changed whenever required. Display the original and current size of the vector.
3. It can store simple objects. MSBTE : Winter 15, Marks 8

Following are some most commonly used methods of OR Write a program to implement a vector class and its
vector class - method for adding and removing elements. After remove
display remaining list.
MSBTE : Summer 16, Marks 8
Method Description
Solution:
void addElement(object ) For adding some element in
import java.io.*;
the vector this method is used.
import java.util.*;
Object elementAt(int index) It returns the element present class VectorProg
at specified location(index) in {
public static void main(String[] args)throws IOException
vector.
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 15 Derived Syntactical Constructs in Java

Vector obj=new Vector(); System.out.println("\nThe elements in the vector are


obj.add(10); "+obj);
obj.add(30); System.out.println("\n Inserting 2 float values...");
obj.add(50); fval=11;
obj.add(20); obj.addElement(fval);
obj.add(40); fval=22;
obj.add(10); obj.addElement(fval);
obj.add(20); System.out.println("\n Inserting 2 string values...");
System.out.println("\nThe elements in the vector are s1="AAA";
"+obj); obj.addElement(s1);
System.out.println("\n Removing 3rd Element"); s2="BBB";
obj.remove(2);//3rd element obj.addElement(s2);
System.out.println("\n Removing 4th Element");
obj.remove(3); System.out.println("\n The size of vector is "+obj.size());
System.out.println("\nThe elements in the vector are System.out.println("\n The elements in the vector are
"+obj); "+obj);
System.out.println("\n Inserting element 100 at 3rd System.out.println("Removing first element");
Position"); obj.remove(0);
obj.insertElementAt(100,2);//inserting 100 at 3rd position System.out.println("\nNow The elements in the vector
System.out.println("\nThe elements in the vector are are "+obj);
"+obj); }
} }
}
Output
Output Inserting 2 integer values...
The elements in the vector are [10, 30, 50, 20, 40, 10, 20]
Removing 3rd Element The elements in the vector are [10, 20]
Removing 4th Element
The elements in the vector are [10, 30, 40, 10, 20] Inserting 2 float values...
Inserting element 100 at 3rd Position
The elements in the vector are [10, 30, 100, 40, 10, 20] Inserting 2 string values...

Example 2.13.2 : Write a program to add 2 integer, 2 string


and 2 float objects to a vector. The size of vector is 6
Remove element specified by user and display the list.
MSBTE : Summer 17, Marks 8 The elements in the vector are [10, 20, 11.0, 22.0, AAA,
Solution : BBB]
Removing first element
import java.io.*;
import java.util.*;
Now The elements in the vector are [20, 11.0, 22.0, AAA,
class VectorProg BBB]
{
public static void main(String[] args)throws IOException Board Questions
{
1. Differentiate vector and array with any 4 points.
Vector obj=new Vector(3);
MSBTE : Summer 15, Winter 16 Marks 4
int ival;
float fval; 2. What is the difference between array and vector ?
String s1,s2; Explain elementAt( ) and addElement( ) method.
char ans='y'; MSBTE : Winter 15, Marks 4
System.out.println("\n Inserting 2 integer values... "); 3. Explain following methods of vector class :
ival=10; i) elementAt ( ) ii) addElement ( )
obj.addElement(ival);
iii) removeElement ( )
ival=20;
MSBTE : Summer 15, Marks 6
obj.addElement(ival);
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 16 Derived Syntactical Constructs in Java

4. What is : i) Add Element ( ) and ii) Element At  Suppose an object for holding an integer value is
( ) command in vector created then we can retrieve the integer value from it
MSBTE : Winter 16, Marks 4
using typevalue() method. For instance the object obj
2.14 Wrapper Classes contains an integer value then we can obtain the
MSBTE : Summer 15, Winter 17, Marks 8 integer value from obj. It is as follows -
 Wrapper classes are those classes that allow primitive int num=obj.intValue();

data types to be accessed as objects. Similarly we can use floatValue(), doubleValue() and
 The wrapper class is one kind of wrapper around a longValue().
primitive data type. The wrapper classes represent the  Similarly in order to convert the numerical value to
primitive data types in its instance of the class. string the toString() method can be used. For instance
 Following table shows various primitive data types and str=Integer.toString(int_val)

the corresponding wrapper classes - The varibale int_val can be converted to string str.
 For converting the string to numerical value the
Primitive data type Wrapper class
parseInt or parseLong methods can be used.
boolean Boolean
Points to remember about wrapper classes
byte Byte
1. The wrapper classes do not contain the constructors.
char Character 2. The methods of the wrapper classes are static.
3. After assigning the values to the wrapper class we
double Double
cannot change them.
float Float
Example : Java Program
int Integer import java.io.*;
import java.lang.*;
long Long class WrapperDemo
{
short Short public static void main(String[] args)
{
void Void System.out.println("Creating an object for value 10");
Integer i=new Integer(10);
 Methods to handle wrapper classes are enlisted in the
System.out.println("Obtaining the value back from the
following table - object: "+i.intValue());
String str="100";
Method used Description
System.out.println("The string is: "+str);
System.out.println("Obtaining the numeric value from the
Integer val=new An object is created for the integer
string: "+ Integer.parseInt(str));
Integer(int_var) variable int_var. }
}
Float val=new An object is created for the Float
Float(f_var) variable f_var.
Output
Double val=new An object is created for the double Creating an object for value 10
Obtaining the value back from the object: 10
Double(d_var) variable d_var.
The string is: 100
Obtaining the numeric value from the string: 100
Long val=new An object is created for the Long
Long(Long_var) variable Long_var.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 17 Derived Syntactical Constructs in Java

Example 2.14.1 Define wrapper class. Give the following 2) Wrapper classes are used to convert numeric value to
wrapper class methods with syntax and use : string using wrapper class.
1) To convert integer number to string.
2) To convert numeric string to integer number. 3) Wrapper class is a medium to store primitive data type
3) To convert object numbers to primitive numbers sing type in an object.
value ( ) method. 4) Using the typeValue() method we can retrieve value
MSBTE : Summer 15, Marks 8
of the object as its primitive data type.
Solution : Wrapper class – Refer section 2.14.
class WrapperDemo1 Board Question
{ 1. What is the use of wrapper classes in Java ?
public static void main(String args[]) Explain float wrapper with its methods.
{ MSBTE : Winter 17, Marks 4
System.out.println("\tInteger to String Conversion");
int i=100; 2.15 Enumerated Types
String str=Integer.toString(i);
 The enumerated data types can be denoted by the
System.out.println("int Value: "+i);
System.out.println("Equivalent String: "+str);
keyword enum.
System.out.println("\tString to Integer Conversion");  The enum helps to define the user defined data type.
str="500";
 The value can also be assigned to the elements in the
int j=Integer.parseInt(str);
System.out.println("String: "+str);
enum data type.
System.out.println("Equivalent int: "+j); Java Program[EnumDemo.java]
System.out.println("\tobject to Primitive number using public class EnumDemo
typeValue Conversion"); {
Integer a=new Integer(1000);//creating object for float enum Fruit
value {
int val=a.intValue(); Mango,
System.out.println("Integer: "+a); Guava,
Orange,
System.out.println("Equivalent int value: "+val);
Apple
Float b=new Float(2000);//creating object for float value
}
float f=b.floatValue(); public static void main(String[] args)
System.out.println("Float: "+b); {
System.out.println("Equivalent float value: "+f); for(Fruit f:Fruit.values())
} {
} Test(f);
}
Output }
Integer to String Conversion private static void Test(Fruit f)
int Value: 100 {
Equivalent String: 100 if(f.equals(Fruit.Mango))
String to Integer Conversion System.out.println("Mango is yellow");
if(f.equals(Fruit.Orange))
String: 500
System.out.println("The color and name of orange is the
Equivalent int: 500 same");
object to Primitive number using typeValue }
Conversion }
Integer: 1000
Output
Equivalent int value: 1000 Mango is yellow
Float: 2000.0 The color and name of orange is the same
Equivalent float value: 2000.0
Uses of Wrapper Class 
1) Wrapper classes are used to convert numeric strings
into numeric values.
TM
Technical Publications - An up thrust for knowledge
Java Programming 2 - 18 Derived Syntactical Constructs in Java

Notes

TM
Technical Publications - An up thrust for knowledge
Java Programming 3-1 Inheritance, Interface and Package

UNIT - II

3 Inheritance, Interface and Package

 Inheritance is represented diagrammatically as follows

Part I : Inheritance

3.1 Inheritance
 Definition: Inheritance is a mechanism in Java by
which derived class can borrow the properties of base
class and at the same time the derived class may have
some additional properties. Fig. 3.1.1
 The inheritance can be achieved by incorporating the
3.2 Types of Inheritance
definition of one class into another using the keyword
MSBTE : Summer 15, 17, 18, Winter 16, 17, Marks 8
extends.
1. Single inheritance :
Inheritance Features:
 In single inheritance there is one parent per derived
1) It helps in reduced code.
class. This is the most common form of inheritance.
2) It makes use of reusability of code.
3) It enhances readability of code.
4) Execution of code is efficient.

Concept of Base Class and Derived Class


 The inheritance is a mechanism in which the child
class is derived from a parent class.
 This derivation is using the keyword extends. Fig. 3.2.1 Single inheritance

 The parent class is called base class and child class is 2. Multiple inheritance :
called derived class. In multiple inheritance the derived class is derived from
 For example more than one base class.
Class A  This is Base class
{

}
Class B extends A  This is Derived class
{
… // uses properties of A
}
Fig. 3.2.2 Multiple inheritance

TM
Technical Publications (3 --An
1) up thrust for knowledge
Java Programming 3-2 Inheritance, Interface and Package

Java does not implement multiple inheritance directly {


a=i;
but it makes use of the concept called interfaces to
}
implement the multiple inheritance. void show_a()
{
3. Multilevel inheritance :
System.out.println("The value of a= "+a);
When a derived class is derived from a base class which }
itself is a derived class then that type of inheritance is }
class B extends A //extending the base class A
called multilevel inheritance.
{
For example - If class A is a base class and class B is int b;
another class which is derived from A, similarly there is void set_b(int i)
another class C being derived from class B then such a {
b=i;
derivation leads to multilevel inheritance.
}
void show_b()
{
System.out.println("The value of b= "+b);
}
void mul()
{
int c;
c=a*b;
System.out.println(" The value of c= "+c);
}
}
Fig. 3.2.3 Multilevel inheritance class InheritDemo1
{
4. Hybrid inheritance :
public static void main(String args[])
When two or more types of inheritances are combined {
together then it forms the hybrid inheritance. The A obj_A=new A();
B obj_B=new B(); Note that object of class
following Fig. 3.2.4 represents the typical scenario of B is accessing method of
obj_B.set_a(10);
hybrid inheritance. class A
obj_B.set_b(20);
obj_B.show_a();
obj_B.show_b();
obj_B.mul();
}
}

Output
The value of a= 10
The value of b= 20
Fig. 3.2.4 Hybrid inheritance The value of c= 200

Example 3.2.1 : Implement single level inheritance. Explain


Program Explanation
Solution :
In above program, we have created two classes : class A
class A
{
and B. In class A we have declared one integer a and in
int a; class B we have declared an integer b. There are two
void set_a(int i) methods defined in class A namely: set_a and show_a.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-3 Inheritance, Interface and Package

Similarly, in class B there are two methods defined name=nm;


}
namely: set_b and show_b. As the name suggests these
void display_personInfo()
methods are for setting the values and for showing the {
contents. System.out.println("Name: "+name);
In the class InheriDemo1, in the main function we have System.out.println("age: "+age);
}
created two objects for class A and class B. The program
}
allows us to access the variable a (belonging to class A) class Employee extends Person //extending the base class
and the variable b (belonging to class B) using the object //Person
for class B. Thus it is said that class B has inherited value {
String emp_designation;
of variable a .
float emp_salary;
The class A is called Superclass and the class B is called void get_employeeInfo(String designation,float salary)
Subclass. A Superclass is also called as parent class or {
emp_designation=designation;
base class. Similarly, the Subclass is also called as child
emp_salary=salary;
class or derived class.
}
void display_empInfo()
{
System.out.println("Employee Designation:
"+emp_designation);
System.out.println("Employee Salary: "+emp_salary);
}
}
class InheritDemo
{
public static void main(String args[])
{
Employee e=new Employee();
e.get_personInfo(25,"Ankita");
e.display_personInfo();
Fig. 3.2.5 Single inheritance e.get_employeeInfo("Manager",10000);
e.display_empInfo();
Example 3.2.2 : Write a program to implement following }
inheritance :
}

Output
Name: Ankita
age: 27
Employee Designation: Manager
Employee Salary: 10000.0

MSBTE : Summer 15, Marks 4 Example 3.2.3 : Create a class ‘Rectangle’ that contains
Solution : ‘length’ and ‘width’ as data members. From this class derive
class box which has additional data member ‘depth’. Class
class Person ‘Rectangle’ consists of a constructor and an area ( ) function.
{ The derived ‘Box’ class have a constructor and override
String name; function named area ( ) which returns surface area of ‘Box’ and
int age; a volume ( ) function. Write a java program calling all the
member function.
void get_personInfo(int ag,String nm)
MSBTE : Winter 16, Marks 6
{
age=ag;
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-4 Inheritance, Interface and Package

Solution : The area of Box is: 2200.0


The volume of Box is: 6000.0
class Rectangle {
double length; Example 3.2.4 : Write a java program to implement multilevel
double width; inheritance with 4 levels of hierarchy.
MSBTE : Summer 18, Marks 8
Rectangle(double l,double w)//constructor
Solution :
{
this.length=l; class Vehicle { //level1
this.width=w; public Vehicle()
} {
double area() System.out.println("Class Vehicle");
{ }
double result; public void objectType()
result=length*width; {
return result; System.out.println("Object Type: Vehicle");
} }
} }
class Box extends Rectangle
{ class Car extends Vehicle { //level 2
double depth; public Car()
Box(double l,double w,double d) {
{ System.out.println("Class Car");
super(l,w);//passing len and width }
//from derived class to base class public void vehicleType()
this.depth=d; {
} System.out.println("Vehicle Type: Car");
double area() }
{ }
double result; class Honda extends Car{ //level 3
result= public Honda()
2*((length*width)+(length*depth)+(width*depth)); {
return result; System.out.println("Class Honda");
} }
double volume() public void brand()
{ {
double v=length*width*depth; System.out.println("Brand: Honda");
return v; }
} public void speed()
} {
class MainClass System.out.println("Max: 90Kmph");
{ }
public static void main(String args[]) }
{ public class HondaCity extends Honda { //level 4
Box b=new Box(10,20,30);
Rectangle r=new Rectangle(11,22); public HondaCity()
System.out.println("The area of rectangle is: "+r.area()); {
System.out.println("The area of Box is: "+b.area()); System.out.println("Class HondaCity");
System.out.println("The volume of Box is: "+b.volume()); }
} public void speed()
} {
System.out.println("Max Speed: 100Kmph");
Output
}
The area of rectangle is: 242.0
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-5 Inheritance, Interface and Package

public static void main(String args[]) Board Questions


{
1. What is single level inheritance ? Explain with
HondaCity obj=new HondaCity();
suitable example. MSBTE : Summer 17, Marks 6
obj.objectType();
obj.vehicleType(); 2. Explain inheritance and polymorphism features of
obj.brand(); Java. MSBTE : Winter 17, Marks 4
obj.speed(); 3. Write a java program to implement visibility
} controls such as public, private, protected access
} modes. Assume suitable data, if any.
MSBTE : Summer 18, Marks 6
Output
Class Vehicle
3.3 Method Overloading
Class Car
MSBTE : Winter 15, Marks 4
Class Honda
Class HondaCity Definition : Overloading is a mechanism in which we can
Object Type: Vehicle use many methods having the same function name but can
Vehicle Type: Car pass different number of parameters or different types of
Brand: Honda
Max Speed: 100Kmph
parameter.
For example :
Example 3.2.5 : Write a Java program to implement visibility
controls such as public, private, protected access modes. int sum(int a,int b);
Assume suitable data if any. double sum(double a,double b);
Solution: int sum(int a,int b,int c);
class A That means, by overloading mechanism, we can handle
{
different number of parameters or different types of
private int a;
protected void msg() parameter by having the same method name.
{ Following Java program explains the concept
System.out.println("Hello"); overloading -
a=10;//access to private member
} Example : Java Program
public void display() public class OverloadingDemo {
{ public static void main(String args[]) {
System.out.println("a = "+a); System.out.println("Sum of two integers");
} Sum(10,20); <-------------- line A
} System.out.println("Sum of two double numbers");
class B extends A //Class B is a child of Class A Sum(10.5,20.4); <-------------- line B
{ System.out.println("Sum of three integers");
public static void main(String args[]) Sum(10,20,30); <-------------- line C
{ }
B obj = new B(); public static void Sum(int num1,int num2)
obj.msg(); //access to protected member {
obj.display(); //access to public member int ans;
} ans=num1+num2;
} System.out.println(ans);
Output }
D:\> javac B.java public static void Sum(double num1,double num2)
D:\> java B {
Hello double ans;
a = 10 ans=num1+num2;
System.out.println(ans);
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-6 Inheritance, Interface and Package

public static void Sum(int num1,int num2,int num3) 3.4 Constructor Overloading
{ MSBTE : Winter 17, Marks 8
int ans;
 Constructor overloading in Java allows to have more
ans=num1+num2+num3;
System.out.println(ans);
than one constructor inside one Class.
}  Multiple constructor with different signatures is called
} as overloaded constructor.
Output  Following is a simple Java program that illustrates the
Sum of two integers concept of constructor overloading.
30
 Example Program
Sum of two double numbers
public class Rectangle2
30.9
{
Sum of three integers
int height,width;
60
double ht,wd;
Rectangle2(int h,int w)//constructor with two integer
Program Explanation
//values
In above program, we have used three different methods {
possessing the same name. Note that, height=h;
width=w;
on line A }
We have invoked a method to which two integer Rectangle2(double h,double w)//constructor with two
//double values
parameters are passed. Then compiler automatically
{
selects the definition public static void Sum(double ht=h;
num1,double num2) to fulfil the call. Hence we get the wd=w;
output as 30 which is actually the addition of 10 and 20. }
Rectangle2(int val)//constructor with single integer value
on line B {
height=val;
We have invoked a method to which two double
}
parameters are passed. Then compiler automatically void area1()
selects the definition public static void Sum(double {
num1,double num2) to fulfill the call. Hence we get the System.out.println("Now, The function is called...");
int result=height*width;
output as 30.9 which is actually the addition of 10.5 and
System.out.println("The area is "+result);
20.4. }
void area2()
on line C
{
We have invoked a method to which the three integer System.out.println("Now, The function is called...");
parameters are passed. Then compiler automatically double result=ht*wd;
selects the definition public static void Sum(int System.out.println("The area is "+result);
}
num1,int num2,int num3) to fulfil the call. Hence we
void area3()
get the output as 60 which is actually the addition of 10, {
20 and 30. System.out.println("Now, The function is called...");
int result=height*height;
Board Question System.out.println("The area is "+result);
1. Explain method overloading with example. }
MSBTE : Winter 15, Marks 4 }
class OverLoadConstr
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-7 Inheritance, Interface and Package

public static void main(String args[]) this.name=name;


{ this.panno=panno;
Rectangle2 obj1=new Rectangle2(11,20); }
obj1.area1();//call the to method Person(int adharno, String name)//overloaded constructor
Rectangle2 obj2=new Rectangle2(11.33,20.22); {
obj2.area2();//call the to method this.adharno=adharno;
Rectangle2 obj3=new Rectangle2(10); this.name=name;
obj3.area3();//call the to method this.panno="Not Assigned";
} }
} void display()
{
Output
System.out.println("Adhar No: "+adharno);
Now, The function is called...
System.out.println("Name: "+name);
The area is 220
System.out.println("Pan No: "+panno);
Now, The function is called...
}
The area is 229.09259999999998
}
Now, The function is called...
class Test
The area is 100
{
public static void main(String args[])
Program Explanation
{
In above program, Person p1,p2,p3,p4,p5;
1) We have defined three constructors; there are two String n,pnno;
int adhno;
integer parameters that are passed to the first
Scanner input = new Scanner(System.in);
constructor. This constructor invokes the method System.out.println("\tEnter data for Person#1");
area1. System.out.println("Enter Adhar Number: ");
2) To the second constructor the two double values are adhno=input.nextInt();
System.out.println("Enter Name: ");
passed as arguments. This constructor invokes the
n=input.next();
method area2. System.out.println("Enter Pan Number: ");
3) Then the third constructor is defined which has only pnno=input.next();
one argument passed to it. This constructor invokes p1=new Person(adhno,n,pnno);//call to first constructor

the method area3.


System.out.println("\tEnter data for Person#2");
4) Depending upon the number of parameters passed the System.out.println("Enter Adhar Number: ");
appropriate constructor gets invoked. This mechanism adhno=input.nextInt();
System.out.println("Enter Name: ");
is called constructor overloading.
n=input.next();
Example 3.4.1 : Define a class person with data member as System.out.println("Enter Pan Number: ");
Aadharno, name, Panno implement concept of constructor pnno=input.next();
overloading. Accept data for 5 object and print it.
p2=new Person(adhno,n,pnno);//call to first constructor
MSBTE : Winter 17, Marks 8
Solution :
System.out.println("\tEnter data for Person#3");
import java.util.*; System.out.println("Enter Adhar Number: ");
class Person adhno=input.nextInt();
{ System.out.println("Enter Name: ");
int adharno; n=input.next();
String name; p3=new Person(adhno,n);//call to second constructor
String panno;
Person(int adharno,String name,String panno) System.out.println("\tEnter data for Person#4");
{ System.out.println("Enter Adhar Number: ");
this.adharno=adharno; adhno=input.nextInt();
TM
Technical Publications - An up thrust for knowledge
Java Programming 3-8 Inheritance, Interface and Package

System.out.println("Enter Name: "); EEE


n=input.next(); Enter Pan Number:
p4=new Person(adhno,n);//call to second constructor EEE55
Displaying all the records...
System.out.println("\tEnter data for Person#5"); Adhar No: 123
System.out.println("Enter Adhar Number: "); Name: AAA
adhno=input.nextInt(); Pan No: AAA12
System.out.println("Enter Name: "); Adhar No: 222
n=input.next(); Name: BBB
System.out.println("Enter Pan Number: "); Pan No: BBB22
pnno=input.next(); Adhar No: 333
p5=new Person(adhno,n,pnno);//call to first constructor Name: CCC
Pan No: Not Assigned
System.out.println("\t Displaying all the records..."); Adhar No: 444
p1.display(); Name: DDD
p2.display(); Pan No: Not Assigned
p3.display(); Adhar No: 555
p4.display(); Name: EEE
p5.display(); Pan No: EEE55
}
3.5 Overriding
} MSBTE : Winter 17, Marks 4

Output
Definition: Method overriding is a mechanism in
Enter data for Person#1
Enter Adhar Number: which a subclass inherits the methods of superclass
123 and sometimes the subclass modifies the
Enter Name: implementation of a method defined in superclass.
AAA
Enter Pan Number:  The method of superclass which gets modified in
AAA12 subclass has the same name and type signature.
Enter data for Person#2
 The overridden method must be called from the
Enter Adhar Number:
222
subclass.
Enter Name:  Consider following Java Program, in which the
BBB method(named as fun ) in which a is assigned with
Enter Pan Number:
some value is modified in the derived class. When an
BBB22
Enter data for Person#3 overridden method is called from within a subclass, it
Enter Adhar Number: will always refer to the version of that method
333 redefined by the subclass. The version of the method
Enter Name:
defined by the superclass will be hidden.
CCC
Enter data for Person#4  Example Program
Enter Adhar Number:
444 class A
Enter Name: {
DDD int a=0;
Enter data for Person#5 void fun(int i)
Enter Adhar Number: {
555 this.a=i;
Enter Name: }

TM
Technical Publications - An up thrust for knowledge
Java Programming 3-9 Inheritance, Interface and Package

} Definition: Dynamic method dispatch is a technique in


class B extends A
which a call to overridden method is resolved at run time
{
int b; instead of compile time.
void fun(int i) During dynamic method dispatch following steps are
{ applied to achieve it -
1. The overridden methods are written.
int c;
b=20; 2. The reference of super class is created in main
super.fun(i+5); method.
System.out.println("value of a:"+a); 3. The reference of derived class is assigned to the
System.out.println("value of b:"+b);
reference created in step 2 and corresponding method
c=a*b;
of derived class is invoked using this reference.
System.out.println("The value of c= "+c);
} Following Java program illustrates this concept.
}
Example Program
class OverrideDemo
class OS
{ {
public static void main(String args[]) void display()
{ {
B obj_B=new B(); System.out.println("Operating System");
obj_B.fun(10);//function re-defined in derived class }
} }
class WindowsOS extends OS
}
{
void display()
Output {
System.out.println("Windows Operating System");
value of a:15
}
value of b:20
}
The value of c= 300 class UNIXOS extends OS
{
Program Explanation void display()
{
In above program,
System.out.println("Unix Operating System");
1) There are two classes - class A and class B. }
}
2) The class A acts as a superclass and the class B acts as class MainClass
a subclass. In class A, a method fun is defined in {
public static void main(String args[])
which the variable a is assigned with some value.
{
3) In the derived class B, we use the same function name OS obj1=new OS();
fun in which, we make use of super keyword to WindowsOS obj2=new WindowsOS();
UNIXOS obj3=new UNIXOS();
access the variable a and then it is multiplied by b and OS ref;//reference of type OS
the result of multiplication will be printed.
ref=obj1;
Board Question obj1.display();

1. Explain method overriding with suitable example. ref=obj2;


MSBTE : Winter 17, Marks 4 obj2.display();

3.6 Dynamic Method Dispatch ref=obj3;


MSBTE : Winter 17, Marks 6 obj3.display();
}
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 10 Inheritance, Interface and Package

Output {
Operating System final void fun()
Windows Operating System {
Unix Operating System System.out.println("\n Hello, this another function");
}
Program Explanation : In above program,
}
1) The base class is OS, and two classes namely
Output
WindowsOS and UNIXOS is derived from it. Test.java:10: fun() in Test1 cannot override fun() in Test;
2) In main method, the objects for these three classes are overridden method is final
final void fun()
created.
^
3) The reference variable ref for base class is also 1 error
created. Now this reference is assigned with each of
these three objects. Program Explanation : The above program,
4) The display method (which is actually overridden 1) on execution shows the error. Because the method fun
method) is invoked using the objects. Thus is declared with the keyword final and it cannot be
appropriate display() method is invoked at runtime. overridden in derived class.

Board Question Three uses of Final Keyword


1. Write a single program to implement inheritance 1) The final variables can not be modified.
and polymorphism in java. 2) The final method cannot be overridden.
MSBTE : Winter 17, Marks 6
3) The final class can not be inherited.
3.7 Final Variables and Final Methods
MSBTE : Summer 15, 16,17,Marks 6 Board Questions
1. State the use of final keyword w.r.t. a method and
 A variable can be declared as final. If a particular
the variable with suitable example.
variable is declared as final then it cannot be modified MSBTE : Summer 15, Marks 4
further.
 The final variable is always a constant. For example - 2. Describe final method and final variable with
final int a=10; respect to inheritance. MSBTE : Summer 16, Marks 6
 The final keyword can also be applied to the method. 3. State three uses of final keyword.
When final keyword is applied to the method, the MSBTE : Summer 17, Marks 4

method overriding is avoided. That means the methods 3.8 Use of Super
those are declared with the keyword final cannot be MSBTE : Summer 16, Winter 15, 17, Marks 6
overridden. Super is a keyword used to access the immediate parent
 Consider the following Java program which makes use class from subclass.
of the keyword final for declaring the method - There are three ways by which the keyword super is
 Example Program used.
class Test
{
final void fun()
{
System.out.println("\n Hello, this function declared using
final");
}
} Fig. 3.8.1 Use of super
class Test1 extends Test

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 11 Inheritance, Interface and Package

Let us understand these uses of keyword super with class B extends A


{
illustrative Java programs.
void fun()
1. The super() is used to invoke the class method of {
immediate parent class. System.out.println("Method: Class B");
}
Java Program[B.java] void display()
class A {
{ super.fun();
int x=10; }
} public static void main(String args[])
class B extends A {
{ B obj=new B();
int x=20; obj.display();
void display() }
{ }
System.out.println(super.x); Output
} Method: Class A
public static void main(String args[])
Program Explanation : In above program, the derived
{
class can access the immediate parent's class method
B obj=new B();
using super.fun(). Hence is the output. You can change
obj.display();
super.fun() to fun(). Then note that in this case, the
}
output will be invocation of subclass method fun.
}
3. The super() is used to invoke the immediate parent class
constructor.
Output Example Program[B.java]
10
class A
{
Program Explanation : In above program class A is a A()
immediate parent class of class B. Both the class A and {
Class B has variables x. In class A, the value of x variable System.out.println("Constructor of Class A");
}
is 10 and in class B the value of variable x is 20. In
}
display function if we would write class B extends A
System.out.println(x); {
The output will be 20 but if we user super.x then the B()
{
variable x of class A will be referred. Hence the output is
super();
10. System.out.println("Constructor of Class B");
}
2. The super() is used to access the class variable of public static void main(String args[])
immediate parent class. {
B obj=new B();
Java Program[B.java] }
class A }
{ Output
void fun() Constructor of Class A
{ Constructor of Class B
System.out.println("Method: Class A");
Program Explanation : In above program, the constructor
}
in class B makes a call to the constructor of immediate
}
parent class by using the keyword super, hence the print
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 12 Inheritance, Interface and Package

statement in parent class constructor is executed and then Java Program[AbstractClsDemo.java]


the print statement for class B constructor is executed. abstract class A
{ This method is so abstract that
Board Questions
it has no definition body.
1. Describe use of ‘super’ and ‘this’ with respect to abstract void fun1();
inheritance. void fun2()
MSBTE : Summer 16, Marks 4, Winter 17, Marks 6 {
2. State the use of ‘super’ and ‘final’ keyword w.r.t. System.out.println("A:In fun2");
inheritance with example. }
MSBTE : Winter 15, Marks 6 }
class B extends A
3.9 Abstract Methods and Classes
{
 In the inheritance hierarchy, the classes become more
void fun1()
specific as we move down towards the subclasses and
{
if we move up in this hierarchy classes become more
System.out.println("B:In fun1");
general. The superclass is supposed to be the most
}
general or less specific. Sometimes superclass is so
general and less specific that it does nothing but lists }
out only common features of other classes. Then such class C extends A
a superclass is refereed as abstract class. {
 For example - In the following Java program we have void fun1()
created three classes - class A is a superclass {
containing two methods, the class B and class C are System.out.println("C:In fun1");
inherited from class A. The class A is an abstract class }
because it contains one abstract method fun1(). We
have defined this method as abstract because, its }
definition is overridden in the subclasses B and C, public class AbstractClsDemo
another function of class A that is fun2() is a normal {
function. Refer Fig. 3.9.1.
public static void main(String[] args)

Fig. 3.9.1 Abstract class


TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 13 Inheritance, Interface and Package

{ 3.10 Static Members MSBTE : Summer 18, Marks 4


B b=new B();  The static members can be static data member or
C c=new C(); static method.
b.fun1(); //invoking the overridden method of class B
 The static members are those members which can be
b.fun2();
accessed without using object.
c.fun1();//invoking the overridden method of class C
c.fun2();
 Following program illustrates the use of static
} members.
}

Output

B:In fun1
A:In fun2
C:In fun1 Example Program
A:In fun2 class StaticProg
{
Program Explanation : In above program, static int a=10;
static void fun(int b)
1) The class A is a superclass. It is an abstract class as
{
well. The name of this class is preceded by the
keyword abstract. This class is abstract because it System.out.println("b= "+b);
contains an abstract method fun1. The method is System.out.println("a= "+a);
called abstract because it does not have any definition
}
body. Note that the abstract method should be
}
declared with the keyword abstract.
class AnotherClass
2) There are two classes B and C which are subclasses of {
superclass A. The function definition fun1 is public static void main(String[] args)

overridden in these classes. {


System.out.println("a= "+StaticProg.a);
3) In the main function we can access the methods of
StaticProg.fun(20);
the subclasses by instantiating their objects. That is
why we have created b as an object of class B and c }
}
as an object of class C. Using these objects
appropriate fun1 can be invoked. Note that the fun2 Output
a= 10
will always be from class A even if we call it using the b= 20
object of class B or C. a= 10

4) If we write a statement A a=new A() i.e. if we


Program Explanation
instantiate the abstract class then it will generate
In above program, we have declared one static variable a
compiler error. That means the abstract classes can and a static member function fun(). These static members
not be instantiated. are declared in one class StaticProg. Then we have
written one more class in which the main method is
defined. This class is named as AnotherClass. From this
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 14 Inheritance, Interface and Package

class the static members of class StaticProg are accessed Difference between Class and Interface
without using any object. Note that we have simple used
An interface is similar to a class but there lies some
a syntax
difference between the two.
ClassName.staticMember
Hence by using StaticProg.a and StaticProg.fun we can Class Interface
access static members
The class is denoted by a The interface is denoted
Restrictions on Static
keyword class. by a keyword interface.
 The static methods must can access only static data.
 The static method can call only the static method and The class contains data The interfaces may
members and methods. But the contain data members and
can not call a non static method.
methods are defined in class methods but the methods
 The static method can not refer to this pointer. implementation. Thus class are not defined. The
 The static method can not refer to super method. contains an executable code. interface serves as an
outline for the class.
Board Question
1. Which are the restrictions present for static By creating an instance of a You can not create an
declared methods ? MSBTE : Summer 18, Marks 4 class the class members can be instance of an interface.
accessed.
Part II : Interface
The class can use various The interface makes use of
3.11 Definition of Interface access specifiers like public, only public access
MSBTE : Summer 16, 17, Marks 8 private or protected. specifier.

Syntax of Interface
The members of a class can be The members of interfaces
 The interface can be defined using following syntax constant or final. are always declared as
access_modifier interface name_of_interface final.
{
return_type
Features of Interface
method_name1(parameter1,parameter2,…parametern);
… 1) An interface can contain any number of methods.
return_type
2) Interface can be written in a file with .java extension.
method_name1(parameter1,parameter2,…parametern);
type static final variable_name=value; 3) An interface does not contain any constructor.
… 4) All the methods in interface are abstract(i.e. they are
not defined;only declared)
}
5) An interface not be extended by class ; it is
 The access_modifier specifies the whether the
implemented by class.
interface is public or not. If the access specifier is not
specified for an interface then that interface will be Board Questions
accessible to all the classes present in that package 1. Write syntax of defining interface. Write any major
only. But if the interface is declared as public then it two differences between interface and class.
will be accessible to any of the class. MSBTE : Summer 16, Marks 6
2. What is meant by interface ? State its need and
 The methods declared within the interface have no
write syntax and features of interface.
body. It is expected that these methods must be defined MSBTE : Summer 17, Marks 8
within the class definition.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 15 Inheritance, Interface and Package

3.12 Implementing Interface Step 1 : Write following code and save it as


MSBTE : Winter 15, Marks 8
my_interface.java
 It is necessary to create a class for every interface. public interface my_interface
{
 The class must be defined in the following form while
void my_method(int val);
using the interface
}
class Class_name extends superclass_name
implements interface_name1,interface_name2,… Do not compile this program. Simply save it.
{
Step 2 : Write following code in another file and save it
//body of class
using InterfaceDemo.java
}

 Let us learn how to use interface for a class

Java Program[InterfaceDemo.java]
class A implements my_interface
{ Defining the method declared in the
public void my_method(int i) interface
{
System.out.println("\n The value in the class A: "+i);
}
public void another_method() //Defining another method not declared in interface
{
System.out.println("\nThis is another method in class A");
}
}
class InterfaceDemo
{
public static void main(String args[])
Object of class A is of type
{ my_interface. Using this object
my_interface obj=new A(); method can be accessed
//or A obj=new A() is also allowed
A obj1=new A();
obj.my_method(100);
obj1.another_method();
}
}

Step 3 : Compile the program created in step 2 and get the following output
The value in the class A: 100

This is another method in class A

Program Explanation :
In above program,
1) The interface my_interface declares only one method i.e. my_method. This method can be defined by
class A.

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 16 Inheritance, Interface and Package

2) There is another method which is defined in class A and that is another_method. Note that this method is
not declared in the interface my_interface. That means, a class can define any additional method which is
not declared in the interface.

Various Forms of Interface Implementation


 The design various ways by which the interface can be implemented by the class is represented by
following Fig. 3.12.1.

Fig. 3.12.1 Design of ways of interface implementation

Board Question
1. What is meant by an interface ? State its need and write syntax and features of an interface. Give one
example. MSBTE : Winter 15, Marks 8

3.13 Accessing Interface


 The interface is a powerful tool. The same interface can be used by different classes for some method.
Then this method can be implemented by each class in its own way.
 Thus the same interface can provide variety of implementations.
 The selection of different implementations is done at the run time. Following is a simple Java program
which illustrates this idea.

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 17 Inheritance, Interface and Package

 Example Program

Step 1 : Write a simple interface as follows


Java Program [interface1.java]
interface interface1
{
void MyMsg(String s);
} Program Explanation :

Step 2 : Write a simple Java program having two classes 1. The selection of method MyMsg is done at the
runtime and it depends upon the object which is
having their own implementation of MyMsg method.
assigned to the reference of the interface.
Java Program[Test.java]
2. We have created reference inter for the interface in
import java.io.*;
which the method MyMsg is declared.
import java.util.*;
class Class1 implements interface1 3. Then the objects obj1 and obj2 are created for the
{ classes class1 and class2 respectively. When the obj1
private String s; is assigned to the reference inter then the message
public void MyMsg(String s) “Hello User1” will be displayed because the string
{ passed to the method MyMsg is “User1”. Similarly,
System.out.println("Hello "+s); when the obj2 is assigned to the reference inter then
} the message “Hello User2” will be displayed because
} the string passed to the method MyMsg is “User2”.
class Class2 implements interface1
4. Thus using the same interface different
{
implementations can be selected.
private String s;
public void MyMsg(String s) 3.14 Variables and Methods Interfaces
{
System.out.println("Hello "+s);  The variables can be assigned with some values within
} the interface. They are implicitly final and static. Even
} if you do not specify the variables as final and static
they are assumed to be final and static.
class Test
{  The members (variables and methods) of interface are
public static void main(String[] args) static and final because -
{ 1) The reason for being static - The members of
interface1 inter;
interface belong to interface only and not object.
Class1 obj1=new Class1();
Class2 obj2=new Class2();
2) The reason for being final - Any implementation
inter=obj1; can change value of fields if they are not defined as
inter.MyMsg("User1"); final. Then these members would become part of
inter=obj2; the implementation. An interface is pure
inter.MyMsg("User2"); specification without any implementation.
}
} 3.15 Extending Interfaces
MSBTE : Winter 16, 17, Summer 15, 16, 17, 18, Marks 8
Step 3 : Execute the program.  Interfaces can be extended similar to the classes. That
means we can derive subclasses from the main class using
the keyword extend, similarly we can derive the
subinterfaces from main interfaces by using the keyword
extends.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 18 Inheritance, Interface and Package

 The syntax is Solution :


interface Interface_name2 extends interface_name1 class Student
{ {
… String name;
… Body of interface int roll_no;
… double m1,m2;
} Student(String name,int roll_no,double m1,double m2)
{
 For example this.name=name;
interface A this.roll_no=roll_no;
{ this.m1=m1;
int val=10; this.m2=m2;
} }
interface B extends A }
{ interface exam
void print_val(); {
} public void per_cal();
That means in interface B, the display method can }
access the value of variable val. class result extends Student implements exam
{
Similarly more than one interfaces can be extended. result(String nm,int roll,double m1,double m2)
interface A {
{ super(nm,roll,m1,m2);
int val=10;
} }
interface B public void per_cal()
{ {
double percentage;
void print_val();
percentage=((m1+m2)/200)*100;
}
System.out.println("The percentage marks:
interface C extends A,B "+percentage);
{ }
… void display()
{
System.out.println("Name: "+name);
System.out.println("Roll_No: "+roll_no);
… System.out.println("Marks m1= "+m1+" m2 = "+m2);
} per_cal();
}
Even-though methods are declared inside the interfaces
}
and sub-interfaces, these methods are not allowed to be class Test
defined in them. Note that methods are defined only in the {
classes and not in the interfaces. public static void main(String args[])
{
Example 3.15.1 : Write a java program.
result r=new result("Parth",10,90,95);
r.display();
}
}

Output
Name: Parth
Roll_No: 10
Marks m1= 90.0 m2 = 95.0
MSBTE : Winter 16, Marks 6 The percentage marks: 92.5

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 19 Inheritance, Interface and Package

Example 3.15.2 : Write a program to implement following salary s=new salary("Parth",BasicSalary);


inheritance :Interface : Gross s.display();
}
}

Output
Name: Parth
Basic Salary: 10000.0
The Gross Salary: 12200.0

MSBTE : Summer 17, Marks 4


Note : Above two examples illustrate use of multiple
Solution : inheritance.
class Employee Board Questions
{
String name; 1. Explain with example how to achieve multiple
double basic_sal; inheritance with interface.
Employee(String name,double basic_sal) MSBTE : Summer 15, Marks 6, Summer 16, Marks 8,
{ Summer 18, Marks 4
this.name=name; 2. How multiple inheritance is achieved in java ?
this.basic_sal=basic_sal; Explain with proper program.
}
MSBTE : Winter 16, Marks 8
}
interface Gross 3. What is the multiple inheritance ? Write a java
{ program to implement multiple inheritance.
public double ta=500; MSBTE : Winter 17, Marks 6
public double da=700; 4. Write a java program to extend interface assuming
public void gross_sal();
suitable data.
}
MSBTE : Summer 18, Marks 6
class salary extends Employee implements Gross
{
3.16 Interface References
double hra=1000;
salary(String nm,double basic) It is possible to create a reference variable (object) of type
{ interface. Using this reference variable we can access the
super(nm,basic);
method defined in the class that implements the interface.
}
public void gross_sal() Following Java program illustrates this idea
{
Step 1 : Define the interface in a separate file.
double Gross;
Gross=basic_sal+ta+da+hra; interface1.java
System.out.println("The Gross Salary: "+Gross); interface interface1
} {
void display() void MyMsg(String s);
{ }
System.out.println("Name: "+name);
Step 2 : Create a Java program in this interface reference
System.out.println("Basic Salary: "+basic_sal); is used to access the method defined in the class.
gross_sal();
Test.java
} import java.io.*;
} import java.util.*;
class SalaryDemo class A implements interface1
{ {
public static void main(String args[]) private String s;
{ public void MyMsg(String s)
double BasicSalary=10000; {
System.out.println("Hello "+s);
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 20 Inheritance, Interface and Package

} interface Area{
} void display();
class Test
}
{
}
public static void main(String[] args)
{ class Test implements Rectangle.Area
interface1 inter;//interface reference {
inter=new A(); public void display()
inter.MyMsg("User"); {
} System.out.println("Formula for calculating area =
} length*breadth");
}
Step 2 : The output can be obtained as-
public static void main(String args[])
D:\MSBTE_JAVA _Programs> javac interface1.java
{
D:\MSBTE_JAVA _Programs> javac Test.java
Rectangle.Area obj=new Test();//upcasting here
D:\MSBTE_JAVA _Programs> java Test
obj.display();
Hello User
}
Program Explanation : In above program, }
1) We have written a simple interface class named Output
interface1. The method declared in this interface is
MyMsg.
2) Now we have also written a Test class for defining the
method MyMsg.
3) Inside the main method, the interface reference in
variable inter is created. We can access the method of
a class using this interface reference. Note that this
reference variable is initialized by instance of a class
A.

3.17 Nested Interfaces 2. Nested Interface declared within the class


 An interface which is declared inside another interface class MyClass
or class is called nested interface. {
interface Area
 It is also known as inner interface.
{
 The nested interface can not be accessed directly. It is void display();
accessed by using outer class or outer interface name }
followed by dot( . ), followed by the interface name. }
class Test implements MyClass.Area
 Purpose : The nested interfaces are used to group
{
related interfaces so that they can be easy to maintain. public void display()
The nested interface must be referred by the outer {
interface or class. It cannot be accessed directly. System.out.println("Formula for calculating area =
 There are two ways of defining nested interface - length*breadth");
}
o Nested Interface which is declared within the public static void main(String args[])
interface. {
o Nested Interface which is declared within the class. MyClass.Area obj=new Test();//upcasting here
obj.display();
Let us understand these implementation using Java }
1. Nested Interface declared within the interface }
interface Rectangle Output
Formula for calculating area = length*breadth;
{
void set_value();

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 21 Inheritance, Interface and Package

Properties of Nested Interface


1) Nested interfaces are static by default. You don’t have
to mark them static explicitly.
2) Nested interfaces declared inside class can take any
access modifier.
3) Nested interface declared inside interface is public Fig. 3.19.1 Built-in Packages
implicitly.
 The purpose of these Java system packages is as given

Part III : Package below -


Package Description
3.18 Definition of Packages
java.applet This package is for creating and implementing
 Definition : Package is a mechanism in which variety applet.
of classes and interfaces can be grouped together.
java.awt This package is for graphical user interface.
 Importance : Following are the benefits of organizing
Using the classes and methods of this package
classes into packages-
various components like button, text box, radio
1. The classes defined in the packages of other buttons and so on can be used.
program can be easily reused.
java.lang This package supports the use of strings, math
2. Two classes from two different packages can have
functions, threads and exception.
the same name. By using the package name the
particular class can be referred. java.util Various utility classes such as vectors, date,
random numbers are used by using this package.
3. Packages provide the complete separation
between the two phases- design and coding. In the java.io For supporting input and output operations this
design phase, we can design the classes and decide package is used in the Java program.
their relationship and then during the coding phase
Board Questions
we can develop the Java code for corresponding
1. State any four system packages along with their
classes and can group them in several packages use. MSBTE : Winter 15, Marks 4
according to their relationship with each other. 2. List any four built-in packages from Java API
4. Using packages it is possible to hide the classes. along with their use. MSBTE : Summer 17, Marks 4
This feature prevents other programs to access the 3. Enlist any four built in packages in java API with
classes that are developed for internal purpose atleast two class name from each package.
MSBTE : Winter 17,Marks 4
only.

3.19 Built-in Java Packages 3.20 Type of Package Naming


MSBTE : Winter 15, 17, Summer 17, Marks 4  For naming the packages some standard rules must be
followed.
 Java API is a collection of various packages in which  Normally, packages begin with lowercase letters and
several classes and methods are grouped together class name begin with capital letters. For accessing
the method belonging to particular class of some
according to their functionality.
package the dot operator is used. For example-
 Fig. 3.19.1 represents the most commonly used Java
API packages -

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 22 Inheritance, Interface and Package

 That is the class Math invokes the method max. This method finds the maximum of the two. This class is
present in the package lang.
 Every package name be unique. Because the duplicate package names may cause the runtime errors.
 According to the naming conventions of packages it is suggested to make use of domain names as prefix to
predefined package names.

3.21 Creating Packages


MSBTE : Winter 15, 17, Marks 8
Following are the steps which show how to create a package in Java.
Step 1 : Create a folder named My_Package and write the following code in a file.
package My_Package; //include this package at the beginning
public class A
{
int a;
void set_val(int n)
{
a=n;
}
void display()
{
System.out.println("The value of a is: "+a);
}
}
class PackageDemo
{
public static void main(String args[]) throws NoClassDefFoundError
{
A obj=new A();
obj.set_val(10);
obj.display();
}
}
Save it by the name PackageDemo.java. This file must be saved within the directory My_Package.
Step 2 : Compile the above java program as follows -
F:\test>cd My_Package
F:\test\My_Package>javac A.java
Now, make sure that the class file A.class and PackageDemo.class gets generated in the folder
My_Package.
Step 3 :Now execute the program using the command to get an output. Using the package name and dot operator
we can execute the program.

Fig. 3.21.1
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 23 Inheritance, Interface and Package

This helps to find the CLASSPATH for the executable file. If there is an hierarchy of packages then it can be
mentioned by names of packages separated by dots. For example
package.my_package.another_package;
Note that one of the class in the java package must be public.
The main advantage of using packages is that we can arrange the classes systematically.
Board Questions
1. What is package ? How to create package ? Explain with suitable example. MSBTE : Winter 15, Marks 6
2. What is package ? How do we create it ? Give the example to create and to access package.
MSBTE : Winter 17, Marks 8

3.22 Accessing Package


MSBTE : Summer 15, 17,18,Marks 6
 Access modifiers control access to data fields, methods, and classes. There are three modifiers used in Java
o public
o private
o default modifier
o public allows classes, methods and data fields accessible from any class.
 private allows classes, methods and data fields accessible only from within the own class.
 If public or private is not used then by default the classes, methods, data fields are assessable by any class
in the same package. This is called package-private or package-access.
 A package is essentially grouping of classes.
For example :
package Test;
public class class1
package another_Test
{
public class class3
public int a;
{
int b;
void My_method() {
private int c;
class1 obj=new class1();
public void fun1() {
obj.a;//allowed
}
obj.b;// error:cannot access
void fun2() {
obj.c;//error:cannot access
}
obj.fun1();//allowed
private void fun3() {
obj.fun2()//error:cannot access
}
obj.fun3()//error:cannot access
}
}
public class class2
}
{
void My_method() {
class1 obj=new class1();
obj.a;//allowed
obj.b;//allowed
obj.c;//error:cannot access
obj.fun1();//allowed
obj.fun2();//allowed
obj.fun3();//error:cannot access
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 24 Inheritance, Interface and Package

In above example, then that variable is accessible by that class only and
o We have created two packages are created namely - its subclass can not access it.
Test and another_Test.
Board Questions
o Inside the package Test there are two classes 1. Write the effect of access specifiers public, private
defined – class1 and class2 and protected in package
o Inside the package another_Test there is only one MSBTE : Summer 15, Marks 4

class defined and i.e. class3. 2. What is package ? State how to create and access
user defined package in Java.
o There are three data fields – a, b and c. The data
MSBTE : Summer 17, Marks 6
field a is declared as public, b is defined as default
3. Which are the ways to access package from
and c is defined as private. another package ? Explain with example.
o The variable a and method fun1() both are MSBTE : Summer 18, Marks 4
accessible from the classes class2 and class3(even
3.23 Import Statement
if it is in another package). This is because they are MSBTE : Summer 16, Marks 4
declared as public.
 All the standard classes in Java are stored in named
o The variable b and method fun2() both are packages.
accessible from class2 because class2 lies in the  There is no standard class present in Java which is
same package. But they are not accessible from unnamed. But it is always complicated to write the
class3 because class3 is defined in another class name using a long sequence of packages
package. containing dot operator. Hence the import statement is
o The variable c and method fun3() both are not needed.
accessible from any of the class, because they are  The import statement can be written at the beginning
declared as private. of the Java program, using the keyword import.
 Protected mode is another access specifier which is  There are two ways of accessing the classes stored in
used in inheritance. The protected mode allows the core package.
accessing the members to all the classes and subclasses 1. Method 1 : We import the java package class using the
in the same package as well as to the subclasses in keyword import. Suppose we want to use the Data class
other package. But the non subclasses in other package stored in the java.util package then we can write the
can not access the protected members. import statement at the beginning of the program. It is as
 The effect of access specifiers for class, subclass or follows -
package is enlisted below -

Specifier Class Subclass Package

private Yes - -
2. Method 2 : There are some situations in which we want
protected Yes Yes Yes to make use of several classes stored in a package. Then
we can write it as
public Yes Yes Yes
import java.util.*
 For example, if some variable is declared as protected,
Here * means any class in the corresponding package.
then the class itself can access it, its subclass can
Example 3.23.1 : Design a package containing a class which
access it, and any class in the same package can also
defines a method to find area of rectangle. Import it in Java
access it. Similarly if the variable is declared as private application to calculate area of a rectangle.
MSBTE : Summer 16, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 25 Inheritance, Interface and Package

Solution : 3.24 Static Import


 Static import is a new feature added in Java.
Step 1 : Create a package named MyPack. Store a Java
file that defines dimensions of rectangle and  In order to access static members, it is necessary to
calculate_area() methods. This file is named as A.java. It qualify references with the class they came from.
is as follows - That means in order to access the static members of a
class , it is a must to write the member along with its
Java Program[A.java] belonging class name. For example –
package MyPack;
public class A
 Example Program
{ class StaticImport
int length,breadth; {
public void set_val(int l,int b) public static void main(String args[])
{ {
length=l; double a=25;
breadth=b; double val=Math.sqrt(a); //note sqrt function is written as
Math.sqrt
}
//Similarly out.println is written as System.out.println
public void calculate_area()
System.out.println("The square root of "+a+" is "+val);
{
}
double area;
}
area=length*breadth;
System.out.println("The area is: "+area);
} Output
} The square root of 25.0 is 5.0

Step 2 : Now create another program outside this In order to avoid unnecessary use of static class members
MyPack folder. This program will invoke the above like Math. and System, we should use static import.
defined class and use the methods defined in above The above code can be changed by using static import,
created Java class. Just note the difference between these two programs -
Java Program[PackageDemo.java]
Java Program[StaticImport.java]
import static java.lang.System.out;
import MyPack.A;
import static java.lang.Math.sqrt;
class PackageDemo Use of static import
class StaticImport
{
{
public static void main(String args[]) throws
public static void main(String args[])
NoClassDefFoundError
{
{
double a=25;
A obj=new A();
double val=sqrt(a);//using sqrt function without specifying
obj.set_val(10,20);
the class name - Math
obj.calculate_area();
out.println("The square root of "+a+" is "+val); //without
}
specifying System class
}
}
Step 3: }

Output Now compile and execute the above program and you
D:\> cd MyPack will get the same output i.e.
D:\MyPack> javac A.java
The square root of 25.0 is 5.0.
D:\MyPack> cd..
D:\> javac PackageDemo.java Note that ambiguous static import is not allowed. That
D:\> java PackageDemo means the two different classes referencing the same
The area is: 200.0
functionality is not allowed.
TM
Technical Publications - An up thrust for knowledge
Java Programming 3 - 26 Inheritance, Interface and Package

Advantage of using Static import package with newly added class.


The advantage of using static import is that readability of D:\My_Package>javac A.java
D:\My_Package>javac B.java
the code increases as it avoids writing of belonging class
name each time. D:\My_Package>javac PackageDemo.java

3.25 Adding Class and Interfaces to a Package


D:\My_Package>java PackageDemo
Summer 15, 18, Winter 16, Marks 8
The value of a is: 10
We can add some class in the existing package. For that class B is now added in the package
purpose following steps are followed-
Board Questions
Step 1 : Write a class (in a separate java file )which is to 1. What is package ? State any four system packages
be added in the existing package. Suppose I want to add along with their use ? How to add class to a user
the class B in the existing package My_Package. I will defined package ?
MSBTE : Summer 15, Marks 8
create a B.java file and store the code in it as follows-
2. How to add new class to a package ? Explain with
Java Program[B.java] an example.
package My_Package; //include this package at the MSBTE : Summer 18, Marks 4
beginning 3. What is Interface ? How to add interfaces to
public class B packages.
{ MSBTE : Winter 16, Marks 4
public void show()
{ 
System.out.println("class B is now added in the package");
}
}

Step 2 : The test program PackageDemo.java can be


edited as follows -
[Note that edited code is in bold]

Java Program [PackageDemo.java]


import My_Package.A;
import My_Package.B; //reference to a B class by import
//statement
class PackageDemo
{
public static void main(String args[]) throws
NoClassDefFoundError
{
A Aobj=new A();
B Bobj=new B(); //creating an object for class B
Aobj.set_val(10);
Aobj.display();
Bobj.show(); //using the object of B class the
//corresponding function can be accessed.
}
}

Step 3 : Issue the following commands to execute the


TM
Technical Publications - An up thrust for knowledge
Java Programming 4-1 Exception Handling and Multithreading

UNIT - IV

4 Exception Handling and


Multithreading

1. Compile time errors -


Part I : Exception Handling
 The errors that are detected by the Java compiler
4.1 Errors and Exception during the compile time are called the compile time
errors.
 Exceptions : Exception is an unusual condition that
can occur in the program. This condition is caused due  When compiler issues the errors it will not generate the
to run time error in the program. .class file. Hence we must eliminate all the compile
time errors first.
 Errors : When any kind of serious problem occurs
which could not be handled easily like  The most commonly occurring compile time errors
OutOfMemoryError then an error is thrown. are -
1. Missing semicolons.
Benefits of Exception Handling
2. Wrong spelling of keywords and identifiers.
Following are the benefits of exception handling -
3. Missing brackets of classes and methods.
1. Using exception the main application logic can be
4. Missing double quotes in the string.
separated out from the code which may cause some
5. Use of undeclared variables.
unusual conditions.
6. Use of = instead of ==
2. When calling method encounters some error then the
exception can be thrown. This avoids crashing of the 7. Incompatible types in assignment statement.
entire application abruptly. 8. Illegal reference to the object.
3. The working code and the error handling code can be 2. Run time errors
separated out due to exception handling mechanism.  Sometimes the program is free from the compile time
Using exception handling, various types of errors in errors and creates a .class file. But it does not yield the
the source code can be grouped together. results as per our expectations. In such situation we
4. Due to exception handling mechanism, the errors can declare that the program has run time errors.
be propagated up the method call stack i.e. problems  The runtime errors are basically the logical errors, that
occurring at the lower level can be handled by the get caused due to the wrong logic.
higher up methods.
 The most commonly occurring run time errors are -
4.2 Types of Errors 1. Accessing the array element which is out of the
MSBTE : Summer 18, Marks 4 index.
There are two types of errors - 2. In an expression, divide by zero.
1. Compile time errors 2. Run time errors 3. Trying to store a value into an array of
Let us discuss them incompatible type.

TM
Technical Publications (4 --An
1) up thrust for knowledge
Java Programming 4-2 Exception Handling and Multithreading

4. Passing the parameters that is not in the valid  There is another block defined by the keyword catch
range. which is responsible for handling the exception thrown
5. Converting invalid string to numbers. by the try block.
6. Trying to illegally change the state of thread.  As soon as exception occurs it is handled by the catch
7. Trying to access the character which is out of block.
bounds of a string.  The catch block is added immediately after the try
Board Question block.
1. State and explain types of errors in Java.
Syntax :
MSBTE : Summer 18, Marks 4
try
4.3 Concept of Exception {
//exception gets generated here
 Exception is an unusual condition that can occur in the
}
program. This condition is caused due to run time error catch(Type_of_Exception e)
in the program. {
 In Java, whenever the exception occurs then it creates //exception is handled here
an exception object and throws it. }

 If the exception object is not caught and handled  If any one statement in the try block generates
properly then the interpreter will display an error exception then remaining statements are skipped and
message. And ultimately the program will terminate. the control is then transferred to the catch statement.
Even though the exception occur and if we want to
Example Program
continue the execution of remaining code then it is
class RunErrDemo
necessary to handle the error condition properly by
{
displaying the appropriate messages. This mechanism public static void main(String[] args)
is called the exception handling mechanism. {
 In Java Exception handling is done with the help of int a,b,c;
various keywords like try, catch, throw and throws. a=10;
b=0;
Exception occurs because the
4.4 try-catch Statement try
{ element is divided by 0.
MSBTE : Summer 15,18, Winter 15,16 17, Marks 8
c=a/b;
} Exception is handled
catch(ArithmeticException e)
using catch block
{
System.out.println("\n Divide by zero");
}
System.out.println("\n The value of a: "+a);
System.out.println("\n The value of b: "+b);
}
}

Output
Divide by zero
Fig. 4.4.1 Exception handling mechanism
 The statements that are likely to cause an exception are The value of a: 10
enclosed within a try block. For these statements the
exception is thrown. The value of b: 0

TM
Technical Publications - An up thrust for knowledge
Java Programming 4-3 Exception Handling and Multithreading

Note that even if the exception occurs at some point, the program does not stop at that point.

Board Questions
1. Define an exception. How it is handled ? MSBTE : Summer 15,Winter 15,16 Marks 4
2. What is exception ? Why the exception occurred in program ? Explain with suitable example.
MSBTE : Winter 17,Marks 8
3. With syntax and example explain try and catch statement. MSBTE : Summer 18, Marks 4

4.5 Nested try Statement


 When there are chances of occurring multiple exceptions of different types by the same set of statements
then such situation can be handled using the nested try statements.
 Following is an example of nested try-catch statements –

Java Program[NestedtryDemo.java]
class NestedtryDemo
{
public static void main (String[] args)
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int ans = 0;

try
{
ans = a / b;
System.out.println("The result is "+ans);
} Inner try-catch Outer try-catch
catch (ArithmeticException e)
{
System.out.println("Divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect type of data");
}
}
}

Output

D:\>javac NestedtryDemo.java

D:\>java NestedtryDemo 20 10
The result is 2

D:\>java NestedtryDemo 20 a Outer catch handles the error


TM
Technical Publications - An up thrust for knowledge
Java Programming 4-4 Exception Handling and Multithreading

Incorrect type of data

D:\>java NestedtryDemo 20 0
Divide by zero Inner catch handles the error

4.6 Throws Statement


MSBTE : Summer 16, Marks 4
 When a method wants to throw an exception then keyword throws is used. The syntax is -
method_name(parameter_list) throws exception_list
{

}
 Let us understand this exception handling mechanism with the help of simple Java program.

Java Program
/* This programs shows the exception handling mechanism using throws
*/
class ExceptionThrows
{
static void fun(int a,int b) throws ArithmeticException
{
int c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Caught exception: "+e);
}
}

public static void main(String args[])


{
int a=5;
fun(a,0);
}
}

Output
Caught exception: java.lang.ArithmeticException: / by zero

Program Explanation:
 In above program the method fun is for handling the exception divide by zero. This is an arithmetic exception
hence we write
static void fun(int a,int b) throws ArithmeticException
 This method should be of static type. Also note as this method is responsible for handling the exception the
try-catch block should be within fun.
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-5 Exception Handling and Multithreading

4.8 finally Statement


Board Question MSBTE : Winter 15, 17, Summer 18, Marks 4
1. Describe use of ‘throws’ with suitable example.  Sometimes because of execution of try block the
MSBTE : Summer 16, Marks 4
execution gets break off. And due to this some
4.7 Using Throw important code (which comes after throwing off an
exception) may not get executed. That means,
 For explicitly throwing the exception, the keyword
sometimes try block may bring some unwanted things
throw is used. The keyword throw is normally used
to happen.
within a method. We can not throw multiple
 The finally block provides the assurance of execution
exceptions using throw.
of some important code that must be executed after the
 Java Programming Example try block.
class ExceptionThrow
{
 Eventhough there is any exception in the try block the
static void fun(int a,int b) statements assured by finally block are sure to execute.
{ These statements are sometimes called as clean up
int c; code. The syntax of finally block is
if(b==0) finally
throw new ArithmeticException("Divide By Zero!!!"); {
else //clean up code that has to be executed finally
c=a/b; }
}
 The finally block always executes. The finally block is
public static void main(String args[])
{ to free the resources.
int a=5; Java Program [finallyDemo.java]
fun(a,0); /*
} This is a java program which shows the use of finally block
} for handling exception
*/
Output
class finallyDemo
Exception in thread "main" {
java.lang.ArithmeticException: Divide By Zero!!! public static void main(String args[])
at ExceptionThrow.fun(ExceptionThrow.java:7) {
at ExceptionThrow.main(ExceptionThrow.java:14) int a=10,b=-1;
 Difference between throw and throws try
{
Sr. Throw Throws b=a/0;
No. }
catch(ArithmeticException e)
1 For explicitly throwing the For declaring the
{
exception, the keyword exception the keyword
System.out.println("In catch block: "+e);
throw is used. throws is used. }
2 Throw is followed by Throws is followed by finally
{
instance. exception class.
if(b!=-1)
3 Throw is used within the Throw is used with System.out.println("Finally block executes without
method. method signature. occurrence of exception");
else
4 We cannot throw multiple It is possible to declare
System.out.println("Finally block executes on occurrence
exceptions. multiple exceptions of exception");
using throws. }

TM
Technical Publications - An up thrust for knowledge
Java Programming 4-6 Exception Handling and Multithreading

}
} IOException When an illegal
input/output operation
Output
In catch block: java.lang.ArithmeticException: / by zero is performed then this
Finally block executes on occurrence of exception exception is raised.

Program Explanation IndexOutOfBoundsException An index when gets out


 In above program, on occurrence of exception in try of bound ,this
block the control goes to catch block, the exception of exception will be
instance ArithmeticException gets caught. This is caused.
divide by zero exception and therefore / by zero will
ArrayIndexOutOfBoundsException Array index when gets
be printed as output. Following are the rules for using
out of bound,
try, catch and finally block
this exception will be
1. There should be some preceding try block for catch
caused.
or finally block. Only catch block or only finally
block without preceding try block is not at all ArrayStoreException When a wrong object is
possible. stored in an array this
2. There can be zero or more catch blocks for each try exception must occur.
block but there must be single finally block present
at the end. EmptyStackException An attempt to pop the
element from empty
Board Questions stack is made then this
1. Define throws and finally statements with its syntax exception occurs
and example. MSBTE : Summer 18, Marks 4
2. Explain the following clause w.r.t. exception NumberFormatException When we try to convert
handling : an invalid string to
(i) try (ii) catch number this exception
(iii) throw (iv) finall MSBTE : Winter 15, Marks 4 gets caused.
3. What is the use of try catch and finally statement
give example. MSBTE : Winter-17,Marks 4 RuntimeException To show general run

4.9 Built in Exception time error this


exception must be
 Various common exception types and causes are
raised.
enlisted in the following table -
Exception This is the most
Exception Description
general type of
ArithmeticException This is caused by error exception
in Math operations. For
ClassCastException This type of exception
e.g. Divide by zero.
indicates that one tries
NullPointerException Caused when an to cast an object to a
attempt to access an type to which the
object with a Null object can not be
reference is made. casted.
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-7 Exception Handling and Multithreading

if(b==0)
IllegalStateException This exception shows {
that a method has been ArithmeticException ex = new
invoked at an illegal or ArithmeticException("This is arithmetic exception");
ex.initCause( new IOException(" is cause") );
inappropriate time.
throw ex;
That means when Java }
environment or Java else
application is not in an {
System.out.println(a/b);
appropriate state then
}
the method is invoked. }
public static void main(String[] args)
4.10 Chained Exception {
Chained exception is a newly added feature in Java. It try
{
allows to relate one exception with other exception. That
divide(100, 0);
means using one exception we can obtain the cause of }
other exception. catch(ArithmeticException ex) {
System.out.println( "caught : " +ex);
For example - When we perform division operation a/b
System.out.println("actual cause: "+ex.getCause());
and if value of b is 0 then we get divide by zero }
execution. This execution is normally thrown as }
“ArithmeticException”. But actual cause of this }
exception is wrong input value to variable b. That means Output
the cause is actually IOException. caught : java.lang.ArithmeticException: This is arithmetic
exception
The chained exception is used to handle this kind of
actual cause: java.io.IOException: is cause
situation.
There are two important constructors used to support 4.11 Creating Own Exception Subclasses
MSBTE : Summer 15,16, 17, Winter 15, 16, 17, Marks 8
chained exception
1) Throwable(Throwable cause)  We can throw our own exceptions using the keyword
throw.
2) Throwable(String str, Throwable cause)
 The syntax for throwing out own exception is -
The cause specifies the actual cause of exception. The str
throw new Throwable’s subclass
is a exception description string.
 Here the Throwable’s subclass is actually a subclass
There are two important methods used in chained
derived from the Exception class.
exception -
getCause(): this method returns actual cause associated For example -
throw new ArithmeticException();
with current exception.
initCause() this method sets underlying cause (exception)
with invoking exception. Throwable’s subclass
 Let us see a simple Java program which illustrates this
Example Program
import java.io.IOException;
concept.
public class ChainedException
Java Program[MyExceptDemo.java]
{
import java.lang.Exception;
public static void divide(int a, int b)
class MyOwnException extends Exception
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 4-8 Exception Handling and Multithreading

{  At the end the finally block gets executed.


MyOwnException(String msg)
{ Example 4.11.1 : What is exception ? WAP to accept a
password from the user and throw “Authentication Failure”
super(msg);
exception if the password is incorrect.
} MSBTE : Winter 15, Summer 17, Marks 8
} Solution :
class MyExceptDemo
{ Exception is an unusual condition that can occur in the
public static void main (String args []) program. This condition is caused due to run time error in
{
the program.
int age;
import java.lang.Exception;
age=15;
import java.util.Scanner;
try
class MyOwnException extends Exception
{
{
if(age<21)
MyOwnException(String msg)
throw new MyOwnException("Your age is very less
than the condition"); {
super(msg);
} }
catch (MyOwnException e) }
{ class MyExceptDemo1
System.out.println ("This is My Exception block"); {
System.out.println (e.getMessage()); public static void main (String args [])
} {
finally System.out.println("Enter your Password");
{ Scanner in=new Scanner(System.in);
System.out.println ("Finally block:End of the String password=in.next();
program"); try
} {
} if(!password.equals("ABC123"))
} throw new MyOwnException("Authentication
Failure!!!");
Output else
This is My Exception block System.out.println("Welcome User");
Your age is very less than the condition
Finally block:End of the program }
catch (MyOwnException e)
Program Explanation {
 In above code, the age value is 15 and in the try block System.out.println (e.getMessage());
- the if condition throws the exception if the value is }
}
less than 21. As soon as the exception is thrown the
}
catch block gets executed. Hence as an output we get
Output
the first message “This is My Exception block”. Then
the control is transferred to the class (Run1)
D:\MSBTE_JAVA _Programs> javac MyExceptDemo1.java
MyOwnException(defined at the top of the program).
D:\MSBTE_JAVA _Programs> java MyExceptDemo1
The message is set and it is “Your age is very less than Enter your Password
the condition”. This message can then printed by the abcd123
catch block using the System.out.println statement by Authentication Failure!!!
means of e.message.

TM
Technical Publications - An up thrust for knowledge
Java Programming 4-9 Exception Handling and Multithreading

(Run2) import java.util.Scanner;


D:\MSBTE_JAVA _Programs> javac MyExceptDemo1.java class NoMatchException extends Exception
D:\MSBTE_JAVA _Programs> java MyExceptDemo1 {
Enter your Password NoMatchException(String msg)
ABC123 {
Welcome User super(msg);
}
Example 4.11.2 : Write a program to input name and age of }
a person and throws an user define exception if entered age is
class MyExceptDemo2
negative.
MSBTE : Summer 15,16, Marks 8 {
public static void main (String args [])
Solution :
{
import java.lang.Exception; System.out.println("Enter your String");
import java.util.Scanner; Scanner in=new Scanner(System.in);
class AgeException extends Exception String str=in.next();
{ try
AgeException(String msg) {
{ if(!str.equals("MSBTE"))
super(msg); throw new NoMatchException("Wrong Input!!!");
} else
} System.out.println("Welcome");
class MyExceptDemo3
{ }
public static void main (String args []) catch (NoMatchException e)
{ {
System.out.print("Enter your age: "); System.out.println (e.getMessage());
Scanner in=new Scanner(System.in); }
int age=in.nextInt(); }
try }
{
if(age<0) Output
throw new AgeException("Negative Age!!!"); Enter your String
else computer
Wrong Input!!!
System.out.println("Correct Age");
Example 4.11.4 : Write a program to input name and balance
} of customer and throw an user defined exception if balance less
catch (AgeException e) than 1500.
{ MSBTE : Winter 17,Marks 4
System.out.println (e.getMessage()); Solution :
} import java.lang.Exception;
} import java.util.Scanner;
} class BalanceException extends Exception
Output {
Enter your age: -10 BalanceException(String msg)
Negative Age!!! {
Example 4.11.3 : Define an exception called ‘No match super(msg);
Exception’ that is thrown when a string is not equal to }
“MSBTE”. Write program. }
MSBTE : Winter 16, Marks 8 class MyExceptDemo4
Solution : {
import java.lang.Exception; public static void main (String args [])

TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 10 Exception Handling and Multithreading

{ o sing runnable interface.


Scanner in=new Scanner(System.in);
System.out.print("Enter Name: ");
String Name=in.next();
System.out.print("Enter Balance: ");
int balance=in.nextInt();
try
{
if(balance<1500)
throw new BalanceException(Name+" is Not
Having Sufficient Balance");
else
System.out.println("Sufficient Balance");
}
catch (BalanceException e) Fig. 4.13.1 : Creation of Java thread
{
System.out.println (e.getMessage());
As given in Fig. 4.13.1, there are two methods by which
} we can write the Java thread programs one is by
} extending thread class and the other is by implementing
}
Output the Runnable interface.
Enter Name: Rupali
 The run() method is the most important method in any
Enter Balance: 1000
Rupali is Not Having Sufficient Balance threading program. By using this method the thread's
behaviour can be implemented. The run method can be
Part II : Multithreading written as follows -
public void run()
4.12 Concept of Multithreading {
//statements for implementing thread
 One of the exciting features of Windows operating
}
system is that - It allows the user to handle multiple
For invoking the thread's run method the object of a
tasks together. This facility in Windows operating
system is called multitasking. thread is required. This object can be obtained by creating
 In Java we can write the programs that perform and initiating a thread using the start() method.
multitasking using the multithreading concept. Thus Extending Thread Class
Java allows to have multiple control flows in a single
 The Thread class can be used to create a thread.
program by means of multithreading.
 Using the extend keyword your class extends the
 Definition of thread : Thread is a tiny program
Thread class for creation of thread. For example if I
running continuously. It is sometimes called as light-
have a class named A then it can be written as
weight process. But there lies differences between
thread and process. class A extends Thread

 Constructor of Thread Class : Following are various


4.13 Creating a Thread
MSBTE : Winter 16, 17, Summer 17, 18, Marks 8
syntaxes used for writing the constructor of Thread
Class.
 In Java we can implement the thread programs using
Thread()
two approaches -
Thread(String s)
o Using Thread class Thread(Runnable obj)
Thread(Runnable obj, String s);
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 11 Exception Handling and Multithreading

 Various commonly used methods during thread Program Explanation :


programming are as given below – In above program,
Method Purpose 1) We have created two classes.
2) One class named MyThread extends the Thread
start() The thread can be started and invokes the run
class. In this class the run method is defined.
method.
2) This run method is called by t.start() in main()
run() Once thread is started it executes in run method. method of another class ThreadProg
setName() We can give the name to a thread using this 3) The thread gets created and executes by displaying the
method. message “Thread is created!!!”

getName() The name of the thread can be obtained using Implementing Runnable Interface

this name.  The thread can also be created using Runnable


interface.
join() This method waits for thread to end
 Implementing thread program using Runnable
Following program shows how to create a single thread interface is preferable than implementing it by
by extending Thread Class. extending the thread class because of the following
Java Program two reasons -
class MyThread extends Thread 1. If a class extends a thread class then it can not
{ extends any other class which may be required to
public void run()
extend.
{
System.out.println("Thread is created!!!"); 2. If a class thread is extended then all its
} functionalities get inherited. This is an expensive
} operation.
class ThreadProg
{  Following Java program shows how to implement
public static void main(String args[]) Runnable interface for creating a single thread.
{
MyThread t=new MyThread(); Java Program
t.start(); class MyThread implements Runnable
} {
} public void run()
{
Output System.out.println("Thread is created!");
}
}
class ThreadProgRunn
{
public static void main(String args[])
{
MyThread obj=new MyThread();
Thread t=new Thread(obj);
t.start();
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 12 Exception Handling and Multithreading

Output }
}
class B extends Thread
{
public void run()
{
System.out.println("Odd Numbers Thread!!!");
try{
for(int i=1;i<=20;i++)
{
if(i%2!=0)
System.out.println(i);
Thread.sleep(500);
}
Program Explanation : }catch(InterruptedException e){}
 In above program, we have used interface Runnable. }
}
 While using the interface, it is necessary to use
class TwoThreads
implements keyword. {
 Inside the main method public static void main(String args[])
{
1. Create the instance of class MyClass.
A t1=new A();
2. This instance is passed as a parameter to Thread t1.start();
class. try {
t1.join();// This is for execution of second thread
3. Using the instance of class Thread invoke the
//only after execution of first thread completely
start method. }catch(InterruptedException e){}
4. The start method in-turn calls the run method B t2=new B();
written in MyClass. t2.start();
}
 The run method executes and display the message for }
thread creation.
Output
Example 4.13.1 : Write a program to create two thread one to Even Numbers Thread!!!
print odd number only and other to print even numbers. 2
MSBTE : Winter 17,Marks 4
4
Solution : 6
class A extends Thread 8
{ 10
public void run() 12
{ 14
int n,m=0,flag=0; 16
System.out.println("Even Numbers Thread!!!"); 18
try { 20
for(int i=1;i<=20;i++) Odd Numbers Thread!!!
{ 1
if(i%2==0) 3
System.out.println(i); 5
Thread.sleep(500); 7
} 9
}catch(InterruptedException e){} 11
13

TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 13 Exception Handling and Multithreading

15 t1.join();// This is for execution of second thread


17 //only after execution of first thread completely
19 }catch(InterruptedException e){}
B t2=new B();
Example 4.13.2 : Write a program to define two thread one
to print from 1 to 100 and other to print from 100 to 1. First t2.start();
thread transfer control to second thread after delay of 500 ms. }
MSBTE : Winter 17,Marks 8 }
OR Write a program to create two threads, one to print Output
numbers in original order and other in reverse order from 1 to
Normal Order Thread!!!
10.
MSBTE : Summer 17, Marks 8 1 2 3 4 5 6 7 8 9 10
Reverse OrderThread!!!
Solution : 10 9 8 7 6 5 4 3 2 1
class A extends Thread
{ Board Question
public void run() 1. Write a java program to implement runnable
{ interface with example.
int n,m=0,flag=0; MSBTE : Winter 16, Summer 18, Marks 8
System.out.println("Normal Order Thread!!!");
try { 4.14 Life Cycle of Thread
for(int i=1;i<=10;i++) // for 100 number change MSBTE : Summer 15, 16, 17, 18, Marks 8
// 10 by 100 Thread is life cycle specifies how a thread gets processed
{
in the Java program. By executing various methods.
System.out.print(" "+i);
Thread.sleep(500); Following figure represents how a particular thread can
} be in one of the state at any time.
}catch(InterruptedException e){}

}
}
class B extends Thread
{
public void run()
{
System.out.println("\nReverse OrderThread!!!");
try{
for(int i=10;i>=1;i--)// for 100 number change
// 10 by 100 Fig. 4.14.1 Life cycle of thread
{
New state
System.out.print(" "+i);
Thread.sleep(500);  When a thread starts its life cycle it enters in the new
} state or a create state.
}catch(InterruptedException e){}
} Runnable state
}
 This is a state in which a thread starts executing.
class TwoThreads
{  Waiting state
public static void main(String args[])  Sometimes one thread has to undergo in waiting state
{
because another thread starts executing.
A t1=new A();
t1.start();
try {
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 14 Exception Handling and Multithreading

Timed waiting state try {


//statement causing exception
 There is a provision to keep a particular threading }
waiting for some time interval. This allows to execute catch(InterruptedException e)
high prioritized threads first. After the timing gets {
over, the thread in waiting state enters in runnable …
… //can not handle in current state
state.

}
Blocked state
catch(IllegalArgumentException e)
 When a particular thread issues an Input/Output {
request then operating system sends it in blocked state … //Illegal Method argument
until the I/O operation gets completed. After the I/O }
catch(Exception e)
completion the thread is sent back to the runnable
{
state. … //some general type of exception
}
Terminated state
 After successful completion of the execution the thread 4.16 Thread Priority and Methods
in runnable state enters the terminated state. MSBTE : Summer 15, 16,17, Marks 8
In Java threads scheduler selects the threads using their
Board Questions
priorities. The thread priority is a simple integer value
1. With suitable diagram explain life cycle of Thread.
that can be assigned to the particular thread. These
MSBTE : Summer 15, Marks 8
priorities can range from 1 (lowest priority) to 10 (highest
2. Describe life cycle of thread.
MSBTE : Summer 16, Marks 4
priority).
3. What is thread ? Draw thread life cycle diagram in There are two commonly used functionalities in thread
Java. scheduling -
MSBTE : Summer 17, Marks 4  setPriority
4. With proper syntax and example explain following
 getPriority
thread methods :
The function setPriority is used to set the priority to each
(1) wait( ) (2) sleep( )
thread
(3) resume( ) (4) notify( )
MSBTE : Summer 18, Marks 4 Thread_Name.setPriority(priority_val);
The priority_val is a constant value denoting the priority
4.15 Thread Exceptions
for the thread. It is defined as follows -
 When we use sleep() method during thread MAX_PRIORITY = 10
programming, then we must enclose this sleep()
MIN_PRIORITY = 1
method within a try block because sleep method
NORM_ PRIORITY = 5
throws an exception.
The function getPriority is used to get the priority of the
 Java will throw IllegalThreadStateException whenever
thread.
we attempt to call a method which cannot be handled
Thread_Name.getPriority();
by thread.
 Various types of exceptions that can be used during Preemption

thread execution can be denoted by sample try…catch Preemption is a situation in which when the currently
block executed thread is suspended temporarily by the highest
priority thread.
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 15 Exception Handling and Multithreading

B: 1
The highest priority thread always preempts the lowest
B: 2 Thread 2 preempts the
priority thread. B: 3 execution of thread 1
Let us see the illustration of thread prioritizing with the B: 4
help of following example - B: 5
-----End of Thread#2-------
Java program[Thread_PR_Prog.java] A: 1
class A extends Thread A: 2
Then Thread 1 continues
{ A: 3
A: 4 its execution
public void run()
{ A: 5
System.out.println("Thread #1");
for(int i=1;i<=5;i++) -----End of Thread#1-------
{
System.out.println("\tA: "+i); Program explanation
} In above program
System.out.println("\n-----End of Thread#1-------");
1) We have created two threads - the Thread#1 and
}
}
Thread#2.
class B extends Thread 2) We assign highest priority to Thread#2.
{
3) In the main function both the threads are started but as
public void run()
{
the Thread#2 has higher priority than the thread#1, the
System.out.println("Thread #2"); Thread#2 preempts the execution of Thread#1. Thus
for(int k=1;k<=5;k++) Thread#2 completes its execution and then Thread#1
{ completes.
System.out.println("\tB: "+k);
} Board Questions
System.out.println("\n-----End of Thread#2-------");
1. Explain thread priority and method to get and set
}
priority values.
}
MSBTE : Summer 15, Marks 4
class Thread_PR_Prog
{ 2. What is thread priority ? How thread priority are
public static void main(String[] args) set and changed ? Explain with example.
{ MSBTE : Summer 16, Marks 8
A obj1=new A(); 3. What is thread priority ? Write default priority
B obj2=new B(); values and methods to change them.
obj1.setPriority(1); MSBTE : Summer 17, Marks 4
obj2.setPriority(10);//highest priority
System.out.println("Strating Thread#1"); 4.17 Synchronization
obj1.start(); MSBTE : Winter 16, Marks 4
System.out.println("Strating Thread#2");
 When two or more threads need to access shared
obj2.start();
}
memory, then there is some way to ensure that the
} access to the resource will be by only one thread at a
time. The process of ensuring one access at a time by
Output
Strating Thread#1 one thread is called synchronization. The
Strating Thread#2 Thread 1 and synchronization is the concept which is based on
Thread #1 Thread 2 starts monitor. Monitor is used as mutually exclusive lock or
Thread #2
mutex. When a thread owns this monitor at a time then

TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 16 Exception Handling and Multithreading

the other threads can not access the resources. Other }


public void run()
threads have to be there in waiting state.
{
 In Java every object has implicit monitor associated th2.display(100);
with it. For entering in object's monitor, the method is }
associated with a keyword synchronized. When a }
class MySynThread
particular method is in synchronized state then all {
other threads have to be there in waiting state. public static void main(String args[])
 There are two ways to achieve the synchronization - {
Test obj=new Test();
1. Using Synchronized Methods A t1=new A(obj);
2. Using Synchronized Blocks (Statements). B t2=new B(obj);
Let us make the method synchronized to achieve the t1.start();
t2.start();
synchronization by using following Java program - }
}
1. Using Synchronized Method
class Test
{ Output
This is a
synchronized void display(int num)
{ synchronized
System.out.println("\nTable for "+num); method
for(int i=1;i<=10;i++)
{
System.out.print(" "+num*i);
}
System.out.print("\nEnd of Table");
try
{
Thread.sleep(1000);
}catch(Exception e){}
} Program Explanation :
}
 In above program we have written one class named
class A extends Thread
{
Test. Inside this class the synchronized method named
Test th1; display is written. This method displays the table of
A(Test t) numbers.
{
 We have written two more classes named A and B for
th1=t;
} executing the thread. The constructors for class A and
public void run() Class B are written and to initialize the instance
{ variables of class Test as th1 (as a variable for class
th1.display(2);
A)and th2(as a variable for class B)
}
}  Inside the run methods of these classes we have
class B extends Thread passed number 2 and 10 respectively and display
{ method is invoked.
Test th2;
B(Test t)
 The display method executes firstly for thread t1 and
{ then for t2 in synchronized manner.
th2=t;
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 17 Exception Handling and Multithreading

2. Using Synchronized Block class B extends Thread


{
 When we want to achieve synchronization using the Test th2;
synchronized block then create a block of code and B(Test t)
mark it as synchronized. {
th2=t;
 Synchronized statements must specify the object that
}
provides the intrinsic lock. public void run()
{
Syntax
th2.display(100);
The syntax for using the synchronized block is - }
synchronized(object reference ) }
{ class MySynThreadBlock
statement; {
statement; //block of code to be synchronized public static void main(String args[])
. {
. Test obj=new Test();
. A t1=new A(obj);
} B t2=new B(obj);
t1.start();
Java Program t2.start();
class Test }
{ }
void display(int num)
Output
{
synchronized(this)
{
System.out.println("\nTable for "+num);
for(int i=1;i<=10;i++)
{ This is a
System.out.print(" "+num*i); synchronized
} Block
System.out.print("\nEnd of Table");
try
{
Thread.sleep(1000);
}catch(Exception e){} Board Question
}
1. What is synchronization ? When do we use it ?
}
Explain synchronization of two threads.
}
MSBTE : Winter 16, Marks 4
class A extends Thread
{ 4.18 Interthread Communication
Test th1;
A(Test t)  Two or more threads communicate with each other by
{ exchanging the messages. This mechanism is called
th1=t; interthread communication.
}
public void run()  Polling is a mechanism generally implemented in a
{ loop in which certain condition is repeatedly checked.
th1.display(2);  To better understand the concept of polling, consider
}
producer-consumer problem in which producer thread
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 18 Exception Handling and Multithreading

produces and the consumer thread consumes whatever public static Object obj1 = new Object();
public static Object obj2 = new Object();
is produced.
 Both must work in co-ordination to avoid wastage of private static class A extends Thread
CPU cycles. {
public void run()
 But there are situations in which the producer has to
{
wait for the consumer to finish consuming of data. synchronized (obj1)
Similarly the consumer may need to wait for the {
producer to produce the data. System.out.println("Thread 1: Holding object1...");
try
 In Polling system either consumer will waste many {
CPU cycles when waiting for producer to produce or Thread.sleep(10);
the producer will waste CPU cycles when waiting for }
the consumer to consume the data. catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for
 In order to avoid polling there are three in-built object2...");
methods that take part in inter-thread communication -
synchronized (obj2)
notify() If a particular thread is in the sleep mode then
{
that thread can be resumed using the notify System.out.println("Thread 1: Holding
call. object1 and object2...");
}
notifyall() This method resumes all the threads that are in }
suspended state. }
}
wait() The calling thread can be send into a sleep
private static class B extends Thread
mode. {
public void run()
4.19 Deadlock {
Deadlock is a situation in which two or more threads are synchronized (obj2)
{
waiting for object lock which is hold by some another
System.out.println("Thread 2: Holding object2...");
thread. try
For example - Consider thread A is waiting for object {
obj2 which is locked by thread B and thread B is waiting Thread.sleep(10);
}
for object obj1 which is locked by thread A. This situation
catch (InterruptedException e) {}
is described as deadlock. System.out.println("Thread 2: Waiting for
object1...");

synchronized (obj1)
{
System.out.println("Thread 2: Holding object1
and object2...");
Fig. 4.19.1 : Deadlock }
}
Following Java program shows the deadlock situation }
}
Java Program[DeadLockDemo.java]
public static void main(String args[])
public class DeadLockDemo
{
{
A T1 = new A();
TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 19 Exception Handling and Multithreading

B T2 = new B(); Thread 2: Waiting for object1...


T1.start(); The above program will hang forever because neither of
T2.start(); the threads in position to proceed and waiting for each
} other to release the lock.
} If we simply change the order of the objects lock then one
can come out of the above situation.
Output
Thread 1: Holding object1...
Thread 2: Holding object2... 
Thread 1: Waiting for object2...

TM
Technical Publications - An up thrust for knowledge
Java Programming 4 - 20 Exception Handling and Multithreading

Notes

TM
Technical Publications - An up thrust for knowledge
Java Programming 5-1 Java Applets and Graphics Programming

UNIT - V

5 Java Applets and Graphics


Programming

Difference between Applet and Application

Part I : Java Applets Sr. Applets Applications


No.
5.1 Concept of Applet
MSBTE : Summer 15,17 Marks 4 1. Applets do not have Application programs
 Applets are the small Java programs that can be used main method. On have main method.
in internetworking environment. loading of applets some Within the main method
 These programs can be transferred over the internet methods of applet class the call to another
from one computer to another and can be displayed on get called automatically. methods of Java class is
various web browsers. given.
 Various applications of applets are in performing 2. Applets cannot run Applications program run
arithmetic operations, displaying graphics, playing
independently. They can independently.
sounds, creating animation and so on.
be either embedded in
 Following are the situations in which we need to use
web page or can be run
applet -
using appletviewer.
1. For displaying the dynamic web pages we need an
3. Applets cannot be read Application programs
applet. The dynamic web page is a kind of web
from file. Similarly make use of I/O functions
page on which the contents are constantly
appletscan not write to and can read a file or
changing. For example an applet that can represent
files. write to file.
the sorting process of some numbers. During the
process of sorting the positions of all the elements 4. Applets cannot Java programs can
communicate with others communicate with other
is changing continuously.
on the network. programs in distributed
2. If we want some special effects such as sound,
environment.
animation and much more then the applets are
used. 5. Applets cannot execute Applications can execute
any program on local a program on local
3. If we want that the particular application should be
computer. computer.
used by any user who might be located remotely .
Then in such situation the applets are embedded Board Question
into the web pages and can be transferred over the 1. Differentiate applet and application with any four
points. MSBTE : Summer 15,17 Marks 4
internet.

TM
Technical Publications (5 --An
1) up thrust for knowledge
Java Programming 5-2 Java Applets and Graphics Programming

5.2 Applet Life Cycle 2. Running state


MSBTE : Summer 15, 17, 18, Winter 16, 15, Marks 8
When the applet enters in the running state, it invokes the
There are various methods which are typically used in start( ) method of Applet class.
applet for initialization and termination purpose. These
This method is called only after the init method. After
methods are
stopping the applet when we restart the applet at that time
1. Initialization
also this method is invoked. The syntax can be
2. Running state
public void start()
3. Idle state {
4. Dead or destroyed state (Refer Fig. 5.2.1 for applet’s …
life cycle) }

3. Display state
Applet enters in the display state when it wants to display
some output. This may happen when applet enters in the
running state. The paint( ) method is for displaying or
drawing the contents on the screen. The syntax is
public void paint(Graphics g)
{

}
Fig. 5.2.1 Applet’s life cycle An instance of Graphics class has to be passed to this
When applet begins, the AWT calls following methods function as an argument. In this method various
in sequence - operations such as display of text, circle, line are invoked.
a) init() b) start() c) paint() 4. Idle state
When applet is terminated following method are invoked This is an idle state in which applet becomes idle. The
in sequence. stop( ) method is invoked when we want to stop the
a) stop() b) destroy() applet. When an applet is running if we go to another
1. Initialization state page then this method is invoked. The syntax is
public void stop()
When applet gets loaded it enters in the initialization
{
state. For this purpose the init( ) method is used. In this …
method you can initialize the required variables. This }
method is called only once initially at the execution of the
program. The syntax can be 5. Dead state
public void init() When applet is said to be dead then it is removed from
{ memory. The method destroy( ) is invoked when we
//initialization of variables
want to terminate applet completely and want to remove it
}
from the memory.
In this method various tasks of initialization can be
public void destroy()
performed such as - {
1. Creation of objects needed by applet …
2. Setting up of initial values }

3. Loading of image It is a good practice to call stop prior to destroy method.


4. Setting up of colors.
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-3 Java Applets and Graphics Programming

Board Questions This is an optional attribute.


1. Describe following states of applet life cycle :
a) Initialization state. b) Running state. HSPACE = pixels When ALIGN is either LEFT or
c) Display state. RIGHT this attribute is used. It
MSBTE : Summer 15, Marks 4
specifies the amount of horizontal
2. Explain applet life cycle with suitable diagram. blank spaces the browser should
MSBTE : Winter 15,Summer 17, Marks 8, Summer 18, Marks 4
leave around the applet. This is an
3. Describe following methods of applet :
optional attribute.
(i) suspend ( ) (ii) resume ( )
(iii) sleep ( ) (iv) notify ( ) VSPACE = pixels When ALIGN is either TOP or
(v) stop ( ) (vi) wait ( ) BOTTOM this attribute is used. It
MSBTE : Winter 16, Marks 6
specifies the amount of vertical
5.3 Applet Tag blank spaces the browser should
MSBTE : Winter 15, Summer 16, 17, 18, Marks 4 leave around the applet. This is an
The <APPLET> tag can be specified with the help of optional attribute.
various attributes. These attributes help to integrate the
applet into overall design of the web page. ALT = alternate text The non Java browser can display

Various attributes of APPLET tag are - the alternate text in place of


applet. This is an optional
Attribute Description attribute.

CODE = The specified applet can be loaded


Board Questions
appletfilename in the web page. This attribute
1. Explain all attributes available in < applet > tag.
must be specified in order to MSBTE : Winter 15, Marks 4
embed the applet in the HTML 2. Explain <applet> tag with its major attributes
file. only.
MSBTE : Summer 16, Marks 4
WIDTH = pixels This attribute specifies the width 3. Describe the following attributes of applet :
HEIGHT = pixels and height of the applet. (i) Codebase (ii) Alt
(iii) Width (iv) Code
ALIGN = alignment This attribute is for specifying the MSBTE : Summer 17, Marks 4
alignment. Various alignments are 4. Explain any four applet tag.
- TOP, BOTTOM, LEFT, RIGHT, MSBTE : Summer 18, Marks 4
MIDDLE, ABSMIDDLE,
5.4 Creating Applet
ABSBOTTOM, TEXTTOP and
BASELINE. This is an optional
 Normally the applet code makes use of two classes -
attribute. Applet and Graphics.
 For the applet class the package java.applet is
CODEBASE = It specifies the name of the required. This class provides the applet’s life cycle
codebase_URL directory in which the applet is method such as init( ), start( ) and paint( ).
stored. This attribute is required  The Graphics class is supported by the package
when the attribute is not there in java.awt.
the current working directory.
 Here is a simple applet.
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-4 Java Applets and Graphics Programming

Example Program passed as an object of class graphics. Therefore an object


/* g of class Graphics is passed.
This is my First Applet program
*/
 Using this object the method drawstring of Graphics
import java.awt.*; class is invoked. [N ote that Graphics class is a part of
import java.applet.*; java.awt package].
public class FirstApplet extends Applet
{ g.drawString("This is my First Applet",50,30);
public void paint(Graphics g) To method drawstring, firstly we have passed a string
{
which we want to be displayed, then 50 and 30 represents
g.drawString("This is my First Applet",50,30);
} the position of the string on the screen i.e. x and y
} positions respectively.
Program Explanation : 5.5 Executing Applet Code
 In above given small applet program, the main MSBTE : Winter 15, Marks 6, Summer 18, Marks 8
intension is to display the message “This is my First There are two methods of executing an applet program -
Applet”. Let us start from the beginning of the 1. Adding Applet to HTML File
program -
2. Using Appletviewer tool
 The first three lines represent a comment statement.
Let us discuss these methods in detail
 Then next comes
import java.awt.*; 5.5.1 Adding Applet to HTML File
import java.applet.*; Following are the steps that need to be followed for
We always need these two packages to be imported in the adding applet to HTML file.
program. The java.awt package consists of java awt Step 1 : Write a Java applet program in a notepad. The
classes. Here awt stands for abstract window toolkit. The code is as follows
AWT provides the support for window based graphical
Java Program[FirstApplet.java]
interface such as for drawing screen, windows, buttons,
/*
text boxes, menus and so on. The other imported package
This is my First Applet program
is java.applet. This is essential because we need to use */
Applet class in our applet program which is included in import java.awt.*;
java.applet package. import java.applet.*;
public class FirstApplet extends Applet
 The functionalities that are required to run applet {
inside the web browser are supported by java.applet. public void paint(Graphics g)
 Then comes {
g.drawString("This is my First Applet",50,30);
public class FirstApplet extends Applet
}
The class FirstApplet is a subclass of class Applet. Hence }
the keyword extends is used. Java requires that your Step 2 :Compile your applet source program using javac
applet subclass (here it is FirstApplet) should be declared compiler, i.e.
as public. Hence is the declaration! D:\test>javac FirstApplet.java
 We have then defined a method Step 3 : Write following code in notepad/wordpad and
public void paint(Graphics g) save it with filename and extension .html. For example
This method is used to paint something on the screen and following code is saved as Exe_FirstApplet.html, The
it can be text, line, circle, rectangle or anything. Thus code is
paint is a method which provides actual appearance on <html>
the screen. And this method requires a parameter to be <body>
<applet code="FirstApplet" width=300 height=100>
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-5 Java Applets and Graphics Programming

</applet>
</body>
</html>
For embedding the applet in the HTML document the <APPLET> tag is used. The <APPLET> tag supplies
the name of the applet to be loaded. Suppose we want to load the applet FirstAppletprogram in the web
page then the applet tag will be
<APPLET CODE= FirstAppletprogram.class
WIDTH = 500
HEIGHT = 300
</APPLET>
The HTML code tells the web browser to load the compiled code of applet FirstAppletprogram.class. Note
that this class file must be present in the same directory where the web page is stored.

Step 4 : Load html file with some web browser, This will cause to execute your html file. It will look like this -

Note this
URL

5.5.2 Embedding Applet Code in Java

We can embed the applet code in Java using comment statements. It is as shown in following illustration.

Step 1 : Write Java Program as given below


/*
This is my First Applet program
*/
import java.awt.*;
import java.applet.*;
Embedded Applet in
/*
Java
<applet code="FirstApplet" width=300 height=100>
</applet>
*/
public class FirstApplet extends Applet
{
public void paint(Graphics g)

TM
Technical Publications - An up thrust for knowledge
Java Programming 5-6 Java Applets and Graphics Programming

{ Output
g.drawString("This is my First Applet",50,30);
}
}
In above code we have added applet code at the beginning
of the program.
<applet code="FirstApplet" width=300 height=100>
</applet>
This will help to understand Java that the source program
is an applet with the name FirstApplet.

Step 2 :By this edition you can run your applet program
5.6 Passing Parameter to Applet
merely by Appletviewer command.
MSBTE : Winter 15, 16,17, Summer 15, 17, 18, Marks 8
D:\test>javac FirstApplet.java
D:\test>Appletviewer FirstApplet.java  Parameters are passed to applets in NAME=VALUE
pairs in <PARAM> tags between the opening and
And we will get
closing APPLET tags.
 There can be any number of <PRAM> tags inside
APPLET tag.
 Inside the applet, you read the values passed through
the PARAM tags with the getParameter( ) method of
the Applet class.
 The program below demonstrates this idea -
Example 5.6.1 : How can parameters be passed to an applet
? Write an applet to accept user name in the form of parameter
Example 5.5.1 : Define applet. Write a program to create an and print ‘Hello < username >’.
applet to display message MSBTE : Winter 15, Marks 8
“Welcome to java applet”. Solution :
MSBTE : Winter 15, Marks 6, Summer 18, Marks 8
Solution : import java.applet.Applet;
import java.awt.Graphics;
FirstApplet.java /*
/* <applet code="WelcomeParam" width=200 height=200>
This is my First Applet program <param name="Username" value="Parth">
*/ </applet>
import java.awt.*; */
import java.applet.*; public class WelcomeParam extends Applet
/* {
<applet code="FirstApplet" width=300 height=100> String msg="";
</applet> public void init()
*/ {
public class FirstApplet extends Applet msg = getParameter("Username");
{ msg = "Welcome " + msg;
public void paint(Graphics g) }
{ public void paint(Graphics g)
g.drawString("Welcome to Java Applet",50,30); {
} g.drawString(msg,50,50);
} }
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5-7 Java Applets and Graphics Programming

Output Output

Example 5.6.3 : Design an applet which accepts username as


a parameter for html page and display number of characters
from it.
MSBTE : Summer 17, Marks 4
Example 5.6.2 : Write an applet program that accepts two Solution :
input, strings using <Param> tag and concatenate the strings
and display it in status window.
MSBTE : Winter 16, Marks 8
Step 1 : Create HTML page as follows -
Solution : test.html
<html>
TwoStrings.java <head>
import java.applet.*; <title> Parameter Demo </title>
import java.awt.*; </head>
<applet code = "LengthDemo.class" width =300 height =300>
<PARAM name="uname" value="Chitra">
/*
</applet>
<APPLET code="TwoStrings" width="300" height="100">
</html>
<PARAM name="str1" value="First">
<PARAM name="str2" value="Second"> Step 2 : Create Java program for the applet class as
</APPLET> follows -
*/ LengthDemo.java
public class TwoStrings extends Applet import java.applet.*;
import java.awt.*;
{
public class LengthDemo extends Applet
{
public void paint(Graphics g) public void paint(Graphics g)
{ {
String str = this.getParameter("uname");
String s1 = this.getParameter("str1"); int len;
String s2 = this.getParameter("str2"); len=str.length();
String msg="The length of string 'Chitra' is: "+len;
String s3;
g.drawString(msg,50,30);
s3=s1+s2;
}
showStatus(s3); }
}
} Step 3 : Compile the program created in step 2 using
following command on command prompt
D:\>javac LengthDemo.java

Step 4 : Open the web browser and type the name of the
html file created in step 1. The output will be -
TM
Technical Publications - An up thrust for knowledge
Java Programming 5-8 Java Applets and Graphics Programming

Board Questions
1. Explain <PARAM> Tag of applet with suitable
example. MSBTE : Summer 15, Marks 6
2. Explain following methods for applet with an
example :
1) Passing parameter to applet
2) Embedding <applet> tags in java code.
MSBTE : Summer 18, Marks 8

5.7 Adding Controls to Applets


Example 5.6.4 : How to pass parameter to an applet ? Write
an applet to accept Account No and balance in form of We can add various controls such as textbox, Push
parameter and print message “low balance” if the balance is Button, Radio button, Check box to the applet. Let us
less than 500. understand this with illustrative examples –
MSBTE : Winter 17,Marks 8
1) Adding Button to the applet
Solution :
The Button class is used to add the labeled button to the
import java.applet.*;
import java.awt.*; applet. The caption of the button is passed as a parameter
to it. The syntax is
/* Button button_object=new Button(caption string)
<APPLET code="BalanceChk" width="300" height="100">
Using add method we can add the button control on the
<PARAM name="AccNo" value=1001>
<PARAM name="Balance" value=300>
applet window. Following program shows how to add
</APPLET> button to the applet.
*/ Example Program
public class BalanceChk extends Applet import java.awt.*;
{ import java.awt.event.*;
public void paint(Graphics g) import java.applet.*;
{ /*
int balance = <applet code="Button1" width=350 height=200>
Integer.parseInt(this.getParameter("Balance")); </applet>
if(balance<500) */
g.drawString("Low Balance",50,30); public class Button1 extends Applet
else {
Button button=new Button("Click Me");
g.drawString("Sufficient Balance",50,30);
public void init()
}
{
}
add(button);
Output }
}

Output

TM
Technical Publications - An up thrust for knowledge
Java Programming 5-9 Java Applets and Graphics Programming

2) Adding Textfield to the applet */


public class CheckBoxDemo extends Applet
The TextField class allows to add the single line text. {
Following program shows how to add a textfield control Checkbox cb1=new Checkbox("Adhar Card",true);
to the applet. Checkbox cb2=new Checkbox("Pan Card");
public void init()
Example Program {
import java.awt.*; add(cb1);
import java.awt.event.*; add(cb2);
import java.applet.*; }
/* }
<applet code="TextFieldDemo" width=350 height=200>
Output
</applet>
*/
public class TextFieldDemo extends Applet
{
TextField tf=new TextField("Hello, How are you?");
public void init()
{
add(tf);
}
}

Output

4) Adding Radio Button to the applet


For creating a radio button style control, the
CheckboxGroup is used. There is no special control for
Radio button. Following program shows how to use
CheckboxGroup to create radio buttons.

Example Program
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="RadioButtonDemo" width=350 height=200>
3) Adding Checkbox to the applet </applet>
*/
The Checkbox class is used to create check boxes. It is public class RadioButtonDemo extends Applet
used to turn an option true or false. Following program {
shows the use of checkbox CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("Male",cbg,false);
Example Program Checkbox cb2=new Checkbox("Female",cbg,true);
import java.awt.*; public void init()
import java.awt.event.*; {
import java.applet.*; add(cb1);
/* add(cb2);
<applet code="CheckBoxDemo" width=350 height=200> }
</applet> }
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 10 Java Applets and Graphics Programming

Output 5.8.1 Graphics Classes

 The hierarchy components classes are -


o Component : This is the super class of all the
graphical classes from which variety of graphical
classes can be derived. It helps in displaying the
graphical object on the screen. It handles the mouse
and keyboard events.
o Container : This is a graphical component derived
from the component class. It is responsible for
managing the layout and placement of graphical
components in the container.
o Window : The top level window without border
Part II : Graphics Programming and without the menu bar is created using the
window class. It decides the layout of the window.
5.8 Introduction to Graphics Programming
o Panel : The panel class is derived from the
MSBTE : Winter 15, 16, 17, Summer 16, 17, Marks 8
container class. It is just similar to window -
 The graphics programming in Java is supported by the
without any border and without any menu bar,
AWT package. The AWT stands for Abstract Window
Toolkit. title bar.

 The AWT contains large number of classes which help o Frame : This is a top-level window with a border

to include various graphical components in the Java and menu bar. It supports the common window
program. These graphical components include text events such as window open, close, activate and
box, buttons, labels, radio buttons, list items and so on. deactivate.
We need to import java.awt package for using these o The co-ordinate system of Java can be represented
components.
by following Fig. 5.8.2.
 These classes are arranged in hierarchical manner
which is recognised as AWT hierarchy. (Refer
Fig. 5.8.1)

Fig. 5.8.1 AWT hierarchy


TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 11 Java Applets and Graphics Programming

Fig. 5.8.2 Co-ordinate system

5.8.2 Lines

 Drawing the line is the simplest thing in Java. The syntax is,
void drawLine(int x1,int y1,int x2,int y2);
Where x1 and y1 represents the starting point of the line and x2 and y2 represents the ending point of the line.

Fig. 5.8.3 Line


Example Program
import java.awt.*;
import java.applet.*;
/*
<applet code="LineDemo" width=310 height=200>
</applet>
*/
public class LineDemo extends Applet
{
public void paint(Graphics g)
{
g.drawLine(0,0,200,100);//diagonal line from top-left
g.drawLine(0,100,100,0);//another diagonal line
g.drawString("Its a Line Demo",50,80);
}
}

Output

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 12 Java Applets and Graphics Programming

Output
5.8.3 Rectangles
In Java we can draw two types of rectangles : Normal
rectangle and the rectangle with round corners. The
syntax of these methods are -
void drawRect(int top,int left,int width,int height)
void drawRoundRect(int top,int left,int width,int height,int
xdimeter,int ydimeter)

For example

Example 5.8.1 : Design an applet which display equals size


three rectangle one below the other and fill them with orange,
white and green color respectively.
MSBTE : Winter 17,Marks 6
Solution :
import java.awt.*;
import java.applet.*;
/*
<applet code="RectangleDemo1" width=300 height=200>
Fig. 5.8.4 Rectangle </applet>
The rectangle can be filled up with following methods, */
void fillRect(int top,int left,int width,int height) public class RectangleDemo1 extends Applet
void fillRoundRect(int top,int left,int width,int height,int {
xdimeter,int ydimeter) public void paint(Graphics g)
{
Example Program[RectangleDemo.java] g.setColor(Color.ORANGE);
import java.awt.*; g.fillRect(10,10,50,50);
g.setColor(Color.WHITE);
import java.applet.*;
g.fillRect(10,50,50,50);
/*
g.setColor(Color.GREEN);
<applet code="RectangleDemo" width=310 height=200> g.fillRect(10,90,50,50);
</applet>
*/ }
public class RectangleDemo extends Applet }
{ Output
public void paint(Graphics g)
{
g.drawRect(10,10,50,50);
g.drawRoundRect(70,30,50,30,10,10);
g.fillRect(40,100,150,100);
g.fillRoundRect(200,10,70,100,10,10);
g.drawString("Its a Rectangle Demo",30,90);
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 13 Java Applets and Graphics Programming

5.8.4 Ellipse and Circle Output


To draw circle and ellipse we can use the function
drawOval( ) method. The syntax of this method is ,
void drawOval(int top, int left, int width, int height)
To fill this oval we use fillOval( ) method. The syntax of
this method is,
void fillOval(int top, int left, int width, int height)
We can specify the color for filling up the rectangle using
setColor method. For example
g.drawOval(10,10,200,100);
g.setColor(Color.blue);
g.fillOval(30,50,200,100);
Example 5.8.2 : Write a program to design an applet to
The top and left values specify the upper left corner and display three circles filled with three different colors on screen.
width and height is for specifying the width and heights MSBTE : Winter 15, Marks 4
Solution :
respectively.
import java.applet.*;
import java.awt.*;
/*
<applet code = "ThreeColorCircles.class" width =300 height
=300>
</applet>
*/
public class ThreeColorCircles extends Applet
{
Fig. 5.8.5 Ellipse public void paint(Graphics g)
{
Let us understand the functioning of these methods with g.setColor(Color.red);
the help of some example g.fillOval(50,50,50,50);
g.setColor(Color.blue);
Java Program[ovalDemo.java] g.fillOval(100,50,50,50);
import java.awt.*; g.setColor(Color.green);
g.fillOval(150,50,50,50);
import java.applet.*;
/* }
<applet code="ovalDemo" width=310 height=200>
</applet> }
*/ Output
public class ovalDemo extends Applet
{
public void paint(Graphics g)
{
g.drawOval(10,10,50,50);
g.fillOval(200,10,70,100);
g.drawString("Its a Circle and Oval Demo",40,90);
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 14 Java Applets and Graphics Programming

Example 5.8.3 : Write a simple applet program which display


three concentric circle.
MSBTE : Summer 16, Marks 8
Solution :
Three Circles.Java
import java.applet.*;
import java.awt.*;
/*
<applet code = "ThreeCircles.class" width =300 height
=300>
</applet> Fig. 5.8.6
*/
public class ThreeCircles extends Applet Java Program[arcDemo.java]
{ import java.awt.*;
public void paint(Graphics g) import java.applet.*;
{ /*
g.drawOval(50,50,100,100);//outermost circle <applet code="arcDemo" width=310 height=200>
g.drawOval(40,40,120,120);//middle circle </applet>
g.drawOval(30,30,140,140);//innermost circle */
} public class arcDemo extends Applet
} {
public void paint(Graphics g)
Output {
g.drawArc(100,60,100,100,0,90);
g.setColor(Color.green);//fills the arc with green
g.fillArc(100,60,55,70,0,90);
g.setColor(Color.black);
g.drawArc(100,100,70,90,0,270);
g.drawString("Its an arch Demo",120,160);
}
}

Output

5.8.5 Arcs

To draw an arc the drawArc( ) and to fill an arc fillArc( )


are the functions. The syntax of these methods is as
follows -
void drawArc(int top,int left,int width,int height,int angle1,int
angle2)
void fillArc(int top,int left,int width,int height,int angle1,int
angle2) Example 5.8.4 : Write an applet to display smiley face.
The angle1 represents the starting angle and the angle2 Solution :
represents the angular distance. import java.awt.*;
import java.applet.*;
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 15 Java Applets and Graphics Programming

/*
/*<applet code=smiley.class height=300 <applet code="Polyg" width=310 height=200>
width=300></applet>*/ </applet>
public class smiley extends Applet */
{
public void paint(Graphics g) public class Polyg extends Applet
{ {
g.drawOval(20,40,250,250); public void paint(Graphics g)
g.drawOval(70,100,50,50); {
g.drawOval(180,100,50,50); int xpt[]={50,20,20,20,130};
g.drawArc(100,150,100,100,180,180); int ypt[]={80,30,200,200,30};
}
} int num=5;
g.drawPolygon(xpt,ypt,num);
Output
g.setColor(Color.magenta);
g.fillPolygon(xpt,ypt,num);
g.setColor(Color.black);
g.drawString("Its a polygon Demo",100,100);
}
}

Output

5.8.6 Polygons

In order to draw polygons following function is used


Polygon(int[ ] xpoints,int[ ] ypoints,int npoints)
The xpoints represent the array of x co-ordinates. The
ypoints represent the array of y co-ordinates. And the
npoints represents the number of points.
For filling up the polygon the fillPolygon method is used. Example 5.8.5 : Write java program to display triangle filled
with red colour.
MSBTE : Winter 16, Marks 4
Solution :
import java.awt.*;
import java.applet.*;
/*
<applet code="TriangleDemo" width=200 height=200>
</applet>
*/

public class TriangleDemo extends Applet


Java Program[Polyg.java]
{
import java.awt.*;
public void paint(Graphics g)
import java.applet.*;
{
TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 16 Java Applets and Graphics Programming

int xpt[]={20,100,60}; Similarly to set the background color of applet window


int ypt[]={60,60,10};
we use
int num=3;
void setBackground(Color colorname)
g.drawPolygon(xpt,ypt,num);
g.setColor(Color.red);
g.fillPolygon(xpt,ypt,num); where colorname denotes the name of the background
} color. In the same manner we can also specify the
}
foreground color i.e. color of the text by using method
Output

void setForeground(Color colorname)

We can specify the colorname using the Color object as


follows -
Color.black Color.lightGray

Color.blue Color.magenta

Color.cyan Color.orange

Color.darkGray Color.pink

Color.gray Color.red

Board Questions Color.green Color.white


1. State syntax and explain it with parameters for : Color.yellow
i) drawRect ( ) ii) drawOral ( )
MSBTE : Summer 16, Marks 4
Here is a simple demo -
2. Write syntax and example of following Graphics Java Program[ColorDemo.java]
class methods : import java.awt.*;
(i) drawOval( ) (ii) drawPolygon( ) import java.applet.*;
(iii) drawArc( ) (iv) drawRect( )
MSBTE : Winter 15, Marks 8 /*
<applet code="ColorDemo" width=300 height=100>
3. Explain the following methods of applet class :
</applet>
(i) drawRect() (ii) drawPolygon() */
(iii) drawArc() (iv) drawRoundRect() public class ColorDemo extends Applet
MSBTE : Summer 17, Marks 8 {
4. Give the syntax of following methods of graphics public void paint(Graphics g)
class. Explain their use with suitable program : {
setBackground(Color.cyan);
(i) drawRoundRect() (ii) drawPolygon()
setForeground(Color.red);
(iii) drawOval() (iv) drawString( ) g.drawString("Its a colorful Applet",50,30);
MSBTE : Winter 17,Marks 8
Color newColor=new Color(255,255,0);
//creating red+green=yellow color
5.9 Colors MSBTE : Summer 16, Winter 17,Marks 4
g.setColor(newColor);
The syntax of specifying color is g.drawString("Its a colorful Applet",50,70);
Color(int R,int G,int B); }
Color(int RGBVal); //here RGBval denotes the value of color }

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 17 Java Applets and Graphics Programming

Output Output

Program Explanation :

In above program,
1) We see one more method related to color and that is
setColor. To set some specific color this method is Example 5.9.2 : Write a applet program to set background
with red colour and fore ground with blue colour.
used. The color name has to be passed as a parameter MSBTE : Winter 17,Marks 4
to this method. Solution :

2) We can create our own color by a method import java.awt.*;


import java.applet.*;
Color(int R,int G,int B). /*
<applet code="ColorDemo1" width=300 height=200>
In above program we have created yellow color(Red +
</applet>
Green = Yellow). And then the string in colored font */
public class ColorDemo1 extends Applet
is written on applet window.
{
Example 5.9.1 : Design an Applet program which displays a public void paint(Graphics g)
rectangle filled with red color and message as “Hello Third year {
Students” in blue color.
setBackground(Color.RED);
MSBTE : Summer 16, Marks 4
g.setColor(Color.BLUE);
Solution :
g.drawString("Hello Third Year Students",10,90);
import java.awt.*; }
import java.applet.*; }
/*
Output
<applet code="RectangleDemo2" width=300 height=200>
</applet>
*/
public class RectangleDemo2 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.fillRect(10,10,50,50);
g.setColor(Color.BLUE);
g.drawString("Hello Third Year Students",10,90);
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 18 Java Applets and Graphics Programming

5.10 Fonts  getFont(): Using this method we can get the


MSBTE : Winter 16, Summer 15, 16, 18, Marks 8 information of the font.
 SetFont(): We can set the desired font using setFont()  getName(): This method returns the name of the font.
function.
 getSize(): This method returns the size of the font.
 The syntax of setFont() method is
 getStyle(): This method returns the style of the font
setFont(Font f)
such as (BOLD, ITALICS or PLAIN)
 The object f of Font class can be created using Font()
 In the following Java program in the init method we
Constructor.
have set a specific font and in the paint method we can
 For using this function we can choose the desired font,
get the font information using getFont() method.
size of the font, style of the font which can be BOLD,
ITALIC or PLAIN. Java Program[FontInfo.java]
import java.awt.*;
 Following program shows how to set font in applet
import java.applet.*;
Java Program[FontsetDemo.java] /*
import java.awt.*; <applet code="FontInfo" width=300 height=200>
</applet>
import java.applet.*;
/* */
<applet code=”FontsetDemo” width=310 height=200> public class FontInfo extends Applet
</applet> {
*/ String msg=" ";
public class FontsetDemo extends Applet Font f;
{ public void init()
String msg=” “; {
public void init() f=new Font("Monotype Corsiva",Font.BOLD,20);
{ setFont(f);
Font f;
}
f=new Font(“Monotype Corsiva”,Font.BOLD,40);
public void paint(Graphics g)
msg=”Hello”;
{
setFont(f);
} f=g.getFont();
public void paint(Graphics g) String name=f.getName();
{ msg="Font Name: "+name;
g.drawString(msg,30,50); g.drawString(msg,30,50);
} String family=f.getFamily();
} msg="Font Family: "+family;
g.drawString(msg,30,70);
Output
int size= f.getSize();
msg="Size: "+size;
g.drawString(msg,30,90);
int style=f.getStyle();//we int value of font Style
if((style & Font.PLAIN)==Font.PLAIN)
msg="Font Style: PLAIN";
if((style & Font.BOLD)==Font.BOLD)
msg="Font Style: BOLD";
if((style & Font.ITALIC)==Font.ITALIC)
msg="Font Style: ITALIC";
g.drawString(msg,30,110);
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 19 Java Applets and Graphics Programming

Output

Output

Example 5.10.1 : Write a program to display a string


“concentric circles” using font ‘Arial’ size as 12 and style as bold
+ italic and display three concentric circles with different
colours on the applet. MSBTE : Winter 16, Marks 8 Board Questions
Solution : 1. Write syntax and example of
import java.awt.*; 1) drawString ( ) 2) drawRect ( ) ;
import java.applet.*; 3) drawOval ( ) 4) drawArc ( )
/* MSBTE : Summer 15, Marks 8
<applet code="ConcCircles" width=300 height=200> 2. State the use of font class. Describe any three
</applet> methods of font class with their syntax and
*/
example of each.
public class ConcCircles extends Applet
MSBTE : Summer 15, Marks 8
{
Font f;
3. Write method to set font of a text and describe its
public void init() parameters.
{ MSBTE : Summer 16, Marks 6
f=new Font("ARIAL",Font.BOLD+Font.ITALIC,12); 4. State purpose of get Available Font Family N ame
setFont(f); ( ) method of graphics environment class.
} MSBTE : Summer 16, Marks 4
public void paint(Graphics g) 5. Explain following methods :
{
(i) drawrect ( ) (ii) getfont ( )
f=g.getFont();
MSBTE : Winter 16, Marks 4
g.drawString("Concentric Circles",50,20);
g.setColor(Color.RED); 6. With proper syntax and example explain following
g.drawOval(50,50,100,100);//outermost circle graphics methods :
g.setColor(Color.GREEN); (1) SetColor( ) (2) SetForeGround( )
g.drawOval(40,40,120,120);//middle circle (3) getFont( ) (4) setSize( )
g.setColor(Color.BLUE); MSBTE : Summer 18, Marks 6
g.drawOval(30,30,140,140);//innermost circle
} 
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 5 - 20 Java Applets and Graphics Programming

Notes

TM
Technical Publications - An up thrust for knowledge
Java Programming 6-1 Managing Input, Output Files in Java

UNIT - VI

6 Managing Input, Output Files


in Java

6.1 Introduction and Concept of Stream

Definition :
 Stream is basically a channel on which the data flow from sender to receiver.
 An input object that reads the stream of data from a file is called input stream.
 The output object that writes the stream of data to a file is called output stream.

6.2 Stream Classes


MSBTE : Summer 16, Marks 4
 In Java input and output operations are performed using input stream and output stream classes
respectively.
 Java implements streams within the classes that are defined in java.io.

Fig. 6.2.1 Serialization with stream classes

 As shown in above Fig. 6.2.1, A file or Console containing some input is given to the Java Program. This
input is read by our Java program with the help of input stream classes.
 The output generated by our Java program, is then moved on to Output Stream classes. Using theses
classes we can store the output either in some another file or display it on Console(i.e. on output screen)
 There are basically two types of streams used in Java.

Board Question
1. Explain serialization with stream classes. MSBTE : Summer 16, Marks 4

TM
Technical Publications (6 --An
1) up thrust for knowledge
Java Programming 6-2 Managing Input, Output Files in Java

6.3 Byte Stream Classes.


MSBTE : Summer 18, Marks 4
 The byte stream is used for inputting or outputting the bytes.
 There are two super classes in byte stream and those are InputStream and OutputStream from which
most of the other classes are derived.
 These classes define several important methods such as read() and write().
 The input and output stream classes are as shown in Fig. 6.3.1 and Fig. 6.3.2.

Fig. 6.3.1 InputStream classes

Fig. 6.3.2 OutputStream classes

Board Question
1. Explain byte stream class in detail. MSBTE : Summer 18, Marks 4

6.4 Character Stream Classes


MSBTE : Summer 15,16, Winter 15, 16, Marks 4

 The character stream is used for inputting or outputting the characters.


 There are two super classes in character stream and those are Reader and Writer.
 These classes handle the unicode character streams.
 The two important methods defined by the character stream classes are read() and Write() for reading
and writing the characters of data.
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-3 Managing Input, Output Files in Java

 Various Reader and Writer classes are – 6.5 Using File Class
 Various classes that work on the Input/Output system
FileReader FileWriter
makes use of the Java package java.io, however the
PipeReader PipeWriter File class works on file and file system.
 That means the File class does not contain methods for
FilterReader FilterWriter reading and writing the file contents, but it describes
the properties of file itself.
BufferedReader BufferedWriter
 A File object is used to manipulate the information
DataReader DataWriter present in the disk file. Files are useful for storing the
persistent and shared information.
LineNumberReader LineNumberWriter
Various commonly used operations using File class are –
PushbackReader PushbackWriter 1) File creation.
2) Opening a file.
ByteArrayReader ByteArrayWriter
3) Closing a file.
SequenceReader SequenceWriter 4) Getting name of file.
5) Renaming a file.
StringBufferReader StringBufferWriter
6) Checking whether the file is writable.
7) Checking whether the file is readable.

6.6 I/O Exception


While performing input and output operations using files,
the program may generate input and output related
exceptions. There are some commonly used I/O exception
classes that are described in the following
table -
I/O Exception Class Purpose
IOException If some sort of I/O related
exception occurs then this class is
used to handle it.
FileNotFoundException This is the most commonly used
exception during I/O operations
using files. If the desired file for
Fig. 6.4.1 performing I/O is not found then
this exception is used.
Board Questions
EOFException If we come across end of file
1. What are stream classes ? List any two input
unexpectedly then this exception
stream classes from character stream.
MSBTE : Summer 15,16, Winter 15 Marks 4
is raised.

2. Draw the hierarchy of writer stream classes and InterruptedIOException If I/O operation is interrupted ,
hierarchy of Readerstream classes. then this exception is used to
MSBTE : Winter 16, Marks 4 handle the situation.

TM
Technical Publications - An up thrust for knowledge
Java Programming 6-4 Managing Input, Output Files in Java

The skeleton code is FileWriter fwrt;


try{
try
fwrt=new FileWriter(outFile);
{
fwrt.write("Java Programming is Fun!!!");
//code for opening the file
fwrt.close();
}
}
catch(FileNotFoundException e)
catch(Exception e)
{
{
… . //appropriate message of exception handling
System.out.println(e);
}
}
6.7 Creation of Files The above code makes use of following five steps for file
File stream object is an important entity which helps us to creation
locate desired file using a filename. We need to create a
Step 1 : Select filename.
file first and then initialize the file stream object.
There are two ways to create the file and initialize the file Step 2 : Declare file object.
stream object. Step 3 : Give the selected name to the file object
Method 1 : This is a direct approach of creating a file and declared.
initializing the file stream object. For that we have to use
Step 4 : Declare a file stream object.
either character stream classes or byte stream classes.
Following sample code makes use FileWriter class (This Step 5 : Connect the file to the file stream object.
is character stream class using which the file can be This approach can be represented by following Fig. 6.7.2
created and opened up for writing purpose).
try{
FileWriter fwrt=new FileWriter("D:\\myfile.txt");
fwrt.write("Java Programming is Fun!!!"); Fig. 6.7.2
fwrt.close();
} 6.8 Reading/Writing Characters
catch(Exception e) MSBTE : Summer 15,18, Winter 16, Marks 8
{ Let us discuss how to handle input/output operations with
System.out.println(e);
the help of character stream classes.
}
In above code we have created a file named myfile.txt Write Operations
and initialize the file stream object named fwrt. Note that  For performing write operation using Character Stream
we have enclose this code in try …catch block for safe
classes we use an important class i.e. FileWriter
programming. This direct approach of file creation is
represented by following Fig.6.7.1  Declaration Syntax : The FileWriter class can be
declared as follows –
public class FileWriter extends OutputStreamWriter

 Useful Methods : The most commonly used methods


Fig. 6.7.1 of FileWriter class are as shown by following table –

Method 2 : This is indirect method of file creation in Method Purpose


which File class is used.The sample code is void write(String text) It is used to string into FileWriter.
File outFile;
void close() It is used to close the FileWriter
outFile=new File(“D:\\myfile.txt”);
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-5 Managing Input, Output Files in Java

Let us now discuss how to write Java program using Output


character stream classes for Write operation Java Programming is Fun!!!
import java.io.FileWriter; Example 6.8.1 : Write a program to copy contents of one file
public class WriterDemo to another file using character stream class.
{ MSBTE : Summer 15,Winter 16, Marks 4
public static void main(String args[]) OR Write a java program to copy the content of the file
{ “file1.txt” into new file“file2.txt”.
try{ MSBTE : Summer 18, Marks 8
FileWriter fwrt=new FileWriter("D:\\myfile.txt"); Solution :
fwrt.write("Java Programming is Fun!!!");
import java.io.FileReader;
fwrt.close();
import java.io.FileWriter;
}catch(Exception e){System.out.println(e);}
public class CopyFileProg
System.out.println("Data is written to file...");
{
}
} public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\file1.txt");
Output FileWriter fwrt=new FileWriter("D:\\file2.txt");
Data is written to file...
int i;
If we open the myfile.txt file then we get –
while((i=fr.read())!=-1)
Java Programming is Fun!!!
{
Read Operations fwrt.write((char)i);
}
 For performing read operation using character Stream System.out.println("The Data is copied from file1 to
classes we use an important class i.e. FileReader file2");
fr.close();
 Declaration Syntax : The FileReader class can be
fwrt.close();
declared as follows - }
public class FileReader extends InputStreamReader }
 Useful Methods : The most commonly used methods Output
of FileReader class are as shown by following table - The Data is copied from file1 to file2
D:\MSBTE_JAVA _Programs> cd..
Method Purpose D:\> type file1.txt
void read() It is used to read character data in read. Java is fun!!!
D:\> type file2.txt
void close() It is used to close the FileReader class. Java is fun!!!
D:\>
Example Program[ReaderDemo.java]
Example 6.8.2 : Write a program that will count no. of
import java.io.FileReader; characters in a file.
public class ReaderDemo MSBTE : Winter 16, Marks 4
{ Solution :
public static void main(String args[])throws Exception{
import java.io.FileReader;
FileReader frt=new FileReader("D:\\myfile.txt");
import java.io.FileWriter;
int i;
public class CharacterNumbers
while((i=frt.read())!=-1)
{
System.out.print((char)i);
public static void main(String args[])throws Exception{
frt.close();
FileReader fr=new FileReader("D:\\file1.txt");
}
}
int i,ch=0;

TM
Technical Publications - An up thrust for knowledge
Java Programming 6-6 Managing Input, Output Files in Java

while((i=fr.read())!=-1)
{
ch++;
}
System.out.println("Total number of characters: "+ch);
fr.close();
}
}

Output
Total number of characters: 14

6.9 Reading/ Writing Bytes


MSBTE : Summer 15, 17, Winter 15, 17, Marks 4
Let us discuss how to handle input/output operations with the help of byte stream classes.

Write Operations
 For performing write operation using byte stream classes we use an important class i.e.
FileOutputStream.
 Declaration Syntax : The FileOutputStream class can be declared as follows -
public class FileOutputStream extends OutputStream
 Useful Methods : The most commonly used methods of FileOutputStream class are as shown by following
table -
Method Purpose

void write( byte[] array) The array.length bytes can be written to the file output stream.

void write(byte[] array, int The len bytes can be written from byte array at the location
offset, int len) denoted by offset to the file output stream.

void write(int b) It is used to write the specified bytes to file output stream.

void close() It is used to close the file output stream.

Let us now discuss how to write Java program using byte stream classes for Write operation

Example 1 : Writing Single Byte to the File


import java.io.FileOutputStream;
public class WriteDemo1
{
public static void main(String args[])
{
try{
FileOutputStream fout=new FileOutputStream("D:\\output.txt");
fout.write(90); //Ascii value for character Z
fout.close();
System.out.println("Data is written to the file...");
}catch(Exception e){System.out.println(e);}
}
}
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-7 Managing Input, Output Files in Java

Output

Program Explanation : In above program, Output


Data is written to the file...
Step 1 : Import java.io.FileOutputStream; at the If we open the output file output.txt then we get -
beginning of your Java program.

Step 2 : We have created an object for


FileOutputStream class. This object is named as fout.

Step 3 : Using fout we have used the write method to


write the single byte(for character Z) to the file named
output.txt which is present on D:\ drive.

Step 4 : Then we close the output file stream using


close() operation.
Note that it is important to perform all the above steps
from 2 to 4 within the try…catch block with exception Program Explanation : In above program,
Exception. 1) We have used FileOutputStream class to write the
contents to the file.
Example 2 : Writing String to the File
2) We cannot directly write some string to the file using
import java.io.FileOutputStream;
public class WriteDemo2 byte stream classes. For that matter we have to first
{ convert it to byte stream using getBytes() method.
public static void main(String args[]) And then these bytes can be written to the file.
{
try Read Operations
{
 For performing read operation using Byte Stream
FileOutputStream fout=new FileOutputStream
("D:\\output.txt");
classes we use an important class i.e.
String s="I am writing this line to file."; FileInputStream.
byte b[]=s.getBytes();//converting string into byte  Declaration Syntax: The FileInputStream Class can
array
be declared as follows –
fout.write(b);
public class FileInputStream extends InputStream
fout.close();
System.out.println("Data is written to the file...");  Useful Methods: The most commonly used methods
}catch(Exception e){System.out.println(e);} of FileInputStream class are as shown by following
}
table -
}

TM
Technical Publications - An up thrust for knowledge
Java Programming 6-8 Managing Input, Output Files in Java

Method Purpose 2 : We have created an object for FileInputStream class.


This object is named as fin.
void read() It is used to read byte of data from the
input stream.
3 : Using fin we have used the read method to read the
single byte from the file named myfile.txt which is
void read( byte[] The array.length bytes can be read from
present on D:\ drive. Note that the we obtain the first
array) the file using input stream.
byte from the file, this single byte must be converted
void read(byte[] The len bytes can be read into byte to character by typecasting (char) i. Then only this
array, int offset, int array at the location denoted by offset to character can be displayed on console.
len) the file input stream. 4 : Then we close the input file stream using close()
void close() It is used to close the input stream operation.
Let us now discuss how to write Java program using byte Note that it is important to perform all the above steps
stream classes for Read operation from 2 to 4 within the try…catch block with exception
Exception.
Example 1 : Reading Single Byte from the file
Example 2 : Reading string of bytes from the file
Step 1 : Create an input file named myfile.txt and write
Step 1 : Create an input file named myfile.txt and write
the contents to the file as
the contents to the file as
myfile.txt myfile.txt
Java Java Program is fun!!!
Step 2 : Now write the following Java Program Step 2 : Now write the following Java Program
import java.io.FileInputStream; import java.io.FileInputStream;
public class ReadDemo1 public class ReadDemo2
{ {
public static void main(String args[]) public static void main(String args[])
{ {
try try
{ {
FileInputStream fin=new FileInputStream("D:\\myfile.txt"); FileInputStream fin=new
int i=fin.read(); FileInputStream("D:\\myfile.txt");
System.out.println("Following data is read from int i=0;
file..."); System.out.println("Following data is read from
System.out.println((char)i); file...");
fin.close(); while((i=fin.read())!=-1)
}catch(Exception e){System.out.println(e);} {
} System.out.print((char)i);
} }
fin.close();
Save and execute the above program using Javac
Step 3 : }catch(Exception e){System.out.println(e);}
command. Following output can be obtained. }
Following data is read from file... }

J Output
Following data is read from file...
Program Explanation : In above program,
Java Program is fun!!!
1 : Import java.io.FileInputStream; at the beginning of
Example 6.9.1 : Write a program to copy contents of one file
your Java program. to another. Using byte stream classes.
MSBTE : Winter 17, Marks 4
TM
Technical Publications - An up thrust for knowledge
Java Programming 6-9 Managing Input, Output Files in Java

Solution : Java Program[PrimitiveDemo.java]


import java.io.*;
import java.io.FileInputStream;
class PrimitiveDemo
import java.io.FileOutputStream;
{
public class CopyFileProg1
public static void main(String args[]) throws IOException
{
{
public static void main(String args[])throws Exception
//creating file and data stream object and initializing
{
them for writing purpose
FileInputStream fin=new FileInputStream("D:\\file1.txt");
File f=new File("d:\\Primfile.txt");
FileOutputStream fout=new FileOutputStream("D:\\file2.txt");
FileOutputStream fos=new FileOutputStream(f);
int i;
DataOutputStream dos=new DataOutputStream(fos);
while((i=fin.read())!=-1)
//Writing primitive data to the file
{
System.out.println("\tWriting some data to the file ...");
fout.write((char)i);
dos.writeInt(301);
}
dos.writeChar('A');
System.out.println("The Data is copied from file1 to
dos.writeBoolean(true);
file2");
dos.writeDouble(123.45);
fin.close();
//closing the output streams of filestream and
fout.close();
datastream classes
}
dos.close();
}
fos.close();
6.9.1 Handling Primitive Data Types //initializing file and data stream objects for reading
purpose
 The primitive data types used in Java are int, FileInputStream fis=new FileInputStream(f);
char,float, double and boolean. DataInputStream dis=new DataInputStream(fis);
//Reading primitive data from the file
 For writing any primitive type of data to the file we
System.out.println("\tReading some data from the file
can make use of data stream classes namely ...");
DataInputStream and DataOutputStream. System.out.println(dis.readInt());
System.out.println(dis.readChar());
 Before using the data stream classes we need i) Filter
System.out.println(dis.readBoolean());
class and ii) Data interface. This hierarchy of data System.out.println(dis.readDouble());
stream classes is as shown below – //closing the input streams of filestream and
datastream classes
dos.close();
fos.close();
}
}

Output
Writing some data to the file ...
Reading some data from the file ...
301
A
true
123.45

Program Explanation : In above program,


1) We have created a file object named f using File class.
Fig. 6.9.1 Hierarchy of Data Stream Classes The filename is Primfile.txt.
 Following example illustrates how to use primitive
data types in file I/O.
TM
Technical Publications - An up thrust for knowledge
Java Programming 6 - 10 Managing Input, Output Files in Java

2) Then first of all we have prepared filestream object 7) Finally filestream object and datastream objects are
and datastream objects for writing primitive data type closed.
values to the Primfile.txt.
Board Questions
3) Then using writeType() methods (like writeInt,
1. Write any two methods of file and file input stream
writeChar and so on) we can write data to the file. class each.
4) The stream objects are then closed. MSBTE : Summer 15, Winter 15, Marks 4

5) We initialize the filestream object and datastream 2. Write any four methods of file class with their use.
MSBTE : Summer 17, Marks 4
objects for reading primitive data type values from
3. Write any four methods of file input stream class
Primfile.txt
give their syntax.
6) Then using readType() methods(like readInt, readChar MSBTE : Winter 17, Marks 4
and so on) we can reads primitive data type data from
the file. 



TM
Technical Publications - An up thrust for knowledge
Java Programming L-1 Java Programming Laboratory

Java Programming
LABORATORY

Example 1 : Set up a Java Programming development environment by using :


(a) command Prompt (b) Any IDE(Eclipse, JCreator etc.)

Solution :

(a) Command Prompt :

Step 1 : For running Java we require JDK i.e. Java Development Kit. It can be downloaded from the website
http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Step 2 : Click the Download button Under "Java Platform, Standard Edition" ⇒ "Java SE 10.0.{x}", where {x}
denotes update number.

Step 3 : Then check “Accept License Agreement”.

Step 4 : Choose JDK for your operating system i.e. Windows 32 bit or 64 bit. And download installer. Run the
installer.

Step 5 : Accept the defaults and proceed by clicking the Next button.
This installer installs both the JDK and JRE.

By default :

 JDK is installed in directory "C:\Program Files\Java\jdk-10.0.{x}", where {x} denotes the upgrade
number; and
 JRE is installed in "C:\Program Files\Java\jre-10.0.{x}".

Step 5 : Thus now we have Java installed on our PC. The last important task which we have to do is: setting up of
environmental variables. This will help us to run our java programs. For setting the environmental variables
just go to the control panel. You find the System folder over there. Click over there to set the system
properties. Following screen may appear by this

TM
Technical Publications
(L- -An1)up thrust for knowledge
Java Programming L-2 Java Programming Laboratory

Click on Environment Variables tab in order to set the environment variables. Under the “System Variables”
(the bottom Pane), Scroll down to select “Path” => Click “Edit..” Thus we should have –
Variable name : PATH
Variable value : c:\Program Files\Java\jdk-10.0.{x}\bin;
We can set the path variable by mentioning the directory C:\Program Files\jdk10.0.X\bin. Note that in the
subdirectory bin of our jdk directory the executable file of java is downloaded. Hence the bin directory has to
be mentioned in the path. Click OK to save these settings. Do not delete any other entries if present under the
“path” variable. Separate our Java entry by semicolon.
Many applications require the environment variable JAVA_HOME to be set to the installed JDK directory.
To set the JAVA_HOME environment variable :
(1) First find where your JDK is installed. By default it is installed at “C:\Program Files\Java.
(2) Check if JAVA_HOME is already set. Start a Command Prompt and issue:
SET JAVA_HOME
If you get a message "Environment variable JAVA_HOME not defined", proceed to the next step.
(3) To set the environment variable JAVA_HOME in Windows 10/8/7: Launch "Control Panel" ⇒ (Optional)
System and Security ⇒ System ⇒ Advanced system settings ⇒ Switch to "Advanced" tab ⇒ Environment
Variables ⇒ System Variables (the bottom pane) ⇒ "New"

TM
Technical Publications - An up thrust for knowledge
Java Programming L-3 Java Programming Laboratory

Step 6 : We can verify the installation of Java using Command prompt. For that - Launch a Command Prompt
shell via one of the following means :
 Click "Search" button ⇒ Enter "cmd" ⇒ Choose "Command Prompt", or
 right-click "Start" button ⇒ run... ⇒ enter "cmd", or
The command prompt window will appear , go to the command-prompt and type javac over there.

Thus we have got the fully functioning java software ready to run our java programs.

(b) Any IDE(Eclipse) :

Installation of Eclipse IDE


The Eclipse is a popular IDE used for Java programming. IDE stands for Interface Development Environment.
Step 1 Before installing Eclipse, you must download JDK. Download Eclipse from the site
:
www.eclipse.org/downloads/index.php
Step 2 :This download will be delivered as a compressed (i.e. zip)file. Decompress this file into the directory of
your choice. For example – C:\eclipse
TM
Technical Publications - An up thrust for knowledge
Java Programming L-4 Java Programming Laboratory

Step 3 : Create a shortcut for eclipse.exe on your Desktop. Click on this eclipse.exe to launch Eclipse.
Step 4 : The workspace launcher will appear. Click OK and proceed. Eventually Welcome tab will appear. You
can terminate this table by clicking X on top right corner.
Step 5 : Click Window and click Preferences in its pull down menu. The following screenshot illustrates –

Step 6 : Disclose Java by clicking the + in front of Java or double-clicking Java (after the +); the + changes to a -
Disclose Installed JREs similarly. The Preferences pop-up window should appear as follows

TM
Technical Publications - An up thrust for knowledge
Java Programming L-5 Java Programming Laboratory

Step 7 : Click Add External Jars....


In the Jar Selection window, navigate to your workspace folder, and double-click the file introlib.jar.
Then Click Finish and then click OK.
Thus Eclipse is now installed for Java.
Example 2 : Test the JDE set up by implementing a small program

Solution : Refer section 1.4


Example 3 : Develop programs to demonstrate use of if statements and its different forms.

Solution : Refer sections 1.8.1, 1.8.2, 1.8.3 and 1.8.4


Example 4 : Develop programs to demonstrate use of :
(a) switch case (b) conditional if

Solution : Refer sections 1.8.5 and 1.7.5


Example 5 : Develop programs to demonstrate use of Looping Statement ‘for’

Solution : Refer section 1.8.9


Example 6 : Develop programs to demonstrate use of ‘while’ and ‘do while’

Solution : Refer sections 1.8.7 and 1.8.8


Example 7 : Develop a program for implementation of implicit type casting in Java. Part I.

Solution : Refer section 1.6.6


Example 8 : Develop a program for implementation of implicit type casting in Java. Part II.

Solution : Refer section 1.6.6


Example 9 : Develop a program for implementation of explicit type conversion in Java.

Solution : Refer section 1.6.6


Example 10 : (a) Develop a program for implementation of Constructor
(b) Develop a program for implementation of multiple constructors in a class.

Solution : (a) Refer section 2.1 (1) (b) Refer section 3.4.
Example 11 : Develop a program for implementation of different functions of String. Part I

Solution : Refer section 2.12.1


Example 12 : Develop a program for implementation of different functions of String. Part II

Solution : Refer section 2.12.2


Example 13 : Develop a program for implementation of Arrays in Java.

Solution : Refer section 2.11


Example 14 : Develop a program for implementation of Vectors in Java.

Solution : Refer section 2.13


Example 15 : Develop a program for implementation of Wrapper Class to convert Primitive into Object.

Solution : Refer section 2.14

TM
Technical Publications - An up thrust for knowledge
Java Programming L-6 Java Programming Laboratory

Example 16 Develop a program for implementation of Wrapper Class to convert object into primitive.
Solution : Refer example 2.14.1
Example 17 Develop program which implements the concept of overriding.
Solution : Refer section 3.5
Example 18 Develop a program for implementation of Single and Multilevel inheritances.
Solution : Refer examples 3.2.1, and 3.2.4
Example 19 Develop a program for implementation of multiple inheritance.
Solution : Refer example 3.15.2
Example 20 Develop a program to import different classes in a package.

Solution : Refer section 3.25


Example 21 Develop a program for implementation of multi-threading operation Part I.

Solution : Refer section 4.13

Example 22 Develop a program for implementation of multi-threading operation Part II.

Solution : Refer section 4.13


Example 23 Develop a program for implementation of try-catch block. Part I

Solution : Refer section 4.4


Example 24 Develop a program for implementation of try-catch block. Part II

Solution : Refer section 4.5


Example 25 Develop a program for implementation of try-catch and finally block.

Solution : Refer section 4.8


Example 26 Develop programs for implementation of throw and throws clause. Part I.

Solution : Refer section 4.6


Example 27 Develop programs for implementation of throw and throws clause. Part II.

Solution : Refer section 4.7


Example 28 Develop minimum two basic Applets. Display output with applet viewer and browser.
(a) Develop a program on basic applet.
(b) Develop a program using control loops in applets.

Solution : (a)Refer section 5.4 (b) Refer example 2.7.4


Example 29 Write a program to create animated shape using graphics and applets. You may use following shapes.
(a) Lines and Rectangles
(b) Circles and Ellipse
(c) Arcs
(d) Polygons with fillPolygon method.

Solution : (a) Refer sections 5.8.2 and 5.8.3


(b) Refer section 5.8.4
(c) Refer section 5.8.5
(d) Refer section 5.8.6
TM
Technical Publications - An up thrust for knowledge
Java Programming L-7 Java Programming Laboratory

Example 30 Develop a program to draw following shapes, graphics and applet


a) Cone b) Cylinder c) Cube
d) Square inside a circle e) Circle inside a square

Solution :
import java.awt.*;
import java.applet.*;
/*<applet code="Shape.class" height=400 width=500>
</applet>
*/
public class Shape extends Applet
{
public void paint(Graphics g)
{
//drawing Cylinder
g.drawLine(20,20,20,100);
g.drawOval(20,0,90,50);
g.drawLine(110,20,110,100);
g.drawOval(20,80,90,50);
g.drawString("Cylinder",30,160);
//drawing cone
g.drawOval(150,90,90,50);
g.drawLine(195,10,150,110);
g.drawLine(195,10,240,110);
g.drawString("Cone",180,160);
//drawing Cube
g.drawRect(300,10,100,100);
g.drawRect(320,30,100,100);
g.drawLine(300,10,320,30);//slanting top left
g.drawLine(400,10,420,30);//slanting top right
g.drawLine(300,110,320,130);//slanting bottom left
g.drawLine(400,110,420,130);//slanting bottom right
g.drawString("Cube",340,160);
//Square Inside Circle
g.drawOval(100,200,100,100);
g.drawRect(115,215,70,70);
g.drawString("Square Inside Circle",90,320);
//Circle Inside Square
g.drawRect(300,200,100,100);
g.drawOval(300,200,100,100);
g.drawString("Circle Inside Square",290,320);
}
}

TM
Technical Publications - An up thrust for knowledge
Java Programming L-8 Java Programming Laboratory

Example 31 Develop a program for implementation of I/O Stream Classes.

Solution : Refer section 6.9


Example 32 Develop a program for implementation of file stream Classes.

Solution : Refer sections 6.7 and 6.8



TM
Technical Publications - An up thrust for knowledge
Java Programming M-1 Solved Model Question Paper

Solved Model Question Paper


MSBTE
Java Programming
S.Y. Diploma, Semester - IV
(Computer Engg. Group & Information Technology)
[Time : 3 Hours] Total Marks : 70]

Q.1 Attempt Any FIVE of the Following : [Marks 10]


(a) Explain any Two features of Java programming. (Refer section 1.1)
(b) Explain any Two mathematical functions. (Refer section 1.7.10)
(c) Define Vector (Refer section 2.13)
(d) List different types of inheritance. (Refer section 3.2)
(e) What are two types of errors ? (Refer section 4.2)
(f) Define the term - interface (Refer section 3.11)
(g) Define the term- Applet (Refer section 5.1)
Q.2 Attempt Any THREE of the Following : [Marks 12]
(a) Differentiate vector and array with any four points. (Refer section 2.13)
(b) Explain applet life cycle. (Refer section 5.2)
(c) Write a program to copy contents of one file to another file using character stream class.
(Refer example 6.8.1)
(d) What is abstract class and method ? Explain. (Refer section 3.9)
Q.3 Attempt Any THREE of the Following : [Marks 12]
(a) Compare String class and StringBuffer class. (Refer section 2.12.2)
(b) Explain any two bitwise operators with example. (Refer section 1.7.6)
(c) Explain all attributes available in <applet> tag. (Refer section 5.3)
(d) Describe nested try statement with suitable example. (Refer section 4.5)
Q.4 Attempt Any THREE of the Following : [Marks 12]
(a) What the concept of wrapper classes with illustrative example. (Refer section 2.14)
(b) List any four built in packages from Java API along with their use. (Refer section 3.19)
(c) Give and explain any four I/O Exceptions used during File handling. (Refer section 6.6)
(d) State syntax and explain it with parameters for : (Refer sections 5.8.3 and 5.8.4)
i) drawRect ( ) ii) drawOral ( )
Q.5 Attempt any TWO of the Following : [Marks 12]
(a) Write a program to accept two numbers as command line arguments and print the addition of those
numbers. (Refer example 2.6.2)
(b) Explain the concept of thread priority and its methods. (Refer section 4.16)

TM
Technical Publications - An up thrust for knowledge
Java Programming M-2 Solved Model Question Paper

(c) How to add applet to HTML file. Explain it with suitable example. (Refer section 5.5.1)
Q.6 Attempt any TWO of the Following : [Marks 12]
(M - 1)
(a) Explain the different methods of passing arguments to the function with supporting Java programs
(Refer section 2.4)
(b) Write a Java program to display following number pattern. (Refer example 1.8.10)
1
12
123
1234
12345
(c) Explain the concept of creating own exception subclass with suitable example. (Refer section 4.11)



TM
Technical Publications - An up thrust for knowledge
Java Programming S-1 Solved Board Question Papers

Summer 2015
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (21415)

3 Hours/100 Marks
Instructions :
(1) All questions are compulsory.
(2) Answer each next main question on a new page.
(3) Illustrate your answers with neat sketches wherever necessary.
(4) Figures to the right indicate full marks.
(5) Assume suitable data, if necessary.
(6) Preferably, write the answers in sequential order.
1. A) Attempt any three of the following : (3×4=12)
a) What is JVM ? What is byte code ? (Refer section 1.2)
b) Write any two methods of file and file input stream class each. (Refer section 6.9)
c) ‘? :’ What this operator is called ? Explain with suitable example. (Refer section 1.7.5)
d) Define an exception. How it is handled ? (Refer section 4.4)
B) Attempt any one of the following : (1×6=6)
a) Define a class ‘employee’ with data members empid, name and salary. Accept data for five objects
using array of objects and print it. (Refer example 2.11.1)
b) Explain with example how to achieve multiple inheritance with interface. (Refer example 3.15.1)
2. Attempt any two of the following : (2×8=16)
a) Define wrapper class. Give the following wrapper class methods with syntax and use :
1) To convert integer number to string.
2) To convert numeric string to integer number.
3) To convert object numbers to primitive numbers using typevalue ( ) method. (Refer example 2.14.1)
b) Write syntax and example of
1) drawString ( ) 2) drawRect ( ) ;
3) drawOval ( ) 4) drawArc ( ) (Refer section 5.10)
c) What is package ? State any four system packages along with their use ? How to add class to a user
defined package ? (Refer sections 3.18, 3.19 and 3.24)
3. Attempt any four : 16
a) Differentiate vector and array with any 4 points. (Refer section 2.13)
b) Write a program to accept a number as command line argument and print the number is even or odd.
(Refer example 2.6.1)

TM
Technical Publications - An up thrust for knowledge
Java Programming S-2 Solved Board Question Papers

c) Write a program to copy contents of one file to another file using character stream class.
(Refer example 6.8.1)
d) State the use of final keyword w.r.t. a method and the variable with suitable example.
(Refer section 3.7) (S - 1)

e) Describe following states of applet life cycle :


a) Initialization state. b) Running state. c) Display state. (Refer section 5.2)
4. A) Attempt any three : (4×3=12)
a) Compare string class and stringBuffer class with any four points. (Refer section 2.12)
b) Explain thread priority and method to get and set priority values. (Refer section 4.16)
c) Define a class having one 3 digit number, num as data member, initialize and display reverse of that
number. (Refer example 1.8.2)
d) Write syntax and function of following methods of Date class :
i) getTime ( ) ii) getDate ( ) (Not in new syllabus)
B) Attempt any one of the following : (1×6=6)
a) Explain following methods of vector class :
i) elementAt ( ) ii) addElement ( ) iii) removeElement ( ) (Refer section 2.13)
b) Explain <PARAM> Tag of applet with suitable example. (Refer section 5.6)
5. Attempt any two of the following : (2×8=16)
a) Write a program to input name and age of a person and throws an user define exception if entered age
is negative. (Refer example 4.11.2)
b) With suitable diagram explain life cycle of Thread. (Refer section 4.14)
c) State the use of font class. Describe any three methods of font class with their syntax and example of
each. (Refer section 5.10)
6. Attempt any four of the following : (4×4=16)
a) Differentiate applet and application with any four points. (Refer section 5.1)
b) Define JDK. List the tools available in JDK explain any one in detail. (Refer section 1.2)
c) Write a program to implement following inheritance : (Refer example 3.2.2)

d) Write the effect of access specifiers public, private and protected in package. (Refer section 3.22)
e) What are stream classes ? List any two input stream classes from character stream. (Refer section 6.4)

TM
Technical Publications - An up thrust for knowledge
Java Programming S-3 Solved Board Question Papers

Winter 2015
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (15116)

3 Hours / 100 Marks


1. (A) Attempt any THREE of the following : 3 × 4 = 12
(a) Explain any four features of Java. (Refer section 1.1)
(b) What is exception ? How it is handled ? Explain with suitable example. (Refer section 4.4)
(c) Describe break and continue statement with example. (Refer sections 1.8.10 and 1.8.11)
(d) What are streams ? Write any two methods of character stream classes. (Refer section 6.4)
(B) Attempt any ON E of the following : 1×6=6
(a) What is package ? How to create package ? Explain with suitable example. (Refer section 3.21)
(b) State the use of ‘super’ and ‘final’ keyword w.r.t. inheritance with example. (Refer section 3.8)
2. Attempt any TWO of the following : 2 × 8 = 16
(a) Write a program to create a vector with seven elements as (10, 30, 50, 20, 40, 10, 20). Remove
element at 3rd and 4th position. Insert new element at 3rd position. Display the original and
current size of the vector. (Refer example 2.13.1)
(b) What is meant by an interface ? State its need and write syntax and features of an interface. Give one
example. (Refer section 3.12)
(c) Write syntax and example of following Graphics class methods :
(i) drawOval( )(ii) drawPolygon( )
(iii) drawArc( ) (iv) drawRect( ) (Refer section 5.8)
3. Attempt any FOUR of the following : 4 × 4 = 16
(a) What is constructor ? Describe the use of parameterized constructor with suitable example.
(Refer section 2.2)
(b) Describe?, : (Ternary operator) in Java with suitable example. (Refer section 1.7.5)
(c) What is the difference between array and vector ? Explain elementAt( ) and addElement( ) method.
(Refer section 2.13)
(d) Write any two methods of File and FileInputStream class each. (Refer section 6.9)
(e) Write a program to design an applet to display three circles filled with three different colors on screen.
(Refer example 5.8.2)
4. (A) Attempt any THREE of the following : 3 × 4 = 12
(a) Write a program to check whether the entered number is prime or not. (Refer example 1.8.6)
(b) Explain the following clause w.r.t. exception handling :
(i) try (ii) catch (iii) throw (iv) finally (Refer section 4.8)
(c) Explain any two bit-wise operators with example. (Refer section 1.7.6)
(d) Explain all attributes available in < applet > tag. (Refer section 5.3)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-4 Solved Board Question Papers

(B) Attempt any ON E of the following : 1×6=6


(a) Differentiate between applet and application and also write a simple applet which display message
‘Welcome to Java’. (Refer example 5.5.1)
(b) Describe the following string class methods with examples :
(i) length( ) (ii) charAt( ) (iii) CompareTo( ) (Refer section 2.12)
5. Attempt any TWO of the following : 2 × 8 = 16
(a) Write a program to accept password from user and throw ‘Authentication failure’ exception if
password is incorrect. (Refer example 4.11.1)
(b) Explain life cycle of thread with a neat diagram.(Refer section 4.14)
(c) How can parameters be passed to an applet ? Write an applet to accept user name in the form of
parameter and print ‘Hello < username >’. (Refer example 5.6.1)
6. Attempt any FOUR of the following : 4 × 4 = 16
(a) Explain method overloading with example. (Refer section 3.4)
(b) State any four system packages along with their use. (Refer section 3.18)
(c) What is use of ArrayList Class ? State any three methods with their use from ArrayList.
(Not in new syllabus)
(d) Explain serialization in relation with stream classes.(Refer section 6.2)
(e) What is byte code ? Explain any two tools available in JDK. (Refer section 1.2)

Summer 2016
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (15162)

3 Hours / 100 Marks


1. A) Attempt any three of the following. (3×4=12)
a) Describe any two relational and any two logical operators in Java with simple example.
(Refer sections 1.7.2 and 1.7.3)
b) What are stream classes ? List any two input stream classes from character stream. (Refer section 6.4)
c) Write general syntax of any two decision making statements and also give its examples.
(Refer section 5.1.8)
d) Describe life cycle of thread. (Refer section 4.14)
B) Attempt any one of following. (1×6=6)
a) Explain following methods of string class with their syntax and suitable example.
i) substring ( ) ii) replace ( ) (Refer section 2.12)
b) Write syntax of defining interface. Write any major two differences between interface and a class.
(Refer section 3.11)
2. Attempt any two of the following. (2×8=16)
a) Write a program to implement a vector class and its method for adding and removing elements. After
remove display remaining list. (Refer example 2.13.1)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-5 Solved Board Question Papers

b) Describe with example how to achieve multiple inheritance with suitable program. (Refer section 3.15)
c) Write a simple applet program which display three concentric circle. (Refer example 5.8.3)
3. Attempt any four of following : (4×4=16)
a) Define constructor. Explain parameterized constructor with example. (Refer section 2.2)
b) Write a program to check whether an entered number is prime or not. (Refer example 1.8.6)
c) Explain serialization with stream classes. (Refer section 6.2)
d) State syntax and explain it with parameters for :
i) drawRect ( ) ii) drawOral ( ) (Refer section 5.8.4)
e) Describe use of ‘super’ and ‘this’ with respect to inheritance. (Refer sections 2.5 and 3.8)
4. A) Attempt any three of following. (3×4=12)
a) Explain break and continue statements with example. (Refer section 1.8)
b) Describe use of ‘throws’ with suitable example. (Refer section 4.6)
c) State syntax and describe working of ‘for each’ version of for loop with one example.
(Refer section 1.8)
d) State syntax and describe any two methods of map class. (Not in new syllabus)
B) Attempt any one of following. (1×6=6)
a) Write method to set font of a text and describe its parameters. (Refer section 5.10)
b) Describe final method and final variable with respect to inheritance. (Refer section 3.7)
5. Attempt any two of following. (2×8=16)
a) What is thread priority ? How thread priority are set and changed ? Explain with example.
(Refer section 4.16)
b) Write a program to input name and age of person and throws user defined exception, if entered age is
negative. (Refer example 4.11.2)
c) Explain <applet> tag with its major attributes only. State purpose of get Available Font Family N ame
( ) method of graphics environment class. (Refer sections 5.2 and 5.10)
6. Attempt any four of the following. (4×4=16)
a) Define a class Item having datamember code and price. Accept data for one object and display it.
(Refer example 1.5.1)
b) What is use of Array list class ? State any two methods with their use from Array List.
(Not in new syllabus)
c) Design an Applet program which displays a rectangle filled with red color and message as “Hello
Third year Students” in blue color. (Refer example 5.9.1)
d) Design a package containing a class which defines a method to find area of rectangle. Import it in Java
application to calculate area of a rectangle. (Refer example 3.23.1)
e) Define a class having one 3-digit number as a data member. Initialize and display reverse of that
number. (Refer example 1.8.2)

TM
Technical Publications - An up thrust for knowledge
Java Programming S-6 Solved Board Question Papers

Winter 2016
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (16117)

3 Hours / 100 Marks


1. (A) Attempt any THREE of the following : 12
(a) How java is different than other programming language ? (Refer section 1.3)
(b) What is scope of variable ? Give example of class variable, instance variable and local variable.
(Refer section 1.6.5)
(c) What is an exception ? How it is handled ? Give suitable example. (Refer section 4.4)
(d) Explain methods of map class and set class in jdk frame work. (Not in new syllabus)
(B) Attempt any ON E of the following : 1×6=6
(a) Create a class ‘Rectangle’ that contains ‘length’ and ‘width’ as data members. From this class derive
class box which has additional data member ‘depth’. Class ‘Rectangle’ consists of a constructor
and an area ( ) function. The derived ‘Box’ class have a constructor and override function named area
( ) which returns surface area of ‘Box’ and a volume ( ) function. Write a java program calling all the
member function. (Refer example 3.2.3)
(b) Write a java program. (Refer example 3.15.1)

2. Attempt any TWO of the following : 16


(a) Write a program to create a class Account having variable accno, accname and balance. Define
deposite ( ) and withdraw ( ) methods. Create one object of class and perform the operation.
(Refer example 1.5.2)
(b) How multiple inheritance is achieved in java ? Explain with proper program. (Refer section 3.15)
(c) Write an applet program that accepts two input, strings using <Param> tag and concatenate the
strings and display it in status window. (Refer example 5.6.2)
3. Attempt any FOUR of following : 16
(a) How garbage collection is done in Java ? Which methods are used for it ? (Refer section 2.8)
(b) What is the difference between vector and array ? Give suitable example. (Refer section 2.13)
(c) Write a program to compute the sum of the digits of a given integer numbers. (Refer example 1.8.5)
(d) Explain following methods :
(i) drawrect ( ) (ii) getfont ( ) (Refer section 5.10)
(e) Write a program that will count no. of characters in a file. (Refer section 6.8.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-7 Solved Board Question Papers

4. (A) Attempt any THREE of following : 12


(a) In what ways does a switch statement differ from an if statements ? (Refer example 1.8.1)
(b) Write a program to find the no. of and sum of all integers greater than 100 and less than 200 that are
divisible by 7. (Refer example 1.8.4)
(c) What is synchronization ? When do we use it ? Explain synchronization of two threads.
(Refer section 4.17)
(d) Draw the hierarchy of Writer stream classes, and hierarchy of Reader stream classes.
(Refer section 6.4)
(B) Attempt any ON E of following : 6
(a) What are the access control parameters ? Explain the concept with suitable example.
(Refer section 2.10)
(b) Describe following methods of applet :
(i) suspend ( ) (ii) resume ( )
(iii) sleep ( ) (iv) notify ( )
(v) stop ( ) (vi) wait ( ) (Refer section 5.2)
5. Attempt any TWO of following : 16
(a) Write a thread program for implementing the ‘Runnable interface’. (Refer section 4.13)
(b) Define an exception called ‘N o match Exception’ that is thrown when a string is not equal to
“MSBTE”. Write program. (Refer example 4.11.3)
(c) Write a program to display a string “concentric circles” using font ‘Arial’ size as 12 and style as
bold + italic and display three concentric circles with different colours on the applet.
(Refer example 5.8.1)
6. Attempt any FOUR of the following : 16
(a) What is the use of new operator ? Is it necessary to be used whenever object of the class is created ?
Why ? (Refer section 1.5)
(b) Perform following string / string buffer operations, write java program.
(i) Accept a password from user
(ii) Check if password is correct then display “Good”, else display “Wrong”
(iii) Display the password in reverse order.
(iv) Append password with “welcome”. (Refer example 2.12.2)
(c) What is :
(i) Add Element ( ) &
(ii) Element At ( ) command in vector (Refer section 2.13)
(d) What is Interface ? How to add interfaces to packages. (Refer sections 3.24 and 3.11)
(e) Write java program to display triangle filled with red colour. (Refer example 5.8.5)
(f) Write a java program to copy contents of one file to another file. (Refer example 6.8.1)

TM
Technical Publications - An up thrust for knowledge
Java Programming S-8 Solved Board Question Papers

Summer 2017
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (16172)

3 Hours / 100 Marks Seat No.


1. (A) Attempt any THREE of the following : 3  4 = 12
(a) State and explain any four features of Java. (Refer section 1.1)
(b) Write any four methods of file class with their use. (Refer section 6.9)
(c) Explain any two relational operators in Java with example. (Refer section 1.7)
(d) What is thread ? Draw thread life cycle diagram in Java. (Refer section 4.14)
(B) Attempt any ON E of the following : 16=6
(a) What is single level inheritance ? Explain with suitable example. (Refer section 3.2)
(b) What is package ? State how to create and access user defined package in Java. (Refer section 3.22)
2. Attempt any TWO of the following : 2  8 = 16
(a) Write a program to add 2 integer, 2 string and 2 float objects to a vector.
Remove element specified by user and display the list. (Refer example 2.13.2)
(b) What is meant by interface ? State its need and write syntax and features of interface.
(Refer section 3.11)
(c) Explain applet life cycle with suitable diagram. (Refer section 5.2)
3. Attempt any FOUR of the following : 4  4 = 16
(a) Explain the following methods of string class with syntax and example :
(i) substring() (ii) replace()(Refer section 2.12)
(b) Write a program to find sum of digit of number entered by user. (Refer example 1.8.4)
(c) What is Iterator class ? Give syntax and use of any two methods of Iterator class.(Not in new syllabus)
(d) Describe the following attributes of applet :
(i) Codebase (ii) Alt (iii) Width (iv) Code (Refer section 5.2)
(e) State three uses of final keyword. (Refer section 3.7)
4. (A) Attempt any THREE of the following : 3  4 = 12
(a) Write all primitive data types available in Java with their storage sizes in bytes. (Refer section 1.6.1)
(b) What is thread priority ? Write default priority values and methods to change them.
(Refer section 4.16)
(c) Write a program to generate Fibonacci series 1 1 2 3 5 8 13 21 34 55 89. (Refer example 1.8.5)
(d) Differentiate between Applet and Application (any 4 points). (Refer section 5.1)
(B) Attempt any ON E of the following : 16=6
(a) Write a program to draw a bar chart for plotting students passing percentage in last 5 years.
(Not in new syllabus)
(b) What is garbage collection in Java ? Explain finalize method in Java. (Refer section 2.8)
TM
Technical Publications - An up thrust for knowledge
Java Programming S-9 Solved Board Question Papers

5. Attempt any TWO of the following : 2  8 = 16


(a) What is exception ? WAP to accept a password from the user and throw “Authentication Failure”
exception if the password is incorrect. (Refer section 4.3 and example 4.11.1)
(b) Write a program to create two threads, one to print numbers in original order and other in reverse
order from 1 to 10. (Refer example 4.13.2)
(c) Explain the following methods of applet class :
(i) drawRect() (ii) drawPolygon()
(iii) drawArc() (iv) drawRoundRect()(Refer section 5.8)
6. Attempt any FOUR of the following : 4  4 = 16
(a) Write a program to implement following inheritance : (Refer example 3.15.2)

(b) What is use of ArrayList class ? State any two methods with their use from ArrayList.
(Not in new syllabus)
(c) Design an applet which accepts username as a parameter for html page and display number of
characters from it. (Refer example 5.6.3)
(d) List any four built-in packages from Java API along with their use. (Refer section 3.19)
(e) Write a program to accept two numbers as command line arguments and print the addition of those
numbers. (Refer example 2.6.2)

Winter 2017
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (11718)

3 Hours / 100 Marks


1. (A) Attempt any THREE of the following : 3 × 4 = 12
(a) Explain inheritance and polymorphism features of Java. (Not in new syllabus)
(b) Write any two methods of array list class with their syntax. (Not in new syllabus)
(c) Why java became platform independent language ? Explain. (Refer section 1.1)
(d) Write a program to input name and balance of customer and thread an user defined exception if
balance less than 1500. (Refer example 4.11.4)
(B) Attempt any ON E of the following : 1×6=6
(a) Design an applet which display equals size three rectangle one below the other and fill them with
orange, white and green color respectively. (Refer example 5.8.1)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 10 Solved Board Question Papers

(b) What is the multiple inheritance ? Write a java program to implement multiple inheritance.
(Refer section 3.15)
2. Attempt any TWO of the following : 2 × 8 = 16
(a) Define a class person with data member as Aadharno, name, Panno implement concept of constructor
overloading. Accept data for 5 object and print it. (Refer example 3.4.1)
(b) What is package ? How do we create it ? Give the example to create and to access package.
(Refer section 3.21)
(c) Give the syntax of following methods of graphics class. Explain their use with suitable program :
(i) drawRoundReel() (ii) drawPolygon()
(iii) drawOval() (iv) drawString( ) (Refer section 5.8)
3. Attempt any FOUR of the following : 4 × 4 = 16
(a) Describe following string class method with example :
(i) compareTo( ) (ii) equalsIgnoreCase( ) (Refer section 2.12)
(b) Write a program to copy contents of one file to another. Using byte stream classes.
(Refer example 6.9.1)
(c) Explain method overriding with suitable example. (Refer section 3.5)
(d) Enlist any four built in packages in java API with atleast two class name from each package.
(Refer section 3.19.1)
(e) Write a program to check whether given number is prime or not. (Refer example 1.8.6)
4. (A) Attempt any THREE of the following : 3 × 4 = 12
(a) Write a program to print the following output : (Refer example 1.8.1)
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
(b) Illustrate with example the use of switch case statement. (Refer section 1.8.5)
(c) Write a program to create two thread one to print odd number only and other to print even numbers.
(Refer example 4.13.1)
(d) What is the use of try catch and finally statement give example. (Refer section 4.8)
(B) Attempt any ON E of the following : 1×6=6
(a) What is importance of super and this keyword in inheritance ? Illustrate with suitable example.
(b) Write a single program to implement inheritance and polymorphism in java. (Refer section 3.6)
5. Attempt any TWO of the following : 2 × 8 = 16
(a) What is exception ? Why the exception occurred in program ? Explain with suitable example.
(Refer section 4.4)
(b) Write a program to define two thread one to print from 1 to 100 and other to print from 100 to 1. First
thread transfer control to second thread after delay of 500 ms. (Refer example 4.13.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 11 Solved Board Question Papers

(c) How to pass parameter to an applet ? Write an applet to accept Account N o and balance in form of
parameter and print message “low balance” if the balance is less than 500. (Refer example 5.6.4)
6. Attempt any FOUR of the following : 4 × 4 = 16
(a) What is the use of wrapper classes in Java ? Explain float wrapper with its methods.
(Refer section 2.14)
(b) Write a program to accept number from command line and print square root of the number.
(Refer example 2.6.3)
(c) Write any four methods of File Input stream class give their syntax. (Refer section 6.9)
(d) Write a applet program to set background with red colour and fore ground with blue colour.
(Refer example 5.9.2)
(e) Describe access control specifiers with example. (Refer section 2.10)

Summer 2018
Java Programming Solved Paper
Semester – IV
(Computer Engg. Group & Information Technology) (21718)

3 Hours / 100 Marks


1. (A) Attempt any THREE of the following : 12
(a) Define throws & finally statements with its syntax and example. (Refer section 4.8)
(b) Which are the restrictions present for static declared methods ? (Refer section 3.10)
(c) Explain any four features of java programming. (Refer section 1.1)
(d) Explain how interface is used to achieve multiple Inheritance in Java. (Refer section 3.15)

(B) Attempt any ON E of the following : 6


(a) Write a java program to implement visibility controls such as public, private, protected access modes.
Assume suitable data, if any. (Refer example 3.2.5)
(b) With proper syntax and example explain following graphics methods :
(1) SetColor( ) (2) SetForeGround( )
(3) getFont( ) (4) setSize( ) (Refer section 5.10)
Q.2 Attempt any TWO of the following : 16
(a) Write a java program to copy the content of the file “file1.txt” into new file “file2.txt”.
(Refer example 6.8.1)
(b) Write a java program to implement multilevel inheritance with 4 levels of hierarchy.
(Refer example 3.2.1)
(c) Define applet. Write a program to create an applet to display message
“Welcome to java applet”. (Refer example 5.5.1)
3. Attempt any FOUR of the following : 16
(a) Explain any four applet tag. (Refer section 5.2)
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 12 Solved Board Question Papers

(b) Which are the ways to access package from another package ? Explain with example.
(Refer section 3.22)
(c) Define a class and object. Write syntax to create class and object with an example.
(Refer section 1.5)
(d) With proper syntax and example explain following thread methods :
(1) wait( ) (2) sleep( ) (3) resume( ) (4) notify( ) (Refer section 4.14)
(e) What is type casting ? Explain its types with proper syntax and example. (Refer section 1.6.6)
Q.4 (a) Attempt any THREE of the following : 12
(a) State & explain scope of variable with an example. (Refer section 1.6.5)
(b) With syntax and example explain try & catch statement. (Refer section 4.4)
(c) Explain applet life cycle with suitable diagram. (Refer section 5.2)
(d) Explain byte stream class in detail. (Refer section 6.3)
(B) Attempt any ON E of the following : 6
(a) Write a java program to implement following functions of string :
(1) Calculate length of string
(2) Compare between strings
(3) Concatenating strings (Refer section 2.12)
(b) Write a java program to extend interface assuming suitable data.(Refer section 3.15)
5. Attempt any TWO of the following : 16
(a) Write a java program to implement runnable interface with example. (Refer section 4.13)
(b) Write a java program to display all the odd numbers between 1 to 30 using for loop & if statement.
(Refer example 1.8.8)
(c) Explain following methods for applet with an example :
(1) Passing Parameter to applet (Refer section 5.6)
(2) Embedding <applet> tags in java code. (Refer section 5.3)
6. Attempt any FOUR of the following : 16
(a) Explain following bitwise operator with an example :
(1) left shift operator
(2) write shift operator (Refer section 1.7.6)
(b) State & explain types of errors in Java. (Refer section 4.2)
(c) Enlist types of constructor. Explain any two with example. (Refer section 2.2)
(d) How to add new class to a package ? Explain with an example. (Refer section 3.24)
(e) Explain Array list & Iterator methods of collections with an example. (Not in new syllabus)



TM
Technical Publications - An up thrust for knowledge
Java Programming S - 13 Solved Board Question Papers

Summer 2019
Solved Paper
Java Programming
S.Y. Diploma Semester - IV 21819
(Computer Engg. Group & Information Technology) (CO/CM/IF/CW)

3 Hours / 70 Marks
Instructions :
1) All questions are compulsory.
2) Answer each next main question on a new page.
3) Figures to the right indicate full marks.
4) Assume suitable data, if necessary.
5) Use of Non-programmable Electronic Pocket Calculator is permissible.
6) Mobile Phone, Pager and any other Electronic Communication devices are not permissible in
Examination Hall.
1. Attempt any FIVE of the following : [10]
a) List any eight features of Java . \(Refer section 1.1)
b) State use of finalize( ) method with its syntax. (Refer section 2.8)
c) N ame the wrapper class methods for the following : (Refer section 2.14)
(i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
d) List the types of inheritances in Java. (Refer section 3.2)
e) Write the syntax of try-catch-finally blocks. (Refer section 4.4)
f) Give the syntax of < param > tag to pass parameters to an applet. (Refer section 5.6)
g) Define stream class. List its types. (Refer section 6.2)
2. Attempt any THREE of the following : [12]
a) Explain the concept of platform independence and portability with respect to Java language.
(Refer section 1.1(3))
b) Explain the types of constructors in Java with suitable example. (Refer section 2.2)
c) Explain the two ways of creating threads in Java. (Refer section 4.13)
d) Distinguish between input stream class and output stream class. (Refer section 6.3)
3. Attempt any THREE of the following : [12]
a) Define a class student with int id and string name as data members and a method void SetData ( ).
Accept and display the data for five students.
Ans. :
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class Student
TM
Technical Publications(S -- An
13)up thrust for knowledge
Java Programming S - 14 Solved Board Question Papers

{
int id;
String name;
public void setData()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter id: ");
id=in.nextInt();
System.out.println("Enter name: ");
name=in.next();
}
public void display()
{

System.out.println(id+"\t\t"+name);
}
}
class MyClass
{
public static void main(String args[])
{
Student S[]=new Student[5];
int i;
for(i=0;i<5;i++)
{
S[i]=new Student();
S[i].setData();
}
System.out.println("Data For Five Students is...");
System.out.println("ID \t\t Name ");
for(i=0;i<5;i++)
S[i].display();
}
}
Output
Enter id:
10
Enter name:
AAA
Enter id:
20
Enter name:
BBB
Enter id:
30
Enter name:
CCC
Enter id:
40
Enter name:
DDD
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 15 Solved Board Question Papers

Enter id:
50
Enter name:
EEE
Data For Five Students is...
ID Name
10 AAA
20 BBB
30 CCC
40 DDD
50 EEE
b) Explain dynamic method dispatch in Java with suitable example. (Refer section 3.6)
c) Describe the use of following methods : (i) Drawoval( ) (ii) getFont( ) (iii) drawRect( )
(iv) getFamily ( )
Ans. :

Method Purpose

drawOval() This method is used to draw a circle or oval.

getFont() This method is used to get the current font object.

drawRect() This method is used to draw the rectangle.

getFamily() This method is used to get font family name

d) Write a program to count number of words from a text file using stream classes.
Ans. :
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class WordCount


{
public static void main(String[] args) throws IOException
{
File f1=new File("input.txt");
String[] words=null; //Intialize the word Array
int count=0; //Intialize word count to zero
FileReader fr = new FileReader(f1); //Creation of File Reader object
BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
String s;
while((s=br.readLine())!=null) //Reading Content from the file
{
words=s.split(" "); //Split the word using space
count=count+words.length; //increase the word count for each word
}
fr.close();
System.out.println("Number of words in the file:" +count); //Print the word count
}
}
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 16 Solved Board Question Papers

4. Attempt any THREE of the following : [12]


a) Describe instance Of and dot ( . ) operators in Java with suitable example. (Refer section 1.7.7)
b) Explain the four access specifiers in Java. (Refer section 3.22)
c) Differentiate between method overloading and method overriding.
Ans. :

Sr. Method overloading Method overriding


No.
1. It occurs at compile time. It occurs at run time or execution
time

2. Different number of parameters can The number of parameters that are


be passed to the function. passed to the function are the same.

3. The overloaded functions may have In the method overriding all the
different return types. methods will have same return type.

4. Method overloading is performed Method overriding is normally


within a class. performed between two classes that
have inheritance relationship.

d) Differentiate between Java Applet and Java Application ( any four points) (Refer section 5.1)
e) Write a program to copy content of one file to another file. (Refer example 6.9.1)
5. Attempt any TWO of the following : [12]
a) Describe the use of any methods of vector class with their syntax. (Refer section 2.13)
b) Explain the concept of dynamic method dispatch with suitable example. (Refer section 3.6)
c) Write a program to create two threads. One thread will display the numbers from 1 to 50 (ascending
order) and other thread will display numbers from 50 to 1 (descending order). (Refer example 4.13.2)
6. Attempt any TWO of the following : [12]
a) Explain the command line arguments with suitable example. (Refer section 2.6)
b) Write a program to input name and salary of employee and throw user defined exception if entered
salary is negative.
Ans. :
import java.lang.Exception;
import java.util.Scanner;
class SalException extends Exception
{
SalException(String msg)
{
super(msg);
}
}
class SalaryExceptionDemo
{
public static void main (String args [])
TM
Technical Publications - An up thrust for knowledge
Java Programming S - 17 Solved Board Question Papers

{
Scanner in=new Scanner(System.in);
System.out.print("Enter name: ");
String name=in.next();
System.out.print("Enter salary: ");
int salary=in.nextInt();
try
{
if(salary<0)
throw new SalException("Negative Salary!!!");
else
System.out.println("Correct Salary");

}
catch (SalException e)
{
System.out.println (e.getMessage());
}
}
}
Output
Enter name: aaa
Enter salary: -100
Negative Salary!!!
c) Describe the applet life cycle in detail. (Refer section 5.2)



TM
Technical Publications - An up thrust for knowledge
Java Programming S - 18 Solved Board Question Papers

N otes

TM
Technical Publications - An up thrust for knowledge
Books available @

MUMBAI NASHIK
Student Agencies Pvt. Ltd. Rahul Book Centre
Ph. - 022 - 40496161 / 31 Ph. - 0253 - 27424287
Vidyarthi Sales Agencies Maharashtra Pustak Bhandar
Ph. - 022 - 23829330 Ph. - 0253 - 2317506
022 - 23851416 / 23867279 New India Book House
Bharat Sales Ph. - 9623123458
Ph. - 022 - 23821307 / 7580 Anmol Pustakalaya
Ph. - 9822306289
AHMEDNAGAR Anmol Books
Ph. - 0253 - 2505501
Shripad Granth Bhandar
Ph. - 9922664979 Om Pustakalaya
Ph. - 9422246809
SANGAMNER Pragati Books & Stationers
Ph. - 7721014040
Amrut Book Stall
Ph. - 9850663354 New Om Stationers
& General Stores
NARAYANGAON Ph. - 0253 - 2378874
Shri Ganesh Book Depot
Sunil General Stores
Ph. - 9890335806
Ph. - 9850725770
Eakveera Books
KOPARGAON Ph. - 9422754746

Mauli Books & General Store Yuvraj Books & Stationers


Ph. - 9890451467 Ph. - 9850725770

Kohinoor Book Stall New Anand Pustakalaya


Ph. - 9371719996 Ph. - 9881540440 / 7720054040

KARAD JALGAON
Archana Bazar Parvati Traders
Ph. - 7588065287 Ph. - 9422277738

(i)
R

TECHNICAL PUBLICATIONS - An up thrust for knowledge


SANGALI BARAMATI
G. R. Tamhankar Sankalp World
Ph. - 9422041091 Ph. - 7020837475 / 9765851000
Mirji Book House
Ph. - 9422613980 YEOTMAL
Sankalp Enterprises
Shri Aadhinath Book Centre
Ph. - 9823619823
Ph. - 9422866072
KOLHAPUR
NAGPUR
Granth The Book Word
Ph. - 9922295522 Venus Book Centre
Ph. - 9975768899
DHULE
AURANGABAD
Kushal Book Shop
Ph. - 02562 - 280468 New Arihant Stationers
& Book Centre
LATUR Ph. - 9850697469 / 9420263132
Umade Book Centre
Gatagat Stores Ph. - 9881218686
Ph. - 9422611032
Maya Book Centre
Ph. - 9766660310
AKOLA Vidhyarthi Bhandar
Harne Book Depot Ph. - 9764422777
Ph. - 9922669647
BULDHANA
AMRAVATI
Agrasen Sales Corporation
Navyug Book Stall Ph. - 9422181542 / 9422882542
Ph. - 7212672664

(ii)
R

TECHNICAL PUBLICATIONS - An up thrust for knowledge

You might also like