Java
Java
Java
OBJECT ORIENTED
PROGRAMMING USING
JA V A - I
For T.Y.B.Sc. Computer Science : Semester – V
[Course Code CS 355 : Credits - 2]
CBCS Pattern
As Per New Syllabus, Effective from June 2021
Price ` 600.00
N5865
OBJECT ORIENTED PROGRAMMING USING JAVA - I ISBN 978-93-5451-188-2
Second Edition : September 2022
© : Authors
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any
computer storage system or device for distribution including photocopy, recording, taping or information retrieval system or
reproduced on any disc, tape, perforated media or other information storage device etc., without the written permission of
Authors with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any
mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. It is notified
that neither the publisher nor the authors or seller shall be responsible for any damage or loss of action to any one, of any kind, in
any manner, therefrom. The reader must cross check all the facts and contents with original Government notification or
publications.
Published By : Polyplate Printed By :
NIRALI PRAKASHAN YOGIRAJ PRINTERS AND BINDERS
Abhyudaya Pragati, 1312, Shivaji Nagar, Survey No. 10/1A, Ghule Industrial Estate
Off J.M. Road, Pune – 411005 Nanded Gaon Road
Tel - (020) 25512336/37/39 Nanded, Pune - 411041
Email : niralipune@pragationline.com
DISTRIBUTION CENTRES
PUNE
Nirali Prakashan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S. No. 28/27, Dhayari Narhe Road, Near Asian College 119, Budhwar Peth, Jogeshwari Mandir Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145
Email : bookorder@pragationline.com Email : niralilocal@pragationline.com
MUMBAI
Nirali Prakashan
Rasdhara Co-op. Hsg. Society Ltd., 'D' Wing Ground Floor, 385 S.V.P. Road
Girgaum, Mumbai 400004, Maharashtra
Mobile : 7045821020, Tel : (022) 2385 6339 / 2386 9976
Email : niralimumbai@pragationline.com
DISTRIBUTION BRANCHES
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, Above Maratha Mandir, Shop No. 3,
4575/15 Omkar Tower, Agarwal Road No. 99, 6th Cross, 6th Main, First Floor, Rani Jhanshi Square,
Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi Nagpur 440012 (MAH)
Mobile : 9555778814/9818561840 Karnataka; Mob : 9686821074 Tel : (0712) 254 7129
Email : delhi@niralibooks.com Email : bengaluru@niralibooks.com Email : nagpur@niralibooks.com
marketing@pragationline.com | www.pragationline.com
Also find us on www.facebook.com/niralibooks
Preface …
A special word of thank to Shri. Dineshbhai Furia, and Mr. Jignesh Furia for
showing full faith in us to write this text book. We also thank to Mr. Amar Salunkhe and
Mr. Akbar Shaikh of M/s Nirali Prakashan for their excellent co-operation.
We also thank Ms. Chaitali Takle, Mr. Ravindra Walodare, Mr. Sachin Shinde, Mr. Ashok
Bodke, Mr. Moshin Sayyed and Mr. Nitin Thorat.
Although every care has been taken to check mistakes and misprints, any errors,
omission and suggestions from teachers and students for the improvement of this text book
shall be most welcome.
Authors
Syllabus …
1. An Introduction to Java (6 Lectures)
• Object Oriented Programming Concepts
• A Short History of Java
• Features or Buzzwords of Java
• Java Environment
• Simple Java Program
• Java Tools – jdb, javap, javadoc
• Types of Comments
• Data Types
• Final Variable
• Declaring 1D, 2D Array
• Accepting Input (Command Line Arguments, BufferedReader, Scanner)
2. Objects and Classes (7 Lectures)
• Defining Your Own Classes
• Access Specifiers - (public, protected, private, default)
• Array of Objects
• Constructors, Overloading Constructors and Use of ‘this’ Keyword, Static Block, Static Fields
and Methods
• Predefined Classes
o Object Class, Methods (equals(), toString(), hashcode(), getClass())
o String Class and StringBuffer Class, Formatting String Data using format() Method
• Creating, Accessing and Using Packages
• Wrapper Classes
3. Inheritance and Interface (8 Lectures)
• Inheritance Basics (extends Keyword) and Types of Inheritance
• Superclass, Subclass and Use of Super Keyword
• Method Overriding and Runtime Polymorphism
• Use of Final Keyword related to Method and Class
• Use of Abstract Class and Abstract Methods
• Defining and Implementing Interfaces
• Runtime Polymorphism using Interface
• Concept of Marker and Functional Interfaces
4. Exception and File Handling (5 Lectures)
• Dealing with Errors, Exception Class, Checked and Unchecked Exception
• Catching Exceptions, Multiple Catch Block, Nested Try Block
• Creating User Defined Exception
• Introduction to Files and Streams
• Input-OutputStream: FileInput/OutputStream, BufferedInput/OutputStream,
DataInput/OutputStream
• Reader-Writer: FileReader/Writer, BufferedReader/Writer, InputStreamReader,
OutputStreamWriter
5. User Interface with AWT and Swing (10 Lectures)
• What is AWT? What is Swing? Difference between AWT and Swing
• The MVC Architecture and Swing
• Layouts and Layout Managers
• Containers and Components – JFrame, JButton, JLabel, JText, JTextArea, JCheckBox and
JRadioButton, JList, JComboBox, JMenu and related Classes
• Dialogs (Message, Confirmation, Input), JFileChooser, JColorChooser
• Event Handling: Event Sources, Listeners
• Adapters and Anonymous Inner Class
Contents …
1.0 INTRODUCTION
• Java is a general-purpose, high level, robust, Object-Oriented Programming (OOP)
language developed by Sun Microsystems in 1991.
• OOP is a programming paradigm that uses objects and their interactions to design
applications and computer programs.
• A programming paradigm describes the structure of a program. In other words, it
determines how the instructions are placed in a program.
• Java programming language was initiated by James Gosling. He is called father of Java
programming.
• The first version of Java 1.0 was released by Sun Microsystems in 1995. It made the
promise of "Write Once, Run Anywhere (WORA)", with free (no cost) runtimes on
popular platforms such as Enterprise applications.
• With the advancement of Java and its widespread popularity, use new enhanced
versions of Java have been released. The new J2 versions were renamed as Java SE,
Java EE, and Java ME respectively.
• Java Platform, Standard Edition (Java SE) is a computing platform for development
and deployment of portable code for desktop and server environments. Java SE was
formerly known as Java 2 Platform, Standard Edition (J2SE).
• Java Platform, Micro Edition (Java ME) is a computing platform for development and
deployment of portable code for embedded and mobile devices (micro-controllers,
sensors, mobile phones, Personal Digital Assistants (PDAs etc.)). Java ME was formerly
known as Java 2 Platform, Micro Edition (J2ME).
• Java Platform, Enterprise Edition (Java EE) is a computing platform, extending Java SE
with specifications for enterprise features such as distributed computing and web
services. Java EE was formerly known as Java 2 Platform, Enterprise Edition (J2EE).
1.1
Object Oriented Programming using Java - I An Introduction to Java
• The latest release/version of the Java programming language is Java SE 16. Java 16
contains new features, enhancements and bug fixes to improve efficiency to develop
and run Java programs.
• Java programming language is mainly used to create these following four types of
applications:
1. Web Applications: Web application is an application which creates a dynamic
page and runs on the side of server. At present time, technologies that are used to
create web application in Java programming language are Struts, Spring, Servlet,
Hibernate, JSP, JSF, etc.
2. Mobile Applications: Mobile application refers to application that is developed for
mobile devices. At present time, platforms that are used to develop mobile
applications in Java programming language are Java ME and Android.
3. Standalone Applications: Desktop applications and Window based applications
are the other name of standalone applications. We need to install this traditional
software on every machine. Media player and antivirus are the examples of these
applications. At current time, for the creation of standalone applications AWT and
swing are used in Java programming language.
4. Enterprise Applications: Enterprise applications are those applications which are
distributed in nature. Banking application is the example of enterprise
applications. It gives programmer the advantage of high level security, clustering
and load balancing. At present time, EJB is used in Java programming language for
developing enterprise applications.
• An object has identity which differentiates one object from the other. Object name is
used to identify the object. Hence, name itself is an identity.
• Objects are generally used to access members (data and methods) of class.
For example: Person p = new Person();. In this statement 'p' is an object of Person
class.
• Fig. 1.1 shows example of class and objects. Fig. 1.1 shows class Car has objects like
Audi, Nissan, Volvo.
class objects
• The data is not accessible to the outside world and only functions which are wrapped
in the class can access it.
• Thus, insulation of data from direct access from program is called data hiding.
5. Inheritance:
• Inheritance is the process by which object of one class can acquire the properties of
the objects of another class.
• Inheritance means one class of object inherits the data and behavior (methods) from
another class.
• The old class is referred as a base class (parent class or super class) and new class is
called as derived class (child class or sub class). The new class has combined features
of both the classes.
• Fig. 1.2 shows a class called Vehicle, which has two subclasses called Car and Truck.
The Vehicle class is the superclass of Car and Truck.
Vehicle
Car Truck
Fig. 1.2: Classes Car and Truck inherits from the class Vehicle
6. Polymorphism:
• Polymorphism is the ability to take more than one form. In short, polymorphism is the
ability of an object to take on many forms.
• The most common use of polymorphism in OOP occurs when a parent class reference
is used to refer to a child class object.
• For example: An operation may demonstrate different behavior in different instance.
The behavior depends upon the type of data used in the operation. As addition of two
integer numbers give addition while addition of two strings give concatenation.
7. Dynamic Binding:
• Binding refers to the linking of a procedure call to the procedure definition (code) to
be executed in response to the call.
• Binding is classified as static binding and dynamic binding as explained below:
(i) Static Binding means that the code associated with given procedure call is known
at compile time.
(ii) Dynamic Binding means that the code associated with given procedure call is not
known until the time of the call at run time. Dynamic binding associated with
polymorphism and inheritance.
8. Message Passing:
• In OOP objects are communicate with each other through message passing. A message
for an object is a request for execution of a method.
1.5
Object Oriented Programming using Java - I An Introduction to Java
• Message passing involves specifying the name of object, the name of the method and
the information to be sent.
• For example: p.accept(“abc”,18); here, p is an object of Person class, accept is
message and abc, 18 are arguments is information.
Advantages of OOP:
1. Software is easily developed for complex problems.
2. Using OOP, software reuse is enhanced.
3. Using OOP, software maintenance cost can be reduced.
4. Modularity is achieved using OOP.
5. Software has improved performance.
6. Software quality is improved.
7. Data access is restricted providing better data security.
Disadvantages of OOP:
1. OOP requires intensive testing procedures.
2. Solving a problem using OOP approach consumes more time than the time taken
by structured.
• With every version, Java became stronger and stronger. At the time of writing of the
book, Java had come up with its version SE 8 in April 2014.
• Table 1.1 illustrates the various versions released of Java language, till date.
Table 1.1: History of Java
JAVA SE 9 September, 2017 Fix some open issues and concerns, and to
refine some critical technical questions.
JAVA SE 11 September, 2018 Open for bug fixes. It offers LTS( Long Term
Support).
• There are various features of Java as given in Fig. 1.3. Each feature of Java will tell us
about how and why Java is a powerful object-oriented programming language.
1.7
Object Oriented Programming using Java - I An Introduction to Java
Simple
Object-
Dynamic oriented
Architecure-
Secure neutral
High-
Multi- performance
threaded
Features
Platform
Interactive independent
Distributed
Robust
Interpreted Portable
1.9
Object Oriented Programming using Java - I An Introduction to Java
• The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications.
• JSL also known as the Application Programming Interface (API). The JSL (or API)
includes hundreds of classes and methods grouped into several functional packages.
• Fig. 1.4 depicts a typical Java environment.
.java file Java compiler .class file Class Loader
JVM
Native OS
1.10
Object Oriented Programming using Java - I An Introduction to Java
Class
Class files loader
subsystem
PC Native
Method Heap Java
registers method
area stacks
stacks
Native
Native method method
Execution interface libraries
engine
• When we run a Java program, the virtual machine loads the Java API class files that
are referred to by the program’s class files.
• The combination of all loaded class files (from your program and from the Java API)
and any loaded dynamic libraries (containing native methods) constitute the full
program executed by the Java virtual machine.
Java
program
1.12
Object Oriented Programming using Java - I An Introduction to Java
Class Definition
1.13
Object Oriented Programming using Java - I An Introduction to Java
Output
1.14
Object Oriented Programming using Java - I An Introduction to Java
• To write Java programs, we will need a text editor. A text editor is a type of program
used for editing plain text files. The text editors for Java includes Notepad++, jEdit,
Editplus and so on.
• There are even more sophisticated IDEs (Integrated Development Environment)
available in the market like Eclipse, Netbeans, JCreator and so on.
First Java Program: [Oct. 17, April 18]
public class HelloJavaWorld
{
public static void main(String[] args)
{
System.out.print("Hello");
System.out.println("Java world!");
}
}
Output:
Hello
Java World!
Explanation of above Program:
o The class keyword is used to declare a class in Java. In the above program,
'HelloWorld' defines the class name in Java. Every class definition in Java begins
with an opening brace { and ends with closing brace }.
o The public is a keyword and a access specifier indicates that the class member can
be accessed from anywhere in the program.
o The static keyword indicates that this method can be invoked simply by using the
name of the class without creating any class-object.
o The void keyword specifies that this method will not return any type of data.
The main() method is the main entry point of the program, to start execution. First
of all JVM calls the main method of a class and start execution. JVM (Java Virtual
Machine) is responsible for running Java programs.
o args is a string array that takes values from Java command line. It's index starts
from '0'. We can access values by writing args[0], args[1] etc.
o The print word sends the information into a buffer. This buffer is not flushed till a
newline or end-of-line character is send. So it prints output on one line and cursor
is blinking on the same line.
o The println() function prints the output to the standard output stream i.e. monitor.
o The out word represents the standard output stream (monitor).
Compiling the Program: [Oct. 17]
o To compile the HelloWorld program, execute the compiler, javac specifying the
name of the source file on the command line. This is shown below:
$ javac HelloJavaWorld.java
1.15
Object Oriented Programming using Java - I An Introduction to Java
o Javac compiler creates a file named 'HelloJavaWorld.class' which contains the byte
code version of the program. It is an intermediate representation of the program.
Executing the Program:
o To actually run the program we must use the Java application launcher called
‘java’. This is shown below:
$ java HelloJavaWorld
1.6.1 javac
• javac is the primary java compiler included in the JDK. javac is used to compile Java
source into bytecode.
• The java source code is written in files with extension .java. In order to execute the
program, these files need to be compiled in .class files. javac translates or converts the
".java" file to a ".class" file.
Syntax: $ javac filename.java
Example: $ javac HelloJavaWorld.java
1.16
Object Oriented Programming using Java - I An Introduction to Java
1.6.2 java
• In Java language, java is launcher for Java program. java is the interpreter which
launches a java program.
• The java interpreter executes the bytecode files produced by the Java compiler. It
translates the Java bytecode into the code that can be understood by the Operating
System (OS).
Syntax: $ java filename
Example: $ java HelloJavaWorld
• Fig. 1.10 shows java interpreter process.
Java program
Compiler javac
2
Internet
JVM
Tool Interface
JDWP
Java Debug
Wire Protocol
JDI
Java Debug
Interface
1.18
Object Oriented Programming using Java - I An Introduction to Java
1.19
Object Oriented Programming using Java - I An Introduction to Java
• The javap command displays information about the fields, constructors and methods
present in a class file.
Syntax: javap class_name
Example:
class Simple
{
public static void main(String args[])
{
System.out.println("hello java");
}
}
• Now let use the javap tool to disassemble the class file.
javap Simple
Output: Compiled from ".java"
class Simple
{
Simple();
public static void main(java.lang.String[]);
}
• It's output depends on the options used. The important options of javap tools are as
follows:
Option Description
-help Print the help message.
-l Prints line number and local variable.
-c Disassembles the code.
-s Prints internal type signature.
-sysinfo Shows system info (path, size, date, MDS hash).
-constants Shows static final constants.
-version Shows version information.
1.20
Object Oriented Programming using Java - I An Introduction to Java
Where, destination file_list can have more than one file separated by space, ?, & and *
are the wildcard characters used with filenames.
Options Description
c Creates new or empty ·jar file.
f Created jar file named on command line.
t Lists the table of contents.
v Generates additional output.
x Extract the file on command line.
0 (digit zero) No compression and store the file.
Example: jar cf first.jar second.class
jar tf newjar.jar
1.7.1 Comments
• Comments are non-executable statements and are ignored by the Java compiler. The
comment increases the readability of the programs.
• Comments help the person/user reading the code better understand the intent and
functionality of the program.
• All characters available inside any comment are ignored by Java compiler. Java
language provides three styles or types of comments as given in following table:
Sr.
Type of Comment Description
No.
1. /* Multiline comment */ Multi line comments start with /* and ends
with */. Any text between /* and */ will be
ignored by Java compiler.
Example: /* Welcome to Nirali Prakashan.
A text book publishing firm */
2. // Single line comment Single-line comments start with two forward
slashes (//). Any text between // and the end of
the line is ignored by Java (will not be
executed).
Example: // Welcome to Nirali Prakashan.
contd. …
1.21
Object Oriented Programming using Java - I An Introduction to Java
• Data types specify the different values that can be stored in the variable. Variables are
nothing but reserved memory locations to store values.
• The type of value that a variable can hold is called as data type. The main purpose of
data types in Java is to determine what kind of value we can store into the variable.
• The data type of a variable determines the value which a variable can contain and the
operations that can be performed on it. Every variable must have a data type.
• Java has a rich set of data types. The data types in Java are shown in Fig. 1.13.
1.22
Object Oriented Programming using Java - I An Introduction to Java
Data Types
Primitive Non-Primitive
byte short
1.7.3 Tokens
• The smallest individual units in a Java program are called tokens. Java tokens are
smallest elements of a Java program which are identified by the compiler.
• Tokens in Java include variables, constants, identifiers, keywords, literals, operators,
special characters, separators and so on.
Java Identifiers:
• Identifiers are used for naming classes, methods, variables, objects, labels, packages
and interfaces in a program.
• In Java, there are several rules for identifiers. They are as follows:
1. All identifiers should begin with a letter (A to Z or a to z), currency character ($) or
an underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A keyword cannot be used as an identifier.
4. Identifiers are case sensitive so Amar and amar has different meaning.
• Examples of legal identifiers: age, $salary, _phone, _ID.
• Examples of illegal identifiers: 123abc, -salary.
Constants in Java:
• In java constants, refer to fixed values that do not change during the execution of a
program.
1.24
Object Oriented Programming using Java - I An Introduction to Java
• Constants are also called as literals which has fixed values in a program. Java supports
several types of constants below:
1. Integer Constants:
• An integer constant means the sequence of digits. There are three types of integers:
(i) Decimal Integer: Decimal integers consists of a set of digits, 0 through 9
preceded by an optional minus sign.
For example: 325, −978, 45673.
Embedded spaces, commas and non-digits characters are not allowed between
digits.
For example: 15 78, $657−, #47 is illegal number.
(ii) Octal Integer: An octal integer constant consists of any combination of digits
from the set 0 through 7, with al leading 0.
For example: 027, 0, 0231, 0341.
(iii) Hexadecimal Integer: A sequence of digits preceded by 0X or 0X is considered a
hexadecimal integer (hex integer).They may also include alphabet A through F or
a through f. A letter A through F represents the number 1 through 15.
For example: 0X4, 0X15, 0xabed.
2. Real Constant:
• Integers numbers are insufficient to represents quantities that vary continuously,
such as distance heights, temperature, prices, and so on.
• Numbers having fractional parts like 17.548 represents these quantities. Such
numbers are called real (or floating point) constants.
For example: 1.9783, 0 0047
• The real number constant can comprise of four parts namely, whole number, decimal
point, fractional part and exponent part.
• These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer.
For example: 0.035, 111.98.
• A real number may also be expressed as in exponential (or scientific) notation. For
example, the value 215.65 may be written as 2.1565e2 in exponential notation. e2
means multiply by 10^2. .
For example: 0.65e4, 15e−5, 2.6e+6 56.E4.
3. Character Constant:
• A single character constant or character constant contains a single character enclosed
within a pair of single quote marks.
• Examples are ‘7’, ‘A’, ‘*’, ‘ ’.
• The character constant ‘7’ is not the same as the number 7. The last constant is blank
space.
4. String Constant:
• A string constant is a sequence of character enclosed between double quotes in which
the character may be alphabets, digits, special characters and blank spaces.
• For example: “WELCOME”, “@june”, “abhishek”, “!NIDHI!”
1.25
Object Oriented Programming using Java - I An Introduction to Java
Backslash Characters:
• The backslash character constant are used with output statements for getting more
effects like tab, new line, single quote etc. Java support some special backslash
character constants.
• A backslah (\) precedes that character to represent it as an escape sequence. For
example, the character n represents the alphabet n, where \n represents a new line
character. Here, \n is an escape sequence that uses an available printable character n.
• A list of such backslash character constant is given following table. Each one of them
represents one character, although they consist of two character. These characters
combinations are known as escape sequences.
1.26
Object Oriented Programming using Java - I An Introduction to Java
Separator:
• In java separators are symbols used to show the separated code, they describe
function of our code.
• Table 1.5 shows various type of separators used in Java.
Table 1.5: Type of Separators
Name Use
() Parameter in method definition, containing statements for
conditions, etc.
{} Used for define a code for method and classes.
[] Used for declaration of array.
; Used to show that separate statement.
, Used to show the separation in identifier in variable declaration.
. Used to show the separate package name from sub-packages and
classes, separate variable and method from reference variable.
Operators in Java:
• Operator is a symbol that represents some operation that can be performed on data.
Operators perform some specific operations using the operands and operator.
• For example, answer can be given using expression 4 + 5 is equal to 9. Here, 4 and 5
are called operands and + is called operator.
• The operator that uses a single operand is called a unary operator and that which uses
two operands is known as a binary operator. A ternary operator uses three operands.
• Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the various groups Arithmetic Operators, Relational Operators,
Bitwise Operators, Logical Operators, and Assignment Operators and so on.
1. Arithmetic Operators:
• Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.
• Table 1.6 lists the arithmetic operators. Assume integer variable A holds
10 and variable B holds 20.
Table 1.6: Arithmetic Operators
Sr.
Operator Description Example
No.
1. + (Addition Adds values on either side of the A + B will give 30
Operator) operator.
2. − (Subtraction Subtracts right hand operand from left A − B will give − 10
Operator) hand operand.
contd. …
1.27
Object Oriented Programming using Java - I An Introduction to Java
2. Relational Operators:
• Relational operators are also called as comparison operators used for comparing
values of two variables.
• Table 1.7 shows relational operators supported by Java language. Assume variable A
holds 10 and variable B holds 20.
Table 1.7: Relational Operators
Sr.
Operator Description Example
No.
1. == Checks if the values of two operands are equal or (A = = B) is not
(Equal to not, if yes then condition becomes true. true.
Operator)
2. != (Not Checks if the values of two operands are equal or (A != B) is true.
Equal to not, if values are not equal then condition becomes
Operator) true.
3. > Checks if the value of left operand is greater than (A > B) is not
(Greater the value of right operand, if yes then condition true.
than becomes true.
Operator)
4. < (Less Checks if the value of left operand is less than the (A < B) is true.
than value of right operand, if yes then condition
Operator) becomes true.
5. >= ( Checks if the value of left operand is greater than (A >= B) is not
Greater or equal to the value of right operand, if yes then true.
than or condition becomes true.
Equal to
Operator)
6. <= (Less Checks if the value of left operand is less than or (A <= B) is true.
than or equal to the value of right operand, if yes then
Equal to condition becomes true.
Operator)
Program 1.3: Program for relational operators.
public class Sample
{
public static void main(String args[])
{
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a < b = " + (a < b) );
System.out.println("c > b = " + (c > b) );
1.29
Object Oriented Programming using Java - I An Introduction to Java
Output:
(a > b && c == d) = true
(a < b && c == d) = false
(a < b || c == d) true
!(a < b) = true
4. Assignments Operators:
• Assignment operators are used to assign values to variables.
Table 1.9: Assignments Operators
Sr.
Operator Description Example
No.
1. = (Simple Assignment Assigns values from right C = A + B will assign value of
Operator) side operands to left side A + B into C
operand
2. += (Add and It adds right operand to C += A is equivalent to C = C
Assignment Operator) the left operand and +A
assign the result to left
operand
3. −= (Subtract and It subtracts right operand C -= A is equivalent to C = C −
Assignment Operator) from the left operand and A
assign the result to left
operand
4. *= (Multiply and It multiplies right C *= A is equivalent to C = C
Assignment Operator) operand with the left *A
operand and assign the
result to left operand
5. /= (Divide and It divides left operand C /= A is equivalent to C = C /
Assignment Operator) with the right operand A
and assign the result to
left operand
6. % = (Modulus and It takes modulus using C %= A is equivalent to C = C
Assignment Operator) two operands and assign %A
the result to left operand
7. <<= Left Shift AND C <<= 2 is same as C = C << 2
Assignment Operator.
8. >>= Right shift AND C >>= 2 is same as C = C >> 2
Assignment Operator.
9. &= Bitwise AND Assignment C &= 2 is same as C = C & 2
Operator.
10. ^= Bitwise Exclusive OR AND C ^= 2 is same as C = C ^ 2
Assignment Operator.
11. |= Bitwise Inclusive OR AND C |= 2 is same as C = C | 2
Assignment Operator.
1.31
Object Oriented Programming using Java - I An Introduction to Java
5. << (Binary Left Shift The left operands value A << 2 will give 240
Operator) is moved left by the which is 1111 0000
number of bits specified
by the right operand.
6. >> (Binary Right Shift The left operands value A >> 2 will give 15 which
Operator) is moved right by the is 1111
number of bits specified
by the right operand.
7. >>> (Shift right zero fill The left operands value A >>>2 will give 15
operator) is moved right by the which is 0000 1111
number of bits specified
by the right operand and
shifted values are filled
up with zeros.
Program 1.7: Program for bitwise operators.
public class Sample
{
public static void main(String args[])
{
int a = 60;
int b = 20;
System.out.println("a & b = " + (a & b) );
System.out.println("a | b = " + (a | b) );
System.out.println("a << 2 = " + (a << 2) );
System.out.println("a >> 2 = " + (a >> 2) );
System.out.println("a >>> 2 = " + (a >>> 2) );
}
}
Output:
a & b = 20
a | b = 60
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
8. Special Operators:
• There are few other operators supported by Java language as explained below:
(i) instanceof Operator:
• This operator is used only for object reference variables. The operator checks whether
the object is of a particular type(class type or interface type).
1.34
Object Oriented Programming using Java - I An Introduction to Java
1.36
Object Oriented Programming using Java - I An Introduction to Java
1.7.4 Variables
• Variables are containers for storing data values. Variables are the basic units used to
store any information in Java.
• A variable is an identifier that denotes a storage location used to store a data value.
The value in the variable can be changed during the program’s execution.
• Variables are nothing but reserved memory locations to store values. This means that
when we create a variable we reserve some space in memory.
• Following are the some rules used for variable naming:
1. Variable name must begin with either a letter or the dollar sign "$" or the
underscore character "_".
2. Variable names are case-sensitive. Upper case and lower case must be distinct this
means that the variable Abc is not the same as abc or ABC.
3. Variable must not begin with a digit.
4. White space is not allowed in variable naming.
5. Variable name should not be a keyword.
6. Variable names can be of any length.
Variable Declaration:
• In Java, all the variables must be declared before use. A variable declaration, in its
simplest form, includes the name and the data type of variables.
• Declaration does following three things:
1. It tells variable name to the compiler.
2. It specifies the data type of the data hold by variable.
3. The place of declaration in the program decided the scope of the variable.
• Following is the basic form/syntax of a variable declaration:
data_type variable_Name;
Here, data_type is one of Java's data types and variable_Name is the name of the
variable.
• To declare more than one variable of the specified type, you can use a comma-
separated list as given below:
data_type variable_Name1, variable_Name2, …… variable_NameN;
Example:
int age; // Declares age
int a, b, c; // Declares three ints, a, b, and c.
Variable Initialization:
• Variable initialization means assigning a value to variables. Initializing a variable
means specifying an initial value to assign to it (i.e., before it is used at all).
• In Java, we can assign a value to variables in two ways:
1. Static: This means that the memory is determined for variables when the
program starts. Variables can be assigned initial values at the time of declaration.
Assignment operator (=) assigns the value of an expression to a variable.
Syntax: variable_name=value; OR data_type variable_name=value;
1.37
Object Oriented Programming using Java - I An Introduction to Java
Examples: IntitalValue = 0;
a = b = c = 0;
int a = 10, b = 10; // Variable initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
2. Dynamic: Dynamic means that in Java, we can declare variables anywhere in the
program, because when the statement is executed the memory is assigned to them.
Java allows its programmers to initialize a variable at run time also. Initializing a
variable at run time is called dynamic initialization.
Program 1.10: Program for dynamic initialization of variables.
class DynamicInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("C=" + c);
}
}
Output:
C=5.0
Scope of Variables:
• The area of the program where the variable is accessible is called its scope. Scope
refers to the lifetime and accessibility of a variable.
• The scope of a variable defines the section of the code in which the variable is
accessible or visible.
• Scope is the lifetime of a variable and refers to how long the variable exists before it is
destroyed.
• Scope itself specifies that the system allocates and de-allocates the memory for the
variable.
• Java variables are actually classified into three categories and their scope is defined
according their category as given below:
1. Instance Variables: Instances are declared inside the class. Instance variables are
created when the objects are instantiated (created) and those are associated with
the objects. They take different values for each object. Instance variables are
declared in a class, but outside a method, constructor or any block. The instance
variables are visible for all methods, constructors and block in the class.
2. Class/Static Variables: Class variables are declared inside the class and global to
the class and belong to the entire set of object and that class creates. Only one
memory location is created for each class variable. Visibility is similar to instance
variables.
1.38
Object Oriented Programming using Java - I An Introduction to Java
3. Local variables: Local variables declared and used inside the methods. They are
not available outside of the method definition. Local variables can be declared
inside the program blocks that are defined between the opening { and closing
braces }. These variables are visible to the program only. When the program
control leaves block, all the variables in the block will cease to exit.
Sr.
Characteristic Local Variable Instance Variable Class Variable
No.
1.39
Object Oriented Programming using Java - I An Introduction to Java
1.40
Object Oriented Programming using Java - I An Introduction to Java
1.41
Object Oriented Programming using Java - I An Introduction to Java
T F
while do for
Fig. 1.15: Java control statements
1.7.8 Selection / Decision Making Statements
• A selection statement is a control statement that allows choosing between two or more
execution paths in a program.
• The decision making statements are used to change the flow of the program based on
conditions.
• Various selection statements are discussed below:
1. if Statement:
• The if statement is a powerful and simplest decision making statement and is useful to
control the flow of execution of program statement.
• In 'if' statement if the condition is true then, it executes statement or statements which
are present under if statement. Otherwise (if the condition is false) it goes out of loop
or control transfer out of loop.
1.43
Object Oriented Programming using Java - I An Introduction to Java
if(condition)
boolean if condition is True
{
expression
// Statements;
}
if condition is Flase if code
rest of code
(a) Syntax (b) Flow Diagram
Fig. 1.16: if Statement
Program 1.13: Program for if statement.
public class ExampleIf
{
public static void main(String[] args)
{
int number = 25; //defining an variable
if(number >0)
{
System.out.print("Number is greater than zero (0) ");
}
}
}
Output:
Number is greater than zero (0)
2. if else Statement:
• It is basically extension of if statement. If the Boolean-expression is True if code gets
executed. If Boolean expression is False else code gets executed.
• In this decision making statements generally either of the block gets executed whether
it’s if code or else code, after either execution rest code gets executed.
Start
• Fig. 1.17 shows syntax and flow diagram of if-else statement.
if(Boolean expression)
{
//if code goes here…
Executes when the Boolean if condition is True
expression is True…; Boolean-expression
}
else
{
//else code goes here
Executes when the Boolean if condition is False if code
expression is False…;
} else code
rest-of-code;
Rest of code
Program 1.14.: Program to find even or odd number using if else statement.
public class IfElseExample
{
public static void main(String[] args) {
//defining a variable
int number=13; //defining a variable
if(number%2==0) //Check if the number is divisible by 2 or not
{
System.out.println("Even number");
}
else
{
System.out.println("Odd number");
}
}
Output:
Odd number
Nested ‘if’ Statement:
• The nested if statement represents the if statement within another if statement. Here,
the inner if statement condition executes only when outer if statement condition is
True.
Syntax:
if(Boolean expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean expression 2)
{
// Executes when the Boolean expression 2 is true
}
}
Program 1.15: Program for nested if statement.
public class JavaNestedIfExample
{
public static void main(String[] args)
{
int age=20; //Creating two variables for age and weight
int weight=80;
//applying condition on age and weight
1.45
Object Oriented Programming using Java - I An Introduction to Java
if(age>=18)
{
if(weight>50)
{
System.out.println("Eligible to donate blood");
}
}
}
}
Output:
Eligible to donate blood
Nested if else Statement:
• The nested if-else statements are used where we want to make series of decision
making. Thus one if-else is nested within another if-else. Therefore nested if-else give
us to make a decision within a decision already taken.
• The syntax for nested if-else statement given below:
if(Boolean expression 1)
{
if(Boolean expression 2)
{
// Statement 1;
}
else
{
// Statement 2;
}
}
else
{
// Statement 3;
}
Program 1.16: Program for nested if else statement.
public class JavaNestedIfElseExample
{
public static void main(String[] args)
{
int age=25; //Creating two variables for age and weight
int weight=48;
1.46
Object Oriented Programming using Java - I An Introduction to Java
Rest-of-code;
rest of code
case 'M':
System.out.println
("Internal Combustion Engines, Mechanical Vibration");
break;
}
break;
case 4:
switch(branch)
{
case 'C':
System.out.println
("Data Communication and Networks, MultiMedia");
break;
case 'E':
System.out.println("Embedded System, Image Processing");
break;
case 'M':
System.out.println
("Production Technology, Thermal Engineering");
break;
}
break;
}
}
}
Output:
Data Communication and Networks, MultiMedia
1.7.9 Loops
• There may be a situation when we need to execute a block of code several number of
times.
• A loop statement allows us to execute a statement or group of statements multiple
times until conditions become true.
• The process of repeatedly performing tasks is known as looping. There is either entry
controlled loop or exit controlled loop.
• If a loop first checks condition for execution then it is called as entry controlled loop
and if a loop checks condition after the execution of statement then they are called as
exit controlled loops.
1.51
Object Oriented Programming using Java - I An Introduction to Java
• The for and while loops are known as entry controlled loop. The do-while loop is exit
controlled loop.
• Java is having three different loop statements, i.e., while loop, do-while loop and for
loop.
1. while Loop:
• In Java while loop is used when as single or a group of statements is to be executed
repeatedly as long as a given condition is satisfied.
• The while loop is entry controlled loop statement. The while statement continually
executes a block of statements while a particular condition is true.
• Fig. 1.19 shows syntax and control flow of while loop. Start
False
Test Condition
True
while(condition) Body of
while loop
{
//body of the loop;
}
Exit while
loop
1.52
Object Oriented Programming using Java - I An Introduction to Java
Output:
1
2
3
4
5
6
7
8
9
10
2. do-while Loop:
• Sometimes, in the program it is desirable to execute the loop at least once. The
do-while loop can be applied in this case.
• The loop is executed first and then the loop condition is checked. The condition is
written at the end of the loop.
• This is also called as exit-controlled loop. Start
Body of
do-while loop
do Test Condition
True False
{
//body of the loop;
}while(condition);
Exit while
loop
1.53
Object Oriented Programming using Java - I An Introduction to Java
Declare counter
for(initialization; condition;
Increment counter
increment/decrement)
{
//Body of the loop; Conditional code
}
Condition
If condition
is True
If condition
is False
(a) Syntax (b) Flow Diagram
Fig. 1.21: for Loop
1.54
Object Oriented Programming using Java - I An Introduction to Java
1.58
Object Oriented Programming using Java - I An Introduction to Java
Output:
Tables
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
3. Nested do while Loop:
• We can use do while loop inside another do while loop is called nested do while loop.
• The syntax for a nested do...while loop as follows:
do
{
//Statement(s);
do
{
//Statement(s);
}while(condition);
}while(condition);
Program 1.27: Program to print triangle of numbers.
public class NestedDOWhileLoop
{
public static void main(String args[])
{
int i=1, j=1;
do
{
int k = 5;
do
{
System.out.print(" ");
k--;
}while(k>=i);
j = 1;
1.59
Object Oriented Programming using Java - I An Introduction to Java
do
{
System.out.print(i + " ");
j++;
}while(j<=i);
System.out.println("");
i++;
}while(i<=5);
}
}
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
{
flag=1;
break;
}
else
{
flag=0;
}
}
if(flag==0)
System.out.println(num +"is prime");
else
System.out.println(num +" is not prime");
}
}
Output:
7 is prime
Program 1.29: Program to break statement with label.
Public class BreakWithLabelDemo
{
public static void main(String[] args)
{
int a[][] = {{ 32, 87, 3, 589 }, { 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }};
int num = 12;
int i;
int j = 0;
boolean flag = false;
search: for (i = 0; i <a.length; i++)
{
for (j = 0; j < a[i].length; j++)
{
if (a[i][j] == num)
{
flag = true;
break search;
}
}
}
if (flag)
System.out.println("Found " + num + " at " + i + ", " + j);
else
System.out.println(num + " not in the array");
}
}
Output:
Found 12 at 1, 0
1.61
Object Oriented Programming using Java - I An Introduction to Java
2. continue Statement:
• The continue statement causes the loop to be continued with the next iteration after
skipping any statements in between.
• The continue statement is used when it is necessary to skip a part of the body of the
loop under certain conditions.
• The continue statement tells the compiler, "skip or omit the statements mentioned and
continue with the next iteration."
• In while and do loops, using the continue statement, the control to go directly to the
test condition and then continue the iteration process.
• In the case of for loop, the increment section of the loop is executed before the test
condition is evaluated.
• The continue statement skips the current iteration of a for, while or do-while loop.
• The unlabeled form skips to the end of the innermost loop's body and evaluatesthe
Boolean expression that controls the loop.
Syntax: continue;
Program 1.30: Program for continue statement.
public class Sample
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
if(i==4)
continue;
System.out.println("i=" + i);
}
}
}
Output:
i=1
i=2
i=3
i=5
i=6
i=7
i=8
i=9
i=10
1.62
Object Oriented Programming using Java - I An Introduction to Java
3. return Statement:
• The return statement exits from the current method and control flow returns to where
the method was invoked.
• A return statement causes the program control to transfer back to the caller of a
method.
Syntax: return;
Program 1.31: Program for return statement.
public class ReturnTest
{
public int add()
{ // without arguments
int x = 30;
int y = 70;
int z = x+y;
return z;
}
public static void main(String args[])
{
ReturnTypeTest1 test = new ReturnTypeTest1();
int add = test.add();
System.out.println("The sum of x and y is: " + add);
}
}
Output:
The sum of x and y is: 100
• An array is a group of contiguous memory locations to store the data of common type.
An array is a collection of similar type of elements that have contiguous memory
location.
• Java array is an object that contains elements of similar data type. It is a data structure
where we store similar elements. We can store only fixed set of elements in a java
array.
• Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
• Commonly used terms or element in array are explained below:
1. Element: Element of an array is the items it contains. An array can contain one or
more elements.
1.63
Object Oriented Programming using Java - I An Introduction to Java
0 1 2 3 4 5 6 7 8 9 Indices
Array length is 10
0 1 2 3 4 Indices
Array length is 5
Fig. 1.23: One Dimensional (1D) Array
1.64
Object Oriented Programming using Java - I An Introduction to Java
num
num = new int [5];
Points to int
object
num [0]
num [1]
num [2]
num [3]
num [4]
1.68
Object Oriented Programming using Java - I An Introduction to Java
for(int i=0;i<n;i++)
{
System.out.printf("a[%d]=%d\n",i,a[i]);
}
}
public static void reverse(int[] a)
{
// Loop for length/2 times only else re-swapping takes place
for(int i=0;i<a.length/2;i++)
{
int temp=a[i];
a[i]=a[(a.length-1)-i];
a[(a.length-1)-i]=temp;
}
}
}
Output:
Enter the no. of elements
4
Enter the elements into the array
1
2
3
4
a[0]=4
a[1]=3
a[2]=2
a[3]=1
Program 1.37: Program for transpose matrix.
public class TransposeaMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix:");
m = in.nextInt();
n = in.nextInt();
int matrix[][] = new int[m][n];
System.out.println("Enter the elements of matrix:");
1.70
Object Oriented Programming using Java - I An Introduction to Java
• Java provides different ways to get or accept input from the user. In Java, there are
different ways for reading input from the user in the command line environment
(console).
• The three common techniques for accepting input in Java are using BufferedReader
class, Scanner class and Command line arguments.
Using BuferedReader Class:
• The Java.io.BufferedReader class reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.
1.71
Object Oriented Programming using Java - I An Introduction to Java
Output:
Enter data:
Hello World
data is: Hello World
Using Command Line Arguments:
• The Java command line argument is an argument i.e. passed at the time of running the
Java program.
• The arguments passed from the console can be received in the java program and it can
be used as an input.
• A command-line argument is the information that directly follows the program's name
on the command line when it is executed.
• An argument which is supplied/passed to the main() from the command line at the
time of calling the main() by the java interpreters is called command line argument.
• The arguments supplied from the command line are of string type arguments.
Therefore these arguments are stored in the parameter of main() which is an array of
string objects i.e. args[].
public static void main(String args[])
• Each element in the array is one command-line argument.
Program 1.39: Program to display all command line arguments.
public class commdLineArg
{
public static void main(String args[])
{
System.out.println ("Total arguments passed are" + args.length);
System.out.println ("Each of them are");
for(int k = 0; k < args.length; k++)
System.out.println ("arg[" + k + "]:" + args [k]);
} //end main
} //end class
Output:
java commdLineArg I am a girl
Total argument's passed are 4
Each of them are:
arg[o] = I
arg[1]: am
arg[2]: a
arg[3]: girl
Using Scanner Class:
• This is probably the most preferred method to take input. The Scanner class is used to
read Java user input.
1.73
Object Oriented Programming using Java - I An Introduction to Java
• The main purpose of the Scanner class is to parse primitive types and strings using
regular expressions, however, it is also can be used to read input from the user in the
command line.
• Java Scanner class allows the user to take input from the console. It is used to read the
input of primitive types like int, double, long, short, float, and byte. It is the easiest way
to read input in Java program.
• In order to use the object of Scanner, we need to import java.util.Scanner package.
Java Scanner class provides the following methods to read different primitives types:
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a Boolean
value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
Program 1.40: Program for java Scanner nextInt().
import java.util.Scanner;
public class Sample1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); // creates a Scanner object
System.out.println("Enter an integer: ");
int number = input.nextInt(); // reads an int value
System.out.println("Number using nextInt(): " + number);
input.close();
}
}
Output:
Enter an integer: 22
Number using nextInt(): 22
1.74
Object Oriented Programming using Java - I An Introduction to Java
PROGRAMS
Program 1: Program to display message.
import java.io.*;
class MsgExample
{
public static void main(String s[])
{
System.out.println(“Welcome to Java World ”);
}
}
Output:
Welcome to Java World
Program 2: Program to display string.
import java.io.*;
class FirstExample
{
public static void main(String s[])
{
String str = "Object Oriented Programming – I ";
System.out.println("String = "+str);
}
} //end of class
Output:
String = Object Oriented Programming – I
Program 3: Program to constant integer number.
import java.io.*;
class JConstant
{
public static void main(String s[])
{
int a,b;
a = 400;
b = 100;
System.out.println("a = "+a);
System.out.println("b = "+b);
}
}//end of class
Output:
a = 400
b = 100
1.75
Object Oriented Programming using Java - I An Introduction to Java
Output:
Enter the values
3
5
2
Maximum Number =5
Program 13: Program to display even numbers.
public class Examplewhile
{
public static void main(String[] args)
{
int i =2; // initalization of variable
while(i<=10) // check the condition
{
System.out.println(i);
i+=2; //increment variable by 2
}
}
}
Output:
2
4
6
8
10
Program 14: Program for reverse a number.
import java.util.Scanner;
public class Examplereverseno
{
public static void main(String[] args)
{
int rev = 0,sum = 0;
System.out.print("Enter the number: ");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
1.80
Object Oriented Programming using Java - I An Introduction to Java
while(num>0)
{
rev = (rev *10)+ ( num%10);
num = num /10;
}
System.out.println("The reverse of the given number is: " + rev);
}
}
Output:
Enter the number: 345
The reverse of the given number is: 543
Program 15: Program for pattern.
import java.util.Scanner;
public class Pattern2
{
public static void main(String[] args)
{
int lim;
Scanner sc = new Scanner(System.in); // creates an object of Scanner
System.out.print("Enter your name: ");
lim = sc.nextInt(); // takes input from the keyboard
for(int i=lim;i>0;i--)
{
for(int j = 1; j<=i ;j++)
{
System.out.print(" "+j);
}//j loop
System.out.println();//new line
}//i loop
}
} //end of class
Output:
Enter your name: 5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
1.81
Object Oriented Programming using Java - I An Introduction to Java
for(int i=0;i<arr.length;i++)
{
System.out.print(" " + arr[i]); //display elements
}
}
}
Output:
arr [0] = 11
arr [1] = 22
arr [2] = 44
arr [3] = 55
arr [4] = 77
Array Elements are:
11 22 44 55 77
Program 18: Program to print odd and even numbers from an array.
public class Exoddevenarray
{
public static void main(String args[])
{
int arr[]={10,23,54,61,32,22}; //Declaration of Array
System.out.println("Even Array Elements:");
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
System.out.println(arr[i]);
}
}
System.out.println("Odd Array Elements:");
for(int i=0;i<arr.length;i++)
{
if(arr[i]%2!=0)
{
System.out.println(arr[i]);
}
}
}
} //end of class
1.83
Object Oriented Programming using Java - I An Introduction to Java
Output:
Even Array Elements:
10
54
32
22
Odd Array Elements:
23
61
Program 19: Program to display the array element in descending order.
import java.util.Scanner;
public class Exdessort
{
public static void main(String[] args)
{
int n,temp;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the Limit: ");
n=sc.nextInt(); //enter the number of elements
int[] array = new int[10]; //declare the array element
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
array[i]=sc.nextInt(); //reading array elements from the user
}
System.out.println("Array elements are: ");
for (int i=0; i<n; i++)
{
System.out.print(" "+array[i]);
// accessing array elements using the for loop
}
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
{
if(array[i]<array[j])
{
1.84
Object Oriented Programming using Java - I An Introduction to Java
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println(" \nSorted Array elements are: ");
for (int i=0; i<n; i++)
{
System.out.print(" "+array[i]);
}
}
} //end of class
Output:
Enter the Limit: 5
Enter the elements of the array:
78
5
91
2
15
Array elements are:
78 5 91 2 15
Sorted Array elements are:
91 78 15 5 2
Program 20: Program to read and display 2D array.
class Example2d
{
public static void main(String[] args)
{
int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 },{7, 8, 9 } };
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.println("arr[" + i + "][" + j + "] = " + arr[i][j]);
}//j
}//i
1.85
Object Oriented Programming using Java - I An Introduction to Java
1.89
Object Oriented Programming using Java - I An Introduction to Java
while(num>0)
{
remainder = num%10;
result = result + remainder;
num = num/10;
}
System.out.println("Sum of digits of given number is: "+result);
}
}
Output:
Enter number: 5 5 5
Sum of digits of given number is: 15
Program 25: Program to accept two numbers as command line arguments and print the
addition of those numbers.
class addition
{
public static void main(String args[])
{
int num1=Integer.parseInt(args[0]);
int num2=Integer.parseInt(args[1]);
int result=0;
result=num1+num2;
System.out.println("Addition of two numbers is: " +result);
}
}
Output:
10 20
Addition of two numbers is: 30
Program 26: Program to find whether number is palindrome or not.
class palindrome
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
int n=num;
int reverse=0,remainder;
while(num>0)
{
remainder=num%10;
reverse=reverse*10+remainder;
num=num/10;
}
1.91
Object Oriented Programming using Java - I An Introduction to Java
if(reverse==n)
System.out.println(n+"is a palindrome number");
else
System.out.println(n+" is not palindrome number");
}
}
Output:
121
121 is a palindrome number
Program 27: Program to generate Fibonacci series 1 1 2 3 5 8 13 21 34 55 89.
class Fibonacci
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
System.out.println("Fibonacci series are: ");
int f1,f2=0,f3=1;
for(int i=1;i<=num;i++)
{
System.out.print(f3+" ");
f1=f2;
f2=f3;
f3=f1+f2;
}
}
}
Output:
11
Fibonacci series are:
1 1 2 3 5 8 13 21 34 55 89
Program 28: Program to check whether an entered number is prime or not.
import java.io.*;
class PrimeNo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number: ");
int num = Integer.parseInt(br.readLine());
int flag=0;
1.92
Object Oriented Programming using Java - I An Introduction to Java
for(int i=2;i<num;i++)
{
if(num%i==0)
{
System.out.println(num + " is not a prime number");
flag=1;
break;
}
}
if(flag==0)
System.out.println(num + " is a prime number");
}
}
Output:
Enter number:5
5 is a prime number
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. An expression involving byte, int, and literal numbers is promoted to which of
these?
(a) long (b) int
(c) byte (d) float
2. Which of following literals can be contained in float data type variable?
(a) − 1.7e + 308 (b) − 3.4e + 038
(c) + 1.7e + 308 (d) − 3.4e + 050
3. With x = 0, which of the following are legal lines of Java code for changing the
value of x to 1?
(i) x++; (ii) x = x + 1; (iii) x + = 1; (iv) x = + 1;
(a) (i), (ii) and (iii) (b) (i) and (iv)
(c) (ii) and (iii) (d) (i), (ii), (iii) and (iv)
4. What is true about a break?
(a) break stops the execution of entire program
(b) break forces the control out of the loop and starts the execution of next
iteration
(c) break halts the execution and forces the control out of the loop
(d) break halts the execution of the loop for certain time frame
5. Which of the following is used with the switch statement?
(a) break (b) continue
(c) exit (d) do
1.93
Object Oriented Programming using Java - I An Introduction to Java
1.95
Object Oriented Programming using Java - I An Introduction to Java
28. Binding of data and functions into a single unit known as,
(a) Object (b) Class
(c) Encapsulation (d) Polymorphism
29. Which a request for execution of a method?
(a) Object (b) Class
(c) Message (d) Polymorphism
30. Java environment includes,
(a) JSL (b) JDK
(c) Both (a) and (b) (d) None of mentioned
31. Which is a Java application launcher?
(a) java (b) javac
(c) javadoc (d) jdb
32. Primitive data types of Java includes,
(a) int (b) char
(c) float (d) All of mentioned
33. Which operator is used only for object reference variables?
(a) instanceof (b) dot
(c) ternary (d) None of mentioned
34. Which is an identifier who’s values can changed during execution of program?
(a) constant (b) variable
(c) operator (d) literal
35. To declare a final variable, following which keyword is used.
(a) var final (b) final
(c) const (d) finalize
36. Which is an expression is a combination of operators and operands which reduces
to a single value.
(a) Statement (b) Operator
(c) Expression (d) None of mentioned
37. Following which is a multi-way selection statement.
(a) if (b) if else
(c) switch (d) None of mentioned
38. Which statements allows to execute a statement or group of statements multiple
times until conditions become true?
(a) sequential (b) looping
(c) selection (d) decision
39. Following which statement causes the program control to transfer back to the
caller of a method.
(a) return (b) break
(c) continue (d) exit
40. Which is a collection of similar type of elements that have contiguous memory
location?
(a) Object (b) Array
(c) Class (d) Method
1.96
Object Oriented Programming using Java - I An Introduction to Java
41. The array having only one subscript variable is called as,
(a) One Dimensional (1D) array (b) Two Dimensional (2D) array
(c) Multi-dimensional array (d) None of mentioned
42. The three common techniques for accepting input in Java includes,
(a) BufferedReader class (b) Scanner class
(c) Command line arguments (d) All of mentioned
43. Which Java class allows the user to take input from the console?
(a) BufferReader (b) Scanner
(c) Command line parameters (d) All of mentioned
Answers
1. (b) 2. (b) 3. (d) 4. (c) 5. (a) 6. (d) 7. (c) 8. (a) 9. (a) 10. (c)
11. (b) 12. (a) 13. (c) 14. (a) 15. (c) 16. (c) 17. (b) 18. (c) 19. (d) 20. (a)
21. (b) 22. (c) 23. (a) 24. (b) 25. (d) 26. (a) 27. (b) 28. (c) 29. (c) 30. (c)
31. (a) 32. (d) 33. (a) 34. (a) 35. (b) 36. (c) 37. (c) 38. (b) 39. (a) 40. (b)
41. (a) 42. (d) 43. (b)
Q.II Fill in the Blanks:
1. ____ and do while loops can be used where the number of iteration is not known
before hand.
2. _______ is a concept in OOP which hides unimportant implementation details from
other.
3. _______ method can be called without the instance of a class.
4. Operator _______ is used to crate an array.
5. _______ variables are nothing but constants.
6. A break statement inside a loop like while, for, do while and enhanced-for causes
the program execution _______ loop.
7. In Java language, break or continue statements can be implemented inside a loop
only with the help of _______ statements to avoid never-ending loops.
8. An enhanced for loop in Java misses _______ and Increment/ Decrement compared
to the old-style for loop.
9. A break-with-label or continue-with-label are used in particular in Java to select
_______ loop either to break or continue.
10. _______ is used to find and fix bugs in the Java programs.
11. Platform independent code file created from Source file is understandable by
______ .
12. Java programming was designed by _______.
13. Class file must have extension _______.
14. Java has _______ primitive types of data.
15. Integer Data type does not include following primitive data type _______.
16. _______ Gosling initiated Java language project in June 1991.
17. To write Java programs, we will need a _______ editor like Notepad++ while even
more sophisticated IDEs like Eclipse, Netbeans available in the market.
1.97
Object Oriented Programming using Java - I An Introduction to Java
18. Names used for classes, variables, and methods are called _______.
19. Arrays are objects that store multiple variables of the _______ type.
20. The _______ may not be used as constant or variable or any other identifier names.
21. The inheritance concept allows to _______ the fields and methods of the existing
class without having to rewrite the code in a new class.
22. A _______ is a blueprint from which individual objects are created.
23. The _______ keyword is used to create the object.
24. _______ are nothing but reserved memory locations to store values.
25. _______ data types are predefined by the language and named by a keyword like
int. float, char and so on.
26. A variable provides us with _______ storage that the programs can manipulate.
27. Java provides a number of _______ modifiers to set access levels for classes,
variables, methods and constructors.
28. In _______ statement, if the Boolean expression evaluates to true then the block of
code inside the if statement will be executed.
29. _______ is the ability of an object to take on many forms.
30. The _______ is the interpreter which launches a java program.
31. A _______ statement allows us to execute a statement or group of statements
multiple times.
32. In Java the _______ command disassembles a class file.
33. The type of value that a variable can hold is called as _______ type.
34. _______ refer to fixed values that do not change during the execution of a program.
35. OOP emphasis on _______ rather than procedure.
36. An object is an _______ of a class and has two general characteristics namely, state
and behavior.
37. We access an array element by referring to the _______ number.
38. The _______ keyword causes the loop to immediately jump to the next iteration of
the loop.
39. The while loop loops through a block of code as long as a specified condition
is _______.
40. _______ refers to act of representing essential features without including
background details or explanations.
41. _______ translates or converts the ".java" file to a ".class" file.
42. _______ perform some specific operations using the operands and operator.
43. The _______ stores a fixed-size sequential collection of elements of the same type.
44. Java is an _______ language, i.e. programs run directly from the source code.
45. The _______ is a software development environment which is used to develop Java
applications.
46. When the _______ statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
47. _______ is Java debugger that helps us in finding errors in Java programs.
1.98
Object Oriented Programming using Java - I An Introduction to Java
48. _______ line arguments is the way to pass argument to the main method in Java.
49. The _______ class is used to get user input, and it is found in the java.util package.
Answers
1. while 2. Encapsulation 3. static 4. [] 5. Final
6. exit 7. if else 8. Initialization 9. Outer loop 10. jdb
11. JVM 12. Sun 13. .class 14. eight (8) 15. double
16. James 17. text 18. identifiers 19. same 20. keywords
21. reuse 22. class 23. new 24. Variables 25. Primitive
26. named 27. access 28. if 29. Polymorphism 30. java
31. loop 32. javap 33. data 34. Constants 35. data
36. instance 37. index 38. continue 39. true 40. Abstraction
41. javac 42. Operators 43. array 44. interpreted 45. JDK
46. break 47. Jdb 48. Command 49. Scanner
Q.III State True or False:
1. All bitwise operations are carried out with the same level of precedence in Java.
2. Consider the statement "x = (a > b) ? a: b"; then the value of x is 27, if a = 18 and
b = 27.
3. An array in the Java programming language has the ability to store many different
types of values.
4. Variables declared inside a for loop are limited in scope to the loop.
5. The operations y >> 3 and y >>> 3 produce the same result when y > 0.
6. In Java, an array can be declared without initialization without mentioning the
size.
7. We should not specify the array size if declaration and initialization are done at
the same time.
8. An array in Java can be declared only of some predefined types.
9. A WHILE loop in Java executes the statements at least once even the condition is
not satisfied.
10. Allocating memory with the keyword "new" causes the array elements to carry
default values.
11. A loop in Java generally contains a Loop-Counter variable.
12. The keyword "goto" can be used in Java programs with labels.
13. Java Programming promises programmer - "Write Once, Run Anywhere".
14. The name of the class file is created automatically when you compile the program
with the javac command.
15. An Increment operator "++" and/or a Decrement operator "--" are used along with a
Loop- Counter variable in Java.
16. Loops are in Java save time, reduce errors, and they make code more readable.
17. Encapsulation in Java is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit.
1.99
Object Oriented Programming using Java - I An Introduction to Java
43. Loop is designed to execute particular code block till the specified condition is
false.
44. In Java, the nested if statement is a if inside another if. In this, one if block is
created inside another if block when the outer block is true then only the inner
block is executed.
45. The if else statement consists of conditional based cases and a default case.
46. The if-else statement is used for testing condition. If the condition is true, if block
executes otherwise else block executes. The else block execute only when
condition is false.
47. Break statement is used to break the current execution of the program.
48. Multi-Dimensional Array represent data into tabular form in which data is stored
into row and columns.
49. The BufferedReader class of Java is used to read the stream of characters from the
specified source (character-input stream).
50. The break statement is used to skip the current iteration of the loop. It jumps to the
next iteration of the loop immediately.
51. Bitwise operators are used to perform operations bit by bit.
52. The command line argument is the argument that passed to a program during
runtime. It is the way to pass argument to the main method in Java.
53. Initialization is a process of allocating memory to an array.
54. Logical operators are used to perform arithmetic operations like: addition,
subtraction etc and helpful to solve mathematical expressions.
55. An array is a collection of similar data types.
56. Relational operators are used to test comparison between operands or values in
two variables.
57. Operator is a symbol which tells to the compiler to perform some operation.
58. Assignment operators are used to assign a value to a variable.
59. Conditional operator is also known as ternary operator because it works
with three operands.
60. Single dimensional array use multi index to store elements.
Answers
1. (F) 2. (T) 3. (F) 4. (F) 5. (T) 6. (T) 7. (F) 8. (F) 9. (F) 10. (T)
11. (T) 12. (F) 13. (T) 14. (T) 15. (T) 16. (T) 17. (T) 18. (F) 19. (T) 20. (T)
21. (T) 22. (F) 23. (T) 24. (T) 25. (T) 26. (T) 27. (F) 28. (T) 29. (T) 30. (T)
31. (T) 32. (T) 33. (T) 34. (T) 35. (T) 36. (F) 37. (T) 38. (T) 39. (T) 40. (T)
41. (F) 42. (T) 43. (T) 44. (F) 45. (F) 46. (T) 47. (T) 48. (T) 49. (T) 50. (F)
51. (T) 52. (T) 53. (T) 54. (F) 55. (T) 56. (T) 57. (T) 58. (T) 59. (F) 60. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. What is OOP?
2. What is Java?
1.101
Object Oriented Programming using Java - I An Introduction to Java
April 2017
1. What is Javadoc? [1 M]
Ans. Refer to Section 1.6.5.
2. List primitive data types in Java with their width in bits. [1 M]
Ans. Refer to Section 1.7.2 Point (2).
3. Why is Java called purely object oriented programming language? Explain features
of Java. [5 M]
Ans. Refer to Section 1.1.
October 2017
1. Justify true/false ‘Java is not fully object oriented’. [1 M]
Ans. Refer to Section 1.1.
2. Explain the process of compilation of a Java program. [5 M]
Ans. Refer to Page 1.15.
3. Explain how the input is accepted from command line with the help of
program. [5 M]
Ans. Refer to Section 1.9.
April 2018
1. What do you mean by jdb? [1 M]
Ans. Refer to Section 1.6.4.
2. Write a java program to find second smallest element in an array. [5 M]
Ans. Refer to Section 1.8.
October 2018
1. What is the use of javap tool? [1 M]
Ans. Refer to Section 1.6.6.
2. What is blank final variable? [1 M]
Ans. Refer to Section 1.7.5.
3. “Java is platform dependant language.” True/False ? Justify. [1 M]
Ans. Refer to Section 1.3.3.
April 2019
1. What is JAR file? [1 M]
Ans. Refer to Section 1.6.7.
2. What is Javadoc comments? [1 M]
Ans. Refer to Section 1.6.5.
3. Write a Java program to find second smallest element in an array. [5 M]
Ans. Refer to Section 1.8.
1.104
CHAPTER
2
Objects and Classes
Objectives…
To understand Basic Concepts of Objects and Classes
To study Constructors and Access Specifiers
To learn Predefined Classes in Java
To study Concepts of Packages
To learn Wrapper Classes
2.0 INTRODUCTION
• Java is an object-oriented programming language. Objects and classes are the basic
building blocks of OOP. Everything in Java is associated with classes and objects.
• Anything we wish to represent in Java must be encapsulated in a class that defines the
“state” and “behavior” of the basic program components known as objects.
• An object is a basic unit of OOP and represents the real life entities like a house, a tree
etc. A class is a template for defining the behavior and states of the objects.
• Classes create objects and objects use methods to communicate between them
i.e. all about object-oriented programming.
• A Java package is a mechanism for organizing Java classes. Packages are used in Java,
in-order to avoid name conflicts and to control access of class, interface and so on.
2.1
Object Oriented Programming using Java - I Objects and Classes
Class in Java:
• A class can be defined as "a template/blueprint that describes the behaviors/states that
object of its type support".
• A class is a user-defined type which groups data members and its associated functions
together.
• In Java language the data members are called fields and the functions are called
methods. Calling a specific method in an object is described as sending the object of
message.
• Example of class and objects: class Student has objects like Yogi, Atharva, Rudra,
Amita.
• Take another example of class and objects: class Car has objects like Ford, Toyota,
Volkswagaon.
Car class
Car Objects
• The data in a class is in the form of instance variables. We can declare the instance
variables exactly the same way as we declare the local variables.
For example: Here, class name is Employee which contents two instance variables E_id
and Salary.
class Employee
{
int E_id;
float Salary;
}
Program 2.1: Creating a simple class in Java.
public class Student
{
int id;//declaration of data member or instance variable
String name;
public static void main(String args[]) //creating main
{
Student s1=new Student();//creating an object of Student
System.out.println("Student id = "+s1.id);
//accessing member through reference variable
System.out.println("Student name = "+s1.name);
}
}
Output:
Student id = 0
Student name = null
Methods in Java:
• A Java method is a collection of statements that are grouped together to perform a
certain task.
• Method describes behavior of an object. A method is a collection of statements that are
group together to perform an operation.
Syntax:
return_type methodName(parameter_list)
{
//body of method …
}
2.3
Object Oriented Programming using Java - I Objects and Classes
Example of a Method:
public String getName(String st)
{
String name="Nirali Prakashan";
name=name+st;
return name;
}
• For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).
• The process of method calling is simple, when a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when:
1. The return statement is executed.
2. It reaches the method ending closing brace.
Program 2.2: Program to show how to define a method and how to call it.
public class ExampleMinNumber
{
public static void main(String[] args)
{
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/* returns the minimum of two numbers */
public static int minFunction(int n1, int n2)
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Output:
Minimum value = 6
2.4
Object Oriented Programming using Java - I Objects and Classes
Creating Objects:
• Objects are programming units of a particular class. Creating an object of the class is
also called as instantiating an object.
• There are three steps when creating an object from a class:
1. Declaration of an Object:
We have to specify what type (i.e. class) the object will be. A variable declaration with
a variable name with an object type.
Syntax: <class name> object name;
Where, class name is the name of the already defined class and the object name is a
valid identifier.
2. Instantiation (Creating Objects):
Objects are created using the ‘new’ keyword. This ‘new’ keyword creates an object of
the specified class and returns the reference of that object.
The 'new' keyword is followed by a call to a constructor. This call initializes the new
object.
Syntax: <objectname>=new classname([arguments]);
Let us create an object for the already defined Rectangle class in the previous chapter
Rectangle r1; //Rectangle name of the class, r1 name of the object
r1=new Rectangle(); //Allocating memory
Fig. 2.2 illustrates the above process.
Rectangle r1; Null
For example:
class a
{
int p;
int get() // accessor method
{ return p; }
void setp(int q) //mutator method
{ p = q; }
}
Program 2.4: Program shows the usage of mutator method.
class area
{
float length;
float breadth;
void setd (float x, float y)
{
length = x;
breadth = y;
}
}
class mainarea
{
public static void main (String args[])
{
float a;
area ob1=new area();
ob1.setd(8, 10);
a = ob1.length * ob1.breadth;
System.out.println ("Area = " +a);
}
}
Output:
Area = 80
2.7
Object Oriented Programming using Java - I Objects and Classes
• The visibility modifiers are also known as access modifiers. Java provides a number of
access modifiers to set access (scope) levels for classes, variables, methods and
constructors. The four access levels are:
1. Visible to the package (default/friendly),
2. Visible to the class only (private),
3. Visible to the world (public), and
4. Visible to the package and all subclasses (protected).
• Let us see above access specifiers in detail.
1. Default / Friendly Access Modifier (No Keyword):
• If we give no specifier at all, the access is referred as friendly. It means that all the
other classes in the current package have access to the friendly member but to all the
classes outside the package the members appear to be private.
• Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.
• A variable or method declared without any access control modifier is available to any
other class in the same package.
• The fields in an interface are implicitly public static final and the methods in an
interface are by default public.
• Variables and methods can be declared without any modifiers, as in the following
examples:
String version = "1.5.1";
Boolean processOrder()
{
return true;
}
2. Private Access Modifier (private):
• Methods, variables and constructors that are declared private can only be accessed
within the declared class itself.
• Private access modifier is the highest degree restrictive access level. Class and
interfaces cannot be private.
• Variables that are declared private can be accessed outside the class if public getter
methods are present in the class.
• Using the private modifier is the main way that an object encapsulates itself and hide
data from the outside world.
• The following class uses private access control:
public class PLog
{
private String format;
public String getFormat()
{
return this.format;
}
2.9
Object Oriented Programming using Java - I Objects and Classes
• Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.
• The following parent class uses protected access control, to allow its child class
override openSpeaker()method:
class AudioPlayer
{
protected boolean openSpeaker(Speaker sp)
{
// implementation details …
}
}
class StreamingAudioPlayer
{
boolean openSpeaker(Speaker sp)
{
// implementation details
}
}
• In above program code, if we define openSpeaker() method as private, then it would
not be accessible from any other class other than AudioPlayer. If we define it as public,
then it would become accessible to all the outside world. But our intension is to expose
this method to its subclass only, that's why we used protected modifier.
• Following table summarizes visibility of field in a class of Java:
Friendly Private
Access Public Protected Private
(Default) Protected
Location Modifier Modifier Modifier
Modifier Modifier
Same class Yes Yes Yes Yes Yes
Subclass in same Yes Yes Yes Yes No
package
Other classes in Yes Yes Yes No No
same package
Subclass in other Yes Yes No Yes No
packages
Non-subclasses in Yes No No No No
other packages
2.11
Object Oriented Programming using Java - I Objects and Classes
• Let us now suppose that we have a class, ArrayDemo. We have to create an array of
objects of this class. To create an array of objects to ArrayDemo class see the following
example:
ArrayDemo a_obj[ ] = new ArrayDemo [2]:
• The a_obj array can hold 2 objects of ArrayDemo class. To use the a_obj array, we have
to create objects of every array index.
• See the following code snippet to create objects of every index of a_obj array:
a_obj [0] = new ArrayDemo();
a_obj [1] = new ArrayDemo();
Variable 1
Variable 2
Object[0]
Object[1] Variable 1
Variable 2
Object[2]
Variable 1
Variable 2
2.5 CONSTRUCTORS
• A constructor is a special method of a class in Java programming that initializes an
object of that type.
• Constructors have the same name as the class itself. A constructor is automatically
called when an object is created.
2.14
Object Oriented Programming using Java - I Objects and Classes
• Constructor constructs the values i.e. provides data for the object that is why it is
known as constructor.
Syntax:
class_Name
{
constructor_Name (same as class_Name); // Constructor
{
//constructor body…..
}// end of Constructor
}// end of Class
• There are basically following rules defined for the constructor:
1. Constructor name must be same as its class name.
2. Constructor must have no explicit return type.
3. Constructors may be private, protected or public.
4. Multiple constructors may exist, but they must have different signatures,
i.e., different numbers and/or types of input parameters.
Program 2.7: Program for constructors.
class Rectangle
{
int length;
int breadth;
//constructor to initialize length and breadth of rectangle
Rectangle()
{
length = 5;
breadth= 6;
}
//method to calculate area of rectangle
int area()
{
int rectArea = length * breadth;
return rectArea ;
}
}
//class to create rectangle objects and calculates area
class ConstructorExample
{
public static void main(String[] args)
{
Rectangle firstRect = new Rectangle();
System.out.println("Area of Rectantangle: "+ firstRect.area());
}
}
Output:
Area of rectangle: 30
2.15
Object Oriented Programming using Java - I Objects and Classes
• Constructors can be classified into two types, default constructors and parametarized
constructors.
1. Default Constructor:
• The constructor which does not accept any argument is called default constructor. The
argument list is void.
• In other word, when the object is created Java creates a no-argument constructor
automatically known as default constructor.
• It does not contain any parameters nor does it contain any statements in its body. Its
only purpose is to enable you to create object of class type.
• Default constructor provides the default values to the object like 0, null etc. depending
on the type.
Syntax: <class_name>()
{
// Body of the constructor…
}
Program 2.8: Program for default constructor.
class StudentInfo
{
int rollno;
int marks1;
int marks2;
int total;
StudentInfo() //no-arg default constructor
{
rollno=2;
marks1=30;
marks2=40;
}
//method to calculate total
int Total()
{
total = marks1 + marks2;
return total;
}
//method to display the result
void displayResult()
{
System.out.println(“Roll no of student is” + rollno );
System.out.println(“marks1 are” + marks1 );
System.out.println(“marks2 are” + marks2);
System.out.println(“total is” + total);
}
}
2.16
Object Oriented Programming using Java - I Objects and Classes
class StudentResult
{
public static void main(String args[])
{
int total1,total2,grandtotal;
StudentInfo student1 =new StudentInfo(); //creates first object
StudentInfo student2 =new StudentInfo(); //creates second object
total1=student1.Total();
total2=student2.Total();
grandtotal=total1+total2;
student1.displayResult();
student2.displayResult();
System.out.println(“Grand Total is” + grandtotal);
}
}
Output:
Roll no of student is 2
marks1 are 30
marks2 are 40
total is 70
Roll no of student is 2
marks1 are 30
marks2 are 40
total is 70
Grand Total is 140
2. Parameterized Constructor:
• A constructor that has parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.
• Using parameterized constructor, it is possible to initialize objects with different set of
values at the time of their creation. These different set of values initialized to objects
must be passed as arguments when constructor is invoked.
• The parameter list can be specified in the parentheses in the same way as parameter
list is specified in the method.
• The syntax for constructor is as follows:
ConstructorName([parameterList])
{
// Constructor body…
}
• Here, the ConstructorName is same as the class name it belongs to. The parameterList
is the list of optional zero or more parameter(s) that is specified after the classname in
parentheses. Each parameter specification, if any, consists of a type and a name and is
separated from each other by commas.
2.17
Object Oriented Programming using Java - I Objects and Classes
Output:
Roll no of student is 1
marks1 are 50
marks2 are 80
total is 130
Roll no of student is 2
marks1 are 40
marks2 are 60
total is 100
Grand Total is 230
• Constructors can be overloaded. Constructor having the same name with different
parameter list is called as constructor overloading.
Program 2.10: Program for constructor overloading.
class Student
{
int id;
String name;
int age;
Student(int i,String n)
{
id = i;
name = n;
}
Student(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(1,"Amar", 22);
Student s2 = new Student(2,"Amol",20);
s1.display();
s2.display();
}
}
Output:
1 Amar 22
2 Amol 20
2.19
Object Oriented Programming using Java - I Objects and Classes
State
this
Behaviour
Reference
variable
Object
Fig. 2.4: this Keyword
Example:
class BoxDim
{
int height;
int depth;
int length;
BoxDim(int height, int depth, int length)
{
this.height = height;
this.depth = depth;
this.length = length;
}
}
• The class ‘BoxDim’ contains three instance variables i.e. height, depth and length. The
constructor of the class also contains three different local variables with the same
names of instance variables.
2.20
Object Oriented Programming using Java - I Objects and Classes
• Compiler will not show any error here. Then how differentiate among these variables?
The ‘this’ keyword does this job. ‘this’ will refer to the variables of its own class. It is
acting as the object of the current class.
• In method also the ‘this’ keyword is used to differentiate between instance and local
variables. This concept is also referred as ‘Instance variable hiding’. This resolves the
name-space collisions.
Program 2.11: Program for 'this' keyword.
class Rectangle
{
int length,breadth;
void show(int length,int breadth)
//Formal and instance variable name are same
{
this.length=length; //Use of this keyword
this.breadth=breadth;
}
int calculate()
{
return(length*breadth);
}
}
/* Main class */
public class UseOfThisOperator
{
public static void main(String[] args)
{
Rectangle rectangle=new Rectangle();
rectangle.show(8,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is: " + area);
}
}
Output:
The area of a Rectangle is: 48
• In Java basically, class contains variables called instance variables and methods called
instance method.
• When we create an object the memory gets allocated for the variables and methods
also. If we create one more object, same thing happens again.
2.21
Object Oriented Programming using Java - I Objects and Classes
2.22
Object Oriented Programming using Java - I Objects and Classes
• A static field of a class is often referred to as a class variable because static field is
associated with a class and not with individual instances of the class.
• A static field gets memory only once for the whole class no matter how many objects
of a class are created.
• To declare a static field, prefix the field declaration in the class with the static
modifier. It's syntax is,
static datatype fieldName;
Properties/Characteristics of Static Field:
1. There is only one copy of static field in a class which is shared among all the
objects of the class.
2. A static field can be accessed before any object of a class is created, without
reference to any object.
3. To make a static field constant in Java, make a variable as both static and final.
• The static field is similar to static variable. The main difference is that a static variable
is used to retain information between calls whereas static field is used to share
information among multiple objects of a class.
Program 2.13: Program shows use of static fields.
class Rectangle
{
int length; //length of rectangle
int breadth; //breadth of rectangle
static int rectCount =0; //count rectangle objects
void setData(int l,int b)
{
length=l;
breadth=b;
rectCount++;
}
//method to calculate area of rectangle
int area()
{
int rectArea;
rectArea = length * breadth;
return rectArea;
}
}
2.24
Object Oriented Programming using Java - I Objects and Classes
• It is possible to have static methods in a class in the same way as we have static fields.
If you apply static keyword with any method, it is known as static method.
• A static method belongs to the class rather than object of a class. A static method can
be invoked without the need for creating an instance of a class.
• Static method can access static data member and can change the value of it. The static
method is similar to instance method of a class but the only difference is that the static
method can be called through its class name without creating any object of that class.
• A static method is also called class method as it is associated with a class and not with
individual instance of the class.
• A static method cannot access non-static method either because non-static methods
are usually associated with instance variable state.
• To call a particular static method, the syntax is given below:
classname.staticmethodname (arg-list);
Program 2.14: Program using static method which maintains bank account information
about various customers.
class Account
{
int accountNo; //account ID)
double balance;
static double rate = 0.05;
void setData(int n,double bai)
{
accountNo = n;
balance = bai;
}
void quarterRatecal()
{
double interest = balance * rate * 0.25;
balance += interest;
}
static void modifyRate(double incr)
{
rate += incr;
System.out.println("Modified Rate of Interest: " + rate);
}
2.26
Object Oriented Programming using Java - I Objects and Classes
void show()
{
System.out.println("Account Number: " + accountNo);
System.out.println("Rate of Interest: " +rate)
System.out.println("Balance: "+ balance);
}
}
public class StaticMethod
{
public static void main(String[] args)
{
Account acc1 = new Account();
Account acc2 = new Account();
Account.modifyRate(0.01);
System.out.println("Customerl Information......");
acc1.setData(201,1000);
acc1.quarterRatecal(); //Calculate interest
acc1.show(); //display account interest
System.out.println("Customer2 Information......");
acc1.setData(202,1000);
acc2.quarterRatecal(); //Calcuate interest
acc2.show(); //display account information
}
}
Output:
Modified Rate of Interest: 0.060000000000000005
Customer1 Information …
Account Number: 201
Rate of Interest: 0.06
Balance: 1000.0
Customer2 Information …
Account Number: 202
Rate of Interest: 0.06
Balance of 1000.0
• The Account class in Program 2.14 contains a static method modifyRate ().It modifies
the rate of interest by the value specified as argument (0.01).
• The method modifyRate() is made static in the class as we are only using static field
rate in it. Only static method can access a static field.
2.27
Object Oriented Programming using Java - I Objects and Classes
• The object class is the parent class of all the classes in Java by default. In other words,
it is the topmost class of java.
• The java.lang.Object class is the root of the class hierarchy. Every class has Object as a
superclass. All objects, including arrays, implement the methods of this class.
• Following is the declaration for java.lang.Object class:
public class Object
• The Object class provides some common behaviours to all the objects such as object
can be compared, object can be cloned, object can be notified etc.
Object
•••
•••
•••
•••
•••
•••
••• •••
• We already known object class is the superclass of all classes. Some methods of the
object class are: [April 18]
o Boolean equals(Object obj): Indicates whether some other object is "equal to"
this one.
o protected Object clone(): Creates and returns a copy of this object.
o Boolean equals(Object obj): Indicates whether some other object is "equal to"
this one.
o protected void finalize(): This method is called by the garbage collector on an
object when garbage collection determines that there are no more references to
the object.
o int hashCode(): Returns a hash code value for the object.
o void notify(): Wakes up a single thread that is waiting on this object's monitor.
2.28
Object Oriented Programming using Java - I Objects and Classes
o void notifyAll():Wakes up all threads that are waiting on this object's monitor.
o String toString(): Returns a string representation of the object.
o getClass(): Returns the runtime class of this object. The class object which is
returned is the object that is locked by static synchronized method of the
represented class.
o void wait(): Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
Program 2.15: Program for object class.
class Rectangle extends Object
{
private double length,breadth;
Rectangle(double x,double y)
{
length = x ;
breadth = y ;
}
public void area()
{
System.out.println("Area of Rectangle is = " + breadth);
}
public void circumference()
{
System.out.println("Circumferencedfcdf of Rectangle is=
"+2*(length+breadth));
}
}
class ObjectClass
{
public static void main(String[] args)
{
Rectangle r = new Rectangle(10,20);
Rectangle rl = new Rectangle(10,20);
System.out.println("String Representation = " + r.toString());
System.out.println("Class Name = " + r.getClass());
System.out.println("Hash Code = " + r.hashCode());
System.out.println("r.rquals(rl) = " + r.equals(rl));
}
}
2.29
Object Oriented Programming using Java - I Objects and Classes
2.31
Object Oriented Programming using Java - I Objects and Classes
Constructors of String:
• Constructors are used to initialize the object. The string class supports several
constructors.
• The following table shows the constructors of the string class.
Sr.
Constructor Description
No.
1. String() This constructor creates an empty
string.
2. String(String value) This constructor creates a new
string that is a copy of the given
string.
3. String(char[] value) This constructor constructs a new
string based on the character array.
4. String(char[] value, int begin, This constructs a new string based
int count) on the character array starting from
the position begin which is 'count'
characters long.
5. String(byte[] value) This constructor creates a new
string by converting the given array
of bytes.
6. String(byte[] value, int offset, This constructor creates a new
int length) string by converting the given sub of
array of bytes.
7. String(StringBuffer buffer) This constructor creates a new
string based on a StringBuffer value.
8. String(char[] value, int begin, int This constructor creates a new
count, String enc) throws string based on the given byte array
UnsupportedEncoding Exception and uses given character encoding
that is denoted by enc.
9. String(char[] value, String enc) This constructor creates a new
throws UnsupportedEncoding Exception string based on the given byte array
and uses given character encoding
that is denoted by enc.
• StringBuffer may have some characters and if needed substring can be inserted in the
middle or appended at the end. StringBuffer automatically provides a room to grow
such additions.
• Java generally manipulate the strings using + as overloaded operator. StringBuffer
class in Java is used to created mutable (modifiable) string.
• The StringBuffer class in Java is same as String class except it is mutable i.e., it can be
changed.
• StringBuffer class is a mutable class unlike the String class which is immutable. Both
the capacity and character string of a StringBuffer Class. StringBuffer can be changed
dynamically.
Advantages of StringBuffer Class:
1. Alternative to String class.
2. Can be used wherever a string is used.
3. More flexible than String.
• The StringBuffer defines three types of constructors which we use to initialize the
string value.
1. StringBuffer()
2. StringBuffer(int size)
3. StringBuffer(String str)
• The first type is the default constructor as it has no parameters. It reserves room for 16
characters without reallocation. The second, type accepts an integer argument which
explicitly sets the size of buffer. In third case, the string argument sets the initial
contents of the StringBuffer object and reverse room for 16 more characters. These 16
characters room is allocated when no specific buffer length is requested. This is
because reallocation is a costly process in terms of time.
• The current length of a StringBuffer can be found via length() method and the total
allocated capacity can be found through capacity() method.
• The general forms are:
int length();
and
int capacity();
• StringBuffer creates string objects that can be changed. StringBuffer provides different
methods which are given below:
charAt() method obtains the character at a specific location.
setCharAt() method sets a character within the string.
• String object is manufactured which contains the substring. In this the original string
is unaltered and immutability remains intact.
• String provides a substring() method which returns a new string. It contains a
specified portion of the invoking string. This method is substring().
• The syntax is given below:
String subString(int start_Index, int endIndex)
• The startIndex specifies the beginning index and endIndex tells us about stopping
point.
2.33
Object Oriented Programming using Java - I Objects and Classes
Where,
o % is special character denotes the start of formatting instructions. String.format()
method supports multiple occurrence of “%” character in a single formatting
String.
o “argument number” specifies the corresponding argument in formatting.
o “flags” are the special instructions used to print String specific formats such as
flags as “;” and to print a semicolon in the output.
o “width” gives us the option to output the minimum number of characters. If the
number is larger than the width, the full number is displayed. Otherwise, it’s
padded with zero.
o “precision” is used for printing the float point format String. It helps to specify the
number of decimal values the floating number should display.
o “type” is a mandatory option. It’s always specified last and specifies the type of the
parameter being formatted. For instance, “%d” is written for integer values.
Simple rules of String Formatting:
• %s: Will print the string with no change.
• %15s: Prints fifteen characters. If the character count is less than 15, the output is
padded on the left.
• %-6s: Prints 6 characters as-is. If the string is less than 6 characters, the output is
padded on the right.
• %.8s: Prints a maximum eight characters.
Program 2.18: Program for string formatting.
class Test
{
public static void main (String[] args) throws.lang.Exception
{
//String is passed in the format function
String str = String.format("Hello %s", "Jack.Where is Jill?");
System.out.println(str);
String str1 = String.format("Hello %15s", "Jack.Where is Jill?");
System.out.println(str1);
String str2 = String.format("Hello %.6s", "Jack.Where is Jill?");
System.out.println(str2);
}
}
Output:
Hello Jack.Where is Jill?
Hello Jack.Where is Jill?
Hello Jack.W
• The String is passed in format function which returns a formatted String. Note that the
format function does not print the value on the screen.
2.37
Object Oriented Programming using Java - I Objects and Classes
• The primitive data types are not objects; they do not belong to any class; they are
defined in the language itself. Sometimes, it is required to convert data types into
objects in Java language.
2.38
Object Oriented Programming using Java - I Objects and Classes
• A data type is to be converted into an object and then added to a Stack or Vector etc.
For this conversion, the designers introduced wrapper classes.
• As the name says, a wrapper class wraps (encloses) around a data type and gives it an
object appearance.
• Wherever, the data type is required as an object, this object can be used. Wrapper
classes include methods to unwrap the object and give back the data type.
List of Wrapper Classes:
• In the above code, Integer class is known as a wrapper class (because it wraps around
int data type to give it an impression of object). To wrap (or to convert) each primitive
data type, there comes a wrapper class.
• Eight wrapper classes exist in java.lang package that represent eight data types as
given in following table:.
Data Types Wrapper Classes
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
• There are mainly four uses of wrapper classes.
1. Converting primitive numbers to objects:
integer iobj=new integer(i) //conversion of primitive int(i) to integer
object (iobj)
float fobj=new float(f) //conversion of primitive float(f) to float
object (fobj)
double dobj=new double(d) //conversion of primitive double(d) to double
object (dobj)
2. Converting objects to primitive numbers:
int i=iobj.intValue() //conversion of integer object (iobj) to
primitive int(i)
float f=fobj.floatValue() //conversion of float object (fobj) to
primitive float(f)
double d=dobj.doubleValue() //conversion of double object (dobj) to
primitive double(d)
3. Converting Numbers to Strings:
String s3 = Integer.toString(i); //conversion of primitive int(i) to
String object
String s4 = Double.toString(d); //conversion of primitive double(i) to
String object
String s4 = Float.toString(d); //conversion of primitive float(i) to
String object
2.39
Object Oriented Programming using Java - I Objects and Classes
java
Fig. 2.6
Sr. Package
Description
No. Name
1. java.lang Language support classes. They are used by java compiler itself
and thus automatically imported. They include classes for
primitive types, strings, math, tread and exceptions.
2. java.io Input/output support classes. They provide support for input
and output.
3. java.util Language utility classes such as Vector, Date ,hash tables,
random numbers etc.
4. java.awt Set of classes for implementing graphical user interface. They
include classes for windows, buttons, lists, menus and so on.
5. java.applet Classes for creating and implementing applets.
6. java.net Classes for networking. They include classes for
communication with local computers as well as with internet
servers.
2.42
Object Oriented Programming using Java - I Objects and Classes
//save by y.java
package mypkg;
import pkg.*;
class Y
{
public static void main(String args[])
{
X obj = new X();
obj.msg();
}
}
Output:
Hello
2. Using packagename.classname:
• If we import package.classname then only declared class of this package will be
accessible.
//save by X.java
package pkg;
public class X
{
public void msg(){System.out.println("Hello");}
}
//save by Y.java
package mypkg;
import pkg.X;
class Y
{
public static void main(String args[])
{
X obj = new X();
obj.msg();
}
}
Output:
Hello
2.44
Object Oriented Programming using Java - I Objects and Classes
lang
Math
sqrt package lang contains classes
sin
cos
tan class contains methods
string
2.45
Object Oriented Programming using Java - I Objects and Classes
• We can access the methods in our program just by including these built in packages as
shown below:
import packagename.classname;
OR
import packagename·*;
• This statement should be the first statement. These packages are named by standard
java naming rules:
o packages begins with lowercase letters.
o The class name always begins with an uppercase letter.
o Method is again in small letters.
For example:
double k = java.lang.Math.sqrt(x);
↑ ↑ ↑
package name class method name
Program 2.23: Program shows the usage of built in packages.
import java.lang.Math;
class mat
{
public static void main(String args[])
{
double K = java.lang.Math.sqrt(25);
System.out.println(k);
}
}
Output:
5.0
Program 2.24:
//packcheck.java
package pack;
public class packcheck
{
public void disp()
{
System.out.println ("packcheck class");
}
}
It is stored as packcheck.java in pack subdirectory. We should compile this java file so
that its ·class file is created.
Output:
exports/usr/pack$
javac packcheck.java
Program 2.25:
import pk.packcheck;
class test
{
public static void main(String args[])
{
pack check ob1 = new packcheck();
ob1.disp();
}
}
This is stored as text ·java. Compile this program and the execute its source file.
/exports/usr/pack$ javac test·java
/exports/usr/pack$ java.test
Output:
packcheck class
• We can include or import more than one packages in our program. Program 2.26
shows another package and Program 2.26 shows our program which calls both the
above packages.
Program 2.26:
package mypack;
public class check
{
protected int k = 5;
public void display()
{
System.out.println("k =" +k);
}
}
2.48
Object Oriented Programming using Java - I Objects and Classes
Program 2.27:
//importing two packages
import pk.packcheck;
import mypack.check;
class doubletest
{
public static void main(String args[])
{
packcheck ob1 = new packcheck();
ob1.disp();
check ob2 = new check();
ob2.display();
}
}
Output:
packcheck class
k = 5
• This shows that we can import multiple packages in our program, similarly two or
more packages contains identical class names:
For example:
package pck1;
public class manager
{ …………… }
public class emp
{ …………… }
package pck2;
public class CEO
{ …………… }
public class emp
{ …………… }
• The java runtime system uses the current working directory as its starting point. This
is first way using which, Java finds its packages and second way as it sets the
CLASSPATH environment variable's path. The first way is always easy to use.
2.49
Object Oriented Programming using Java - I Objects and Classes
PROGRAMS
Program 1: Program for class and object.
class Student
{
int studno; //declaration of variable
String studname;
}
class Examplestud
{
public static void main(String args[])
{
Student s1=new Student();
s1.studno = 100;
s1.studname = "JAVA";
System.out.println("Student id = "+s1.studno); //display members
System.out.println("Student name = "+s1.studname);
}
}
Output:
Student id = 100
Student name = JAVA
Program 2: Program for private member.
class X
{
private String name; // declaration of private variable
}
public class Testprivate
{
public static void main(String[] main)
{
X obj = new X();
obj.name = "Rudra"; // access private variable from another class
System.out.println("Welcome" + obj.name);
}
}
2.50
Object Oriented Programming using Java - I Objects and Classes
Output:
Compile time error
javac Testprivate.java
Testprivate.java:15: error: name has private access in X
obj.name = "Rudra"; // access private variable from another class
^
Testprivate.java:16: error: name has private access in X
System.out.println("Welcome" + obj.name);
^
2 errors
Program 3: Program to define a class 'employee' with data members as empolyee id,
employee name and employee salary. Accept data for 'n' objects using Array of objects and
print it.
import java.util.Scanner;
public class Employee_record
{
int emp_id;
String emp_name;
float emp_salary;
public void emp_getdata()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Employee id: ");
emp_id = in.nextInt();
System.out.print("Enter the Employee Name:");
emp_name = in.next();
System.out.print("Enter the Employee Salary: ");
emp_salary = in.nextFloat();
}
public void emp_putdata()
{
System.out.print(" " + emp_id);
System.out.print("\t" + emp_name);
System.out.print("\t" + emp_salary);
System.out.println();
}
2.51
Object Oriented Programming using Java - I Objects and Classes
2.55
Object Oriented Programming using Java - I Objects and Classes
2.57
Object Oriented Programming using Java - I Objects and Classes
class Exampleparaconst
{
public static void main(String[] args)
{
int lim,i;
Scanner in = new Scanner(System.in);
System.out.println("*** Default Player Information ***");
Player_record obj = new Player_record();
//object create for default constructor
obj.player_putdata();
System.out.print("How many record you want to enter ? ");
lim = in.nextInt();
Player_record obj1[] = new Player_record[10];
//object create for paramterized constructor
for(i=0; i<lim; i++)
{
obj1[i] = new Player_record();
}
for(i=0; i<lim; i++)
{
obj1[i].player_getdata();
}
System.out.println("*** Player Information ***");
System.out.println("Player Id \t Player Name\tPlayer Run");
for(i=0; i<lim; i++)
{
obj1[i].player_putdata();
}
}
}//end of class
Output:
*** Default Player Information ***
7 Ms Dhoni 1000
How many record you want to enter ? 2
Enter the Player id: 5
Enter the Player Name:Yuvraj
Enter the Player Run: 1800
2.58
Object Oriented Programming using Java - I Objects and Classes
2.60
Object Oriented Programming using Java - I Objects and Classes
else
{
System.out.println ("InCorrect Password");
System.exit(0);
}
String msg = "Welcome to Java!!!";
StringBuffer str = new StringBuffer(msg);
str.append(pass1);
System.out.println ("Appended = "+str);
StringBuffer str1 = new StringBuffer(pass1);
str1=str1.reverse();
System.out.println ("String in Reverse Order = "+str1);
System.out.println
("Replaced '*' with '$' = "+pass1.replace('*','$'));
}
}
Output:
Enter the Password
password*
Correct Password
Appended = Welcome to Java!!!password*
String in Reverse Order = *drowssap
Replaced '*' with '$' = password$
Program 14: Program to create a package named Series having class to print series
square of numbers. Write a program to generate ‘n’ terms of the above series.
package series;
public class Sqr
{
public void square(int n)
{
System.out.println("Square of the number is "+(n*n));
}
}
import series.*;
import java.io.*;
import java.util.Scanner;
2.61
Object Oriented Programming using Java - I Objects and Classes
2.63
Object Oriented Programming using Java - I Objects and Classes
Enter marks of students for computer, maths and electronics subject out of
200
178
168
156
Enter the marks of the theory out of 400 and practicals out of 200:
388
179
Enter roll number and name of the student:
30
ram
Enter marks of students for computer, maths and electronics subject out of
200
159
146
187
Enter the marks of the theory out of 400 and practicals out of 200:
364
144
Enter roll number and name of the student:
40
sunny
Enter marks of students for computer, maths and electronics subject out of
200
126
80
154
Enter the marks of the theory out of 400 and practicals out of 200:
205
100
Roll No Name SyTotal TyTotal GrandTotal Percentage Grade
20 amita 502.0 567.0 1069.0 89.08333 A
30 ram 492.0 508.0 1000.0 83.33333 A
40 sunny 360.0 305.0 665.0 55.416668 C
2.65
Object Oriented Programming using Java - I Objects and Classes
Program 16: Program to convert all primitives into its corresponding Wrapper objects.
public class Examplewrapper
{
public static void main(String args[])
{
byte b=50;
short s=40;
int i=70;
long l=20;
float f=3.14F;
double d=67.0D;
char c='M';
boolean bool=true;
// Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=bool;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
}
}
Output:
--Printing object values---
Byte object: 50
Short object: 40
Integer object: 70
Long object: 20
Float object: 3.14
Double object: 67.0
Character object: M
Boolean object: true
2.66
Object Oriented Programming using Java - I Objects and Classes
case 2:
System.out.println("Enter the amount to withdraw: ");
amount = Double.parseDouble(bin.readLine());
a.withdraw(amount);
break;
default:
System.out.println("Enter a valid option: ");
break;
}
}
catch(Exception e)
{
System.out.println("Exception caught: "+e);
}
}
}
Output:
Enter the account name, account number and balance:Saving 1001 5000
Enter
1 for depositing
2 for withdrawal
1
Enter the amount to deposite:5000
Your new available balance is: 10000.0
Program 21: Program to define a class ‘employee’ with data member’s empid, name and
salary. Accept data for two objects using array of objects and print it.
import java.io.*;
class employee
{
int empid;
String name;
double salary;
void getdata()
{
try
{
BufferedReader obj = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter Emp number: ");
empid=Integer.parseInt(obj.readLine());
System.out.print("Enter Emp Name: ");
name=obj.readLine();
System.out.print("Enter Emp Salary: ");
salary=Double.parseDouble(obj.readLine());
}
2.70
Object Oriented Programming using Java - I Objects and Classes
catch(IOException e)
{
System.out.println(e);
}
}
void show()
{
System.out.println("Emp ID: "+empid);
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
}
}
class EmpDetails
{
public static void main(String args[])
{
employee e[] = new employee[5];
for(int i=0; i<5; i++)
{
e[i] = new employee();
}
for(int i=0; i<5; i++)
{
e[i].getdata();
}
System.out.println("Employee Details are: ");
for(int i=0; i<5; i++)
{
e[i].show();
}
}
}
Output:
Enter Emp number: 1001
Enter Emp Name: Ravi
Enter Emp Salary: 50000
Enter Emp number: 1002
Enter Emp Name: Prashant
Enter Emp Salary: 40000
Employee Details are:
Emp ID: 1001
Name: Ravi
Salary: 50000.0
Emp ID: 1002
Name: Prashant
Salary: 40000.0
2.71
Object Oriented Programming using Java - I Objects and Classes
Program 22: Program to define a class ‘Book’ with data members bookid, bookname and
price. Accept data for three objects using Array of objects and display it.
import java.lang.*;
import java.io.*;
class Book
{
String bookname;
int bookid;
int price;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void getdata()
{
try
{
System.out.println("Enter Book ID: ");
bookid=Integer.parseInt(br.readLine());
System.out.println("Enter Book Name: ");
bookname=br.readLine();
System.out.println("Enter Price: ");
price=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Error");
}
}
void display()
{
System.out.println("Book ID: "+bookid);
System.out.println("Book Name: "+bookname);
System.out.println("Price: "+price);
}
}
class bookdata
{
public static void main(String args[])
{
Book b[]=new Book[7];
for(int i=0;i<7;i++)
{
b[i]=new Book();
}
2.72
Object Oriented Programming using Java - I Objects and Classes
for(int i=0;i<7;i++)
{
b[i].getdata();
}
for(int i=0;i<7;i++)
{
b[i].display();
}
}
}
Output:
Enter Book ID:
1001
Enter Book Name:
JPR
Enter Price:
200
Enter Book ID:
1002
Enter Book Name:
MIC
Enter Price:
250
Enter Book ID:
1003
Enter Book Name:
SEN
Enter Price:
150
Book ID: 1001
Book Name: JPR
Price: 200
Book ID: 1002
Book Name: MIC
Price: 250
Book ID: 1003
Book Name: SEN
Price: 150
Program 23: Program to calculate gross salary of employees if Basic, HRA and DA are
given.
import java.io.*;
import java.lang.*;
class Employee
{
String name;
int salary;
double da,hra,gr;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
2.73
Object Oriented Programming using Java - I Objects and Classes
void get()
{
try
{
System.out.println("Enter the name: ");
name=br.readLine();
System.out.println("Enter the salary: ");
salary=Integer.parseInt(br.readLine());
}
catch(Exception ex)
{
System.out.println(ex);
}
}
void show()
{
System.out.println("Name is: "+name);
System.out.println("Basic salary is: "+salary);
hra=(salary*35)/100;
da=(salary*60)/100;
gr=hra+da+salary;
System.out.println("Gross salary is: "+gr);
}
}
class EmpGrossSalary
{
public static void main(String args[])
{
Employee e[]=new Employee[5];
for(int i=0;i<5;i++)
{
e[i]=new Employee();
}
for(int i=0;i<5;i++)
{
e[i].get();
}
for(int i=0;i<5;i++)
{
e[i].show();
}
}
}
2.74
Object Oriented Programming using Java - I Objects and Classes
Output:
Enter the name:Ravi
Enter the salary:50000
Enter the name:Prashant
Enter the salary:40000
Name is: Ravi
Basic salary is: 50000
Gross salary is: 97500.0
Name is: Prashant
Basic salary is: 40000
Gross salary is: 78000.0
Program 24: Program to define a class person with data member as Aadharno, name,
Panno implement concept of constructor overloading. Accept data for 5 objects and print
it.
import java.io.*;
class Person
{
int Aadharno;
String name;
String Panno;
Person(int Aadharno, String name, String Panno)
{
this.Aadharno = Aadharno;
this.name = name;
this.Panno = Panno;
}
Person(int Aadharno, String name)
{
this.Aadharno = Aadharno;
this.name = name;
Panno = "Not Applicable";
}
void display()
{
System.out.println("Aadharno is: "+Aadharno);
System.out.println("Name is: "+name);
System.out.println("Panno is: "+Panno);
}
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Person p, p1, p2, p3, p4;
int a;
String n, pno;
2.75
Object Oriented Programming using Java - I Objects and Classes
try
{
System.out.println("Enter Aadhar no: ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name: ");
n = br.readLine();
System.out.println("Enter panno: ");
pno = br.readLine();
p = new Person(a,n,pno);
System.out.println("Enter Aadhar no: ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name: ");
n = br.readLine();
System.out.println("Enter panno: ");
pno = br.readLine();
p1 = new Person(a,n,pno);
System.out.println("Enter Aadhar no: ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name: ");
n = br.readLine();
p2 = new Person(a,n);
System.out.println("Enter Aadhar no: ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name: ");
n = br.readLine();
p3 = new Person(a,n);
System.out.println("Enter Aadhar no: ");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name: ");
n = br.readLine();
System.out.println("Enter panno: ");
pno = br.readLine();
p4 = new Person(a,n,pno);
p.display();
p1.display();
p2.display();
p3.display();
p4.display();
}
catch(Exception e)
{
System.out.println("Exception caught: "+e);
}
}
}
2.76
Object Oriented Programming using Java - I Objects and Classes
Output:
Enter Aadhar no: 1001
Enter name: Ravi
Enter panno: ABCD
Enter Aadhar no: 1002
Enter name: Prashant
Enter panno: SCVB
Aadharno is: 1001
Name is: Ravi
Panno is: ABCD
Aadharno is: 1002
Name is: Prashant
Panno is: SCVB
Program 25: Program to demonstrate the use of “this” keyword.
class Testthis
{
int a;
int b;
Testthis(int a, int b) // Parameterized constructor
{
this.a = a;
this.b = b;
}
void display()
{
System.out.println("a = " + a + " b = " + b); //Displaying value of
variables a and b
}
public static void main(String[] args)
{
Test this object = new Testthis(10, 20);
object.display();
}
}
Output:
a = 10 b = 20
Program 26: Program of single level inheritance.
class Room
{
int length, breadth;
Room(int a, int b)
{
length=a;
breadth=b;
}
2.77
Object Oriented Programming using Java - I Objects and Classes
int area()
{
return(length*breadth);
}
}
class Bedroom extends Room
{
int height;
Bedroom(int a, int b,int c)
{
super(a, b);
height=c;
}
int volume()
{
return(length*breadth*height);
}
}
class InnerTest1
{
public static void main(String args[])
{
Bedroom room1=new Bedroom(14,12,10);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("Area: "+area1);
System.out.println("Volume: "+volume1);
}
}
Output:
Area: 168
Volume: 1680
Program 27: Program to 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.
import java.io.*;
class Rectangle
{
int length, width;
2.78
Object Oriented Programming using Java - I Objects and Classes
catch(Exception e)
{
System.out.println("Exception caught: "+e);
}
}
}
Output:
Enter the length, width and depth:10 20 30
Area of the Rectangle is: 200
Area of the Box is: 2200
Volume of the Rectangle is: 6000
Program 28: Program to define a class student with roll no. and name, derive class
attendance with member as present days. Write method to calculate and print average
attendance assuming total days as 180.
class stud
{
int rn;
String name;
stud(int r, String n)
{
rn = r;
name = n;
}
void put()
{
System.out.println("Roll no:"+rn);
System.out.println("Name:"+name);
}
}
class stud_att_cal extends stud
{
double preentday;
stud_att_cal(int r, String n, int p)
{
super(r,n);
preentday = p;
}
void calculate()
{
double avg = (100 * preentday)/180;
put();
System.out.println("Present Days : "+preentday);
System.out.println("Average attendance is: "+avg);
}
}
2.80
Object Oriented Programming using Java - I Objects and Classes
class studAttendance
{
public static void main(String args[])
{
stud_att_cal S1 = new stud_att_cal(2,"Ravi",137);
S1.calculate();
}
}
Output:
Roll no:2
Name:Ravi
Present Days: 137.0
Average attendance is: 76.11111111111111
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which of following method of class StringBuffer is used to concatenate the string
representation to the end of invoking string?
(a) concatenate() (b) concat()
(c) append() (d) join()
2. Which of these access specifiers can be used for a class so that its members can be
accessed by a different class in the different package?
(a) No Modifier (b) public
(c) protected (d) private
3. Which of these methods of class StringBuffer is used to find the length of current
character sequence?
(a) length() (b) Length()
(c) capacity() (d) Capacity()
4. Which of these classes is used to create an object whose character sequence is
mutable?
(a) String() (b) StringBuffer()
(c) String() and StringBuffer() (d) stringbuffer()
5. Overloading of constructors in Java means adding more than ________ constructors
with the different argument list.
(a) 1 (b) 2
(c) 3 (d) 8
6. What is not the use of “this” keyword in Java?
(a) Passing itself to another method
(b) Calling another constructor in constructor chaining
(c) Referring to the instance variable when local variable has the same name
(d) Passing itself to method of the same class
2.81
Object Oriented Programming using Java - I Objects and Classes
34. Which classes provide a way to use primitive data types (int, boolean, etc..) as
objects?
(a) Wrapper (b) String
(c) StringBuffer (d) Scanner
35. In Java which is used to group related classes.
(a) class (b) package
(c) string (d) interface
36. Which package contains classes for primitive types, strings, math functions,
threads, and exceptions?
(a) java.lang (b) java.io
(c) java.net (d) java.util
Answers
1. (c) 2. (b) 3. (a) 4. (b) 5. (a) 6. (d) 7. (a) 8. (d) 9. (b) 10. (d)
11. (b) 12. (c) 13. (c) 14. (b) 15. (d) 16. (b) 17. (d) 18. (c) 19. (d) 20. (a)
21. (a) 22. (b) 23. (c) 24. (d) 25. (a) 26. (a) 27. (d) 28. (a) 29. (c) 30. (c)
31. (a) 32. (c) 33. (c) 34. (a) 35. (b) 36. (a)
Q.II Fill in the Blanks:
1. A class is also considered as an _______ factory.
2. An object is a _______ of a class.
3. A constructor is used when an ________ is created.
4. The keyword _______ is used to include a package in a program.
5. Wrapper class uses first letter in ________ case.
6. _______ method of class StringBuffer is used to concatenate the string
representation to the end of invoking string.
7. _______ method of class StringBuffer is used to find the length of current character
sequence.
8. The keyword used to declare a Java package is _______.
9. When importing a Package, the Class is actually importing _______ or interfaces
from the package.
10. _______ method of object class can clone an object.
11. Under which _______ package is the string class encapsulated.
12. _______ keyword is used for accessing the features of a package.
13. String is a sequence of characters, but in java, string is an _______.
14. _______ is the return type of the hashCode() method in the Object class.
15. _______ keyword is used to refer current object of a class.
16. The _______ is called when an object of a class is created.
17. To declare any static method, we have to write a _______ keyword before the
method name.
2.85
Object Oriented Programming using Java - I Objects and Classes
2.86
Object Oriented Programming using Java - I Objects and Classes
Answers
1. object 2. instance 3. object 4. import 5. upper case
6. append() 7. length() 8. package 9. classes 10. objectClone()
11. java.lang 12. import 13. object 14. int 15. this
16. constructor 17. static 18. objects 19. Packages 20. format()
21. wrapper 22. Access 23. package 24. method 25. sequence
26. equals() 27. class 28. private 29. static 30. this
31. Default 32. static 33. import 34. before 35. class
36. private 37. overloading 38. public 39. Object 40. default
41. user 42. String
Q.III State True or False:
1. The string is immutable, but the StringBuffer is mutable.
2. Package names and directory structure are closely related.
3. The private method can be overridden as public method.
4. We call methods using this keyword.
5. We have multiple static blocks in our code.
6. A private member of a class cannot be accessed by the methods of the same class.
7. A protected member of a class can be accessed from its derived class.
8. The public members of class can be accessed by any code in the program can a
class be declared with a protected modifier.
9. When object of class is declared, each object contains its own copy of static
variables.
10. The static methods must only access static data.
11. Constructor can have a return type.
12. A package can be renamed without renaming the directory in which the classes
are stored.
13. In Java, an object is created from a class.
14. The this keyword in Java is a reference variable that refers to the current object of
a method or a constructor.
15. Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class.
16. A constructor in Java is similar to a method that is invoked when an object of the
class is created.
17. We can create a class in Java using the class keyword.
18. Constructors are similar to methods and have the same name as the method.
19. The hashCode() method returns a hash code for the string.
20. Wrapper classes are used to provide a mechanism to ‘wrap’ or bind the values of
primitive data types into an object.
2.87
Object Oriented Programming using Java - I Objects and Classes
21. Access modifiers provide access to members of a class within a Java program.
22. A Java access modifier specifies which classes can access a given class and its
fields, methods, and constructors.
23. Before creating an array of objects, we must create an instance of the class by
using the static keyword.
24. The Java Object getClass() method returns the class name of the object.
25. A package is simply a container that groups related types (Java classes, interfaces,
enumerations, and annotations).
26. We can use the name of objects along with the . operator to access members of a
class.
27. A method is a block of code that performs a specific task.
28. A string is a sequence of operators.
29. We can join two strings in Java using the concat() method.
30. The equals() method checks the content of strings while comparing them.
31. We can also create two or more constructors with different parameters called as
constructors overloading.
32. Access modifiers are used to set the accessibility (visibility) of classes, interfaces,
variables, methods, constructors.
33. A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).
34. The public access modifier in Java denotes that a variable or a method is private to
the class and we cannot access them outside the class.
35. When methods and data members are declared protected, we can access them
within the same package as well as from subclasses.
36. Java allows us to store objects in an array.
37. An class is any entity that has a state and behavior.
38. The protected access modifier in Java denotes that the variable or a method is
accessible to its subclasses but private to all other classes outside the current
package.
39. Declaring a class with the private access modifier would mean that no other
classes can access it.
40. The 'this' keyword can be used to invoke current class constructor.
41. An array that conations class type elements are known as an array of objects
which stores the reference variable of the object.
Answers
1. (T) 2. (T) 3. (F) 4. (T) 5. (T) 6. (F) 7. (T) 8. (T) 9. (F) 10. (F)
11. (F) 12. (F) 13. (T) 14. (T) 15. (T) 16. (T) 17. (T) 18. (F) 19. (T) 20. (T)
21. (T) 22. (T) 23. (F) 24. (T) 25. (T) 26. (T) 27. (T) 28. (F) 29. (T) 30. (T)
31. (T) 32. (T) 33. (T) 34. (F) 35. (T) 36. (T) 37. (F) 38. (T) 39. (T) 40. (T)
41. (T)
2.88
Object Oriented Programming using Java - I Objects and Classes
13. Create a class distance with variable feet and inches, method get_val(), show_dist().
Use constructor. Create two objects and display their distance.
14. Write a short note on:
(i) this keyword
(ii) Object class
(iii) Wrapper classes.
15. What is string? How to format a string? Describe with example.
16. How to accessing packages? Explain with example.
17. Explain the term wrapper classes in detail.
18. With the help of example describe how to create our own classes.
October 2017
1. What are packages? [1 M]
Ans. Refer to Section 2.11.
2. Create two packages, pack1 contains two classes as student and course. Both
classes have method to read corresponding Information. Pack2 contains class
college with method accept(). Write a java program to display all
information. [5 M]
Ans. Refer to Section 2.11.
3. List any two names of Wrapper class. [2 M]
Ans. Refer to Section 2.10.
April 2018
April 2019
1. What is package? How to create a package. Explain with example. [5 M]
Ans. Refer to Sections 2.11 and 2.11.1.
2. Enlist any two method of string with syntax. [2 M]
Ans. Refer to Section 2.9.2.
2.92
CHAPTER
3
Inheritance and Interface
Objectives…
To understand Basic Concpets of Inheritance
To study Basic Concpets in Interfaces
To learn Abstract Class and Methods
To learn Run-time Polymorphism using Interface
3.0 INTRODUCTION
• Inheritance can be defined as, the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
• The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass
(base class, parent class).
• An interface is one of the core concepts in Java and is used to achieve abstraction,
polymorphism and multiple inheritances.
• In this chapter we will study inheritance, runtime polymorphism, interfaces, marker
concept and so on.
3.1
Object Oriented Programming using Java - I Inheritance and Interface
• Fig. 3.1 shows a class called Vehicle, which has two subclasses called Two Wheeler and
Four Wheeler.
Vehicle
Fig. 3.1
Advantages of Inheritance:
1. Code reusability through inheritance is increased.
2. Inheritance provides a clear model structure which is easy and simple to
understand.
3. Code is easy to manage and divided into parent and child classes.
4. No need to write code from scratch. We can start coding with existing class.
5. Using inheritance we can very easily convert small system into large systems.
6. Good at representing the objects.
• Program 3.1 shows an example of simple inheritance in which the ‘Sub’ class is
inherited from ‘Super’ class. So the members of ‘Super’ class that is, ‘i', ‘j’ and method
‘show ()’ are available in ‘Sub’ class.
• By creating the object of ‘Sub’ class we can access all these members. But the methods
‘display()’, ‘sum()’ and variable ‘k’ cannot accessed in ‘Super’ class. So ‘Super’ class
object cannot use these members.
Inherits from
B Derived class
Taxi
Person(String n, int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
}
}
class Employee extends Person
{
String emp_designation;
float emp_salary;
Employee(String p,int q,String r,float s)
{
super(p,q);
emp_designation=r;
emp_salary=s;
}
void display1()
{
display();
System.out.println("Employee Designation="+emp_designation);
System.out.println("Employee Salary="+emp_salary);
}
public static void main(String args[])
{
Employee e=new Employee("Akshay",18,"Manager",25000);
e.display1();
}
}
Output:
Name= Akshay
Age=18
Employee Designation= Manager
Employee Salary=25000
3.5
Object Oriented Programming using Java - I Inheritance and Interface
B is subclass of A
class B
and superclass of C
C is subclass of B
and superclass of D class C
D is subclass of C class D
void final_result()
{
output();
System.out.println("Deposit amount = "+ deposit);
System.out.println("Withdrawal amount = "+ withdrawal);
}
}
class sample
{
public static void main(String args[])
{
Acc_detail a=new Acc_detail("ABC",1803,10000,500,1000,2000);
a.final_result();
}
}
Output:
Customer name = ABC
Account number = 1803
Saving balance = 10000
Minimum balance = 500
Deposit amount = 1000
Withdrawal amount = 2000
3. Hierarchical Inheritance:
• When a class has more than one child classes (sub classes) have the same parent class
then such kind of inheritance is known as Hierarchical inheritance.
• In case of hierarchical inheritance we derive more than one subclass from a single
super class.
• In below example class B, C and D inherits the same class A. A is parent class (or base
class) of B, C and D.
A
B C D
Student
3.9
Object Oriented Programming using Java - I Inheritance and Interface
class MyClass
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA()
obj1.methodB();
obj2.methodA()
obj2.methodC();
obj3.methodA()
obj3.methodD();
}
}
Output:
method of Class A
method of Class B
method of Class A
method of Class C
method of Class A
method of Class D
3.10
Object Oriented Programming using Java - I Inheritance and Interface
• A class that is derived from another class is called a subclass (also a derived class,
extended class, or child class). The class from which the subclass is derived is called a
superclass (also a base class or a parent class).
• Fig. 3.8 (a) shows if class Y is a subclass of class X, we also say that class X is a
superclass of class Y.
• A subclass can add to the structure and behavior that it inherits. It can also replace or
modify inherited behavior (though not inherited structure).
• The relationship between subclass and superclass is shown in Fig. 3.8 (a).
class X
class X
(subclass)
class Y class Z class A
class Y
(subclass) class B
(a) (b)
Fig. 3.8: The Relationship between Subclass and Superclass
• In Java, to create a class named "Y" as a subclass of a class named "X", we would write,
class Y extends X
{
. // additions to, and modifications of,
. // stuff inherited from class X
}
• Several classes can be declared as subclasses of the same superclass. The subclasses,
which might be referred to as "sibling classes," share some structures and behaviors --
namely, the ones they inherit from their common superclass.
• The superclass expresses these shared structures and behaviors. In the Fig. 3.8 (b)
classes Y, Z and A are sibling classes.
• Inheritance can also extend over several "generations" of classes. This is shown in the
Fig. 3.8 (b), where class B is a subclass of class A which is itself a subclass of class X.
• In this case, class B is considered to be a subclass of class X, even though it is not a
direct subclass. This whole set of classes forms a small class hierarchy.
For example:
• Let's look at an example of Vehicles. Suppose that a program has to deal with motor
vehicles, including Car, Truck and Motorcycle. The program could use a class named to
represent all types of vehicles.
• Since cars, trucks, and motorcycles are types of vehicles, they would be represented by
subclasses of the Vehicle class, as shown in Fig. 3.9.
3.11
Object Oriented Programming using Java - I Inheritance and Interface
Vehicle
Motorcycle
Car
Truck
3.12
Object Oriented Programming using Java - I Inheritance and Interface
void show()
{
System.out.println("Super class cal: "+cal);
}
}
class Secondary extends Primary
{
int cal; //declaration2
Secondary(int x,int y) //statement1
{
super(y); //statement2
cal = x; //statement3
}
void display()
{
System.out.println("Sub class cal: "+cal);
}
}
class SuperUse2
{
public static void main(String args[])
{
Secondary s = new Secondary(15,22);
s.show();
s.display();
}
}
Output:
Super class cal: 22
Sub class cal: 15
• The super class ‘Primary’ has been added with a constructor of one parameter. This
constructor has been called in 'sub class’ constructor in statement2 by passing one
parameter to super().
• If the super class contains more number of constructors all that can be called using
super keyword in 'sub class’ constructor. Statement that contains ‘super’ must be a
first statement in the 'sub class’ constructor.
2. 'super' Access Member of Superclass:
• Any member of immediate superclass can be referred in subclass using super
keyword.
3.14
Object Oriented Programming using Java - I Inheritance and Interface
Bank
getRateOflnterest() : int
extends
Fig. 3.10
Program 3.7: Program for method overriding.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class HDFC extends Bank
{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank
{
int getRateOfInterest(){return 7;}
}
class SBI extends Bank
{
int getRateOfInterest(){return 9;}
}
class Test2
{
public static void main(String args[])
{
HDFC s=new HDFC();
ICICI i=new ICICI();
SBI a=new SBI();
System.out.println("HDFC Rate of Interest: "+s.getRateOfInterest());
3.17
Object Oriented Programming using Java - I Inheritance and Interface
3.18
Object Oriented Programming using Java - I Inheritance and Interface
Syntax:
final class ClassName
{
//Members
}
Example:
final class finalclass
{
//Definitions of members …
}
class errorclass extends finalclass
{
//Definitions of members …
}
• The above program segment contains error since we tried to extend a final class.
Program 3.11: Program for 'final' with classes.
import java.io.*;
final class Demo1
{
public void display()
{
System.out.println("hi");
}
}
public class Demo3 extends Demo1
{
public static void main(String args[])
{
Demo1 d=new Demo1();
d.display();
}
}
Output:
Cannot inherit from final Demo1
• The methods which have only declaration and no method body in the base class are
called abstract method.
• The abstract methods are declared using the keyword "abstract". The method
declaration should end with semicolon (;).
• The abstract methods should be defined in the subclass. Abstract method can never be
final and static.
• The keyword "abstract" is used while declaring abstract method but not at the time of
defining.
Syntax: abstract <return_type> <method_name>(arguments);
Example: abstract void area();
• The base class in which abstract methods are declared is called as abstract class. The
"abstract" keyword is used while declaring abstract class.
Syntax: abstract class <class_name>
{
// body of class…
}
• Abstract class can have simple methods as well as abstract methods. Abstract methods
are those methods which are preceded by abstract keyword and user will declare
them in abstract class the definition of abstract method will be carried out in sub class.
• Following table depicts the difference between class and abstract class:
Sr.
Class Abstract Class
No.
1. Object of class can be created. Object of abstract class cannot be
created.
2. It contains non abstract methods It can have abstract and non abstract
(methods with their definitions). methods.
3. Extension of class is not mandatory. Extension of abstract class is
compulsory.
4. Declaration: Declaration:
class class_name abstract class class_name
{ {
} }
Program 3.12: Program abstract classes and methods.
abstract class shape // Abstract class
{
double pi=3.14;
abstract void area(); // Abstract method
void display()
{
System.out.println("\n Non_abstract method of Class shape");
}
}
3.22
Object Oriented Programming using Java - I Inheritance and Interface
void draw()
{
System.out.println("Drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
s.draw();
}
}
Output:
Drawing circle
3.26
Object Oriented Programming using Java - I Inheritance and Interface
implements extends
class Interface
(a) (b)
Fig. 3.11: Multiple Inheritance in Java
Program 3.16: Program to implementation of multiple inheritance.
class employee
{
String ename;
void get_ename(String name)
{
ename = name;
}
void print_ename()
{
System.out.println("Name = " + ename);
}
}
class gross_sal extends employee
{
float basic, da, hra, gsal;
void calc_gross_sal(int b, int dapercent, int hrpercent)
{
basic = b; //calculate DA & HRA
da = basic* dapercent/100;
hra = basic*hrpercent/100;
gsal = basic + da + hra;
}
3.30
Object Oriented Programming using Java - I Inheritance and Interface
void print_gross_sal()
{
System.out.println("Gross sal = " + gsal);
}
}
interface taxes
{
float ptax = 200 F //P.Tax Rs. 200/-
float itaxpercent = 20F //itax 20% on gsal
float calc_taxes();
}
class salary extends gross-sal implements taxes
{
public float calc_taxes()
{ //Method from interface
return ptax + (gsal * itaxpercent/100);
}
void display()
{ //Method not from interface
float tax = calc_taxes();
float nsal = gsal_tax;
print_ename();
print_gross_sal();
System.out.println("taxes=" + tax);
System.out.println("Net Sal = " + nsal);
}
}
class ImplIface6
{
pubic static void main(String args[])
{
//create an object of class salary
salary empsal = new salary();
empsal.get_ename("Pawar Manoj');
empsal.calc_gross_sal(9100,50,10);
empsal.display();
}
}
3.31
Object Oriented Programming using Java - I Inheritance and Interface
Output:
Name = Pawar Manoj
Gross sal = 14560.0
taxes = 3112.0
Net Sal = 11448.0
3.32
Object Oriented Programming using Java - I Inheritance and Interface
3.36
Object Oriented Programming using Java - I Inheritance and Interface
• A functional interface can have methods of object class. See in the following example.
@FunctionalInterface
interface sayable
{
void say(String msg); // abstract method
// It can contain any number of Object class methods.
int hashCode();
String toString();
boolean equals(Object obj);
}
public class FunctionalInterfaceExample2 implements sayable
{
public void say(String msg)
{
System.out.println(msg);
}
public static void main(String[] args)
{
FunctionalInterfaceExample2 fie = new FunctionalInterfaceExample2();
fie.say("Hello there");
}
}
Output:
Hello there
PROGRAMS
Program 1: Program to display the numbers of parent class and child class demonstrate
single inheritance.
import java.util.Scanner;
class A
{
int no1;
void readA()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the Number First : ");
no1= in.nextInt();
}
}
3.39
Object Oriented Programming using Java - I Inheritance and Interface
class B extends A
{
int no2;
void readB()
{
readA();
Scanner in = new Scanner(System.in);
System.out.print("Enter the Number Second : ");
no2= in.nextInt();
}
void display()
{
System.out.println("First Number = "+no1);
System.out.println("Second Number = "+no2);
}
}
public class ExsingleInh
{
public static void main(String[] args)
{
B b = new B();
b.readB();
b.display();
}
}
Output:
Enter the Number First : 5
Enter the Number Second : 10
First Number = 5
Second Number = 10
Program 2: Program to display College and department name using single inheritance
and super keyword.
class College
{
String cname;
public College(String m)
{
cname = m;
}
}
3.40
Object Oriented Programming using Java - I Inheritance and Interface
class Exmultilevelinh
{
public static void main(String args[])
{
CC obj = new CC();
obj.readC();
}
}
Output:
Hello Class A
Hello Class B
Hello Class C
Program 4: Program for final variable.
public class Exfinalvar
{
public static void main(String[] args)
{
final int number = 100;
System.out.println("Number = " + number);
number = 300; // Can't be modified
}
}
Output:
Exfinalvar.java:11: error: cannot assign a value to final variable a
a = 100; // Can't be modified
^
1 error
Program 5: Program for final method.
class Vehicle
{
final void run()
{
System.out.println("Two Wheeler");
}
}
3.42
Object Oriented Programming using Java - I Inheritance and Interface
Program 7: Program for method overriding msg() in super class and sub class.
class Parent
{
void msg()
{
System.out.println("In Parent Class");
}
}
class Child extends Parent
{
void msg() //method overrides show() of Parent
{
super.msg();
System.out.println("In Child Class");
}
}
class Exmethodoverride
{
public static void main(String[] args)
{
Parent obj = new Child();
obj.msg();
}
}
Output:
In Parent Class
In Child Class
Program 8: Program for runtime polymorphism.
class Shape
{
void draw()
{
System.out.println("Geometry Shapes");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Draw Rectangle...");
}
}
3.44
Object Oriented Programming using Java - I Inheritance and Interface
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
abstract class Staff
{
String name,address;
}
class FullTimeStaff extends Staff
{
String department;
double salary;
public void accept() throws IOException
{
System.out.println("Enter the name, address, department and salary:");
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
name=br.readLine();
address=br.readLine();
department=br.readLine();
salary=Double.parseDouble(br.readLine());
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("Department: "+department);
System.out.println("Salary: "+salary);
System.out.println("----------------------");
}
}
class PartTimeStaff extends Staff
{
int hours, rate;
public void accept() throws IOException
{
System.out.println("Enter the name, address, No of working hours and
rate per hour: ");
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
3.50
Object Oriented Programming using Java - I Inheritance and Interface
name=br.readLine();
address=br.readLine();
hours=Integer.parseInt(br.readLine());
rate=Integer.parseInt(br.readLine());
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("No of Working Hours: "+hours);
System.out.println("Rate per hour: "+rate);
System.out.println("----------------------");
}
}
public class sample
{
public static void main(String [] args) throws IOException
{
int i;
System.out.println("Select Any One: ");
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.println("1.Full Time Staff");
System.out.println("2.Part Time Satff");
int ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter the number of Full Time Staff: ");
int n=Integer.parseInt(br.readLine());
FullTimeStaff [] l=new FullTimeStaff[n];
for(i=0;i<n;i++)
{
l[i]=new FullTimeStaff();
l[i].accept();
}
3.51
Object Oriented Programming using Java - I Inheritance and Interface
for(i=0;i<n;i++)
{
l[i].display();
}
break;
case 2:
System.out.println("Enter the number of Part Time Staff: ");
int m=Integer.parseInt(br.readLine());
PartTimeStaff [] h=new PartTimeStaff[m];
for(i=0;i<m;i++)
{
h[i]=new PartTimeStaff();
h[i].accept();
}
for(i=0;i<m;i++)
{
h[i].display();
}
break;
}
}
}
Output:
Select Any One:
1.Full Time Staff
2.Part Time Satff
1
Enter the number of Full Time Staff:
2
Enter the name, address, department and salary:
adhira
pune
hr
40000
Enter the name, address, department and salary:
kishor
nagar
comp
55000
3.52
Object Oriented Programming using Java - I Inheritance and Interface
Name: adhira
Address: pune
Department: hr
Salary: 40000.0
----------------------
Name: kishor
Address: nagar
Department: comp
Salary: 55000.0
----------------------
Program 15: Program to demonstrate runtime polymorphism using interface.
interface Area
{
final static float pi=3.14f;
float compute(float x, float y);
}
class rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements Area
{
public float compute(float x,float y)
{
return(pi*x*y);
}
}
class interfacetest
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cir=new circle();
Area area;
3.53
Object Oriented Programming using Java - I Inheritance and Interface
area=rect;
System.out.println("Area of rectangle =" +area.compute(10,20));
area=cir;
System.out.println("Area of circle="+area.compute(10,10));
}
}
Output:
Area of rectangle =200.0
Area of circle=314.0
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which of these keyword must be used to inherit a class?
(a) super (b) this
(c) extent (d) extends
2. Which of these is correct way of inheriting class A by class B?
(a) class B + class A {} (b) class B inherits class A {}
(c) class B extends A {} (d) class B extends class A {}
3. Which of these keywords is used to refer to member of base class from a sub
class?
(a) upper (b) super
(c) this (d) none of the mentioned
4. A class member declared protected becomes member of subclass of which type?
(a) public member (b) private member
(c) protected member (d) static member
5. What is not type of inheritance?
(a) Single inheritance (b) Double inheritance
(c) Hierarchical inheritance (d) Multiple inheritance
6. Which of the following is used for implementing inheritance through interface?
(a) inherited (b) using
(c) extends (d) implements
7. What would be the result if class extends two interfaces and both have method
with same name and signature?
(a) Runtime error
(b) Compile time error
(c) Code runs successfully
(d) First called method is executed successfully
3.54
Object Oriented Programming using Java - I Inheritance and Interface
19. Super class and subclass have same variable name, which keyword should be used
to use super class?
(a) upper (b) this
(c) super (d) classname
20. The final keyword in java is used with _______.
(a) class (b) class fields
(c) class methods (d) All of the above
21. Which is the capability of one class to inherit capabilities or properties from
another class?
(a) Class (b) Encapsulation
(c) Inheritance (d) Polymorphism
22. In which inheritance there is a single child class that inherits properties from
single parent class.
(a) single (b) multilevel
(c) hierarchical (d) multiple
23. If we initialize a variable with the _______ keyword, then we cannot modify its
value.
(a) static (b) final
(c) abstract (d) extends
24. When a subclass is derived from a derived class then this mechanism is known as,
(a) multilevel inheritance (b) multiple inheritance
(c) single inheritance (d) hierarchical inheritance
25. The final variables cannot be,
(a) static (b) constant
(c) modified (d) abstract
26. Which keyword refers to superclass (parent) objects.?
(a) static (b) abstract
(c) super (d) final
27. The abstract methods are declared using the keyword,
(a) abstract (b) super
(c) extends (d) final
28. Which is a collection of abstract methods?
(a) inheritance (b) package
(c) interface (d) polymorphism
29. Following which method that does not have its body,
(a) abstract (b) static
(c) final (d) All of mentioned
3.56
Object Oriented Programming using Java - I Inheritance and Interface
11. Interface static methods have ________ and backword compatibility with the
existing project code.
12. The annotation used in Java to override the method of a super-class or interface by
the subclass or implementing class is ________.
13. A static method of an interface should be accessed with interface ________ and a dot
operator.
14. An interface with no fields or methods is known as a ________ Interface.
15. ________ class cannot be sub classed.
16. ________ keyword is used to invoke the superclass constructor from subclass.
17. The extends is the keyword used to ________ the properties of a class.
18. An interface can extend ________ interfaces.
19. The final ________ cannot be inherited by other classes.
20. The purpose of creating the final ________ is to restrict the unwanted and improper
use of method definition while overriding the method.
21. We can also declare a class with a ________ keyword in Java.
22. An ________ method contains a method signature, but no method body.
23. An ________ does not contain any constructors.
24. A class uses the________ keyword to implement an interface.
25. The method defined in the subclass is invoked and executed instead of superclass
method known as ________ overriding.
26. We use the abstract keyword to declare an abstract________.
27. One interface can inherit another by use of the keyword ________.
28. A process in which a call to an overridden method is resolved at run-time rather
than compile time is known as ________-time polymorphism.
Answers
1. marker 2. IS-A 3. extends 4. single 5. abstract
6. abstract class 7. implements 8. public 9. abstract 10. public
11. forward 12. @Override 13. name 14. Marker 15. final
16. super 17. inherit 18. multiple 19. classes 20. methods
21. final 22. abstract 23. interface 24. implements 25. method
26. class 27. extends 28. run
Q.III State True or False:
1. All methods must be implemented of an interface.
2. Can “abstract” keyword be used with constructor, initialization block, instance
initialization and static initialization block.
3.58
Object Oriented Programming using Java - I Inheritance and Interface
26. A class which contains the abstract keyword in its declaration is known as abstract
class.
27. The implements keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
28. When an interface has no members (declared or inherited), it is known as a
marker interface.
Answers
1. (T) 2. (F) 3. (T) 4. (F) 5. (F) 6. (T) 7. (T) 8. (T) 9. (T) 10. (F)
11. (T) 12. (T) 13. (F) 14. (F) 15. (T) 16. (F) 17. (T) 18. (T) 19. (T) 20. (T)
21. (T) 22. (T) 23. (F) 24. (T) 25. (T) 26. (T) 27. (F) 28. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. Define inheritance.
2. Which keyword is used for creating inheritance?
3. What is abstract class?
4. Define run time polymorphism.
5. What are the types of inheritance?
6. What is final?
7. What is purpose of super?
8. Define interface?
9. Which keyword is used for implementing interface?
10. Define abstract method.
11. What is marker interface?
12. Give uses of functional interface.
13. Define superclass and subclass.
14. State any two advantages of inheritance.
15. Define final class.
(B) Long Answer Questions:
1. What is inheritance? How to create it? Explain with example.
2. With the help of example describe following inheritances in Java:
(i) Single (ii) Multilevel (iii) Multiple.
3. Describe abstract classes and methods? Also compare them.
4. How to override methods in Java? Describe with example.
5. What is hierarchical inheritance? Explain in detail with example.
6. What is interface? How to implement it? Explain with example.
7. Explain nested interface with example.
8. How to extending Interface? Explain with example.
3.60
Object Oriented Programming using Java - I Inheritance and Interface
1. “super keyword is used by subclass to refer its immediate superclass”. State true or
false. Justify. [1 M]
Ans. Refer to Section 3.2.2.
2. Write a Java program to illustrate multilevel inheritance such that state is
inherited from country. City is inherited from state. Display the areas, city, state
and country. [5 M]
Ans. Refer to Section 3.1.2 Point (2).
October 2016
April 2018
1. When we declare a method or class final? [1 M]
Ans. Refer to Section 3.4.2.
2. What is runtime polymorphism? How is it implemented in Java? Give suitable
example. [5 M]
Ans. Refer to Section 3.3.
3. Explain two types of Inheritance with suitable example. [3 M]
Ans. Refer to Section 3.1.2.
October 2018
1. Write down any two differences between the abstract class and interface. [2 M]
Ans. Refer to Sections 3.5 and 3.6.
April 2019
1. What is use of final keyword? [1 M]
Ans. Refer to Section 3.4.
2. Write difference between Abstract class and Interface. [3 M]
Ans. Refer to Sections 3.5 and 3.6.
3.62
CHAPTER
4
4.0 INTRODUCTION
• It is a common to take mistakes while developing as well as typing a program.
A mistake might lead to an error causing a program to produce unexpected results.
• An error may produce an incorrect output or may terminate the execution of the
program abruptly.
• It is therefore important to detect and manage properly all the possible error
conditions in the program so that the program will not terminate during execution.
• An exception is an unwanted or unexpected event, which occurs during the execution
of a program i.e. at run-time, which disrupts the normal flow of the program’s
instructions.
• When an exception occur the normal flow of the program is disrupted and the
program terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
• Java uses Exception Handling mechanism to handle the runtime errors so that normal
flow of the application can be maintained.
• File handling in Java is one such functionality that allows us to work with files.
A named location used to store related information is known as a file.
• There are several file operations like creating a new file, getting information about
file, writing into a file, reading from a file and deleting a file.
• Java has several methods for handling file operations such as creating, reading,
updating and deleting files.
• When an error occurs, Java will normally stop and generate an error message. The
technical term for this is Java will throw an exception (throw an error).
• An error is a situation or condition when a compiler either doesn’t execute statements
or either compiler will produce wrong result.
• Error is an illegal operation performed by the user which results in the abnormal
working of the program.
• Programming errors often remain undetected until the program is compiled or
executed. So errors should be removed before compiling and executing of the
program.
• Various types of errors in Java are explained below:
1. Syntax Error or Compile Time Error:
• Errors that are detected by the compiler in compilation are called as compile
errors or syntax errors.
• Compiler time error means Java compiler identify the syntax error at the time of
compilation. And without successfully compilation, compiler does not create .class file.
• The compile time errors include misspelled variable and function names, missing
semicolons, improperly matches parentheses, square brackets and curly braces, used
undefined variable, incorrect format in selection and loop statements etc.
2. Run Time Error:
• Several time program may compile successfully and compiler creates the .class file of
the program but when the time of running the program, it shows the error and that
type of error called run-time error.
• Run-time errors are errors which occur when the program is running. Run time errors
are not detected by the java compiler. It is the JVM which detects it while the program
is running.
• Run-time errors are caught by interpreter or at the time of execution when we execute
out program the error is encountered.
• Run time error includes operations those are not possible but a user trying to do them.
Common examples of run-time error are, trying to divide by a variable that contains a
value of zero, trying to open a file that doesn't exist etc.
3. Logical Error:
• Logic errors occur when there is a design flaw in the program. Logic errors occur
when a program does not perform the way it was intended to.
• This type of error doesn’t halt or stops the execution of Java program but they produce
wrong results.
• This type of error is occurred when there is some mistake in logic of user like user
wants to multiply two numbers and user puts addition mark instead of multiplication
then it is called as logical error.
4.2
Object Oriented Programming using Java - I Exception and File Handling
4.2.1 Exceptions
• Exception is an abnormal condition disrupts the normal flow of the program. An
exception (or exceptional event) is a problem that arises during the execution of a
program.
• Exception is a condition that is caused by runtime errors in program. We can define
exception as “an event occurs during the execution of a program that interrupts the
normal flow of the program".
• Exception is a runtime error which can be handled or prevented and occurs during
the execution of the program.
• Some exceptions can be detected by java compiler while compiling and are called
checked exceptions while those detected during runtime by JVM are called unchecked
exceptions.
4.3
Object Oriented Programming using Java - I Exception and File Handling
• An exception can occur for many different reasons. Following are some scenarios
where an exception occurs.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM
has run out of memory.
• Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Program 4.2: Program for exception.
public class ExceptionExample
{
public static void main(String[] args)
{
int x = 100;
int y = 0;
int z = x / y;
}
}
Output:
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:7)
Difference between Exception and Error in Java:
• Exceptions are related to the application and an error is related to the environment in
which the application is running.
• An Error cannot be recovered as it is fatal in nature, whereas Exception that may not
be fatal in all cases.
• Errors mostly occur at runtime that's they belong to an unchecked type. Exceptions
are the problems which can occur at runtime and compile time.
• The error indicates a problem that mainly occurs due to the lack of system resources
and the program should not catch these types of problems. Exception is an event,
which occurs during the execution of a program that disrupts the normal flow of the
program's Instructions.
• An error is irrecoverable while an exception is recoverable.
• Exceptions are divided into two categories such as checked exceptions and unchecked
exceptions. Error classified as an unchecked type
• Exceptions and errors both are subclasses of Throwable class. Example of error is
OutOfMemoryError, IOError while example of exception NullPointerException,
SqlException
4.4
Object Oriented Programming using Java - I Exception and File Handling
SQLException VirtualMachineError
Exception Error
ClassNot OutOfMemoryError
FoundException
IOException StackOverflowError
RuntimeException
SQLException VirtualMachineError
ClassNot OutOfMemoryError
ArithmeticException
FoundException
NuIlPointerException
RuntimeException
NumberFormat
Exception
ArithmeticException
IndexOutOf
NuIlPointerException
BoundsException
NumberFormat
ArrayIndexOutOf
Exception
BoundsException
IndexOutOf
StringIndexOutOf
BoundsException
BoundsException
ArrayIndexOutOf
Fig. 4.1
BoundsException
4.5
Object Oriented Programming using Java - I Exception and File Handling
3. Errors:
• These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer.
• Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs.
• Errors are generated to indicate errors generated by the runtime environment.
Example: JVM is out of memory. Normally, programs cannot recover from errors.
• Errors are typically ignored in the code because we can rarely do anything about an
error. For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
{
int a[] = new int[2];
try {
System.out.println("Access element three:" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown:" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
Output:
Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
4.9
Object Oriented Programming using Java - I Exception and File Handling
Syntax:
try
{
// Protected code…
}
catch (ExceptionName e1)
{
// Catch block…
}
• The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it.
• Every try block should be immediately followed either by a catch block or finally
block. A catch statement involves declaring the type of exception we are trying to
catch.
• If an exception occurs in protected code, the catch block (or blocks) that follows the try
is checked.
• If the type of exception that occurred is listed in a catch block, the exception is passed
to the catch block much as an argument is passed into a method parameter.
Program 4.6: Program for catch block.
import java.io.*;
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three:" + a[3]);
} catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
System.out.println("Out of the block");
}
}
Output:
Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
4.10
Object Oriented Programming using Java - I Exception and File Handling
try
{
z = 50 / x; //statement1
System.out.println("Division: "+z);
Short arr[] = {5,7,8};
arr[10] = 120; //statement2
System.out.println("Try end...");
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array indexing wrong");
}
System.out.println("Program end...");
}
}
Output:
Enter number: 0
Division by zero
Program end...
Enter number: 5
Division: 10
Array indexing wrong
Program end...
• Above Program 4.7 illustrates the use of multiple catch statements with single try. We
have assume that the code written in the try block will cause either divide by zero
error or array index will go out of bounds. If any one of these exceptions is occurred it
will be caught appropriate catch statement and action will be taken.
• Depending upon the type of exception object thrown only one of the catch statements
will be executed. If the exception thrown does not match with the exception object
written in catch block, program will be terminated.
• In above program we have taken input from keyboard. If value of that input i.e. x is 0
then the divide by zero exception will occur at statement1 else array index out of
bounds exception will occur at statement2. These exceptions will be caught by
appropriate catch clause.
4.12
Object Oriented Programming using Java - I Exception and File Handling
4.15
Object Oriented Programming using Java - I Exception and File Handling
4. Throw is used within the method. Throws is used with the method
signature.
5. We cannot throw multiple exceptions. We can declare multiple exceptions
e.g.public void method()throws
IOException, SQLException.
6. Example: Example:
void m(){ void m()throws ArithmeticException{
throw new ArithmeticException("sorry"); //method code
} }
Outputs:
Enter number: 0
Division by zero
Program end...
Enter number: 1
Division: 82
Division by zero
Program end...
Enter number: 2
Division: 41
Array indexing wrong
Outer try end...
Program end...
• Above Program 4.10 has nested two try statements in each other. We have taken input
as a number from keyboard and stored it into variable x. When value of x is inputted
as 0, statement1 will cause an exception “Divide by zero”.
• So program control will directly transfer to catch statement no.2 to take the action.
When value of x inputted is 1. The outer 'try' will work properly. In inner try, the
statement2 will cause the exception of “Divide by zero”.
• In this case, the program control will get directly transferred to inner try’s catch block
i.e. catch clause no. 1. But the exception object will not match. So it will check for outer
try’s catch clause. Now, the match is found. That’s why, we got the output no.2.
• In the third case, when the input is any number other than 0 and 1, statement3 will
cause an exception “Array index out of bounds”. This will be caught by inner try’s
catch clause.
• That is, the outer try’s catch clause will catch all the exception occurred inside it.
Remember, if the exception of “array index out of bounds” is occurred in outer try
then this will not be caught by inner try’s catch clause.
4.4 CREATING USER DEFINED EXCEPTIONS [April 17, 18, 19, Oct. 17]
• Though Java provides an extensive set of in-built exceptions, there are cases in which
we may need to define our own exceptions in order to handle the various application
specific errors that we might encounter.
• If a user is creating his/her own Exception is known as user defined exception
(or custom exception). Java user defined exceptions are used to customize the
exception according to user need.
4.18
Object Oriented Programming using Java - I Exception and File Handling
• In java we can create our own exception class and throw that exception using throw
keyword. There are following two basic reasons for defining our own exception
classes:
1. We want to add information when a standard exception occurs, and
2. We may have error conditions that arise in your code.
Syntax:
class exceptionclassname extends Exception
{
exceptionclassname(parameter)
{
//statements
}
public String toString()
{
return String
}
}
• The user defined exceptions must be explicitly thrown using the ‘throw’ statement
whose syntax is,
throw ThrowableInstance
• ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Following are some of the methods defined by Class Throwable.
Method Meaning
1. String getMessage() Returns a description of the exception.
2. Throwable getCause() Returns the exception that underlies the
current exception.
3. StackTraceElement[]getStackTrace() Returns an array that contains the stack
trace.
4. Void printStackTrace() Prints the Stack trace.
5. String toString() Returns a String object containing a
description of the exception.
Program 4.11: Program for creating own exception.
class NegativeOutputException extends Exception
{
private int det;
NegativeOutputException(int a)
{
det = a;
}
4.19
Object Oriented Programming using Java - I Exception and File Handling
• The input has taken from the command line. First argument is passed to x and second
to y. First time and third time when both the arguments are positive/negative the
result is positive so we will get the output properly.
• But when any one of the arguments is negative the result is also negative. The
statement1 will be true. Now exception is thrown using the throw clause.
• This exception is caught by catch clause. If we do not catch it using catch the compile
time error will occur.
4.5 INTRODUCTION TO FILES AND STREAMS [Oct. 16, 18, April 19]
• A file is a named location that can be used to store related information. The File class
from the java.io package (java.io.File), allows us to work with files.
• The java.io package provides an extensive library of classes for dealing with Input and
Output (I/O).
• Java provides streams as a general mechanism for dealing with data I/O. Java uses the
concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.
• Streams implement sequential access of data. There are two kinds of streams: byte
streams and character streams.
• An input stream is an object that an application can use to read a sequence of data,
and an output stream is an object that an application can use to write a sequence of
data.
• An input stream acts as a source of data, and an output stream acts as a destination of
data.
• Java I/O stream is the flow of data that we can either read from, or we can write to.
It is used to perform read and write operations in file.
• Java I/O stream is also called File Handling, or File I/O. It is available
in java.io package. Java.io package provides classes for system input and output
through files.
• A directory is a collection of files and subdirectories. A directory inside a directory is
known as subdirectory.
• A file can be read either sequentially (continuously) or randomly (here and there).
Constructors:
• File(path): Create File object for default directory (usually where program is
located).
• File(dirpath,fname): Create File object for directory path given as string.
• File(dir, fname): Create File object for directory.
1. Sequential Access File:
• Sequential file access allows data to be read from a file or written to a file from
beginning to end.
4.21
Object Oriented Programming using Java - I Exception and File Handling
• It is not possible to read data starting in the middle of the file, nor is it possible to write
data to the file starting in the middle using sequential methods.
• The input and output streams in Java are sequential.
Methods:
(i) getName(): Return the name of file.
(ii) getParent(): Return the name of Parent directory.
(iii) length(): Return the length of the file.
(iv) isFile(): Returns true if invoking object is file.
(v) getPath(): Returns relative path of the file.
(vi) isDirectory(): Returns true, if the invoking object is directory.
(vii) isAbsolute(): Returns true, if the path is absolute.
while(len>0)
{
System.out.print((char) f.read( ));
len = len - 1;
}
System.out.println("\n\nSize of file:"+f.length( ));
}
}
Output:
Contents of file:
It is very easy to use the class RandomAccessFile.
Size of file:50
// print
System.out.println("File created: "+bool);
}catch(Exception e){
e.printStackTrace();
}
}
}
Output:
File created: false
delete() method is invoked
File created: true
Program 4.15: Program for file creation.
import java.io.File; // Import the File class
import java.io.IOException; //Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
File created: filename.txt
• In the following program, we use the Scanner class to read the contents of the text file.
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
4.25
Object Oriented Programming using Java - I Exception and File Handling
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Files in Java might be tricky, but it is fun enough!
• In the following example, we use the FileWriter class together with its write() method
to write some text to the file we created in the example above. Note that when you are
done writing to the file, you should close it with the close() method.
import java.io.FileWriter; //Import the FileWriter class
import java.io.IOException; //Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun
enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:
Successfully wrote to the file.
4.26
Object Oriented Programming using Java - I Exception and File Handling
4.27
Object Oriented Programming using Java - I Exception and File Handling
• Program 4.16 reads the content of a text file and displays it. In this program to read a
filename readLine() method is used on BufferedReader object which may throws
IOException.
• Creating an object of type FileInputStream opens file. The try/catch blocks are used to
handle the exception while opening file. When EOF is encountered read( ) method
returns –1.
Program 4.16: Reading a file.
import java.io.*;
class readfile
{
public static void main(String args[]) throws IOException
{
int x;
FileInputStream fis;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
System.out.println("\nEnter filename to read: ");
String fname=br.readLine();
try
{
fis=new FileInputStream(fname);
}
catch(FileNotFoundException e)
{
System.out.println("File not found..");
return;
}
//read from file
do
{
x=fis.read();
if (x!=-1)
System.out.print((char)x);
}
while (x!=-1);
fis.close();
}
}
4.28
Object Oriented Programming using Java - I Exception and File Handling
Output:
Enter a filename to read:
abc.txt
Sachin Tendulkar is my favourite player
• Following Program 4.17 copies the content of source file and target file. The program
takes filename through command line arguments. If source file does not exist or target
file can’t create then program catches the FileNotFoundException.
• Program uses read() method of FileInputStream object and return –1 when EOF is
encountered. The ArrayIndexOutOfBoundException is caught to check for number of
command-line arguments passed.
Program 4.17: Copy the content of a file into another. [April 16]
import java.io.*;
class dup
{
public static void main(String args[]) throws IOException
{
int x;
FileInputStream fis;
FileOutputStream fos;
try
{
try
{
fis=new FileInputStream(args[0]);
}
//source file not available
catch(FileNotFoundException e)
{
System.out.println("File not found..");
return;
}
try
{
fos=new FileOutputStream(args[1]);
}
//error in creating target file
catch(FileNotFoundException e)
{
System.out.println("Can not create a file");
return;
}
}
4.29
Object Oriented Programming using Java - I Exception and File Handling
• All the input and output operation of file uses streams. A stream is an abstraction of
I/O devices.
o A stream is a sequence of data. Stream represents flow of data.
o Stream is a logical entity that will be tied up with a data source or destination.
• The stream presents an object oriented and uniform interface between the program
and the input/output devices.
• Every Java program has a source and destination. Source is in the form of keyboard,
mouse, memory, disk, etc. Destination is screen, printer, memory, disk etc. There is an
input and output streams.
• An input stream takes data from source and sends it to the program. An output stream
takes data from the program and sends it to the destination.
• A flow of data is often referred to as a data stream. A stream is an ordered sequence of
bytes that has a SOURCE (input stream) or a DESTINATION (output stream).
• In simple terms, a stream can be defined as "a logical device that represents the flow
of a sequence of characters".
• Programs can get inputs from a data source by reading a sequence of characters from
the input stream. Similarly, programs can produce outputs by writing a sequence of
characters onto an output stream.
• Stream is a logical entity that will be tied up with a data source or destination. Stream
represents flow of data. The representation of stream is as shown in Fig. 4.2.
4.30
Object Oriented Programming using Java - I Exception and File Handling
InputStream OutputStream
Java Data
Data Source 1010101010 Application 1010101010 Destination
Read Write
Source
reads Program
A stream
Writes
Program
Destination
• Java’s stream based I/O has four abstract classes namely, InputStream, OutputStream,
Reader and Writer.
• Inputstream and OutputStream deal with bytes i.e. read/write bytes. Reader and
Writer are designed for character streams.
• An input stream is used to read data from the source. An output stream is used to
write data to the destination.
1010101010 1010101010
Fig. 4.7
• An input stream reads data from the source file and sends it to the program while
output stream takes data from the program and sends it to the destination file.
• Depending upon the data a stream holds, it can be classified into Byte Stream and
Character Stream.
• Byte stream is used to read and write a single byte (8 bits) of data. All byte stream
classes are derived from base abstract classes called InputStream and OutputStream.
• Character stream is used to read and write a single character of data. All the character
stream classes are derived from base abstract classes Reader and Writer.
• java.io.InputStream is an abstract class that contains the basic methods for reading
raw bytes of data from a stream.
• Although InputStream is an abstract class, many methods in the class library are only
specified to return an InputStream.
• Java application uses an input stream to read data from a source. It may be a file, an
array, peripheral device or socket.
Input
Array stream
File Socket
Source Java
1100110100 1100110100
application
FileInputStream
PipedInputStream
ByteArrayInputStream
SequenceInputStream
ObjectInputStream
StringBufferInputStream
FilterInputStream
BufferedInputStream
PushbackInputStream
DataInputStream
• The InputStream class defines following different methods to perform input operation:
o read(): it reads a byte from input stream.
o read(byte arr[]): it reads on array of bytes into arr.
o read (byte arr[], int s, int n): reads in bytes in arr.start position is S.
o available(): returns available number of bytes in the input.
o reset(): moves to the beginning of the stream.
o close(): the input stream is closed.
• The class DataInputStream implements the interface DataInput. All the methods of it
are listed below:
readShort() readFloat() readChar()
readInt() readDouble() readBoolean()
readLong() readLine()
4.34
Object Oriented Programming using Java - I Exception and File Handling
Program 4.18: Program to use of InputStream to count the total number of bytes in a file if
no file is specified.
import java.io.*;
class count
{
public static void main(String args[])
throws IOException
{
InputStream in;
if (args.length = 0)
in = System.in;
else
in = new FileInputStream (args[0]);
int total = 0;
while (in.read() != – 1)
total ++;
System.out.println(total + "bytes");
}
}
• This program takes filename from command line. If a filename is not provided, the
standard inputstream i.e. system in is used. The while loop counts the total number of
bytes in a file. At the end, result will be printed.
Output:
212 bytes
4.6.2 OutputStream
• Java application uses an output stream to write data to a destination. It may be a file,
an array,peripheral device or socket.
Output
stream Array
File Socket
Java Destination
1100110100 1100110100
application
FileOutputStream
PipedOutputStream
ByteArrayInputStream
ObjectOutputStream
FilterOutputStream
BufferedOutputStream
PushbackOutputStream
DataOutputStream
throws IOException
{
byte from = (byte)args[0].charAt(0);
byte to = (byte)args[1].charAt(0);
int b;
while ((b = System.in.read() != – 1)
System.out.write(b == from? to: b);
}
}
• We should invoke this program as,
java trbyte b B
and entered the text abracadabra !
• We will get the output:
aBracadaBra !
• To summarize Byte stream classes:
Byte Stream Class Purpose
DataInputStream To read java standard data types.
DataOutputStream To write java standard data types.
BufferedInputStream For buffered input operations.
BufferedOutputStream For buffered output operations.
FileInputStream To read data from the file.
FileOutputStream To write data to the file.
ByteArrayInputStream To read data from byte array.
ByteArrayOutputStream To write data into byte array.
PrintStream It contains print() and println().
4.6.3 FileInputStream
• This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
• Following constructor takes a file name as a string to create an input stream object to
read the file:
InputStream f = new FileInputStream("/java/nirali");
• A FileInputStream obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. For reading streams of characters, consider using
FileReader.
• It should be used to read byte-oriented data. For example, to read image etc.
4.37
Object Oriented Programming using Java - I Exception and File Handling
4.6.4 FileOutputStream
• It is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output.
• A FileOutputStream is an output stream for writing data to a file.
• If we have to write primitive values then use FileOutputStream. Instead, for character-
oriented data, prefer FileWriter. But we can write byte-oriented as well as character-
oriented data.
• FileOutputStream is used to create a file and write data into it. The stream would
create a file, if it doesn't already exist, before opening it for output.
• Constructors are:
1. FileOutputStream(String filePath)
2. FileOutputStream(File fileObj)
3. FileOutputStream(String filePath, boolean append)
4. FileOutputStream(File fileObj, boolean append)
Program 4.21: Program for FileOutputStream.
import java.io.*;
class Test
{
public static void main(String args[]){
try{
FileOutputstream fout=new FileOutputStream("abc.txt");
4.38
Object Oriented Programming using Java - I Exception and File Handling
4.6.5 BufferedInputStream
• Java BufferedInputStream class is used to read information from stream. It internally
uses buffer mechanism to make the performance fast.
• The important points about BufferedInputStream are:
1. When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time.
2. When a BufferedInputStream is created, an internal buffer array is created.
Constructors:
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and
saves it argument, the input stream IS, for
later use.
BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a
int size) specified buffer size and saves it argument,
the input stream IS, for later use.
Methods:
int available() It returns an estimate number of bytes that
can be read from the input stream without
blocking by the next invocation method for
the input stream.
int read() It read the next byte of data from the input
stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-
input stream into a specified byte array,
starting with the given offset.
contd. …
4.39
Object Oriented Programming using Java - I Exception and File Handling
4.6.6 BufferedOutputStream
• Java BufferedOutputStream class is used for buffering an output stream. It internally
uses buffer to store data.
• It adds more efficiency than to write data directly into a stream. So, it makes the
performance fast.
• For adding the buffer in an OutputStream, use the BufferedOutputStream class.
4.40
Object Oriented Programming using Java - I Exception and File Handling
Constructors:
BufferedOutputStream(OutputStream os) It creates the new buffered output stream
which is used for writing the data to the
specified output stream.
BufferedOutputStream(OutputStream os, It creates the new buffered output stream
int size) which is used for writing the data to the
specified output stream with a specified
buffer size.
Methods:
void write(int b) It writes the specified byte to the buffered
output stream.
void write(byte[] b, int off, It write the bytes from the specified byte-
int len) input stream into a specified byte array,
starting with the given offset
void flush() It flushes the buffered output stream.
4.6.7 DataInputStream
• Java DataInputStream class allows an application to read primitive data from the
input stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can later be
read by a data input stream.
• Following is the constructor to create an InputStream −
InputStream in = new DataInputStream(InputStream in);
Methods:
int read(byte[] b) It is used to read the number of bytes from the
input stream.
int read(byte[] b, int off, It is used to read len bytes of data from the input
int len) stream.
4.6.8 DataOutputStream
• Java DataOutputStream class allows an application to write primitive Java data types
to the output stream in a machine-independent way.
• Java application generally uses the data output stream to write data that can later be
read by a data input stream.
Methods:
int size() It is used to return the number of bytes written to
the data output stream.
void write(int b) It is used to write the specified byte to the
underlying output stream.
void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.
• Java Reader is an abstract class for reading character streams. Reader is the base class
of the character oriented input streams. It provides methods to read a sequence of
Unicode characters.
Reader
PipeReader
InputStreamReader
FileReader
CharArrayReader
BufferedReader
StringReader
FilterReader
PushbackReader
• It is character oriented input operations. The following table shows all the Reader
methods and its description.
• It is an abstract class for character-input streams.
• Java provides the standard I/O facilities for reading text from either the file or the
keyboard on the command line.
• The Reader class is used for this purpose that is available in the java.io package. It acts
as an abstract class for reading character streams.
• Fig. 4.12 shows classes of Reader. The methods for Reader are given in following table:
Methods Description
int read() Reads a single character.
int read(char[]buff) Reads character into the array buff.
int read(char[]buff, int index, Reads character into a portion of the array
int length) buff starting from index upto the length given.
Boolean ready() Returns true if the stream is ready for reading.
long skip(long n) Skips n characters.
void reset() Resets the stream.
void mark(int readLimit) Marks the current position of the stream.
Boolean markSupported() Returns true if the mark operation is executed.
static void close() Closes the stream.
• The implementation of Reader requires that a subclass provide a implementation of
the read method that reads into a char array and the close method.
Difference between Reader and InputStream:
Reader InputStream
1. Reads into a char array. 1. Reads in a single byte.
2. Subclass must implements the abstract 2. Close() is usually overridden.
close method.
3. It has a ready method which tells us if 3. It has available method which tells
there is any data. us how much data is available to
read.
• Program for counts number of whitespace characters in character stream.
Program 4.26:
import java.io.*;
class space1
{
public static void main(String args[])
throws IOException
{
Reader in;
if (args.length == 0)
in = new InputStreamReader(System.in);
else
in = new FileReader(args[0]);
int ch;
4.46
Object Oriented Programming using Java - I Exception and File Handling
int total;
int space = 0;
for (total=0; (ch = in.read())!= - 1; total++)
{
if (Character.isWhitespace ((char)ch))
space ++;
}
system.out.println(total + "chars" + space + "spaces");
}
}
Output:
If the same program name given 453 chars 111 spaces.
4.7.2 Writer
• Writer is an abstract class for writing to character streams. It is an abstract class. It
provides a stream analogous of OutputStream but it uses characters and not bytes.
• The data can be written into a file, memory buffer, or can be displayed in standard
output device.
• It is an abstract class for character-output streams. Fig. 4.13 shows classes and writer.
Writer
PipeWriter
OutputStreamWriter
FileWriter
CharArrayWriter
BufferedWriter
StringWriter
FilterWriter
PrintWriter
• Constructors are:
1. FileReader(String path)
2. FileReader(File obj)
Program 4.28: Program for FileReader.
import java.io.FileReader;
import java.io.File;
class FileRead
{
public static void main(String args[ ])
throws Exception
{
File f = new File("sample.txt");
if(f.exists( ))
{
FileReader fr = new FileReader(f);
int ch;
while((ch = fr.read()) != -1)
System.out.print((char) ch);
fr.close( );
}
}
}
Output:
It is very easy to use the class in Java.
4.7.4 FileWriter
• FileWriter class is used to write character into the file.
• Constructors are:
1. FileWriter(String path)
2. FileWriter(String path, boolean append)
3. FileWriter(File obj)
4. FileWriter(File obj, boolean append)
Program 4.29: Program for FileWriter.
import java.io.FileWriter;
class FileWrite
{
public static void main(String args[ ])throws Exception
{
4.49
Object Oriented Programming using Java - I Exception and File Handling
4.7.5 BufferedReader
• Java BufferedReader class is used to read the text from a character-based input
stream. It can be used to read data line by line by readLine() method.
• It makes the performance fast. It inherits Reader class.
Constructors:
Constructor Description
BufferedReader(Reader rd) It is used to create a buffered character input
stream that uses the default size for an input
buffer.
BufferedReader(Reader rd, int It is used to create a buffered character input
size) stream that uses the specified size for an input
buffer
4.50
Object Oriented Programming using Java - I Exception and File Handling
Methods:
Method Description
int read() It is used for reading a single character.
int read(char[] cbuf, int off, It is used for reading characters into a portion of
int len) an array.
boolean markSupported() It is used to test the input stream support for the
mark and reset method.
String readLine() It is used for reading a line of text.
boolean ready() It is used to test whether the input stream is
ready to be read.
long skip(long n) It is used for skipping the characters.
void reset() It repositions the stream at a position the mark
method was last called on this input stream.
void mark(int readAheadLimit) It is used for marking the present position in a
stream.
void close() It closes the input stream and releases any of the
system resources associated with the stream.
Program 4.30: Program for reading the data from the text file testout.txt using Java
BufferedReader.
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
• Here, we are assuming that we have te data (Welcome to javaTpoint.) in "testout.txt"
file.
Output:
Welcome to javaTpoint.
4.51
Object Oriented Programming using Java - I Exception and File Handling
4.7.6 BufferedWriter
• Java BufferedWriter class is used to provide buffering for Writer instances. It makes
the performance fast. It inherits Writer class.
• The buffering characters are used for providing the efficient writing of single arrays,
characters and strings.
Constructors:
BufferedWriter(Writer wrt) It is used to create a buffered character
output stream that uses the default size for
an output buffer.
BufferedWriter(Writer wrt, int size) It is used to create a buffered character
output stream that uses the specified size
for an output buffer.
Methods:
void newLine() It is used to add a new line by writing a
line separator.
void write(int c) It is used to write a single character.
void write(char[] cbuf, int off, It is used to write a portion of an array of
int len) characters.
void write(String s, int off, It is used to write a portion of a string.
int len)
void flush() It is used to flushes the input stream.
void close() It is used to closes the input stream
Program 4.31: Program for writing the data from the text file testout.txt using Java
BufferedReader.
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}
Output:
Success
testout.txt:
Welcome to javaTpoint.
4.52
Object Oriented Programming using Java - I Exception and File Handling
4.7.7 InputStreamReader
• An InputStreamReader is a bridge from byte streams to character streams: It reads
bytes and decodes them into characters using a specified charset.
• The charset that it uses may be specified by name or may be given explicitly, or the
platform's default charset may be accepted.
Constructors:
Constructor Name Description
InputStreamReader(InputStream in) It creates an InputStreamReader that uses
the default charset.
InputStreamReader(InputStream in, It creates an InputStreamReader that uses
Charset cs) the given charset.
Methods:
Modifier
Method Description
and Type
void close() It closes the stream and releases any system
resources associated with it.
String getEncoding() It returns the name of the character encoding
being used by this stream.
int read() It reads a single character.
int read(char[] cbuf, int It reads characters into a portion of an array.
offset, int length)
boolean ready() It tells whether this stream is ready to be
read.
Program 4.32: Program for InputStreamReader.
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
4.53
Object Oriented Programming using Java - I Exception and File Handling
4.7.8 OutputStreamWriter
• OutputStreamWriter is a class which is used to convert character stream to byte
stream, the characters are encoded into byte using a specified charset.
• The write() method calls the encoding converter which converts the character into
bytes.
• The resulting bytes are then accumulated in a buffer before being written into the
underlying output stream. The characters passed to write() methods are not buffered.
• We optimize the performance of OutputStreamWriter by using it with in a
BufferedWriter so that to avoid frequent converter invocation.
Constructors:
OutputStreamWriter(OutputStream out) It creates an OutputStreamWriter that uses
the default character encoding.
OutputStreamWriter(OutputStream out, It creates an OutputStreamWriter that uses
Charset cs) the given charset.
4.54
Object Oriented Programming using Java - I Exception and File Handling
Methods:
Modifier
Method Description
and Type
void close() It closes the stream, flushing it first.
void flush() It flushes the stream.
String getEncoding() It returns the name of the character
encoding being used by this stream.
void write(char[] cbuf, It writes a portion of an array of characters.
int off, int len)
void write(int c) It writes a single character.
void write(String str, It writes a portion of a string.
int off, int len)
Program 4.33: Program for OutputStreamReader.
public class OutputStreamWriterExample {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("output.txt");
Writer outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write("Hello World");
outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Output:
output.txt file will contains text "Hello World"
PROGRAMS
Program 1: Program for try-catch statement to handle the exception.
public class Demoexception
{
public static void main(String args[])
{
try
{
int data=100/0; // raise exception
}
4.55
Object Oriented Programming using Java - I Exception and File Handling
if (f.exists())
{
System.out.println("File name: " + f.getName());
System.out.println("Absolute path: " + f.getAbsolutePath());
System.out.println("Writeable: " + f.canWrite());
System.out.println("Readable: " + f.canRead());
System.out.println("File size in bytes:" + f.length());
}
else
{
System.out.println("Sorry !!! The file does not exist.");
}
}
}
Output:
Writeable: true
Readable: true
File size in bytes:8
Program 8: Program to write the string into file using Writer.
import java.io.*;
public class Exwriter
{
public static void main(String[] args)
{
try
{
Writer w = new FileWriter("test.txt");
String s = "Covid Vaccine";
w.write(s);
w.close();
System.out.println("Successfully Done...");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Output:
Successfully Done...
4.61
Object Oriented Programming using Java - I Exception and File Handling
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which of these packages contain all the Java’s built in exceptions?
(a) java.io (b) java.util
(c) java.lang (d) java.net
2. Which of these classes is used to create user defined exception?
(a) java.lang (b) Exception
(c) RunTime (d) System
3. What will be the output of the program?
public class X
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
4.62
Object Oriented Programming using Java - I Exception and File Handling
10. Which of the following classes can catch all exceptions which cannot be caught?
(a) RuntimeException (b) Error
(c) ParentException (d) Exception
11. Which are the valid ways to create DataInputStream streams?
(a) new DataInputStream();
(b) new DataInputStream("in.dat", "r");
(c) new DataInputStream(new FileInputStream("in.dat");
(d) new DataInputStream("in.dat")
12. Which of the following strings can be used as mode strings for creating a
RandomAccessFile object?
(i) "r" (ii) "w"
(iii) "rw" (iv) "wr"
(v) "0"
(a) (i), (ii), (iii) & (v) (b) (i), (ii) & (iii)
(c) (i) & (iii) (d) (ii), (iv) & (v)
13. DataInput is _______.
(a) an abstract class defined in java.io.
(b) a class we can use to read primitive data types.
(c) an interface that defines methods to open files.
(d) an interface that defines methods to read primitive data types.
14. The try, catch, finally, throw and throws keywords in java are related to,
(a) Event handling (b) string handling
(c) exception handling (d) inheritance
15. What is subclass in java?
(a) A subclass is a class that extends another class
(b) A subclass is a class declared inside a class
(c) Both (a) and (b)
(d) None of mentioned
16. If class B is subclassed from class A then which is the correct syntax _______.
(a) class B:A{} (b) class B extends A{}
(c) class B extends class A{} (d) class B implements A{}
17. Which of these is a type of stream in Java?
(a) Integer stream (b) Short stream
(c) Byte stream (d) Long stream
4.64
Object Oriented Programming using Java - I Exception and File Handling
18. Which of these classes is used to read characters and strings in Java from console?
(a) BufferedReader (b) StringReader
(c) BufferedStreamReader (d) InputStreamReader
19. Which of these classes is used to read from a file?
(a) InputStream (b) BufferedInputStream
(c) FileInputStream (d) BufferedFileInputStream
20. Which of these method(s) is/are used for writing bytes to an outputstream?
(a) put() (b) print() and write()
(c) printf() (d) write() and read()
21. Which occur naturally when we create, write and develop programs?
(a) Errors (b) Exceptions
(c) Mistakes (d) All of mentioned
22. Which exceptions occurs at the compile time?
(a) unchecked (b) checked
(c) error (d) All of mentioned
23. All the errors and exceptions in Java are the subclasses of which class,
(a) Object (b) String
(c) Throwable (d) Scanner
24. Which occurs during the execution of the program?
(a) unchecked (b) checked
(c) error (d) All of mentioned
25. A catch block always follows the _______ block.
(a) try (b) throw
(c) throws (d) finally
26. Which block is a block where we can handle the exceptions?
(a) try (b) finally
(c) throw (d) catch
27. Which is an unexpected event that occurs during program execution?
(a) error (b) exception
(c) mistake (d) All of mentioned
28. Which statement declares the type of exception that we try to catch?
(a) try (b) throw
(c) catch (d) finally
4.65
Object Oriented Programming using Java - I Exception and File Handling
4.66
Object Oriented Programming using Java - I Exception and File Handling
18. All exception classes are subtypes of the java.lang.Exception class. The exception
class is a subclass of the Throwable class.
19. The Exception class has two main subclasses nsmely, IOException class and
RuntimeException Class.
20. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally
21. A finally block appears at the end of the catch blocks.
22. The FileWriter class of the java.io package can be used to read data (in characters)
from files.
23. FileOutputStream is used to create a file and write data into it.
24. To create a file in Java, we can use the createNewFile() method.
25. We use the FileWriter class together with its write() method to write some text to
the file.
Answers
1. (T) 2. (F) 3. (T) 4. (T) 5. (F) 6. (F) 7. (T) 8. (T) 9. (F) 10. (T)
11. (F) 12. (T) 13. (T) 14. (F) 15. (T) 16. (T) 17. (T) 18. (T) 19. (T) 20. (T)
21. (T) 22. (F) 23. (T) 24. (T) 25. (T)
Q.IV Answer the following Questions:
(A) Short Answer Questions:
1. Define exception.
2. What is error?
3. List types of exceptions.
4. Which statement is used for handling exceptions.
5. Define stream.
6. What is file?
7. What is the purpose of FileReader and FileWriter?
8. Name any two checked exceptions.
9. What is a user-defined exception?
10. Define nested try statement with it syntax.
11. Give the purpose of throw and throws.
12. Define exception handling.
13. What is the use of Reader and Writer?
14. What is the purpose of BufferedReader and BufferedWriter?
4.69
Object Oriented Programming using Java - I Exception and File Handling
October 2016
1. What is the use of finally keyword? [1 M]
Ans. Refer to Section 4.2.4 Point (3).
2. Write a Java program to get file name from command prompt. Check whether a
file by given name exists. If file is a regular file, then display various details about
that file. But if it is a directory, then display number of files in that directory. [5 M]
Ans. Refer to Section 4.5.
3. List and describe any five methods of Reader class along with their syntax. [5 M]
Ans. Refer to Section 4.7.1.
April 2017
1. Write a Java program to accept a file name from command prompt. If the file
exists, then display number of words and lines in that file using FileReader
class. [5 M]
Ans. Refer to Section 4.7.3.
2. List and describe any five methods of InputStream class along with their
syntax. [5 M]
Ans. Refer to Section 4.6.1.
October 2017
1. Give difference between throw and throws. [2 M]
Ans. Refer to Page 4.15.
2. Which stream is used to read primitive data from file? [1 M]
Ans. Refer to Section 4.5.2.
3. Write a java program to delete all the files from the current directory having
extension as .doc also display the count number of .doc files deleted
separately. [5 M]
Ans. Refer to Page 4.27.
4. Explain any three methods of the Input Stream class. [3 M]
Ans. Refer to Section 1.6.1.
5. Write a java program which stores the username and password in two variables. If
username and password are not same, then raise "Invalid password" with
appropriate message. [5 M]
Ans. Refer to Section 4.2.4.
April 2018
1. Write a Java program which displays the contents of file in reverse order. [5 M]
Ans. Refer to Section 4.5.
2. What are user-defined exceptions ? Illustrate them with an example. [5 M]
Ans. Refer to Section 4.4.
4.71
Object Oriented Programming using Java - I Exception and File Handling
October 2018
1. What is the use of finally block? [1 M]
Ans. Refer to Section 4.2.4 Point (3).
2. Which method is used to set the current position of the file pointer within the
file. [1 M]
Ans. Refer to Section 4.5.
3. What is stream ? Explain the types of streams supported by java. [5 M]
Ans. Refer to Section 4.5.2.
4. Write a java program to accept the details of product as productcode,
productname and weight. If weight > 100 then throw an exception as
InvalidProduct Exception and give the proper message. Otherwise display the
product details. Define required exception class. [5 M]
Ans. Refer to Section 4.2.4.
5. What is checked and unchecked exceptions? [2 M]
Ans. Refer to Section 4.2.3.
6. Write a java program to display the contents of the file in reverse order. [4 M]
Ans. Refer to Section 4.5.
April 2019
1. Define unchecked exception. [1 M]
Ans. Refer to Section 4.2.3 Point (2).
2. List any two methods of File class. [1 M]
Ans. Refer to Section 4.5.
3. Write a Java program to appends the content of one file to another. [5 M]
Ans. Refer to Section 4.5.
4. What are user defined exceptions? Illustrate them with an example. [5 M]
Ans. Refer to Section 4.4.
4.72
CHAPTER
5
User Interface with AWT
and Swing
Objectives…
To undertand Concepts in AWT
To study Swing Concepts
To study Layout Manager in AWT
To learn Dialogs
To study EventHandling in Java
5.0 INTRODUCTION
• User Interface abbreviated as UI. It is the junction/interface between a user and a
computer program.
• Every user interface considers the following three main aspects:
1. UI elements: These are the core visual elements the user eventually sees and
interacts with.
2. Layouts: They define how UI elements should be organized on the screen and
provide a final look and feel to the GUI (Graphical User Interface).
3. Behavior: These are events which occur when the user interacts with UI elements.
• The human computer interface is what allows the user to communicate with the
computer and is often called as User Interface (UI).
• There exist several types of user interfaces. We here give you just two examples:
1. Command-Line Interface (CLI): In CLI user provides the input by typing a
command string with the computer keyboard and the system provides output by
printing text on the computer monitor.
2. Graphical User Interface (GUI): The use of pictures rather than just words to
represent the input and output of a program, for example, Linuxjunkies. Input is
accepted via devices such as keyboard and mouse.
• User generally wants the user friendly program. The program which is easily
understood and its functionality is easy to handle. Java provides such controls which
provides this easiness.
• To develop GUI Java provided AWT and Swings. To handle these components we need
event handling. Event Handling is also needed for applet programming.
5.1
Object Oriented Programming using Java - I User Interface with AWT and Swing
• In addition to familiar components such as buttons, check boxes and labels, Swing
provides several advanced components such as tabbed panel, scroll panes, trees,
tables, and lists.
• Unlike AWT components, Swing components are not implemented by platform-
specific code. Instead, they are written entirely in Java and therefore are platform-
independent. The term "lightweight" is used to describe such an element.
• The fundamental idea behind MVC is the separation of data model from its
presentation. MVC has mainly three parts:
1. The model, which stores the data of component.
2. The view, which creates visual representation of the component using the data in
the model.
3. The controller, which deals with the user interaction and modifies the model or
the view in response to user action.
Model
MVC Architecture
Controller View
Fig. 5.1: MVC Architecture
• For example, a data in a spread-sheet can be represented using different types of
charts like bar chart, pie chart, etc. Here data in a spreadsheet is the model and
various chart types are views.
• A single model can have many views. The change to the model causes the changes in a
view.
• The view and controller can be represented by a single composite object called
UI-delegate.
• UI-delegate is responsible for the view and controller roles. It takes care of drawing
the component and representing to user events.
• Fig. 5.2 shows Separate Model Architecture in which the different UI-delegate can
provide a component with a new look and feel.
• The way in which swing objects communicate, by passing events from sources to
listeners is a part of MVC concept of separation.
View
Model
(Component data)
Controller
UI Delegate
Fig. 5.2: Separable Model Architecture
• Event listeners are observers (controllers) and event sources are observerables
(models). When an observable changes or performs a function, it notifies all of its
observers of the activity.
• The java.util.observer interface and java.util.observable class are utilities which
provides fundamental design pattern under the concept of separable model
architecture.
5.5
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.3 LAYOUTS AND LAYOUT MANAGERS [April 16, 18, Oct. 16, 18]
• Layout means the arrangement of components within the container. In other way we
can say that placing the components at a particular position within the container.
• The task of layouting the controls are done automatically by the Layout Manager.
Layout manager is an object which determines the way that components are arranged
in a frame window.
• All of the components that we have shown so far have been positioned by the default
layout manager.
• A layout manager automatically arranges our controls within a window by using some
type of algorithm.
• A layout manager is an instance of any class that implements the LayoutManager
interface.
• The layout manager is set by the setLayout() method. If no call to setLayout() is made,
then the default layout manager is used.
• Whenever, a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.
• The setLayout() method has the following general form/syntax:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. If we wish to disable the
layout manager and position components manually, pass null for layoutObj.
• If we do this, we will need to determine the shape and position of each component
manually, using the setBounds() method defined by Component. Normally, we will
want to use a layout manager.
• Each layout manager keeps track of a list of components that are stored by their
names. The layout manager is notified each time we add a component to a container.
• Whenever, the container needs to be resized, the layout manager is consulted via its
minimum LayoutSize() and preferred LayoutSize() methods.
• Each component that is being managed by a layout manager contains the
getPreferredSize() and getMinimumSize() methods. These return the preferred and
minimum size required to display each component.
• The layout manager will honor these requests if at all possible, while maintaining the
integrity of the layout policy. We may override these methods for controls that we
subclass.
• The layout manager automatically positions all the components within the container.
Default values are provided otherwise.
• Java has several predefined layout manager classes. Layout manager classes are
founded in the java.awt package same as the classes used for displaying graphical
components.
• Several layout managers of which are described next sections. We can use the layout
manager that best fits our application.
5.6
Object Oriented Programming using Java - I User Interface with AWT and Swing
• The java.awt package provides five layout manager classes as given below:
1. FlowLayout: Arranges components in variable-length rows.
2. BorderLayout: Arranges components along the sides of the container and in the
middle.
3. CardLayout: Arrange components in "cards" Only one card is visible at a time.
4. GridBagLayout: Aligns components horizontally and vertically; components can
be of different sizes.
5. GridLayout: Arranges components in fixed-length rows and columns.
class FlowLayoutJavaDemo
{
public static void main(String args[])
{
FlowLayoutDemo frame = new FlowLayoutDemo();
frame.setTitle("FlowLayout in Java Example");
frame.setSize(400,150);
frame.setVisible(true);
}
}
Output:
SOUTH
(a) (b)
Fig. 5.3: Border Layout Manager
• The constructors defined by BorderLayout as given below:
1. BorderLayout(): This constructor creates a default border layout.
2. BorderLayout(int hspace, int vspace): This constructor allows us to specify
the horizontal and vertical space left between components in horz and vert,
respectively.
• To add components in a frame using BorderLayout manager, following form of add
method is used:
void add (Component_obj, Object region)
5.8
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.9
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
Here, deck is a reference to the container (usually a panel) that holds the cards, and
cardName is the name of a card. Calling first() causes the first card in the deck to be
shown. For showing the last card, call last() and for the next card, call next().
• To show the revious card, call previous(). Both next() and previous() automatically
cycle back to the top or bottom of the deck, respectively. The show() method displays
the card whose name is passed in cardName.
Program 5.5: Program to demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
//Class definition
class Panel1 extends Panel
{
//Variable declaration
Label la1,la2,la3;
TextField te1,te2,te3;
Button bu1, bu2, bu3, bu4, bu5;
public Panel1()
{
la1=new Label("Number 1:");
la2=new Label("Number 2:");
la3=new Label("Result:");
te1=new TextField(10);
te2=new TextField(10);
te3=new TextField(10);
te3.setEditable(false);
bu1=new Button("Add");
bu2=new Button("Sub");
bu3=new Button("Mul");
bu4=new Button("Div");
bu5=new Button("Exit");
add(la1);
add(te1);
add(la2);
add(te2);
add(la3);
add(te3);
add(bu1);
add(bu2);
add(bu3);
add(bu4);
add(bu5);
}
}
5.15
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
Container
Window Panel
Frame Applet
Fig. 5.6: Windows classes of AWT
• Fig. 5.6 shows following Windows classes of AWT:
1. Component: It is an abstract class and all GUI components that interact with the
user are subclasses of component class. It defines various methods for managing
events, such as keyboard and mouse input. It also defines attributes to store
current foreground and background colours and font.
2. Container: It inherits various methods and attributes of component class and
having additional methods of nesting other component objects. A container
positions various GUI components within it, with the help of different layout
managers.
3. Panel: Panel is a window that does not contain a title bar, menu bar or border. It is
a superclass of Applet class. Any screen output written an applet is drawn on the
surface of a Panel object. Appletviewer provides title bar, and border to an applet.
We can add GUI components such as buttons, list box etc. to a panel object using
add() method.
5.18
Object Oriented Programming using Java - I User Interface with AWT and Swing
4. Window: This class is used to create a top level window. Generally, windows
objects are not created directly, subclass of window is used to place on the desktop.
5. Frame: Frame class is a subclass of window and it has title bar, menu bar, borders
etc. To create a normal window within an Java application, Frame class is used. In
applets, we need not use frame class to create window because appletviewer
provides title bar, menu bar and borders to an applet.
6. Canvas: Canvas is not subclass of either window or panel. It is one another type of
window which displays a blank window upon which you can draw.
Working with Frame Window:
• A Frame is a top-level window with a title and a border.
• The type of window we will be creating for stand alone application is subclass of
Frame.
• Two of Frame’s constructors:
1. Frame(): The first form creates a standard window that does not contain a title.
2. Frame(String title): The second form creates a window with the title specified
by title.
Setting the Windows Dimensions:
• The setSize() method is used to set the size of the window.
• It's general structure/syntax is shown here:
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
• The new size of the Frame is specified by newWidth and newHeight or by the width
and height fields of the Dimension object passed in newSize. The dimensions are
specified in terms of pixels.
• The getSize() method is used to obtain the current size of a window. Its general syntax
is, Dimension getSize().
• The getSize() method returns the current size of the Frame as the width and height
fields of a Dimension object.
Showing and Hiding Frame:
• After a frame has been created, it will not be visible until we call
setVisible() method. Its general syntax is given below:
void setVisible(boolean visibleFlag)
• The Frame is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Frame’s Title:
• We can set the title of a frame window using setTitle(), which has following general
form/syntax:
void setTitle(String newTitle)
Program 5.6: Program for frame.
import java.awt.*;
class MyFrame extends Frame
{
MyFrame(String title)
{
5.19
Object Oriented Programming using Java - I User Interface with AWT and Swing
setVisible(true);
setSize(100,100);
setTitle(title);
}
public static void main(String args[])
{
MyFrame f= new MyFrame(“My Frame”);
}
}
Output:
2. Push Button:
• A push button is a component that contains a label and that generates an event when
it is pressed.
5.21
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.23
Object Oriented Programming using Java - I User Interface with AWT and Swing
4. Checkbox Group:
• This class is used to create group of checkboxes. From the group of check boxes only
one check box can be checked at a time.
• These check boxes are also called radio buttons. It supports following constructors:
(i) CheckboxGroup CheckboxGroup(): Returns group name.
• Checkboxes of Checkboxgroup can be created using following constructors:
(i) Checkbox(String, boolean, CheckboxGroup)
(ii) Checkbox(String, CheckboxGroup, boolean)
• These creates checkbox with specified label and groupname as parameters. The
boolean type parameter specifies the initial state true/false.
Program 5.10: Program to demonstrate Checkbox group.
import java.awt.*;
class MyFrame extends Frame
{
String msg="";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
MyFrame(String s)
{
super(s);
setVisible(true);
setSize(500,300);
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("MacOS", cbg, false);
setLayout(new FlowLayout());
add(Win98);
add(winNT);
add(solaris);
add(mac);
}
public void paint(Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
public static void main(String[] args)
{
MyFrame f= new MyFrame("Demonstrating Frame");
}
}
5.24
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
5. Choice List:
• The class choice is used to create a drop-down or pop-up list of strings.
• It occupies less screen space than list box control, since it shows only the currently
selected item.
• When user clicks on it, the list of choices drop down. It uses only default constructor
i.e., choice().
• Choice class provides following methods:
(i) void add(String): To add string in the choice list.
(ii) String getSelectedItem(): Determines which item is currently selected.
(iii) int getSelectedIndex(): Determines the index of currently selected item.
(iv) int getItemCount(): Returns number of items in the list.
(v) void Select (int): Selects the item whose index is specified as parameter.
(vi) void Select(String): Selects the item matches with specified string as
parameter.
(vii) String getItem(int): Obtains the name associated with the item at specified
index as parameter.
Program 5.11: Program to demonstrate choice controls.
import java.awt.*;
import javax.swing.*;
class Exchoice
{
static Choice c; // create choice object
static JFrame jframe;
Exchoice()
{
}
public static void main(String args[])
{
jframe = new JFrame("My Choice");// create a frame
JPanel p1 = new JPanel();// create e panel
c = new Choice();// create a choice
5.25
Object Oriented Programming using Java - I User Interface with AWT and Swing
6. Lists:
• List class provides a list of items, which can be scrolled. From list of items, single or
multiple items can be selected.
• It provides three constructors:
(i) List() : Creates a list box in which single selection is possible.
(ii) List(int) : Creates a list-box, specified number of items will always
be visible selection. Selection is possible.
(iii) List(int, boolean) : Creates a list box, first parameter specifies number of
items to be visible. Second parameter specifies whether
multiple selection of item is allowed. True indicates
multiple selection.
• Following methods are supported by list class:
(i) void add(String): Adds item to the end of list.
(ii) void add(String, int): Adds item at the index specified in second parameter.
(iii) String getSelectedItem(): Returns a string which is selected.
(iv) int getSelectedIndex(): Returns an index of the selected item.
(v) String[] getSelectedItems(): Returns an array contains strings which are
selected (Multiselect)
(vi) int[] getSelectedIndexes(): Returns an array contains indexes of the
selected items (Multiselect)
(vii) int getItemCount(): Returns number of items in the list.
(viii) void select(int): Selects the item of a specified index in parameter.
(ix) String getItem(int): Obtains the name of item having specified index.
5.26
Object Oriented Programming using Java - I User Interface with AWT and Swing
7. ScrollBars:
• Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
• Scroll bars may be oriented horizontally or vertically.
• Following constructors are in scrollbar:
(i) Scrollbar() : Creates a vertical scroll bar.
(ii) Scrollbar(int style) : Creates a scrollbar of specified style. It can be
scrollbar.vertical or scrollbar.horizontal.
(iii) Scrollbar (int style, : Creates scrollbar with specified style. Initial value
int start, int thumb, is in second parameter. In third parameter
int min, int max) thumbsize is specified. The minimum and
maximum value is specified in min and max.
• Following methods are used by scrollbar:
(i) int getValue(): To get current value of scroll bar.
(ii) void SetValue(int): To set new value.
(iii) int getMinimum(): To get min value of scrollbar
5.27
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.28
Object Oriented Programming using Java - I User Interface with AWT and Swing
8. TextField:
• The TextField class implements a single-line text-entry area, usually called an edit
control.
• Text fields allow the user to enter strings and to edit the text using the arrow keys, cut
and paste keys, and mouse selections.
• It defines following constructors:
(i) Textfield(): Creates a default textfield.
(ii) Textfield(int): Creates a textfield with specified number of characters.
(iii) TextField(String): Creates a textfield with a specified string initially.
(iv) TextField (String, int): Creates a textfield with a initial text and set its width.
• This class uses following methods:
(i) String getText(): To obtain the content to textfield.
(ii) void setText(String): To set the Text.
(iii) String getSelectedText(): To get currently selected text.
(iv) void select (int StartIndex, int endIndex): To select a portion of a text.
(v) boolean is Editable(): To determine editability.
(vi) void setEditable(boolean): To set or reset editability of textfield.
Program 5.14: Program to demonstrate textfield.
import java.awt.*;
class MyFrame extends Frame
{
TextField name, pass;
MyFrame(String s)
{
super(s);
setVisible(true);
setSize(500,300);
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
setLayout(new FlowLayout());
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
}
public static void main(String[] args)
{
MyFrame f= new MyFrame("Demonstrating Frame");
}
}
5.29
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
9. TextArea:
• Sometimes, a single line of text input is not enough for a given task.
• To handle these situations, the AWT includes a simple multi-line editor called
TextArea.
• Following constructors are available in TextArea:
(i) TextArea() : Creates a default text area.
(ii) TextArea(int, int) : Creates a text area for specified number of lines
and number of characters.
(iii) TextArea (String) : Creates with initial string.
(v) TextArea(String, int, int) : Creates text area with initial string and for
specified number of lines and number of
characters.
(v) Area (String, int : Creates a text area with scroll bars. The value
numliTextnes, int numChar, of sBars must one of following constants.
int sBars) SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY
• TextArea also supports the methods getText(), setText(), getSelectedText(), select(), is
Editable and setEditable(). Methods are similiar to TextField.
• TextArea adds the following methods:
(i) void append (String): Appends specified string at the end of text.
(ii) void insert(String, int): Inserts specified string at the specified index.
(iii) void replaceRange(String, int startIndex, int endIndex): It replaces the
character from start_Index to endIndex–1 with given string.
Program 5.15: Program to demonstrate textarea.
import java.awt.*;
public class Demotextarea
{
Frame frame;
TextArea textArea1, textArea2, textArea3, textArea4;
Demotextarea()
{
frame= new Frame("Demo of TextArea");
textArea1 = new TextArea() //TextArea()
textArea2 = new TextArea(2,2); //TextArea(int rows, int columns)
textArea3 = new TextArea("Third textarea", 10,10);
textArea4 = new TextArea("Fourth textarea", 5,20);
5.30
Object Oriented Programming using Java - I User Interface with AWT and Swing
textArea1.append("First textarea");
textArea2.append("Second textarea");
frame.add(textArea1);
frame.add(textArea2);
frame.add(textArea3);
frame.add(textArea4);
frame.setLayout(new FlowLayout());
frame.setSize(500,400);
frame.setVisible(true);
}
public static void main(String []arg)
{
new Demotextarea();
}
}
Output:
MenuComponent
MenuBar MenuItem
Menu CheckboxMenultem
Fig. 5.7
5.31
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.34
Object Oriented Programming using Java - I User Interface with AWT and Swing
• If the argument enabledFlag is true, the menu item is enabled. If false, the menu item
is disabled.
• We can determine an item’s status by calling isEnabled( ). Its form/syntax is shown
below:
boolean isEnabled()
• The isEnabled() returns true if the menu item on which it is called is enabled.
Otherwise, it returns false.
• We can change the name of a menu item by calling setLabel(). Its form/syntax is
shown below:
void setLabel(String newName)
Here, newName becomes the new name of the invoking menu item.
• We can retrieve the current name by using getLabel(). Its form/syntax is shown below:
String getLabel()
getLabel() returns the current name.
• We can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem(). It has following constructors:
(i) CheckboxMenuItem(): Create a check box menu item with an empty label.
(ii) CheckboxMenuItem(String itemName): Create a check box menu item with the
specified item name.
(iii) CheckboxMenuItem(String itemName, boolean on): Create a check box menu
item with the specified label and state. Here, itemName is the name shown in the
menu. Checkable items operate as toggles. Each time one is selected, its state
changes.
• In the first two forms, the checkable entry is unchecked. In the third form, if on is true,
the checkable entry is initially checked. Otherwise, it is cleared.
5.35
Object Oriented Programming using Java - I User Interface with AWT and Swing
• We can obtain the status of a checkable item by calling getState(). We can set it to a
known state by using setState(). Its form/syntax is shown below:
void setState(boolean checked)
• If the item is checked, getState() returns true, otherwise, it returns false. Its
form/syntax is shown below:
boolean getState()
• For checking an item, pass true to setState(). To clear an item, pass false. Once we have
created a menu item, we must add the item to a Menu object by using add( ), which
has the following general form/syntax:
MenuItem add(MenuItem item)
Here, item is the item being added. Items are added to a menu in the order in which
the calls to add( ) take place. The item is returned.
Once we have added all items to a Menu object, we can add that object to the menu
bar by using this version of add( ) defined by MenuBar.
Menu add(Menu menu)
• Here, menu is the menu being added. The menu is returned. Menus only generate
events when an item of type MenuItem or CheckboxMenuItem is selected.
• They do not generate events when a menu bar is accessed to display a drop-down
menu, for example.
• Each time a menu item is selected, an ActionEvent object is generated. Each time a
check box menu item is checked or unchecked, an ItemEvent object is generated.
• Thus, we must implement the ActionListener and ItemListener interfaces in order to
handle these menu events.
• The getItem() method of ItemEvent returns a reference to the item that generated this
event.
• The general form/syntax of this method is shown below:
Object getItem()
11. Pop-up Menus:
• Pop-up menu represents a menu which can be dynamically popped up at a specified
position within a component.
Constructors:
(i) PopupMenu(): Creates a new popup menu with an empty name.
(ii) PopupMenu(String label): Creates a new popup menu with the specified name.
• Following is an Program 5.17 that adds a series of nested menus to a pop-up window.
The item selected is displayed in the window. The state of the two check box menu
items is also displayed.
Program 5.17: Program to demonstrate pop-up menu.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExMenu
{
Frame frame;
MenuBar menuBar;
Menu menu1, menu2;
MenuItem mItem1, mItem2, mItem3, mItem4, mItem5, mItem6, mItem7;
5.36
Object Oriented Programming using Java - I User Interface with AWT and Swing
ExMenu()
{
frame = new Frame("MenuBar, Menu and MenuItems");
menuBar.add(menu1);
frame.setMenuBar(menuBar);
frame.setSize(330,250);
frame.setVisible(true);
}
public static void main(String arg[])
{
new ExMenu();
}
}
5.37
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
7. Pluggable Look and Feel: We can set the appearance of applets and applications
to one of three standard looks, i.e., Windows, Motif (Unix) or Metal (Standard
swing look).
8. Highly Customizable: Swing controls can be customized in very easy way as
visual appearance is independent of internal representation.
9. New Layout Managers: Swing introduces the BoxLayout and Overlay Layout
layout managers.
Working with Swing:
• While designing any GUI, we need to have a main window on which we can place or
position the different visual components.
• Every top level container has one intermediate container called content pane. This
content pane contains all the visible components in the GUI window.
• In swing, the main window, also called a top level container is the root of a hierarchy,
which contains all the other swing components that appear inside the window. All
swing applications have at least one top level container.
• The content pane is the base pane upon which all other components or container
objects are placed.
• One exception to this rule is, if there is a menu bar in the top level container it will be
placed outside the content pane.
• Fig. 5.8 illustrates the relationship between the components discussed above.
Visible
components
Content
Ok pane
Fig. 5.8
• The general procedure to create top-level container is iven below:
1. Create the container,
2. Set its size (in the case of frames and panels), and
3. Set in visibility (in the case of frames and panels).
• All swing components names start with J. For instance the swing button class is named
as JButton commonly used top-level containers are:
5.39
Object Oriented Programming using Java - I User Interface with AWT and Swing
• Just like AWT application, a Swing application requires a top-level container. There
are three top-level containers in Swing:
1. JFrame: Used for the application's main window (with an icon, a title,
minimize/maximize/close buttons, an optional menu-bar, and a content-pane), as
illustrated.
2. JDialog: Used for secondary pop-up window (with a title, a close button, and a
content-pane).
3. JApplet: Used for the applet's display-area (content-pane) inside a browser’s
window.
• Similarly to AWT, there are secondary containers (such as JPanel) which can be used
to group and layout relevant components.
• Panels are an example of intermediate containers.
Advantages of Swing:
1. Swing provides paint debugging support for when you build your own component.
2. Swing components are lightweight than AWT.
3. Swing components follow the Model-View-Controller (MVC) paradigm and thus can
provide a much more flexible UI.
4. Swing provides both additional components like JTable, JTree etc and added
functionality to replacement of AWT components.
5. Swing provides built-in double buffering.
Disadvantages of Swing:
1. It can be slower than AWT (all components are drawn), when you are not careful
about programming.
2. Swing components might not behave exactly like native components which look
like native components.
3. It requires Java 2 or a separate JAR file.
Object
Recursive Composition
(Composite Design Pattern)
* Component
1 AWT Components...
Container
Fig. 5.9
• Fig. 5.9 shows following classes of JComponent
1. AbstractButton: Abstract super-class for Swing buttons.
2. ButtonGroup: Encapsulates a mutually exclusive set of buttons.
3. ImageIcon: Encapsulates an icon.
4. JApplet: The Swing version of Applet.
5. JButton: The Swing push button class.
6. JCheckBox: The Swing check box class.
7. JComboBox: Encapsulates a combo box, (a combination of a dropdownlist and text
field).
8. JLabel: The Swing version of a label.
9. JRadioButton: The Swing version of a radio button.
10. JScrollPane: Encapsulates a scrollable window.
11. JTabbedPane: Encapsulates a tabbed window.
12. JTable: Encapsulates a table-based control.
13. JTextField: The Swing version of a text field.
14. JTree: Encapsulates a tree-based control.
5.41
Object Oriented Programming using Java - I User Interface with AWT and Swing
• The swing related classes are contained in javax.swing and its subpackages, such as
javax.swing.tree.
• To use a swing class, either use an import statement for a specific class to be imported
from within a swing or import all classes in the swing package as:
javax.swing.*;
• Swing controls or components and their related methods are available in javax.swing
and its subpackages.
5.5.3 JFrame
• The frame is a top-level container or window, on which other swing components are
placed.
• A JFrame component is used to create windows in a swing program. It extends
java.awt.Frame class. Every JFrame object has a root pane.
• Some of the constructors of the JFrame class are shown below:
1. JFrame(): This constructor creates a new frame without title.
2. JFrame(string title): This constructor constructs the new frame with title.
• When adding components to a JFrame window, we must add it to its content pane and
not directly to the JFrame window.
• For example: To add a button for b we would write frame.getContentPane().add(b);
Methods:
1. Container getContentPane(): This method returns, a Content Pane for the JFrame.
2. void setLayout(LayoutManager): This method sets the LayoutManager for the
JFrame.
3. void setJMenuBar(JMenuBar): This method sets the JMenu Bar to the JFrame.
4. void setIconImage(Image image): Prints icon image on JFrame.
5.42
Object Oriented Programming using Java - I User Interface with AWT and Swing
• Here, we have imported the relevant packages necessary to create the frame window.
Then in the constructor we invoked super() which in turn calls the constructor of
JFrame and creates the frame.
• We then sets the size of the frame and changed its visibility to true in order to display
it when it is executed.
5.5.4 JPanel
• The JPanel component which is an intermediate container, is used to group smaller
lightweight components together. By default panels are opaque which means that they
work similar to content panes.
• JPanel objects have FlowLayout as their default layout. Some of the constructors of
JPanel are:
JPanel();
JPanel(LayoutManager LM)
• Most methods of the JPanel API are derived from its super classes, container
JComponent and component.
• Methods:
1. Container getContentPane(): This method returns, a Content Pane for the JPanel.
2. void setLayout(LayoutManager): This method sets the LayoutManager for the
JPanel.
5.43
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.44
Object Oriented Programming using Java - I User Interface with AWT and Swing
class JButtonJavaExample
{
public static void main(String args [])
{
JButtonExample frame = new JButtonExample();
frame.setTitle("JButton in Java Swing Example");
frame.setBounds(200,250,250,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
5.5.6 JToggleButton
• A toggle button is two states button that allows user to switch on and off. To create a
toggle button in Swing we use JToggleButton class.
• JToggle button, when goes to the inward push state as long as the user has pressed the
left mouse key. When he frees the left mouse key, the button comes to its normal state.
• Here, are the most common used constructors of the JToggleButton class:
1. public JToggleButton(): Creates a toggle button without text and icon. The state of
toggle button is not selected.
2. public JToggleButton(Icon icon): Creates a toggle button with icon.
3. public JToggleButton(Icon icon, boolean selected): Creates a toggle button
with icon and initialize the state of toggle button by the boolean parameter selected.
4. public JToggleButton(String text): Creates a toggle button with text.
5. public JToggleButton(String text, boolean selected): Creates a toggle button
with text and initialize the state of the toggle button.
6. public JToggleButton(String text, Icon icon): Creates a toggle button which
displays both text and icon.
7. public JToggleButton(String text, Icon icon, boolean selected): Creates a
toggle button which displays both text and icon. The state of toggle button can be
initialized.
Program 5.21: Program to demonstrate JToggleButton.
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
5.46
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.5.7 JLabel
• One of the simplest Swing components is JLabel. A JLabel object is a component for
placing text in a container.
• This class is used to create single line read only text which describes the other
component.
• Labels can display text as well as Images.
Package: javax.swing
Constructors:
1. JLabel() : Create a empty label having no text and
icon.
2. JLabel(String str) : Create a label having some text.
3. JLabel(ImageIcon i) : Creates a label having icon image.
4. JLabel(String str,ImageIcon i) : Creates a label having string text and icon
image.
Methods:
1. void setHorizontalAlignment(int a): This method sets the alignment of the text.
2. String getText(): This method returns the text associated with the Label.
3. void setText( String s): This method is used to set the text to the Label.
4. void set icon(Icon i): This method sets the Icon to icon.
5.47
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.48
Object Oriented Programming using Java - I User Interface with AWT and Swing
JIcons:
• Icons are encapsulated by the ImageIcon class, which prints an icon from an image.
• Constructors are given below:
1. ImageIcon(String filename): This constructor creates object with image which is
specified by filename.
2. ImageIcon(URL url): This constructor creates object with image in the resource
identified by url.
• Methods:
1. int getIconHeight(): Returns the height of the icon in pixels.
2. int getIconWidth(): Returns the width of the icon in pixels.
3. void paintIcon(Component comp, Graphics g, int x, int y): Paints the icon
at position x, y on the graphics context g. Additional information about the paint
operation can be provided in component.
• Following Program of demonstrate icons.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("Lotus.gif");
// Create a label
JLabel jl = new JLabel("Lotus", ii, JLabel.CENTER);
// Add label to the content pane
contentPane.add(jl);
}
}
5.5.8 JCheckBox
• A checkbox is a control that may be turned ON or OFF by the user to indicate some
option.
• The class JCheckBox is an implementation of a check box - an item that can be selected
or deselected, and which displays its state to the user.
• The JCheckBox class is used to create CheckBox in Swing. CheckBox has the following
constructors:
1. JCheckBox(): Creates an initially unselected check box button with no text, no icon.
5.49
Object Oriented Programming using Java - I User Interface with AWT and Swing
2. JCheckBox(Action a): Creates a check box where properties are taken from the
Action supplied.
3. JCheckBox(Icon icon): Creates an initially unselected check box with an icon.
4. JCheckBox(Icon icon, boolean selected): Creates a check box with an icon and
specifies whether or not it is initially selected.
5. JCheckBox(String text): Creates an initially unselected check box with text.
6. JCheckBox(String text, boolean selected): Creates a check box with text and
specifies whether or not it is initially selected.
7. JCheckBox(String text, Icon icon): Creates an initially unselected check box
with the specified text and icon.
8. JCheckBox(String text, Icon icon, boolean selected): Creates a check box
with text and icon, and specifies whether or not it is initially selected.
Program 5.23: Program to demonstrate JCheckBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class HobbyOfStudent extends JPanel implements ActionListener,ItemListener{
JCheckBox ch1 = new JCheckBox("Playing", false);
JCheckBox ch2 = new JCheckBox("Music", false);
JCheckBox ch3 = new JCheckBox("Painting", false);
JCheckBox ch4 = new JCheckBox("Reading", false);
JLabel j1 = new JLabel("What's student hobby?");
JButton exitbtn = new JButton("Exit");
public HobbyOfStudent()
{
setLayout(new GridLayout(7,1));
ch1.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 14));
ch2.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 14));
ch3.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 14));
ch4.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 14));
ch1.addItemListener(this);
ch2.addItemListener(this);
ch3.addItemListener(this);
ch4.addItemListener(this);
add(j1);
add(ch1);
add(ch2);
add(ch3);
add(ch4);
add(exitbtn);
exitbtn.addActionListener(this);
}
5.50
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.5.9 JTextField
• The JTextField component allows us to enter/edit a single line of text.
• Following are the important constructors of the subclasses of the JTextField class.
1. JTextField(): Constructs a new TextField.
2. JTextField(Document doc, String text, int columns): Constructs a new
JTextField that uses the given text storage model and the given number of columns.
5.51
Object Oriented Programming using Java - I User Interface with AWT and Swing
• The above Program 5.25, create a frame window in Swing. We then set its existing
layout to FlowLayout. We then create a Swing label along with a text field component
and add them to the content pane.
• Text wrapping is possible through the use of a bound property of JTextArea class.
A JTextArea can be created using one of the following constructors:
1. JTextArea(): Constructs a new TextArea.
2. JTextArea(Document doc): Constructs a new JTextArea with the given document
model and defaults for all of the other arguments (null, 0, 0).
3. JTextArea(Document doc, String text, int rows, int columns): Constructs a
new JTextArea with the specified number of rows and columns and the given
model.
4. JTextArea(int rows, int columns): Constructs a new empty TextArea with the
specified number of rows and columns.
5. JTextArea(String text): Constructs a new TextArea with the specified text
displayed.
6. JTextArea(String text, int rows, int columns): Constructs a new TextArea
with the specified text and number of rows and columns.
Program 5.25: Program to demonstrate JTextArea.
import java.awt.*;
import javax.swing.*;
public class TextAreaapplextends JFrame
{
public TextAreaappl()
{
Container con = getContentPane();
con.setLayout(new FlowLayout());
JLabel j11 = new JLabel ("TextArea");
con.add(j11);
JTextArea ta1 = new JTextArea(10, 20);
con.add(ta1);
setSize(600, 600);
setVisible(true);
}
public static void main(String args[])
{
new TextAreaappl();
}
}
Output:
5.53
Object Oriented Programming using Java - I User Interface with AWT and Swing
• The above program creates a standalone Swing application having a frame window
with a text area and a label. To create the text area that is ten rows and twenty
columns wide we use the constructor:
JTextArea ta1= new JTextArea(10, 20);
5.5.11 JRadioButton
• This class is used to create radio button with a text or icon. Radio buttons are
supported by the JRadioButton class, which is aconcrete implementation of
AbstractButton.
• Once, a radio button is created they must be kept in one group, which is created by
using the ButtonGroup class Radio buttons must be configured into a group.
• Only one of the buttons in that group can be selected at any time.
Package: javax.swing
Constructors:
1. JRadioButton(): Create a empty radio button having no title and icon.
2. JRadioButton (String l): Create a radio button having label.
3. JRadioButton (Icon i): Creates a radio button having icon image.
4. JRadioButton (String l, Icon i): Creates a radio button having string label and
icon image.
5. JRadioButton (Siring l, Icon i,boolean selected): Creates a radio button
having string label and icon image and default selected if true is passed.
6. JRadioButton (String l, boolean selected): Creates a radio button having
string label and option for default selected policy.
Button Group:
• This class is useful to group the component such as radio buttons.
• If radio button is not grouped, then they work as checkbox. And multiple selection is
possible.
• To avoid that we group the Radio button object. This class provides the default
constructor ButtonGroup by using this constructor object of button group class is
created.
• Then different component are added to the button group object by using
add() method.
Program 5.26: Program to demonstrate JRadioButton.
import javax.swing.*;
public class JRadioButtonExample
{
JRadioButtonExample()
{
JFrame jframe = new JFrame();
JRadioButton jredioButton1 = new JRadioButton("Covid + ");
JRadioButton jredioButton2 = new JRadioButton("Covid - ",true);
5.54
Object Oriented Programming using Java - I User Interface with AWT and Swing
jredioButton1.setBounds(75,50,100,30);
jredioButton2.setBounds(75,100,100,30);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(jredioButton1);
buttonGroup.add(jredioButton2);
jframe.add(jredioButton1);
jframe.add(jredioButton2);
jframe.setSize(500,500);
jframe.setLayout(null);
jframe.setVisible(true);
}
public static void main(String[] args)
{
new JRadioButtonExample();
}
}
Output:
5.5.12 JList
• In Swing, the JList component is the implementation of the AWT List class.
• JList consists of a range of elements arranged one after another, which can be selected
individually or in a group.
• JList class, unlike its AWT counterpart, is capable of displaying not just the strings, but
also icons.
• Some of the constructors used for creating JList are explained below:
1. public JList(): Constructs a JList with an empty model.
2. public JList(ListModel dataModel): Constructs a JList() that displays the
elements in the specified, non-null list model.
3. public JList(Object [] listData): Constructs a JList() that displays the
elements of the specified array "listData".
5.55
Object Oriented Programming using Java - I User Interface with AWT and Swing
• JList() does not support scrolling. To create a scrolling list the JList() is implemented as
the viewport view of a JScrollPane.
JScrollPane myScrollPane = new JScrollPane();
myScrollPane.getViewport().setView(dataList);
OR
JScrollPane myScrollPane = new JScrollPane(dataList);
• JList does not provide any special support for handling double or triple mouse clicks.
However, using the MouseListener makes it easy to handle these events. The
locationToIndex() method is used to determine the cell that was checked.
Program 5.27: Program to demonstrate JList.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Employees extends JFrame implements ListSelectionListener
{
String Employee[] = {"Amar Salunkhe", "Akbar Shaikh",
"Amol Mahabal", "Kiran Velankar"};
JList departments = new JList(Employee);
JLabel lTE = new
JLabel("Who is your favourite Technical Editor?");
JTextField jt = new JTextField(40);
public Employees(String s) {
super(s);
JPanel p = (JPanel)getContentPane();
p.setLayout(new BorderLayout());
p.add("North", lTE);
departments.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
departments.setSelectedIndex(0);
departments.addListSelectionListener(this);
departments.setBackground(Color.red);
departments.setForeground(Color.black);
p.setBackground(Color.white);
p.setForeground(Color.black);
p.add("Center", new JScrollPane(departments));
p.add("South", jt);
}
5.56
Object Oriented Programming using Java - I User Interface with AWT and Swing
• A combo box is a combination of a list component and text field component. It can
consist of more than one item, however, displays only one item at any point of time. It
also allows user to type their selection.
• Unlike list component, combo box allows user to select only one item at a time. A
combo box is an object of JComboBox class.
• Three of JComboBox’s constructors are shown here:
1. JComboBox(): This constructor creates an empty JComboBox instance.
2. public JComboBox (ComboBoxModel asModel): Creates a JComboBox that takes its
items from an existing ComboBoxModel. asModel is the ComboBoxModel that
provides the displayed list of items.
3. public JComboBox (Object[] items): Creates a JComboBox that contains the
elements of the specified array
• Items are added to the list of choices via the addItem( ) method, whose
signature/syntax is shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box.
Methods:
1. public void setEditable(boolean aFlag): It determines whether the
JComboBox field is editable or not?
2. public boolean isEditable(): It returns true if the JComboBox is editable. By
default, a combo box is not editable.
3. public void setMaximumRowCount(int count): It sets the maximum number of
rows the JComboBox displays. If the number of objects in the model is greater than
‘count’, the combo box uses a scrollbar.
4. public void setSelectedItem(Object anObject): It sets the selected item in the
combo box display area to the object in the argument. If an Object is in the list, the
display area shows an Object selected.
5. public void insertItemAt(Object anObject, int index): It inserts an item
‘anObject’ into the item list at a given ‘index’.
6. public void removeItem(Object anObject): It removes an item ‘anObject’ from
the item list.
7. public void removeItemAt(int anIndex): It removes the item at ‘anIndex’.
• The following example contains a combo box and a label. The label displays an icon.
The combo box contains entries for colors Green, Red, Yellow and Black.
• When a country is selected, the label is updated to display the color for that particular
color. Color jpeg images are already stored in the current directory.
Program 5.28: Program to demonstrate JComboBox.
import javax.swing.*;
import java.awt.event.*;
5.58
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.59
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
Component
Container
JComponent
JMenultem
Menu Controls:
1. JMenuBar: The JMenuBar object is associated with the top-level window.
2. JMenuItem: The items in the menu must belong to the JMenuItem or any of its
subclass.
3. JMenu: The JMenu object is a pull-down menu component which is displayed
from the menu bar.
4. JCheckboxMenuItem: JCheckboxMenuItem is subclass of JMenuItem.
5. JRadioButtonMenuItem: JRadioButtonMenuItem is subclass of JMenuItem.
6. JPopupMenu: JPopupMenu can be dynamically popped up at a specified position
within a component.
5.5.14.1 JMenu
• A menu provides a space-saving way to let the user choose one of several options. The
Menu class represents pull-down menu component which is deployed from a menu
bar.
• In order to create a menu you need to use JMenu class. JMenu class represents the
menu which can attach to a menu bar or another menu.
• Menu directly attached to a menu bar is known as top-level menu. If the menu is
attached to a menu, it is called sub-menu.
• The constructors of JMenu class are given below:
1. JMenu(): This constructor creates an instance of JMenu without text.
2. JMenu(String s): This constructor creates an instance of JMenu a given text.
3. JMenu(String s, boolean tearOffMenu): This constructor creates an instance of
JMenu a given text and specify the menu as a tear-off menu or not.
4. JMenu(Action a): This constructor creates an instance of JMenu whose properties
are taken from the specified Action.
Program 5.29: Program for JMenu.
import java.awt.event.*;
import javax.swing.*;
public class JMenuExample extends JFrame implements ActionListener
{
public static void main(String[] s)
{
new JMenuExample();
}
public JMenuExample()
{
super("JMenu Example");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
5.61
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.62
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.5.14.2 JMenuBar
• The JMenuBar class provides an implementation of a menu bar.
• JMenuBar, which is a drop down menu bar at the top application, and JPopupMenu, a
menu you get when you press the button right mouse on a particular area.
• The components of a menu can be constructed using the JMenuBar, JMenu,
JMenultem, JCheckBoxMenultem and JRadioButtonMenultem classes in a way similar
to the MenuBar, Menu and Menultem classes of AWT.
• When anyone of the menu items in Menu object "BackGround" is selected, the
background colour of the frame is changed to the corresponding colour selected in the
menu item.
5.64
Object Oriented Programming using Java - I User Interface with AWT and Swing
• In the same way, when any of the menu items in the menu for Foreground is selected,
the foreground colour of the frame will change to corresponding colour selected in the
menu, which is displayed in the text field. Similarly if the Exit menu item is selected
from exit menu, the frame is closed.
• Following are the Constructors and methods of the JMenuBar class:
Name of Methods Description
JMenuBar() This constuctor constructs a new menu bar.
JMenu add(Menu menu) This method adds the menu specified by a
parameter, to the end of the menu bar.
Component getComponentAtlndex (int This method returns the component at the
index) specified index passed as a parameter.
int getComponentlndex(Component c) This method returns the index of the
component specified by the parameter.
JMenugetMenu(int index) This method returns the menu at the
specified index that is passed as a parameter
to the function.
int getMenuCount() This method returns a number of menus in
the menu bar.
Program 5.31: Program for JMenuBar.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JMenuBarJavaExample extends JFrame implementsActionListener
{
private JMenuBar MnuBar = new JMenuBar();
private JMenu MnuOne = new JMenu("File");
private JMenu MnuTwo = new JMenu("Colors");
private JMenuItem Exit = new JMenuItem("Exit");
private JMenu bright = new JMenu("Bright");
private JMenuItem dark = new JMenuItem("Dark");
private JMenuItem white = new JMenuItem("White");
private JMenuItem pink = new JMenuItem("Pink");
private JMenuItem yellow = new JMenuItem("Yellow");
private JLabel Lbl = new JLabel("Hello");
public JMenuBarJavaExample()
{
setTitle("Menu Bar In java Swing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
5.65
Object Oriented Programming using Java - I User Interface with AWT and Swing
setLayout(new FlowLayout());
setJMenuBar(MnuBar);
MnuBar.add(MnuOne);
MnuBar.add(MnuTwo);
MnuOne.add(xit);
MnuTwo.add(bright);
MnuTwo.add(dark);
MnuTwo.add(white);
bright.add(pink);
bright.add(yellow);
xit.addActionListener(this);
dark.addActionListener(this);
white.addActionListener(this);
pink.addActionListener(this);
yellow.addActionListener(this);
add(Lbl);
Lbl.setFont(new Font("Times New Roman", Font.BOLD,22));
}
public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
Container cntnr = getContentPane();
if(src == xit)
System.exit(0);
else if(src == dark)
cntnr.setBackground(Color.BLACK);
else if(src == white)
cntnr.setBackground(Color.WHITE);
else if(src == pink)
cntnr.setBackground(Color.PINK);
else cntnr.setBackground(Color.YELLOW);
repaint();
}
public static void main(String[] de)
{
JMenuBarJavaExample frm = newJMenuBarJavaExample();
final int WIDTH = 270;
final int HEIGHT = 220;
frm.setSize(500,500);
frm.setVisible(true);
}
}
5.66
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
5.5.14.3 JMenuItem
• The JMenuItem class represents the actual item in a menu. All items in a menu should
derive from class JMenuItem, or one of its subclasses. By default, it embodies a simple
labeled menu item.
• In order to create menu items in Swing, you need to create new instances of
JMenuItem and set different properties for them. You can create menu item with both
text and icon.
• Constructors of JMenuItem:
1. JMenuItem(): This constructor creates a JMenuItem instance without icon or text.
2. JMenuItem(Icon icon): This constructor creates a JMenuItem instance with a
given icon.
3. JMenuItem(String text): This constructor creates a JMenuItem instance with a
given text.
4. JMenuItem(String text, Icon icon): This constructor creates a JMenuItem
instance with a given text and icon
5. JMenuItem(String text, int mnemonic): This constructor creates a JMenuItem
instance with the given text and keyboard mnemonic.
6. JMenuItem(Action a): This constructor creates a JMenuItem instance whose
properties are taken from the a given Action.
Program 5.32: Program for JMenuItem.
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MenuCreation
{
public static void main(final String args[])
{
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
5.67
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.5.14.4 JPopupMenu
• Another type of a menu is a popup menu. Java Swing has a JPopupMenu class for this
functionality.
• It is also called a context menu and usually shown when we right click on a
component.
• The idea is to provide only the commands that are relevant in the current context. Say
we have an image. By right clicking on the image, we get a popup window with
commands to save, scale, or move the image.
• Popup menu represents a menu which can be dynamically popped up at a specified
position within a component.
• popup menu is a free-floating menu which associates with an underlying component.
This component is called the invoker.
• Most of the time, popup menu is linked to a specific component to display context-
sensitive choices.
• In order to create a popup menu, you use the class JPopupMenu. You then can add
menu itemsJMenuItem to popup menu like normal menu.
• To display the popup menu, we call method show(). Normally popup menu is called in
response to a mouse event.
Constructors:
1. JPopupMenu(): This constructor constructs a JPopupMenu without an "invoker".
2. JPopupMenu(String label): This constructor constructs a JPopupMenu with the
specified title.
5.68
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.69
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
5.5.15 JScrollPane
• A scrolling pane is a container that can be used to hold any component that can be
scrolled.
• By default, the list and textarea component do not scroll automatically when number
of items in the list or text area component go beyond the displayed area. So to make
these components scroll, you must insert them into the scrollpane.
• A scroll pane is a component that presents a rectangular area in which a component
may be viewed.
• Horizontal and/or vertical scroll bars may be provided if necessary. Scroll panes are
implemented in Swing by the JScrollPane class.
Constructors:
1. JScrollPane(Component comp): This creates a scroll pane with the component
specified with comp.
2. JScrollPane(int vsb, int hsb): This creates a scroll panel with the vsb and hsb
are int constants that define when vertical and horizontal scroll bars for this scroll
panel are shown.
3. JScrollPane(Component comp, int vsb, int hsb): This constructor scroll panel
creates a combination of above both constructor.
• Constants of scroll pane are given below:
1. HORIZONTAL_SCROLLBAR_ALWAYS: Always provide horizontal scroll bar.
2. HORIZONTAL_SCROLLBAR_AS_NEEDED: Provide horizontal scroll bar, if needed.
3. VERTICAL_SCROLLBAR_ALWAYS: Always provide vertical scroll bar.
4. VERTICAL_SCROLLBAR_AS_NEEDED: Provide vertical scroll bar, if needed.
• Here, are the steps that you should follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object, (the arguments to the constructor specify the
component and the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.
Program 5.35: Program to demonstrate JScrollPane.
import javax.swing.*;
import java.awt.*;
class JScrollPaneExample extends JFrame
{
JScrollPaneExample()
{
setLayout(new FlowLayout());
5.72
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.6.1 JDialog
• A dialog can be either modal or modeless. Modal dialogs block input to other top-level
windows. Modeless dialogs allow input to other windows.
• A modal dialog blocks user input to all other windows in the same application when it
is visible.
• We have to close a modal dialog before other windows in the same application can get
focus. A modeless one does not block user input.
5.73
Object Oriented Programming using Java - I User Interface with AWT and Swing
• This class extends java.awt.Dialog class. Dialogs are used to accept some inputs from
User. Default layout manager for JDialog class is BorderLayout.
Package: javax.swing
Constructors:
1. JDialog(Frame parent): This constructor creates a new JDialog object which
appears on specified parent Frame.
2. JDialog (Frame parent, Boolean modal): This constructor creates a new
JDialog object which appears on the specified parent frame.
• If we pass second parameter as 'true' then we can not work on the parent window
when dialog is visible, such a Dialog boxes are called as Modal dialog boxes.
• If we pass 'false" then we can work on the parent window when dialog is visible such a
dialog box is called as non-modal dialog box.
1. JDialog (Frame parent. String title): This constructor creates a dialog box
which have some title.
2. JDialog (Frame parent. Siring title. Boolean modal): This constructor
creales a Dialogbox which appears on specified parent frame, with title specified
by the user and modal or non-modal nature is specified.
• Methods:
1. void hide(): This method is used to hide the Dialog box.
2. void show(): This method is used to show the Dialog box.
3. Container getContentPanel(): This method returns, a Content Pane for the
JDialog.
4. void setLayout(LayoutManager): This method sets the LayoutManager for the
Dialog.
5. void setJMenuBar(JMenuBar): This method sets the JMenu Bar to the JDialog box.
6. boolean isModal(): This method checks whether, the dialog is modal or non-
modal.
Program 5.36: Program to demonstrate JDialog.
import javax.swing.*;
import java.awt.*;
class JDialogExample extends JFrame
{
JDialog d1;
public JDialogExample()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JDialog Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
5.74
Object Oriented Programming using Java - I User Interface with AWT and Swing
{
boolean selected = (ev.getStateChange() == ItemEvent.SELECTED);
AbstractButton button = (AbstractButton)ev.getItemSelectable();
String command = button.getActionCommand();
if (selected)
{
int messageType = -1;
String message = "";
if (command.equals("INFORMATION"))
{
messageType = JOptionPane.INFORMATION_MESSAGE;
message = "Information Message";
}
else if (command.equals("WARNING"))
{
messageType = JOptionPane.WARNING_MESSAGE;
message = "Warning Message";
}
else if (command.equals("ERROR"))
{
messageType = JOptionPane.ERROR_MESSAGE;
message = "Error Message";
} else if (command.equals("QUESTION"))
{
messageType = JOptionPane.QUESTION_MESSAGE;
message = "Question Message";
}
// show message
JOptionPane.showMessageDialog(frame,
message,
"Message Dialog",messageType);
}
}
}
JRadioButton r1 = new JRadioButton("Information Message");
r1.setActionCommand("INFORMATION");
JRadioButton r2 = new JRadioButton("Warning Message");
r2.setActionCommand("WARNING");
JRadioButton r3 = new JRadioButton("Error Message");
r3.setActionCommand("ERROR");
JRadioButton r4 = new JRadioButton("Question Message");
r4.setActionCommand("QUESTION");
// add event handler
MyItemListener myItemListener = new MyItemListener();
r1.addItemListener(myItemListener);
r2.addItemListener(myItemListener);
r3.addItemListener(myItemListener);
5.77
Object Oriented Programming using Java - I User Interface with AWT and Swing
r4.addItemListener(myItemListener);
// add radio buttons to a ButtonGroup
final ButtonGroup group = new ButtonGroup();
group.add(r1);
group.add(r2);
group.add(r3);
group.add(r4);
// Frame setting
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
Container cont = frame.getContentPane();
cont.setLayout(new GridLayout(0, 1));
cont.add(new JLabel("Please choose the message type:"));
cont.add(r1);
cont.add(r2);
cont.add(r3);
cont.add(r4);
frame.setVisible(true);
}
}
Output:
When we click on each radio button, it will display corresponding message type.
Constructors:
1. JFileChooser(): This constructor constructs a JFileChooser pointing to the user's
default directory.
2. JFileChooser(File currentDirectory): This constructor constructs a
JFileChooser using the given File as the path.
3. JFileChooser(File currentDirectory, FileSystemView fsv): This constructor
constructs a JFileChooser using the given current directory and FileSystemView.
4. JFileChooser(FileSystemView fsv): This constructor constructs a JFileChooser
using the given FileSystemView.
5. JFileChooser(String currentDirectoryPath): This constructor constructs a
JFileChooser using the given path.
6. JFileChooser(String currentDirectoryPath, FileSystemView fsv): This
constructor constructs a JFileChooser using the given current directory path and
FileSystemView.
• A JFileChooser is a dialog to select a file or files. The return value of the three methods
is one of the following:
1. JFileChooser.CANCEL_OPTION, if the user clicks Cancel.
2. JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button.
3. JFileChooser.ERROR_OPTION, if the user closes the dialog.
Program 5.38: Program for JFileChooser.
package jfilechooserdemo;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
final JFrame frame = new JFrame("JFileChooser Demo");
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setCurrentDirectory(new File("tmp"));
JButton btn1 = new JButton("Show Dialog");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fc.showDialog(frame, "Choose");
}
});
JButton btn2 = new JButton("Show Open Dialog");
5.79
Object Oriented Programming using Java - I User Interface with AWT and Swing
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int retVal = fc.showOpenDialog(frame);
if (retVal == JFileChooser.APPROVE_OPTION)
{
File[] selectedfiles = fc.getSelectedFiles();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < selectedfiles.length; i++)
{
sb.append(selectedfiles[i].getName() + "\n");
}
JOptionPane.showMessageDialog(frame, sb.toString());
}
}
});
JButton btn3 = new JButton("Show Save Dialog");
btn3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fc.showSaveDialog(frame);
}
});
Container pane = frame.getContentPane();
pane.setLayout(new GridLayout(3, 1, 10, 10));
pane.add(btn1);
pane.add(btn2);
pane.add(btn3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Output:
5.80
Object Oriented Programming using Java - I User Interface with AWT and Swing
16. void setColor(int r, int g, int b): This method sets the current color of the
color chooser to the specified RGB color.
17. void setDragEnabled(boolean b): This method sets the dragEnabled property,
which must be true to enable automatic drag handling (the first part of drag and
drop) on this component.
18. void setPreviewPanel(JComponent preview): This method sets the current
preview panel.
19. void setSelectionModel(ColorSelectionModel newModel): This method sets the
model containing the selected color.
20. void setUI(ColorChooserUI ui): This method sets the L&F object that renders
this component.
21. static Color showDialog(Component component, String title, Color
initialColor): This method shows a modal color-chooser dialog and blocks until
the dialog is hidden.
22. void updateUI(): This method shows notification from the UIManager that the
L&F has changed.
Program 5.39: Program for JColorChooser.
package jcolorchooserdemo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
final JFrame frame = new JFrame("JColorChooser Demo");
JButton btn1 = new JButton("Choose Color");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Color newColor = JColorChooser.showDialog(
frame, "Choose Background Color", frame.getBackground());
if(newColor != null)
{
frame.getContentPane().setBackground(newColor);
}
}
});
Container pane = frame.getContentPane();
pane.setLayout(new FlowLayout());
pane.add(btn1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
5.82
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
• Java Uses the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.
• The Delegation Event Model has the following key participants namely:
1. An event is a change of state of an object.
2. The source is an object on which event occurs.
3. Listener is also known as event handler.Listener is responsible for generating
response to an event.
Steps involved in Event Handling:
Step 1 : The User clicks the button and the event is generated.
Step 2 : Now the object of concerned event class is created automatically and
information about the source and the event get populated with in same
object.
Step 3 : Event object is forwarded to the method of registered listener class the
method is now get executed and returns.
Method
Operating Java Events
User Library Method
Action System
(OS) Classes
Method
Fig. 5.12
• The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process events.
• Its concept is quite simple: A source generates an event and sends it to one or more
listeners.
• In this scheme, the listener simply waits until it receives an event. Once received, the
listener processes the event and then returns.
• Fig. 5.13 shows delegation event model. In this model a GUI component such as Button,
MenuItem etc. called as a source, which generates an event.
• The event is passed to one or more listeners. A listener is an object that listens for
particular events.
• Fig. 5.13 shows following key participants:
1. Events:
• Event is an object that describes a state of change in a source.
• Events may be generated as a consequence of a user interacting with the GUI elements
like pressing a button, moving mouse etc.
2. Event Sources:
• "Source" is an object that generates an event. In the delegation event model source
generates an event and sends it to one or more listeners.
5.84
Object Oriented Programming using Java - I User Interface with AWT and Swing
• In this scheme, the listener simply waits until it receives an event. Once received, the
listener processes the event and then returns.
• User interface logic is able to delegate the processing of an event to a separate piece of
code. In the delegation model, listeners must register with the source in order to
receive event notification.
• Notifications are sent only to listeners that want to receive them. Each type of event
has its own registration methods.
Event Invokes
Source
Creates
Registers
Event
Object
onEvent(EventObj) onEvent(EventObj)
Fig. 5.13
• The format of registering listener is as:
public void addTypeListener (TypeListener t1)
where, Type is name of event.
• For example, registration of keyboard event listener is as:
addKeyListener(KeyListener t1)
• The methods that receive and process events are defined in a set of interfaces found in
java.awt.event packages.
3. Listener Interface:
• It is an interface which contains methods that the listener must implement and the
source of the event invokes when the event occurs.
Event Classes:
• When the user interacts with the application by clicking a mouse button or pressing a
key an event is generated.
• The Operating System traps this event and the data associated with it. For example,
info about time at which the event occurred, the event types (like keypress or mouse
click). This data is then passed on to the application to which the event belongs.
• In Java, events are represented by objects, which describe the events themselves. And
Java has a number of classes that describe and handle different categories of events.
• The EventObject class is at the top of the event class hierarchy. It belongs to the
java.util package.
5.85
Object Oriented Programming using Java - I User Interface with AWT and Swing
• While most of the other event classes are present in java.awt.event package. The
getSource() method of the EventObject class returns the object that initiated the event.
The getId () method returns the nature of the event.
• Following Table 5.1 shows some of important classes that represent events.
Table 5.1
Class Generated at which Event
1. WindowEvent Window is activated, closed, deactivated, iconified, opened
etc.
2. MouseEvent Mouse is moved, clicked, released, dragged, enters or exists
component.
3. MouseWheelEvent Mouse wheel is moved.
4. KeyEvent Input is received from Keyboard.
5. ActionEvent A button is pressed, a list item or menu-item is selected.
6. ItemEvent A checkbox or list item is clicked. Also when choice
selection is done or checkable menu item is checked or
unchecked.
7. TextEvent Text area or text field content is changed.
8. AdjustmentEvent A scroll bar is manipulated.
9. FocusEvent A component gains or loses keyboard focus.
Swing Event Classes:
• The Event classes represent the event. Java provides us various Event classes but we
will discuss those which are more frequently used.
EventObject class:
• It is the root class from which all event state objects shall be derived. All Events are
constructed with a reference to the object, the source that is logically deemed to be the
object upon which the Event in question initially occurred upon. This class is defined
in java.util package.
• Following is the declaration for java.util.EventObject class:
public class EventObject
extends Object
implements Serializable
Constructor:
1. EventObject(Object source): This constructor constructs a prototypical Event.
Methods:
1. Object getSource(): This method is an object on which the Event initially
occurred.
2. String toString(): This method returns a String representation of this
EventObject.
5.86
Object Oriented Programming using Java - I User Interface with AWT and Swing
8. ContainerListener Interface:
• The interfaceContainerListener is used for receiving container events.
• The class that process container events needs to implements this interface.
(i) void componentAdded(ContainerEvent e): This method invoked when a
component has been added to the container.
(ii) void componentRemoved(ContainerEvent e): This method invoked when a
component has been removed from the container.
9. MouseMotionListener Interface:
• The interface MouseMotionListener is used for receiving mouse motion events on a
component.
• The class that process mouse motion events needs to implements this interface.
(i) void mouseDragged(MouseEvent e): This method invoked when a mouse button
is pressed on a component and then dragged.
(ii) void mouseMoved(MouseEvent e): This method invoked when the mouse cursor
has been moved onto a component but no buttons have been pushed.
10. FocusListener Interface:
• The interface FocusListener is used for receiving keyboard focus events.
• The class that process focus events needs to implements this interface.
(i) void focusGained(FocusEvent e): This method invoked when a component
gains the keyboard focus.
(ii) void focusLost(FocusEvent e): This method invoked when a component loses
the keyboard focus.
Apple
AppleAdapter Orange
Apple
Act like an
apple now
AppleAdapter
Orange
Fig. 5.14
Adapter Class:
• An adapter class can simplify the creation of event handlers in certain situations.
• An adapter class provides an empty implementation of all methods in an event
listener interface i.e this class itself write definition for methods which are present in
particular event listener interface. However these definitions do not affect program
flow or meaning at all.
• Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.
• We can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which we are interested.
• For example, suppose we want to use MouseClicked Event or method from
MouseListener, if we do not use adapter class then unnecessarily we have to define all
other methods from MouseListener such as MouseReleased, MousePressed etc.
• But if we use adapter class then we can only define MouseClicked method and don’t
worry about other method definition because class provides an empty implementation
of all methods in an event listener interface.
• Below table indicates Listener interface with their respective adapter class:
Listener Interface Adapter Class
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter
5.92
Object Oriented Programming using Java - I User Interface with AWT and Swing
Swing Adapters:
• Following is the list of commonly used adapters while listening GUI events in Swing:
1. FocusAdapter: An abstract adapter class for receiving focus events.
2. KeyAdapter: An abstract adapter class for receiving key events.
3. MouseAdapter: An abstract adapter class for receiving mouse events.
4. MouseMotionAdapter: An abstract adapter class for receiving mouse motion
events.
5. WindowAdapter: An abstract adapter class for receiving window events.
• Program 5.42 shows use of adapter class which handles empty implementation of
event methods which are not provided.
Program 5.40: Use of MouseAdapter class.
import java.awt.*;
import java.awt.event.*;
public class JMouseAdapterExample extends MouseAdapter
{
Frame frame;
JMouseAdapterExample()
{
frame = new Frame("My Mouse Adapter");
frame.addMouseListener(this);
frame.setSize(300,300);
frame.setLayout(null);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent me)
{
Graphics g = frame.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(me.getX(),me.getY(),30,30);
}
public static void main(String[] args)
{
new JMouseAdapterExample();
}
}
5.93
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AnonymousClassAppUseDemo
{
public static void main(String[] args)
{
GreetingFrame hwf = new GreetingFrame();
hwf.CreateFrame();
}
}
class GreetingFrame
{
private JFrame frame;
private JPanel messagePanel;
private JPanel buttonPanel;
private JPanel container;
private JLabel messageLabel;
private JButton greetButton;
private JButton clearButton;
public GreetingFrame ()
{
//beautify the frame
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Hello World");
messagePanel = new JPanel(); //used to place greeting message
buttonPanel = new JPanel(); //used to place command button
container = new JPanel(); //used to place message and button Panels
messageLabel = new JLabel(" "); // contain greeting message
greetButton = new JButton("Greeting"); //display greeting message
when clicked
clearButton = new JButton("Clear"); //clears greeting message when
clicked
}
public void CreateFrame ()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
messagePanel.add(messageLabel);
buttonPanel.add(greetButton);
buttonPanel.add(clearButton);
/* brand new class of super type ActionListener
* will be created anonymously and passed to addActionListener method
5.95
Object Oriented Programming using Java - I User Interface with AWT and Swing
* of greetButton object
*/
greetButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
messageLabel.setText("Hello User! Greetings of the day!");
}
});
/* brand new class of super type ActionListener
* will be created anonymously and passed to addActionListener method
* of clearButton object
*/
clearButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
messageLabel.setText(" ");
}
});
container.add(messagePanel);
container.add(buttonPanel);
frame.getContentPane().add(container);
//Display the window.
frame.setSize(300, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Output:
Benefits:
1. The key benefit of an anonymous class is encapsulation (or clutter reduction).
2. An anonymous class is, in a sense, the ultimate in private object oriented
encapsulation.
3. It is defined exactly where it is needed, it can never be used anywhere else, and it
has totally local scope.
4. Anonymous classes have access to all data and methods of their containing classes,
including private members; meaning that for small highly localized tasks, they
may require less initialization.
Drawbacks:
1. The big drawback with anonymous classes is they can’t have explicit constructors.
2. We can’t pass them any parameters when they are instantiated.
5.96
Object Oriented Programming using Java - I User Interface with AWT and Swing
PROGRAMS
Program 1: Program for JFrame.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample
{
public static void main(String s[])
{
JFrame jframe = new JFrame("Example of JFrame");
JPanel jpanel = new JPanel();
jpanel.setLayout(new FlowLayout());
JLabel jlabel = new JLabel("First JFrame Example");
JButton jbutton = new JButton();
jbutton.setText(" Click Me ");
jpanel.add(jlabel);
jpanel.add(jbutton);
jframe.add(jpanel);
jframe.setSize(400, 300);
jframe.setLocationRelativeTo(null);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
Output:
{
JFrame jframe= new JFrame("JLabel Example");
JLabel jlable1,jlable2;
jlable1=new JLabel("My First Label.");
jlable1.setBounds(50,100, 100,40);
jlable2=new JLabel("My Second Label.");
jlable2.setBounds(50,150, 100,40);
jframe.add(jlable1);
jframe.add(jlable2);
jframe.setSize(400,300);
jframe.setLayout(null);
jframe.setVisible(true);
}
}
Output:
jframe.add(jtextfield2);
jframe.setSize(400,400);
jframe.setLayout(null);
jframe.setVisible(true);
}
}
Output:
Output:
5.100
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
Output:
jpanel.add(jbutton2);
jlabel = new JLabel("File Selected");
jpanel.add(jlabel);
jframe.add(jpanel);
jframe.show();
}
public void actionPerformed(ActionEvent ae)
{
String comm = ae.getActionCommand();
if (comm.equals("SAVE"))
{
JFileChooser jfile = new JFileChooser(FileSystemView.
getFileSystemView().getHomeDirectory());
int ro = jfile.showSaveDialog(null);
if (ro == JFileChooser.APPROVE_OPTION)
{
jlabel.setText(jfile.getSelectedFile().getAbsolutePath());
}
else
jlabel.setText("User Not Select");
}
else
{
JFileChooser jfile1 = newJFileChooser(FileSystemView.
getFileSystemView().getHomeDirectory());
int ro1 = jfile1.showOpenDialog(null);
if (ro1 == JFileChooser.APPROVE_OPTION)
{
jlabel.setText(jfile1.getSelectedFile().getAbsolutePath());
}
else
jlabel.setText("User Not Select");
}
}
}
5.103
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
Program 9: Program to display ten buttons with labels Ten, Twenty,…….., Hundred using
flow layout. Use array of Buttons.
import java.awt.*;
import java.awt.event.*;
class FlowLayoutDemo extends Frame
{
Label label;
public FlowLayoutDemo()
{
String[] names = {"Ten", "Twenty", "Thirty", "Forty",
"Fifty","Sixty","Seventy","Eighty","Ninety","Hundred"};
Button b1[] = new Button[names.length];
5.104
Object Oriented Programming using Java - I User Interface with AWT and Swing
setTitle("FlowLayout ");
setSize(400,400);
setLayout(new FlowLayout());
setVisible(true);
for (int i = 0; i < b1.length; i++)
{
b1[i] = new Button(names[i]);
}
for (int i = 0; i < b1.length; i++)
{
add(b1[i]);
}
add(label);
}
public static void main(String args[])
{
new FlowLayoutDemo();
}
}
Output:
Program 10: Program that displays three concentric circles where ever the user
clicks the mouse on a frame. The program must exit when user clicks ‘X’ on the frame.
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.*;
5.105
Object Oriented Programming using Java - I User Interface with AWT and Swing
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.JPanel;
public class Ovals extends JPanel
{
private Graphics g;
private int prevX, prevY;
private String drawtype;
public Ovals()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
selectpaint();
}
});
}
private void selectpaint()
{
g = getGraphics();
Dimension d = getSize();
int x = d.width/2;
int y = d.height/2;
int r1 = (int) ((d.width < d.height)? 0.4 *
d.width: 0.4 * d.height);
g.setColor(Color.red);
g.fillOval(x-r1, y-r1, 2*r1, 2*r1);
int r2 = (int) ((d.width < d.height)? 0.3 *
d.width: 0.3 * d.height);
g.setColor(Color.blue);
g.fillOval(x-r2, y-r2, 2*r2, 2*r2);
int r3 = (int) ((d.width < d.height)? 0.2 *
d.width: 0.2 * d.height);
g.setColor(Color.yellow);
g.fillOval(x-r3, y-r3, 2*r3, 2*r3);
// to choose polygon to draw
}
5.106
Object Oriented Programming using Java - I User Interface with AWT and Swing
Program 11: Program to design a frame having a text box and a label. As the user types
characters in the text box simultaneously display these type characters in the label. Your
program should exit when user presses the ‘X’ button of the window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class f2
{
JTextField txtsub = new JTextField(20);
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel headerLabel1;
private JLabel statusLabel;
private JPanel controlPanel;
JButton quitButton = new JButton("Quit");
public f2()
{
prepareGUI();
}
5.107
Object Oriented Programming using Java - I User Interface with AWT and Swing
quitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
}
private class KeyHandler implements KeyListener
{
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
if(e.getSource() == txtsub)
{
String passwordTyped = txtsub.getText();
headerLabel.setText(passwordTyped);
}
}
}
}
Output:
5.109
Object Oriented Programming using Java - I User Interface with AWT and Swing
import java.awt.*;
import javax.swing.*;
class Sample extends JFrame
{
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3;
JTextArea t;
JPanel p,p1,p2,p3;
ButtonGroup bg;
JRadioButton m,f;
JCheckBox c1,c2,c3;
JButton b1,b2;
Sample()
{
p =new JPanel();
p1=new JPanel();
l1=new JLabel("First Name: ");
l2=new JLabel("last Name: ");
l3=new JLabel("Address: ");
l4=new JLabel("Mobile No.: ");
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
t=new JTextArea(2,10);
p.add(l1); p.add(t1);
p.add(l2); p.add(t2);
p.add(l3); p.add(t);
p.add(l4); p.add(t3);
p.setLayout(new GridLayout(4,2));
5.110
Object Oriented Programming using Java - I User Interface with AWT and Swing
add(p);
l5=new JLabel("Gender ");
m = new JRadioButton("male");
f = new JRadioButton("female");
bg = new ButtonGroup();
bg.add(m);
bg.add(f);
p1.add(l5);
p1.add(m);
p1.add(f);
p1.setLayout(new GridLayout(1,3));
p2=new JPanel();
l6=new JLabel("Your Interests ");
c1=new JCheckBox("Computer");
c2=new JCheckBox("Sports");
c3=new JCheckBox("Music");
p2.add(l6);
p2.add(c1);
p2.add(c2);
p2.add(c3);
p2.setLayout(new GridLayout(1,4));
p3=new JPanel();
b1=new JButton("submit");
b2=new JButton("clear");
p3.add(b1);
p3.add(b2);
add(p);
add(p1);
add(p2);
add(p3);
setSize(300,400);
setLayout(new FlowLayout(FlowLayout.LEFT));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String a[])
{
new Sample();
}
}
5.111
Object Oriented Programming using Java - I User Interface with AWT and Swing
Output:
m1=new JMenu("Operation");
m2=new JMenu("Compute");
String str[]={"Accept","Exit","GCD","Power"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
mb.add(m1);
mb.add(m2);
m1.add(m[0]);
5.112
Object Oriented Programming using Java - I User Interface with AWT and Swing
m1.add(m[1]);
m2.add(m[2]);
m2.add(m[3]);
setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
setSize(300,150);
setVisible(true);
setLocation(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // constructor
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand(); //return the name of menu
if(s.equals("Exit"))
System.exit(0);
if(s.equals("Accept"))
{
n1=Integer.parseInt(JOptionPane.showInputDialog("Enter 1st no for
Number"));
n2=Integer.parseInt(JOptionPane.showInputDialog("Enter 2nd no for
Number"));
}
if(s.equals("GCD"))
{
int min;
if(n1>=n2)
min=n1;
else
min=n2;
for(int i=1;i<=min;i++)
{
if(n1%i==0 && n2%i==0)
gcd=i;
}
JOptionPane.showMessageDialog(null,"GCD = "+gcd);
}
5.113
Object Oriented Programming using Java - I User Interface with AWT and Swing
if(s.equals("Power"))
{
pow=1;
for(int i=1;i<=n2;i++)
{
pow=pow*n1;
}
JOptionPane.showMessageDialog(null,"Power = "+pow);
}
}
public static void main(String a[])
{
new Demogcd();
}
}
Output:
PRACTICE QUESTIONS
Q.I Multiple Choice Questions:
1. Which object can be constructed to show any number of choices in the visible
Window?
(a) Labels (b) Choice
(c) List (d) Checkbox
2. Which is a component in AWT that can contain other components like buttons,
textfields, labels etc.?
(a) Window (b) Container
(c) Panel (d) Frame
3. Which of these events will be notified if scroll bar is manipulated?
(a) ActionEvent (b) ComponentEvent
(c) AdjustmentEvent (d) WindowEvent
4. How many types of controls does AWT support?
(a) 7 (b) 6
(c) 5 (d) 8
5.114
Object Oriented Programming using Java - I User Interface with AWT and Swing
5.115
Object Oriented Programming using Java - I User Interface with AWT and Swing
26. Which is a component that contains other components like button, textfield, label,
etc.?
(a) Window (b) Component
(c) Container (d) Button
27. Which class creates a top level window?
(a) Frame (b) Panel
(c) Button (d) Window
28. Which is used for placing text in a container?
(a) Button (b) Frame
(c) Label (d) Panel
29. Which is used for displaying single line text?
(a) Label (b) TextField
(c) Frame (d) Window
30. Which is used for creating a drop-down menu of choices?
(a) Choice (b) Chech box
(c) TextArea (d) TextField
31. MVC architecture contains,
(a) Model represents component's data.
(b) View represents visual representation of the component's data.
(c) Controller takes the input from the user on the view and reflects the changes in
Component's data.
(d) All the Mentioned
32. Which refers to the arrangement of components within the container?
(a) Layouts (b) Borders
(c) Menu bars (d) None of mentioned
33. The task of laying out the controls is done automatically by the,
(a) AWT Manager (b) Swing Manager
(c) Layout Manager (d) All of mentioned
34. Which class is the base class for all Swing components except top-level containers?
(a) Component (b) Container
(c) JComponent (d) All of the mentioned
35. Which is is a platform-independent, "model–view–controller" GUI framework for
Java?
(a) AWT (b) Swing
(c) Botn (a) and (b) (d) None of mentioned
36. Which is an interface which implements the classes of the layout manager?
(a) SwingLayoutMananger (b) AWTLayoutMananger
(c) LayoutMananger (d) All of mentioned
37. Which is the default layout that ayouts the components in a directional flow?
(a) BorderLayout (b) CardLayout
(c) FlowLayout (d) GridLayout
5.117
Object Oriented Programming using Java - I User Interface with AWT and Swing
38. Which AWT layout arranges the components in grid cells as rows and columns?
(a) Border (b) Card
(c) Flow (d) Grid
39. Which is the top level class for all menu related controls?
(a) MenuComponent (b) Menut
(c) MenuContainer (d) All of mentioned
40. Change in the state of an object is known as,
(a) source (b) listener
(c) event (d) None of mentioned
41. Which is the mechanism that controls the event and decides what should happen if
an event occurs?
(a) Event handling (b) Source handling
(c) Listener handling (d) All of mentioned
42. Which model defines the standard mechanism to generate and handle the events?
(a) MVC (b) Delegation Event
(c) Both (a) and (b) (d) None of mentioned
43. Which class is the root class from which all events in AWT?
(a) EventObject (b) AWTObject
(c) SwingOBject (d) None of mentioned
44. Which represent the interfaces responsible to handle events?
(a) Event Listener (b) Event Source
(c) Event Handler (d) None of mentioned
45. Which are abstract classes for receiving various events?
(a) Sources (b) Listeners
(c) Adapters (d) All of mentioned
46. Which interface is used for receiving the mouse events?
(a) TextListener (b) KeyListener
(c) ComponentListener (d) MouseListener
47. Which abstract adapter class for receiving focus events?
(a) KeyAdapter (b) MouseAdapter
(c) FocusAdapter (d) WindowAdapter
48. Which class has no name?
(a) inner (b) wrapper
(c) string (d) anonymous
49. In swing which are the subclass of MenuComponent class.
(a) Menu (b) MenuItem
(c) Both (a) and (b) (d) None of mentioned
50. Which AWT control represents a top-level window with a title and a border used
to take some form of input from the user?
(a) Scrollbar (b) Dialog
(c) Button (d) Label
5.118
Object Oriented Programming using Java - I User Interface with AWT and Swing
51. Which is Swing graphical component that can be in either an on (true) or off (false)
state?
(a) JComboBox (b) JCheckBox
(c) JButton (d) JRadioButton
52. Which is AWT control component that has a label and generates an event when
pressed?
(a) List (b) Check box
(c) Button (d) Choice
53. Which control represents a dialog window from which the user can select a file?
(a) MessageDialog (b) FileDialog
(c) Dialog (d) All of mentioned
54. Which Swing component presents the user with a scrolling list of text items?
(a) JTextField (b) JList
(c) JComboBox (d) JCheckBox
55. Which is is a pull-down menu component which is displayed from the menu bar?
(a) JMenu (b) JMenuItem
(c) JMenuBar (d) JPopupMenu
56. Which menu represents a menu which can be dynamically popped up at a
specified position within a component?
(a) MenuBar (b) PopupMenu
(c) MenuItem (d) Menu
57. Which is a top-level window in AWT with a title and a border?
(a) Panel (b) Window
(c) Frame (d) All of mentioned
58. Which Swing control provides a pane of controls designed to allow a user to
manipulate and select a color?
(a) JFileChooser (b) JColorChooser
(c) JDialogChooser (d) None of mentioned
Answers
1. (c) 2. (b) 3. (c) 4. (a) 5. (c) 6. (d) 7. (a) 8. (d) 9. (b) 10. (c)
11. (b) 12. (c) 13. (b) 14. (d) 15. (b) 16. (d) 17. (b) 18. (d) 19. (d) 20. (a)
21. (a) 22. (c) 23. (a) 24. (a) 25. (b) 26. (c) 27. (d) 28. (c) 29. (b) 30. (a)
31. (d) 32. (a) 33. (c) 34. (c) 35. (b) 36. (c) 37. (c) 38. (d) 39. (a) 40. (c)
41. (a) 42. (b) 43. (a) 44. (a) 45. (c) 46. (d) 47. (c) 48. (d) 49. (c) 50. (b)
51. (d) 52. (c) 53. (b) 54. (b) 55. (a) 56. (b) 57. (c) 58. (b)
Q.II Fill in the Blanks:
1. Fill in the blanks so that this program displays a Frame:
import java.awt.*;
public class microGUI
{
public static void main ( String[] args )
{
Frame frm = new frame();
frm.______( 350, 300 );
frm.______( true );
}
}
5.119
Object Oriented Programming using Java - I User Interface with AWT and Swing
2. The classes and interfaces defined in AWT are contained within the ______
package.
3. In Java an event is an ______ which specifies the change of state in the source.
4. Java packages such as ______ support the Event handling mechanism.
5. Panel is used for ______ components.
6. ______ is a superclass of TextField and TextArea classes that is used to create
single-line or multiline textfields respectively
7. A label is a simple control which is used to display ______ on the window.
8. ______ generates action events when an item is double-clicked, generate action
events when an item is selected or deselected.
9. ______ arranges the componemnts into grid
10. ______ classes are derived from the Component class.
11. A label is a simple AWT control which is used to display ______ (non-editable) on
the window.
12. ______ method we can set or change the text in a Label.
13. The classes and interfaces defined in AWT are contained within the ______
package.
14. A class that have no name is known as ______ class.
15. Swing components that does not rely on Native GUI are referred to as ______
component.
16. Swing is a component based ______, whose components are all ultimately derived
from the javax.swing.JComponent class.
17. The base class for all Swing components except top-level containers is ______.
18. ______ in AWT does not have borders and menubar.
19. ______ define how UI elements should be organized on the screen and provide a
final look and feel to the GUI (Graphical User Interface).
20. The layout ______ is associated with every Container object.
21. A ______ object is a top-level window with no borders and no menubar.
22. AWT layout is defined as the order of placement of the ______ in a container and
this arrangement can be done by LayoutManager.
23. The class Component is the ______ base class for the non menu user-interface
controls of AWT.
24. Java provides various layout managers to ______ the controls. Properties like size,
shape, and arrangement varies from one layout manager to the other.
25. ______ is a GUI widget toolkit for Java.
26. The interface between the ______ and application program is known as an user-
interface.
27. Java ______ is an API to develop GUI or window based applications in java.
5.120
Object Oriented Programming using Java - I User Interface with AWT and Swing
28. The screen area on the desktop displaying the data and performing the operations
specified is called as a ______.
29. AWT ______ are nothing but AWT components that allows the user to
communicate or interact with the user in different ways.
30. An object change from one state to another state when used in an application is
known as ______.
31. The layout manager automatically positions all the components within the ______.
32. The standard process of giving directions when an event occurs is called as ______.
33. ______ in AWT is the user-defined text, which cannot be modified by the end-user.
34. ______ in AWT contains a Label and creates an event when clicked on it.
35. ScrollBar in AWT allows the end-user to navigate up and down when there are
______ options in a field.
36. ______ control in AWT decides the state of an event by true or false.
37. ______ control in AWT allows a single selection and List allows multiple selection
of choices.
38. A ______JFrame is a top-level window with a title and a border.
39. ______ is considered as a window without having a menu bar.
40. FlowLayout is the ______ layout manager.
41. Swing API architecture based ______ (Model-View-Controller) architecture.
42. A new LayoutManager can be set by using the method ______.
43. A JComponent is a ______ class for all Swing UI components.
44. ______ arranges the components from top to bottom and left to right with the
preferred sizes on the screen.
45. ______ arranges the components as per the given borders (North, South, East,
West) and Center.
46. GridBagLayout is a ______ AWT Layout.
47. The ______ object treats each component in the container as a card (outputs only
a single card at a time).
48. Textfield control in AWT is used to accept a ______ input from the end-user.
Answers
1. setSize, setVisible 2. java.awt.* 3. object 4. java.awt.event
5. Grouping 6. TextComponent 7. Text 8. Check box
9. GridLayout 10. Container 11. Text 12. setText()
13. java.awt.*; 14. anonymous 15. Ligthweight 16. framework
17. JComponent 18. Window 19. Layouts 20. manager
21. JWindow 22. components 23. abstract 24. position
25. Swing 26. user 27. AWT 28. Window
29. controls 30. event 31. container 32. event handling
33. Label 34. Button 35. multiple 36. Checkbox
37. Choice 38. Dialog 39. Dialog 40. default
41. MVC 42. setLayout() 43. base 44. FlowLayout
45. BorderLayout 46. resizable 47. CardLayout 48. single-line
5.121
Object Oriented Programming using Java - I User Interface with AWT and Swing
25. Swing Dialogues is used to provide the communication between the user and the
system and most of the dialogues are used to display warning messages and alert
messages.
26. JMenuItem is used to display menubar on the window or frame.
27. JFileChooser represents a dialog window from which the user can select file.
28 AWT scrolling is done vertically or horizontally the ScrollBar scrolls vertically and
horizontally from its default value by setting the minimum and maximum values.
29. A JFileChooser control represents a dialog window from which the user can select
a color.
30. Events are generated as result of user interaction with the graphical user interface
components such as clicking on a button, moving the mouse and so on.
31. The source is an object on which event occurs.
32. Listener is also known as event handler which are responsible for generating
response to an event.
33. Java uses the Delegation Event Model to handle the events.
34. Event handling mechanism have the code which is known as event handler that is
executed when an event occurs.
35. A JButton object is a component for placing text in a container.
36. The ActionEvent is generated when button is clicked or the item of a list is double
clicked.
37. A JTextField object is a text component that allows editing of a single line of text.
38. FocusListener is used for receiving the focus events.
39. WindowAdapter is an abstract adapter class for receiving window events.
40. The Menu object is a pull-down menu component which is displayed from the
menu bar.
41. Swing based GUI Application look and feel can be changed at run-time.
42. A JList component presents the user with a scrolling list of text items.
Answers
1. (T) 2. (F) 3. (T) 4. (F) 5. (T) 6. (F) 7. (T) 8. (T) 9. (T) 10. (F)
11. (F) 12. (F) 13. (T) 14. (T) 15. (T) 16. (T) 17. (T) 18. (T) 19. (T) 20. (T)
21. (F) 22. (T) 23. (T) 24. (T) 25. (T) 26. (F) 27. (T) 28. (T) 29. (F) 30. (T)
31. (T) 32. (T) 33. (T) 34. (T) 35. (F) 36. (T) 37. (T) 38. (T) 39. (T) 40. (T)
5.123
Object Oriented Programming using Java - I User Interface with AWT and Swing
October 2017
1. What is the use of adapter class? [1 M]
Ans. Refer to Section 5.8.
2. Give two types of Dialogs. [1 M]
Ans. Refer to Section 5.6.
3. Explain in brief the event handling mechanism in Java with the help of suitable
example. [5 M]
Ans. Refer to Section 5.7.
4. What are the features of Swing? [2 M]
Ans. Refer to Section 5.5.
April 2018
1. Write a syntax of JFileChooser class. [1 M]
Ans. Refer to Section 5.6.3.
2. Why Swing objects are called as light weight components? [1 M]
Ans. Refer to Section 5.5 Point (1).
3. Write a program in Java to create a screen which contains three checkboxes
(.net, php, java) and displays the selected items in a textbox. [5 M]
Ans. Refer to Section 5.4.
October 2018
1. State any four methods of WindowListener. [1 M]
Ans. Refer to Section 5.7.2.
2. How is menu created in Java ? Explain with suitable example. [5 M]
Ans. Refer to Section 5.4 Point (10).
3. What is the use of Checkboxes and RadioButtons ? Explain with suitable
example. [4 M]
Ans. Refer to Section 5.4.
4. Explain layout managers used in AWT. [4 M]
Ans. Refer to Section 5.3.
April 2019
1. What is anonymous classes? [1 M]
Ans. Refer to Section 5.9.
2. Write a Java program which will create a frame if we try to close it. It should
change it’s color Red and it display closing message on the screen.(Use swing) [5 M]
Ans. Refer to Section 5.4.
3. What are the different types of dialogs in Java? Write any one in detail. [3 M]
Ans. Refer to Section 5.6.
4. Which Swing classes are used to create menu? [2 M]
Ans. Refer to Section 5.5.14.
5.126