CORE JAVA Textbook For Absolute Beginners!
CORE JAVA Textbook For Absolute Beginners!
Core Java
For B.B.A.(C.A) : Semester - V
[Course Code CA-503 : Credits-03]
CBCS Pattern
As Per New Syllabus, Effective from June 2021
Price ` 360.00
N4959
CORE JAVA ISBN 978-93-5451-305-3
First Edition : September 2021
© : 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.
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
Preface …
We take an opportunity to present this book entitled as "Core Java" to the students of
Fifth Semester - B.B.A.(C.A). The object of this book is to present the subject matter in a most
concise and simple manner. The book is written strictly according to the New Syllabus
(CBCS Pattern).
The book covers theory of Java Fundamentals, Classes, Objects and Methods, Inheritance,
Package and Collection, File and Exception Handling, Applet, AWT, Event and Swing
Programming.
The book has its own unique features. It brings out the subject in a very simple and lucid
manner for easy and comprehensive understanding of the basic concepts, its intricacies,
procedures and practices. This book will help the readers to have a broader view on Core
Java. The language used in this book is easy and will help students to improve their
vocabulary of Technical terms and understand the matter in a better and happier way.
A special words of thank to Shri. Dineshbhai Furia, Mr. Jignesh Furia for showing full faith
in us to write this text book. We also thank to Mr. Akbar Shaikh of M/s Nirali Prakashan for
their excellent co-operation.
We also thank Mr. Akbar Shaikh, Ms. Chaitali Takale, 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. Java Fundamentals [Lectures 8]
1.1 Introduction to Java
1.2 Basics of Java: Data Types, Variable, Expression, Operators, Constant
1.3 Structure of Java Program
1.4 Execution Process of Java Program
1.5 JDK Tools
1.6 Command Line Arguments
1.7 Array and String
1.7.1 Single Array and Multidimensional Array
1.7.2 String, String Buffer
1.8 Built In Packages and Classes
1.8.1 java.util: Scanner, Date, Math etc.
1.8.2 java.lang
2. Classes, Objects and Methods [Lectures 8]
2.1 Class and Object
2.2 Object Reference
2.3 Constructor: Constructor Overloading
2.4 Method: Method Overloading, Recursion, Passing and Returning Object Form
Method
2.5 New Operator, this and static keyword, finalize() Method
2.6 Nested Class, Inner Class and Anonymous Inner Class
3. Inheritance, Package and Collection [Lectures 10]
3.1 Overview of Inheritance
3.2 Inheritance in Constructor
3.3 Inheriting Data Members and Methods
3.4 Multilevel Inheritance - Method Overriding Handle Multilevel Constructors
3.5 Use of Super and Final Keyword
3.6 Interface
3.7 Creation and Implementation of an Interface, Interface Reference
3.8 Interface Inheritance
3.9 Dynamic Method Dispatch
3.10 Abstract Class
3.11 Comparison between Abstract Class and Interface
3.12 Access Control
3.13 Packages
3.13.1 Packages Concept
3.13.2 Creating User Defined Packages
3.13.3 Java Built Inpackages
3.13.4 Import Statement, Static Import
3.14 Collection
3.14.1 Collection Framework.
3.14.2 Interfaces: Collection, List, Set
3.14.3 Navigation: Enumeration, Iterator, ListIterator
3.14.4 Classes: LinkedList, ArrayList, Vector, HashSet
4. File and Exception Handling [Lectures 8]
Exception
4.1 Exception and Error
4.2 Use of try, catch, throw, throws and finally
4.3 Built in Exception
4.4 Custom exception
4.5 Throwable Class.
File Handling
4.6 Overview of Different Stream (Byte Stream, Character stream)
4.7 Readers and Writers class
4.8 File Class
4.9 File Input Stream, File Output Stream
4.10 Input Stream Reader and Output Stream Writer
Class
4.11 FileReader and FileWriter Class
4.12 Buffered Reader Class
5. Applet, AWT, Event and Swing Programming [Lectures 14]
Applet
5.1 Introduction
5.2 Types Applet
5.3 Applet Lifecycle
5.3.1 Creating Applet
5.3.2 Applet Tag
5.4 Applet Classes
5.4.1 Color
5.4.2 Graphics
5.4.3 Font
AWT
5.5 Components and container used in AWT
5.6 Layout Managers
5.7 Listeners and Adapter Classes
5.8 Event Delegation Model
Swing
5.9 Introduction to Swing Component and Container Classes
5.10 Exploring Swing Controls - JLabel and Image Icon, JText Field, The Swing Buttons
JButton, JToggle Button, JCheck Box, JRadio Button, JTabbed Pane, JScroll Pane,
JList, JTable, JComboBox, Swing Menus, Dialogs, JFileOpen, JColorChooser
Contents …
(v) float:
o float data type is a single-precision 32-bit IEEE 754 floating point.
o float is mainly used to save memory in large arrays of floating point numbers.
o default value is 0.0f.
o float data type is never used for precise values such as currency.
o Example: float f1 = 234.5f
(vi) double:
o double data type is a double-precision 64-bit IEEE 754 floating point.
o This data type is generally used as the default data type for decimal values,
generally the default choice.
o Double data type should never be used for precise values such as currency.
o Default value is 0.0d.
o Example: double d1 = 123.4
(vii) boolean:
o boolean data type represents one bit of information.
o There are only two possible values: true and false.
o This data type is used for simple flags that track true/false conditions.
o Default value is false.
o Example: boolean one = true
(viii) char:
o char data type is a single 16-bit unicode character.
o Minimum value is '\u0000' (or 0).
o Maximum value is '\uffff' (or 65,535 inclusive).
o Char data type is used to store any character.
o Example: char letterA ='A'
2. Reference Data Types:
• Reference data types are made by the logical grouping of primitive data types.
• These are called reference data types because they contain the address of a value
rather than the value itself.
• Arrays, classes, enum etc., are the example of reference data type.
1.2.2 Variables
• Variables are the identifier of the memory location, which used to save data
temporarily for later use in the program. During execution of a program, values can
be stored in a variable, and the stored value can be changed.
• While naming Java variables we have following naming rules.
1. Variable names are case-sensitive.
2. Variable name can be an unlimited-length sequence of Unicode letters and digits.
Core Java [BBA(CA): Sem. V] 1.6 Java Fundamentals
3. Variable name must begin with either a letter or the dollar sign "$", or the
underscore character "_".
4. No white space is permitted in variable names.
5. Variable name must not be a keyword or reserved word.
6. Do not begin with a digit.
7. A name can be of any realistic length.
Program 1.1: Program for variables.
public class AddTwoNumbers
{
public static void main(String args[])
{
int num1 = 50;
int num2 = 15;
int sum;
sum = num1 + num2;
System.out.println("Sum of Numbers: "+sum);
}
}
Output:
Sum of Numbers: 65
1.2.3 Expression
• Expressions are essential building blocks of any Java program, usually created to
produce a new value, although sometimes an expression assigns a value to a variable.
• An expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language that evaluates to a
single value.
• Expression evaluation in Java is based upon the following concepts:
1. Type conversion: It has two types based on how the conversion is performed:
(i) Implicit conversion: It is also known as automatic conversion. This type of
conversion is performed automatically by Java due to performance reasons.
Implicit conversion is not performed at all times. For example, Java will
automatically convert a value of byte into int type in expressions since they are
both compatible and int is larger than byte type.
(ii) Explicit conversion: It is also known as Type Casting. There may be situations
where you want to convert a value having a type of size less than the destination
type size. In such cases Java will not help you. You have do it on your own
explicitly. That is why this type of conversion is known as explicit conversion or
casting as the programmer does this manually.
Core Java [BBA(CA): Sem. V] 1.7 Java Fundamentals
Example:
int a=10;
byte b = (int) a; //integer value to be converted into a byte type
Type promotion rules of Java for expressions are listed below:
o All char, short and byte values are automatically promoted to int type.
o If at least one operand in an expression is a long type, then the entire
expression will be promoted to long.
o If at least one operand in an expression is a float type, then the entire
expression will be promoted to float.
o If at least one operand in an expression is a double type, then the entire
expression will be promoted to double.
2. Operator Precedence: Operator precedence determines the order in which the
operators in an expression are evaluated.
Table 1.1: Operator Precedence
Operators Precedence Associativity
equality == != left to right
bitwise AND & left to right
bitwise exclusive OR ^ left to right
bitwise inclusive OR | left to right
(ii) d=a^b^c
Since exponent operator is right associative therefore b^c will soved first and
then a^ result of b^c .
1.2.4 Operators
• Operators in Java can be classified into 6 types:
1. Unary operators:
+ Unary plus operator; indicates positive value.
− Unary minus operator; negates an expression.
++ Increment operator; increments a value by 1.
−− Decrement operator; decrements a value by 1.
! Logical complement operator; inverts the value of a Boolean.
Program 1.3: Program for unary operator.
public class Unary
{
public static void main(String args[])
{
int a=20;
System.out.println(a++);
System.out.println(++a);
System.out.println(a--);
System.out.println(--a);
}
}
Output:
20
22
22
20
2. Arithmetic operators:
+ Additive operator (also used for String concatenation)
− Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Core Java [BBA(CA): Sem. V] 1.9 Java Fundamentals
4. Logical operator: The logical && operator doesn't check the second condition if the
first condition is false. It checks the second condition only if the first one is true.
logical AND &&
logical OR ||
Program 1.6: Program for Logical Operator.
public class Logical
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);
System.out.println(a<b||a<c);
}
}
Output:
false
true
5. Ternary Operator: Java ternary operator is used as one line replacement for
if-then-else statement and used a lot in Java programming. It is the only conditional
operator which takes three operands.
Syntax: variable = (expression)? expressionIsTrue : expressionIsFalse;
Program 1.7: Program for ternary operator.
public class Ternary
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output:
2
Core Java [BBA(CA): Sem. V] 1.11 Java Fundamentals
1.2.5 Constant
• A value which is fixed and does not change during the execution of a program is
called Constants in java. In other words, Java constants are fixed (known as
immutable) data values that cannot be changed. Java supports various types of
constants.
Core Java [BBA(CA): Sem. V] 1.13 Java Fundamentals
Java Constants
1. Integer Constants:
• An integer constant is a sequence of digits without a decimal point. For example, 10
and -200 are integer constants. There are three types of integer constants. They are as
follows:
o Decimal integer: For example: 24, -55, 0
o Octal integer: Example: 0123,024
o Hexadecimal integer: Example: 0x23, ox5B
2. Real Constants:
• Real constants consist of a sequence of digits with fractional parts or decimal points.
These constants are also called floating-point constants. The valid examples of real
constants are 2.3, 0.0034, −0.75, 56.7, etc.
3. Character Constants:
• A single character constant (or simply character constant) is a single character
enclosed within a pair of single quote. The example of single-character constants are:
'5', 'x', ';' , ' ', etc
4. String Constants:
• A string constant is a sequence of characters within a pair of double-quotes. The
characters can be alphabets, special characters, digits, and blank spaces. The valid
examples of string constants are: "Hello Java", "1924", "?…!", "2+7", "X", etc.
Backslash Character Constants:
• Java provides some special backslash character constants that are used in output
methods. For example, the symbol 'n' which stands for newline character.
• There are various types of backslash character constants that are supported by java.
The list is given in the below table.
Core Java [BBA(CA): Sem. V] 1.14 Java Fundamentals
Constants Meaning
\\ backslash
• Lines 3-6 defines the so-called main() method, which is the entry point for program
execution. Again, the braces {......} encloses the body of the method, which contains
programming statements.
• In Line 5, the programming statement System.out.println("My First Java
Program") is used to print the string "My First Java Program" to the display console.
A string is surrounded by a pair of double quotes and contain texts. The text will be
printed as it is, without the double quotes. A programming statement ends with a
semi-colon (;).
• When we accepting input from console we need to BufferedReader and scanner class.
• BufferedReader improves performance by buffering input. The BufferedReader class
does have a method called readLine that does return a line of text as type by the user.
• In Java, the java.util.Scanner or Scanner class is one of them which allows the user to
read values of various types in java.
0 1 2 3 4 5 6 7 8 9 Indices
Array length is 10
Fig. 1.3: Arrays
• Here, type declares the base type of the array. The base type determines the data type
of each element that comprises the array. Thus, the base type for the array
determines what type of data the array will hold.
• For example, the following declares an array named month_days with the type "array
of int":
int month_days[];
Instantiating Arrays:
• As we mentioned earlier, Java arrays are objects, so to allocate memory for an array,
you need to instantiate the array using the new keyword. Here, is the syntax for
instantiating an array:
array_name = new datatype[size];
Where, size is an expression that evaluates to an integer and specifies the number of
elements in the array.
For example: month_days = new int[12];
Assigning Initial Values to Arrays:
• Java allows you to instantiate an array by assigning initial values when the array is
declared. To do this, you specify the initial values using a comma-separated list
within curly braces as given below:
datatype array_name[] = {value0, valuel, value2, … valueN};
Where, valueN is an expression that evaluates to the data type of the array and is the
value to assign to the element at index N.
• Note that, we do not use the new keyword and we do not specify a size for the array,
the number of elements in the array is determined by the number of values in the
initialization list.
• For example, following statement declares and instantiates an array of Numbers:
int nine = 9;
int[ ] Numbers = {2, 4, 3, 8, one, one + 2, 13, 14, 17, 18};
• Because 10 values are given in the initialization list, this array has 10 elements,
Notice that the values can be an expression, for example, one and one + 2.
Program 1.11: Program for one-dimensional (1D) array.
import java.util.*;
class arraydemo
{
public static void main(String args[])
{
int a[]={2,4,6,3,1};
System.out.println("Number of elements in array a: "+a.length);
System.out.println("Elements in array a:" + a.length);
Core Java [BBA(CA): Sem. V] 1.22 Java Fundamentals
[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]
[1] [0] [1] [1] [1] [2] [1] [3] [1] [4]
Left index
determines row
[2] [0] [2] [1] [2] [2] [2] [3] [2] [4]
[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]
1.7.2 String
1.7.2.1 String (Basic Functions)
• The strings in Java are treated as objects of type 'String' class. This class is present in
the package java.lang.
• This package contains two string classes:
1. String class, and
2. StringBuffer class.
• The string class is used when we work with the string which cannot change whereas
StringBuffer class is used when we want to manipulate the contents of the string.
• When we create object of String Class they are designed to be immutable. As these
objects are immutable, we can alias to a particular string for many time which we
want. Even if we alias the string class objects, they won't affect each other because
they are read only.
• We can use + operator to overload for string objects. Only two operators i.e. '+' & '+="
are overloaded for string classes. In Java, when we use + operator it allows us to
concatenate two or more number of strings together.
Example: String str = "Kal" + "pa" + "na";
Output: Kalpana
• In the above example, a method append() is called which creates the new String object
having "Kal" and concatenate with the next contents. It generally calls toString()
method which allows you to determine the String representation for objects and
classes which are created.
String Class Methods:
• The String class provides various methods that appear to modify strings.
• The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
Table 1.4: String Class Methods
Sr.
Methods Description
No.
1. char charAt(int index) This method returns char at (value for)
the particular index.
2. int length() This method returns string length.
3. static String format(String This method returns formatted string.
format, Object... args)
4. static String format(Locale l, This method returns formatted string
String format, Object... args) with given locale.
contd. …
Core Java [BBA(CA): Sem. V] 1.31 Java Fundamentals
1.7.2.2 StringBuffer
• It is a peer class which provides the functionality of strings. The string generally
represents fixed length, immutable character sequence whereas StringBuffer
represents growable and writeable character sequences.
• 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. 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().
Core Java [BBA(CA): Sem. V] 1.34 Java Fundamentals
Output:
Before formatting: 2021-08-03T07:40:54.347413
After formatting: 03-08-2021 07:40:54
• The "T" in the example above is used to separate the date from the time. You can use
the DateTimeFormatter class with the of Pattern() method in the same package to
format or parse date-time objects.
3. Math:
• java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
• Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same results.
This relaxation permits implementation with better-performance where strict
reproducibility is not required.
• If the size is int or long and the results overflow the range of value, the methods
addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an
ArithmeticException.
• For other arithmetic operations like increment, decrement, divide, absolute value,
and negation overflow occur only with a specific minimum or maximum value. It
should be checked against the maximum and minimum value as appropriate.
Math Methods:
• The java.lang.Math class contains various methods for performing basic numeric
operations such as the logarithm, cube root, and trigonometric functions etc. The
various java math methods are as follows:
Table 1.6: Basic Math methods
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest
value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to
second argument.
Math.signum() It is used to find the sign of a given value.
Math.ceil() It is used to find the smallest integer value that is greater
than or equal to the argument or mathematical integer.
contd. …
Core Java [BBA(CA): Sem. V] 1.39 Java Fundamentals
1.8.2 java.lang
• Provides classes that are fundamental to the design of the Java programming language.
The most important classes are object, which is the root of the class hierarchy, and
class, instances of which represent classes at run time.
Core Java [BBA(CA): Sem. V] 1.41 Java Fundamentals
23. Runtime: Every Java application has a single instance of class Runtime that allows
the application to interface with the environment in which the application is
running.
24. RuntimePermission: This class is for runtime permissions.
25. SecurityManager: The security manager is a class that allows applications to
implement a security policy.
26. Short: The Short class wraps a value of primitive type short in an object.
27. StackTraceElement: An element in a stack trace, as returned by
Throwable.getStackTrace().
28. StrictMath - Set1, Set2: The class StrictMath contains methods for performing
basic numeric operations such as the elementary exponential, logarithm, square
root, and trigonometric functions.
29. String - Set1, Set2: The String class represents character strings.
30. StringBuffer: A thread-safe, mutable sequence of characters.
31. StringBuilder: A mutable sequence of characters.
32. System: The System class contains several useful class fields and methods.
33. Thread: A thread is a thread of execution in a program.
34. ThreadGroup: A thread group represents a set of threads.
35. ThreadLocal: This class provides thread-local variables.
36. Throwable: The Throwable class is the superclass of all errors and exceptions in
the Java language.
37. Void: The Void class is an uninstantiable placeholder class to hold a reference to
the Class object representing the Java keyword void.
Program 1.24: Write a Java program to accept 'n' numbers through command line and
store all prime numbers into an array and display elements of array. [W-18]
import java.io.*;
public class ArrayDemo2
{
public static void main (String args[]) throws IOException
{
int j,s,i,k=0,m=0,n;
int r[]=new int[10] ;
int prime[]=new int[10] ;
int perfect[]=new int[10] ;
BufferedReader br=new BufferedReader(new InputStreamReader
(System.in));
System.out.println("Enter the Number of Elements :=>");
n=Integer.parseInt(br.readLine());
Core Java [BBA(CA): Sem. V] 1.43 Java Fundamentals
for (i=0;i<n;i++)
{
System.out.println("Enter the "+i+" Number of the Array :=> ");
r[i]= Integer.parseInt(br.readLine());
}
for(j=0;j<10;j++)
{
int flag=0;
if(r[j]==0||r[j]==1)
{
continue;
}
else
{
for(i=2;i<r[j];i++)
{
if(r[j]%i==0)
flag=1;
}
}
if(flag==0)
{
prime[k]=r[j];
k++;
}
}
System.out.println("\nPrime Numbers are");
for(i=0;i<k;i++)
{
System.out.print(prime[i]+" ");
}
}
}
Output:
Enter the Number of Elements :=>
3
Enter the 0 Number of the Array :=>
3
Core Java [BBA(CA): Sem. V] 1.44 Java Fundamentals
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i].compareTo(a[j])>0)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Sorted Cities are ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]+" ");
}
}
}
//To create object
public class TestCity
{
public static void main(String args[])
{
City obj=new City();
obj.display();
}
}
Output:
Enter how many city you want to enter : 5
Enter {i+1} element: Pune
Enter {i+1} element: Satara
Enter {i+1} element: Kolhapur
Enter {i+1} element: Nagpur
Enter {i+1} element: Pimpri
Sorted Cities are
Kolhapur Nagpur Pimpri Pune Satara
Core Java [BBA(CA): Sem. V] 1.47 Java Fundamentals
Summary
James Gosling is called Father of Java Programming. Java is an Object Oriented
Programming language means Java enables us not only to organize our program
code into logical unit called objects but also to take advantage of encapsulation,
inheritance and polymorphism and so on.
Various features of java includes Simple, Secure, Portable, Object-oriented,
Robust, Multithreaded, Architecture-neutral, Interpreted, High Performance,
Distributed, Dynamic.
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and Boolean.
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions.
Array is a data structure where we store similar elements. We can store only fixed
set of elements in a Java array. Types of array-1D array, 2D array.
A one-dimensional array having only one subscript. In Java 2D array is a matrix of
rows and columns.
Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Scanner is a class in java.util package used for obtaining the input of the
primitive types like int, double, etc. and strings.
A package is a collection of classes and interfaces.
Practice Questions
1. Which of these is necessary to specify at time of array initialization?
(a) Row (b) Column
(c) Both Row and Column (d) None of the mentioned
2. Which of these classes is not included in java.lang?
(a) Byte (b) Integer
(c) Array (d) Class
3. Which of these is a super class of wrappers Double & Integer?
(a) Long (b) Digits
(c) Float (d) Number
4. Which of the following package stores all the simple data types in java?
(a) lang (b) java
(c) util (d) java.packages
5. Which one of the following will declare an array and initialize it with five
numbers?
(a) Array a = new Array(5); (b) int [] a = {23,22,21,20,19};
(c) int a [] = new int[5]; (d) int [5] array;
Core Java [BBA(CA): Sem. V] 1.48 Java Fundamentals
6. Which Scanner class method is used to read integer value from the user?
(a) next() (b) nextInteger()
(c) nextInt() (d) readInt()
7. What is the output of this program?
class increment
{
public static void main(String args[])
{
int g = 3;
System.out.print(++g * 8);
}
}
(a) 25 (b) 24
(c) 32 (d) 33
8. Which is the correct syntax to declare Scanner class object?
(a) Scanner objectName= Scanner();
(b) Scanner objectName= new Scanner();
(c) Scanner objectName= Scanner(System.in);
(d) Scanner objectName= new Scanner(System.in);
9. How to format date from one form to another?
(a) SimpleDateFormat (b) DateFormat
(c) SimpleFormat (d) DateConverter
10. How to format date from one form to another?
(a) SimpleDateFormat (b) DateFormat
(c) SimpleFormat (d) DateConverter
Answers
1. (a) 2. (c) 3. (d) 4. (a) 5. (b) 6. (c) 7. (c) 8. (d) 9. (a) 10. (a)
Practice Questions
Q.I Answer the following questions in short.
1. What is Java?
2. Why Java is platform-neutral language?
3. Explain the secure feature of Java.
4. Why Java is called portable?
5. How to compile Java program?
6. How to run Java program?
Core Java [BBA(CA): Sem. V] 1.49 Java Fundamentals
Winter 2018
1. Describe any two features of Java programming language. [2 M]
Ans. Refer to Section 1.1.2.
2. What are differences between String and StringBuffer class? [2 M]
Ans. Refer to Section 1.7.2.2.
3. "Import statement is not essential in java." True/False. Justify. [2 M]
Ans. Refer to Section 1.3.
4. Explain Array in Java. How does it differ from C++? [4 M]
Ans. Refer to Section 1.7.1.
5. Write a Java program to accept 'n' numbers through command line and store all
prime numbers into an array and display elements of array. [4 M]
Ans. Refer to Program 1.24.
6. Write a Java Program that displays the number of non-vowels in the given
word. [4 M]
Ans. Refer to Program 1.25.
Summer 2019
1. Does the order of public static void matter in main method. [2 M]
Ans. Refer to Section 1.3.
2. Write a java program to accept n names of cities from users and display them in
descending order. [4 M]
Ans. Refer to Program 1.26.
2…
Classes, Objects and Methods
Learning Objectives…
▣ To understand Basic Concepts of Objects and Classes.
▣ To study Constructors and Methods.
▣ To learn Nested Classes, Inner Class, Anonymous Inner Class in Java.
▣ To learn New Operator, this and static keyword, finalize() method.
Statement Effect
mybox Height
Depth
Box object
Fig. 2.2: Object Instantitation
(iii) Accessing Class Members:
o The dot operator (.) or member selection operator is used to access the instance
variables of the class.
o We cannot access the instance variables outside of the class without referring to
the object.
o Member access follows the following syntax:
objectname.variablename
Here, the objectname is the name of the object and variablename is name of the
instance variable.
o So, the instance variables of the class Employee can be accessed as,
Employee.E_id=1234;
Employee.salary=30000;
Program 2.2: Program for declaration and instantiation of object.
class MyObject
{
public void getMessage()
{
System.out.println("Object Created and Functioned Called");
}
public static void main(String args[])
{
MyObject x = new MyObject(); //x is declared and initialized with an
instance of MyObject
x.getMessage();
}
}
Output:
Object Created and Functioned Called
Core Java [BBA(CA): Sem. V] 2.5 Classes, Objects and Methods
0011
0001 Class1 Class1
Class1 var1 0011 var1
String x 1011 x "hello"
0010
int y 15 y 15
int var2 25 var2 25
1111
1011
Type3 var3 ? var3 ?
String
"hello"
h e l l o
2.3 CONSTRUCTOR
• 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.
• 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.3: 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;
}
}
Core Java [BBA(CA): Sem. V] 2.7 Classes, Objects and Methods
Output:
Roll no of student is 1
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:
• Constructor can take value, value is called as argument. 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.
Program 2.5: Program for parametrized constructor.
class StudentInfo
{
int rollno;
int marks1;
int marks2;
int total;
StudentInfo(int roll_no,int m1,int m2) //Parameterized constructor
{
rollno=roll_no;
marks1=m1;
marks2=m2;
}
Core Java [BBA(CA): Sem. V] 2.10 Classes, Objects and Methods
2.4 METHOD
Methods in Java:
• A Java method is a collection of statements that are grouped together to perform a
certain task.
• Method describes behaviour of an object. A method is a collection of statements that
are group together to perform an operation.
• The only required elements of a method declaration are the method's return type,
name, a pair of parentheses (), and a body between braces {}.
• More generally, method declarations have following components, in order:
1. Modifiers: Such as public, private, default, protected.
2. The return type: The data type of the value returned by the method, or void if the
method does not return a value.
3. The method name: The rules for field names apply to method names as well, but
the convention is a little different.
4. The parameter list in parenthesis: A comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses (). If there are no
parameters, you must use empty parentheses.
5. The method body, enclosed between braces: The method's code, including the
declaration of local variables, goes here.
Syntax:
return_type methodName(parameter_list)
{
//body of method …
}
Program 2.7: Program for the method.
public class Main
{
public String getName(String st)
{
System.out.println("Kamil Ajmal Khan");
}
public static void main(String[] args)
{
Main Obj=new Main();
Obj.getName();
}
}
Output:
Kamil Ajmal Khan
Core Java [BBA(CA): Sem. V] 2.13 Classes, Objects and Methods
{
overload ob1 = new overload();
overload ob2 = new overload(10, 5);
overload ob3 = new overload(25.6, 80.5);
ob1.display();
ob2.display();
ob3.display();
}
}
Output:
5
28 for ob1
10
for ob2
5
25
80 for ob3
• Here, for object ob1, the default constructor is called. For object ob2 the
parameterized constructor "overload (int p, int q)" is called, whereas for object ob3,
the parameterized constructor "overload (double x, double y)" is called. But because of
the data type of m and n are int, the value of x and y i.e. 25.6 and 80.5 get truncated to
integer part.
Table 2.2: Difference between Constructor and Method
Sr. No. Constructor Method
1. Constructor is used to initialize the Method is used to expose behaviour of
state of an object. an object.
2. Constructor name must be same as Method name may or may not be
the class name. same as class name.
3. Constructor is invoked implicitly. Method is invoked explicitly.
4. The java compiler provides a default Method is not provided by compiler in
constructor if you don't have any any case.
constructor.
5. Constructor must not have return Method must have return type.
type.
2.4.2 Recursion
• The process in which a function calls itself directly or indirectly is called recursion
and the corresponding function is called as recursive function. Using recursive
algorithm, certain problems can be solved quite easily. Examples of such problems are
Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,
etc.
Core Java [BBA(CA): Sem. V] 2.15 Classes, Objects and Methods
State
this
Behaviour
Reference
variable
Object
Fig. 2.5: this keyword
Core Java [BBA(CA): Sem. V] 2.19 Classes, Objects and Methods
• 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.
• 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, 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.12: 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);
}
}
Core Java [BBA(CA): Sem. V] 2.20 Classes, Objects and Methods
/* 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
Static Methods:
• The static keyword is used to create methods that will exist independently of any
instances created for the class.
• Static methods do not use any instance variables of any object of the class they are
defined in. Static methods take all the data from parameters and compute something
from those parameters, with no reference to variables.
Program 2.14: Java program to use of static methods.
public class CountInstance
{
private static int numInstances = 0;
protected static int getCount()
{
return numInstances;
}
private static void addInstance()
{
numInstances++;
}
CountInstance()
{
CountInstance.addInstance();
}
public static void main(String[] arguments)
{
System.out.println("Starting with " + CountInstance.getCount()
+ " instances");
for (int i = 0; i < 500; ++i)
{
new CountInstance();
}
System.out.println("Created " + CountInstance.getCount()
+ " instances");
}
}
Output:
Starting with 0 instances
Created 500 instances
Core Java [BBA(CA): Sem. V] 2.22 Classes, Objects and Methods
Program 2.15: Program using static method which maintain 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);
}
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...");
Core Java [BBA(CA): Sem. V] 2.23 Classes, Objects and Methods
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: 1000.0
• The Account class in program 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.5.4 finalize() Method [W-18]
• When the reference of an object is not exists, then it is assumed that object is no
longer needed. And the memory which is occupied by the object is reclaimed. So
garbage collector automatically frees the memory resources used by the objects.
• But sometimes the object may hold some non-java resources such as file handle or
window character font. The garbage collector cannot free these resources.
• In order to free these resources we need finalize() method. This is called finalization.
By using the finalization, we can define specific action that will occur when an object
being destroyed by the garbage collector.
• To add a finalizer to our class, we have to define it as a finalize() method.
• The finalize() method has following general form/Syntax:
protected void finalize()
{
// finalization code here …
}
Here, the keyword protected is a specifier that prevents access to finalize() by code
defined outside its class.
Core Java [BBA(CA): Sem. V] 2.24 Classes, Objects and Methods
• The garbage collector runs periodically. It checks for objects which are no longer
referenced by any running state or indirectly through any running object. Before it
gets free, the java run-time calls the finalize() method.
• Protected keyword prevents the access of finalize() code from outside class. Java does
not support destructors.
Program 2.16: Following example shows that the objects allocated external resources
should provide a finalize method that cleans them up or class will create a resource leak.
import java.util.*;
public class ObjectfinDemo extends GregorianCalendar
{
public static void main(String[] args)
{
try
{
// create a new ObjectfinDemo object
ObjectfinDemo cal = new ObjectfinDemo();
// print current time
System.out.println("" + cal.getTime());
// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
}
catch (Throwable ex)
{
ex.printStackTrace();
}
}
}
Output:
Sat Sep 22 00:27:21 EEST 2014
Finalizing...
Finalized.
Instance
Inner class
Non-Static Local
Inner class
Inner class
Anonymous
Static Inner class
Fig. 2.6: Types of Nested Classes
Types of Nested Classes:
• There are two types of nested classes, Non-static and Static nested classes. The Non-
static nested classes are also known as Inner Classes.
(i) Non-static Nested Class:
• The nested class for which static modifier is not applied, such a class is known as non-
static nested class.
• This class can also be refer as inner class, because it is fully within the scope of its
enclosing class.
• It has access to all the variables and methods of its outer class or enclosing class.
• The general form/syntax of non-static definition is as follows:
public class OutClass
{
//Members of outclass
public class InClass //Nested class
{
//Members of inclass
}
//More members of outclass
}
• You can't create any object of InClass, without creating any object of OutClass. For
example, an object of Outclass can be created as:
OutClass Outobj = new OutClass();
• After creating an object of OutClass, an object of InClass will not be automatically
created. To refer a nested class type, we must have to use the name of enclosing class
as a qualifier.
• For example, to create an object of InClass:
OutClass.InClass InObj = OutObj.new InClass();
• That means an object of the nested class is created in the context of an object of
enclosing class.
• But non-static methods that are members of enclosing class can refer the nested class
without any qualifier.
• The main purpose of nested classes is for grouping a set of related classed under the
single enclosing class.
Core Java [BBA(CA): Sem. V] 2.26 Classes, Objects and Methods
• Following program, illustrates the creation of an object and calling method of inner
class inside outer class. It also shows, how to create and access an object of inner class
outside the outer class.
Program 2.17: Program for Non-static nested class.
class OutClass
{
int a = 5;
void outmethod()
{
//creation of an object of inner class
InClass InObj = new InClass();
InObj.InMethod();
}
class InClass
{
int b = 10;
void Inmethod()
{
//Member of outerclass can refer here
System.out.println("a of OutClass =" + a);
System.out.println("b of InClass =" + b);
}
} //end of inclass
}//end of outclass
Class TestNested1
{
public static void main(String args[])
{
//create object of outclass
Outclass Outobj=new Outclass();
//Call to method of outclass
OutObj.Outmethod();
//Creation of InnerClass Object
OutClass.InClass InObj = OutObj.new InClass();
//Calling a method of inner class
InObj.Inmethod();
}
}
Core Java [BBA(CA): Sem. V] 2.27 Classes, Objects and Methods
Output:
a of OutClass = 5
b of InClass = 10
a of OutClass = 5
b of Inclass = 10
(ii) Static Nested Class:
• A class which is defined as a static inside other enclosing class, such a class is called
as Static Nested Class.
• This type of nested class, cannot refer any member of its enclosing class directly, that
means it must access members of enclosing class through an object. This is shown in
following program.
Program 2.18: Program for Static Nested Class.
class Outclass
{
int a = 5;
public static class InClass
{
int b = 10;
void Inmethod()
{
//Member of enclosing class
//Should refer through its object
OutClass.OutObj=new OutClass();
System.out.println("a of Outclass=" + OutObj.a);
System.out.println("b of Inclass=" + b);
}
}//end of Inclass
}//end of Outclass
class TestNested 2
{
public static void main(String args[])
{
//Nested class object can be created
//Without creating enclosing classobject
Outclass.Inclass Inobj=new Outclass.Inclass();
Inobj.Inmethod();
}
}
Output:
a of Outclass = 5
b of Inclass = 10
Core Java [BBA(CA): Sem. V] 2.28 Classes, Objects and Methods
Summary
A Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements.
Object is the physical as well as logical entity whereas class is the logical entity
only.
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.
We know that constructors are used to initialize an object when it is declared. This
process is referred as initialization.
Core Java [BBA(CA): Sem. V] 2.30 Classes, Objects and Methods
Inner classes are syntactic feature that was added to Java in JDK 1.1. They provide
a convenient way for a developer to define classes within the body of another
class.
Java inner class or nested class is a class i.e. declared inside the class or interface.
An anonymous inner class can be useful when making an instance of an object
with certain "extras" such as overloading methods of a class or interface, without
having to actually subclass a class.
Practice Questions
Q.1 Answer the following Questions in short.
1. What is a method?
2. What is method overloading?
3. What is inner class?
Core Java [BBA(CA): Sem. V] 2.32 Classes, Objects and Methods
Summer 2019
1. Justify True/False Java is not fully object oriented. [2 M]
Ans. Refer to Section 2.1.
3…
Inheritance, Package and
Collection
Learning Objectives…
▣ To understand Basic Concepts of Inheritance.
▣ To study Types of inheritance.
▣ To learn Inheriting Data members and Methods.
▣ To study Use of super and final keyword.
▣ To study abstract class.
▣ To study Interfaces.
▣ To learn about Packages.
▣ To study Creating, Accessing and using Packages.
▣ To study about Collection.
• A class that is derived from any another class is called a subclass or derived class or
extended class or child class. The class from which a subclass is derived is called super
class or base class or parent class.
• Fig. 3.1 illustrating a class called Food, which has two subclasses called Pizza and
Pasta
Food
Pizza Pasta
Output:
Contents of super: i and j: 5 12
Contents of sub: i and j: 11 13 k: 17
Sum of i, j and k in sub: i+j+k: 41
• Above program 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.
3.1.2 Types of Inheritance
• Fig. 3.2 shows various types of inheritance in Java.
Types of inheritance
Inherits from
Second
• Here, 'Second' class is inherited from 'First' class. In 'Second' class, the member
method 'Square()' has been called in an expression. After creating the object of the
'Second' class, we called the method 'init()' of the 'First' class.
2. Multilevel Inheritance:
• We can create any layers/levels in the inheritance as we want, this is called Multilevel
Inheritance. This hierarchy can be created at any level of inheritance.
• When a subclass is derived from a derived class then this mechanism is known as the
Multilevel Inheritance.
• The derived class is called the subclass or child class for its parent class and this
parent class works as the child class for it's just above (parent) class.
• The general form/syntax is,
class A
{
……
……
……
}
class B extends A
{
……
……
……
}
class C extends B
{
……
……
……
}
• Class A may be the superclass for Class B and Class B may be the superclass for Class C
and Class C may be the superclass for Class D. In above case, Class B inherits all
properties of Class A, Class C inherits all properties of Class B and Class D inherits all
properties of Class C.
Core Java [BBA(CA): Sem. V] 3.7 Inheritance, Package and Collection
A is superclass class A
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
B C D
Student
class MyClass
{
public void methodB()
{
System.out.println("Method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
Method of Class A
Method of Class A
Method of Class A
Sports(int i)
{
System.out.println("Sports Parameterized Constructor Called.....");
this.i = i;
}
}
class FootBall extends Sports
{
FootBall()
{
System.out.println("\n FootBall Class Default Constructor Called
.....");
}
}
public class Temp
{
public static void main(String[] args)
{
FootBall obj = new FootBall();
}
}
Output:
Sports Default Constructor Called......
FootBall Class Default Constructor Called.....
Output:
Enjoy DryFruits
i = 10
Dry Friut: = Almond.....
j = 20
Dry Friut: = Pista....
k = 30
Dry Friut: = Walnut....
Output:
__________________
Enjoy Dairy Milk.....
Kuch meetha ho jay. DairyMilk
______________________
Enjoy Dairy Milk.....
Enjoy Dairy Milk Silk....
Kuch meetha ho jay. DairyMilk_Silk
_____________________
Enjoy Dairy Milk.....
Enjoy Dairy Milk Silk....
DairyMilk_Hazelnut..... Enjoyed
Kuch meetha ho jay. DairyMilk_Hazelnut
Primary(int a)
{
cal = a;
}
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);
}
}
public class SuperUse2
{
public static void main(String args[])
{
Secondary s = new Secondary(10,20);
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.
Core Java [BBA(CA): Sem. V] 3.18 Inheritance, Package and Collection
class TestSuper2
{
pubic static void main(String args[])
{
//create object of subclass
SubClass myobj = new SubClass(10,4);
//call display method
myobj.display();
}
}
Output:
n in SuperClass = 10
n in SubClass = 4
• In similar way, super keyword can also be used to call methods of superclass that are
hidden by subclass due to same names. This is called as Method Overriding.
• The above program segment contains error since we tried to extend a final class.
Program 3.13: Program using '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:
error: cannot inherit from final Demo1
3.6 INTERFACE
• An interface in Java is a blueprint of a class. It has static constants and abstract
methods only.
• An interface is a way of describing what classes should do, without specifying how
they should do it.
• There are mainly three reasons to use interface. They are given below:
1. It is used to achieve fully abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
• A class can implement more than one interface. In Java, an interface is not a class but
a set of requirements for the class that we want to conform to the interface.
• All the methods of an interface are by default public. So, it is not required to use the
keyword public when declaring a method in an interface.
• Interfaces can also have more than one method. Interfaces can also define constants
but do not implement methods.
Core Java [BBA(CA): Sem. V] 3.23 Inheritance, Package and Collection
• To make a class implement an interface, we must declare that the class intends to
implement the given interface and we need to supply definitions for all methods
using the implements keyword.
• When an interface has been defined, any of the classes can implement that interface.
• The general form/syntax of the class that includes an implements clause is:
class classname extends superclass implements interface
{
//class body …
}
Program 3.14: Program of interface implementation. [W-18]
import java.io.*;
interface conversions
{
double GM_TO_KG = 1000;
double gmtokg(double gm);
double kgtogm(double kg);
}
class convert implements conversions
{
public double gmtokg(double gm)
{
return gm/GM_TO_KG;
}
public double kgtogm(double kg)
{
return kg*GM_TO_KG;
}
}
public class ImplIface1
{
public static void main(String args[])
{
convert ConvObj = new convert();
conversions c;
c = ConvObj;
System.out.println("2000 gm =" + c.gmtokg(2000) + " kg ");
System.out.println("50 kg = " + c.kgtogm(50) + " gm ");
}
}
Output:
2000 gm = 2.0 kg
50 kg = 50000.0 gm
Core Java [BBA(CA): Sem. V] 3.25 Inheritance, Package and Collection
implements extends
class Interface
(a) (b)
Fig. 3.8: Multiple Inheritance in Java
Program 3.17: Program to implementation of multiple inheritance using Interface.
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;
}
Core Java [BBA(CA): Sem. V] 3.29 Inheritance, Package and Collection
void print_gross_sal()
{
System.out.println("Gross sal = " + gsal);
}
}
interface taxes
{
float ptax = 200f;
float itaxpercent = 20f;
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;
print_ename();
print_gross_sal();
System.out.println("taxes=" + tax);
System.out.println("Net Sal = " + nsal);
}
}
public class ImplIface6
{
public static void main(String args[ ])
{
salary empsal = new salary();
empsal.get_ename("Adhiraj");
empsal.calc_gross_sal(9100,50,10);
empsal.display();
}
}
Core Java [BBA(CA): Sem. V] 3.30 Inheritance, Package and Collection
Output:
Name = Adhiraj
Gross sal = 14560.0
taxes = 3112.0
Net Sal = 14560.0
3.8.1 Nested Interfaces
• An interface which is declared within another interface or class is known as Nested
Interface.
• The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred by the outer interface or class. It
cannot be accessed directly.
• Nested interface must be public if it is declared inside the interface but it can have
any access modifier if declared within the class.
• Nested interfaces are declared static implicitly.
• Syntax of nested interface which is declared within the interface:
interface interface_name
{
...
interface nested_interface_name
{
...
}
}
• Syntax of nested interface which is declared within the class:
class class_name
{
...
interface nested_interface_name
{
...
}
}
Program 3.18: Program declare the Nested Interface and how we can access it.
interface ShowableExe
{
void show();
interface Message
{
void msg();
}
}
Core Java [BBA(CA): Sem. V] 3.31 Inheritance, Package and Collection
• Since, we are accessing the data members of the subclass that are not overridden, the
data members of the parent class will always be invoked.
Program 3.21: Program using Runtime Polymorphism.
class Student
{
String name="Om";
}
class Monitor extends Student
{
String name="Yash";
public static void main(String args[])
{
Student s=new Monitor();
System.out.println(s.name);
}
}
Output: Om
2. Runtime Polymorphism with Multilevel Inheritance:
• In method overriding, a subclass overrides a method with the same signature as that
of in its superclass. Reference type check is made during compile time. We can
override a method at any level of multilevel inheritance. See the program below to
understand the concept.
Program 3.22: Runtime Polymorphism with Multilevel inheritance.
class Electronics
{
void function()
{
System.out.println("Made for various purpose");
}
}
class Phone extends Electronics
{
void function()
{
System.out.println("Display,Voice");
}
}
Core Java [BBA(CA): Sem. V] 3.35 Inheritance, Package and Collection
Consultant
Part-time
Full-time
• A factory method is the method that returns the instance of the class.
• In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
• A Java package is a mechanism for organizing Java classes. Package are used in Java,
in-order to avoid name conflicts and to control access of class, interface and
enumeration etc.
• A package can be defined as, "a group of similar types of classes, interface,
enumeration and sub-packages".
• A package does not contain the source code of any type of Java file. Each Java source
code file is a collection of one or more classes, or one or more interface with their
members.
3.13.1 Packages Concept
• A package is a collection of classes and interfaces.
• A package does not contain the source code of any type of Java file. Each Java source
code file is a collection of one or more classes, or one or more interface with their
members.
• After compilation, a separate class file is created for individual class or interface,
either these are part of one Java file or stored in individual file.
• That class file (byte code) is placed in a particular related package using a package
declaration.
3.13.2 Creating user defined Packages [S-19]
• Java package created by user to categorized classes, interface and enumeration.
• Declaration Syntax:
package <package name>;
• The package declaration statement must be the first statement of the source file. The
package name is stored in the byte code (class file).
• The dot (.) notation is used to distinctively spot (identify) the package name in the
package hierarchy. One naming convention for a package is that, package name is
written in all lowercase. It will escape the confliction with classes and interfaces
name.
• Example:
package mypck;
• Here, mypck is the package name. Moreover a file belonging to same package can
include the same package name.
• We can also create a hierarchy of packages, i.e. package within a package called
subpackage for further classification and categorization of classes and interfaces.
package mypck.mypck2.mypck3;
• Here, mypck2 is a subpackage in package mypck, mypck3 is a subpackage in
subpackage mypck2. If there is no package declaration in a source file, then the
compiled file is stored in the default package (unnamed package), and that is the
current working directory.
Core Java [BBA(CA): Sem. V] 3.42 Inheritance, Package and Collection
Class is member of
package Class X
mypck1.mypck2.mypck3
Fig. 3.10: Package Hierarchy
• In the above package hierarchy class X is identified by the name
mypckl.mypck2.mypck3.
3.13.2.1 Accessing and Using Packages
• There are three ways to access the package from outside the package i.e., import
package.*; import package.classname; fully qualified name.
1. Using packagename:
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
Program 3.26: Program for package that import the packagename. [W-18]
//Program save by X.java
package pkg;
public class X
{
public void msg(){System.out.println("Hello, Take Care");}
}
//save by y.java
package mypkg;
import pkg.*;
class Y
{
public static void main(String args[])
{
X obj = new X();
obj.msg();
}
}
Output:
Hello, Take Care
Core Java [BBA(CA): Sem. V] 3.43 Inheritance, Package and Collection
2. Using packagename.classname:
• If you import package.classname then only declared class of this package will be
accessible.
Program 3.27: Program Using packagename.classname.
//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
3. Using fully qualified name:
• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
Program 3.28: Program using fully qualified name.
//save by X.java
package pkg;
public class X
{
public void msg() {System.out.println("Hello");}
}
//save by Y.java
package mypkg;
Core Java [BBA(CA): Sem. V] 3.44 Inheritance, Package and Collection
class Y
{
public static void main(String args[])
{
pack.X obj = new pack.X(); //Using fully qualified name
obj.msg();
}
}
Output:
Hello
• Java Collections is the standard way of groups of objects that are used by your
program. Collections were not part of the initial Java release. It was added by J2SE 1.2.
Before Collections framework, Java had ad hoc classes such as Dictionary, Vector,
Stack and Properties for manipulating groups of objects.
• Collections altered the architecture of many utility classes. But it did not deprecate
any of the previously used classes. It simply provides a better way of doing things.
3.14.1 Collection Framework
• The Collections Framework defines several interfaces. Collections interfaces
determine the fundamental nature of Collection classes.
• Goals of Collection Framework:
o Framework had to be high performance. Implementations for fundamental
collections are highly efficient.
o Framework had to allow different types of collections to work in a similar
manner.
o Extending and / or adapting a collection had to be easy. Entire Collection
Framework is built upon a set of standard interfaces. Java has provided several
implementations of these interfaces like LinkedList, HashSet, TreeSet etc. You can
use these implementations as it is. But you can implement your own Collection as
well.
o Java provides mechanism for integrating standard arrays into the Collections
Framework.
• Algorithm is another important part of Collection mechanism. They provide standard
means of manipulating Collections.
• Iterator is also very closely associated with Collections Framework. Iterator interface
offers a standard way of accessing elements within a collection.
• Framework also defines several map interfaces and classes. Map stores key and value
pairs. Maps cannot be called as Collections though they come under Collections
Framework. But you can obtain Collection view of Map.
3.14.2 Interfaces: Collection, List, Set
boolean addAll(int index, It adds all elements of c into the invoking list at
Collection<? extends E> c) given index passed in index parameter. Any
previous elements at or after the point of insertion
are shifted up. Thus, elements are not overwritten.
Method returns true if the invoking list changes and
returns false otherwise.
E get(int index) Returns the object E stored at the specified index
within the invoking collection.
int indexOf(Object obj) Returns the index of the first instance of obj in the
invoking list. If obj is not an element of the list, −1 is
returned.
int lastIndexOf(Object obj) Returns the index of the last instance of obj in the
invoking list. If obj is not an element of the list, −1 is
returned.
Listlterator<E> Returns an iterator to the beginning of the invoking
listlterator( ) list.
Listlterator(E> Returns an iterator that starts at the specified index
listlterator(int index) of the invoking list.
E remove(int index) Removes the element at the specified position index
from the invoking list and returns the removed
element. The resulting list is compressed. This
means, the indexes of subsequent elements are
decremented by one.
E set(int index, E obj) Assigns obj to the position specified by index within
the invoking list.
List<E> subList(int start, int Returns a list which includes elements from start to
end) (end −1) in the invoking list. Elements in the
returned list are also referenced by the invoking
object.
ListIterator l1 = k.listIterator();
System.out.println("Iterates in Forward direction");
while (l1.hasNext())
System.out.print(l1.next()+" ");
System.out.print("\n\nIterates in backward direction");
while (l1.hasPrevious())
System.out.print(l1.previous()+" ");
}
}
Output:
Iterates in Forward direction
111 222 333
Iterates in backward direction 333 222 111
while(e1.hasMoreElements())
{
System.out.println(e1.nextElement());
}
}
}
Output:
New Elements In Vector ........
1000
2000
3000
true
import java.util.*;
public class LinkedlistDemo
{
public static void main(String args[])
{
LinkedList linkedlist1 = new LinkedList();
linkedlist1.add("Item 2");
linkedlist1.add("Item 3");
linkedlist1.add("Item 4");
linkedlist1.add("Item 5");
linkedlist1.addFirst("Item 0");
linkedlist1.addLast("Item 6");
linkedlist1.add(1, "Item 1");
System.out.println(linkedlist1);
linkedlist1.remove("Item 6");
System.out.println(linkedlist1);
linkedlist1.removeLast();
System.out.println(linkedlist1);
System.out.println("\nUpdating linked list items");
linkedlist1.set(0, "Red");
linkedlist1.set(1, "Blue");
linkedlist1.set(2, "Green");
linkedlist1.set(3, "Yellow");
linkedlist1.set(4, "Purple");
System.out.println(linkedlist1);
}
}
Output:
[Item 0, Item 1, Item 2, Item 3, Item 4, Item 5, Item 6]
[Item 0, Item 1, Item 2, Item 3, Item 4, Item 5]
[Item 0, Item 1, Item 2, Item 3, Item 4]
Updating linked list Items
[Red, Blue, Green, Yellow, Purple]
• For example,
Integer intAr[] = new Integer[al.size()];
intAr = al.toArray(intAr);
3.14.4.3 Vector
• Vector implements dynamic array. It is similar to ArrayList with two major
differences. Vector class is re-engineered to extend AbstractList and it implements
List interface. It is also re-engineered to implement Iterable interface. Means, Vector
can have its elements traversed through for loop. Vector is fully compatible with
collections.
Table 3.9: Difference between ArrayList and Vector
ArrayList Vector
1. It's faster since it's not synchronized. It's slower since it's synchronized.
2. If the number of elements exceeds If the total number of elements exceeds
from its capacity 50% of current array than its capacity it increases 100% of
size is increased. array size.
void insertElementAt(E element, int index) Adds element to the vector at the location
specified by index.
boolean isEmpty( ) Returns true if the vector is empty, and
returns false if it contains one or more
elements.
E lastElement( ) Returns the last element in the vector.
int lastindexOf(Object element) Returns the index of the last occurrence of
element. If the object is not in the vector,
−1 is returned.
int lastindexOf(Object element, int start) Returns the index of the last occurrence of
element before start. If the object is not in
that portion of the vector, −1 is returned.
void removeAllElements( ) Empties the vector. After this method
executes, the size of the vector is zero.
boolean removeElement(Object element) Removes element from the vector. If more
than one instance of the specified object
exists in the vector, then it is the first one
that is removed. Returns true if successful
and false if the object is not found.
contd. …
Core Java [BBA(CA): Sem. V] 3.61 Inheritance, Package and Collection
Program 3.36: The following program demonstrates Vector class. A program uses a
vector to store various types of numeric objects. It demonstrates several legacy methods
defined by the Vector class. W-18 S-19
File: VectorDemo.java
import java.util.*;
public class VectorDemo
{
public static void main(String args[])
{
Vector vector = new Vector(5);
System.out.println("Size: " + vector.size());
System.out.println("Capacity: " + vector.capacity());
vector.addElement(new Integer(0));
vector.addElement(new Integer(1));
vector.addElement(new Integer(2));
vector.addElement(new Integer(3));
vector.addElement(new Integer(4));
vector.addElement(new Integer(5));
vector.addElement(new Integer(6));
vector.addElement(new Integer(5));
vector.addElement(new Integer(6));
Core Java [BBA(CA): Sem. V] 3.62 Inheritance, Package and Collection
vector.addElement(new Double(3.14159));
vector.addElement(new Float(3.14159));
System.out.println("Capacity: " + vector.capacity());
System.out.println("Size: " + vector.size());
System.out.println(vector);
System.out.println("First item: " + (Integer)vector.firstElement());
System.out.println("Last item: " + (Float) vector.lastElement());
if(vector.contains(new Integer(3)))
System.out.println("Found 3");
}
}
Output:
Size: 0
Capacity: 5
Capacity: 20
Size: 11
[0, 1, 2, 3, 4, 5, 6, 5, 6, 3.14159, 3.14159]
First Item: 0
Last Item: 3.14159
Found 3
3.14.4.4 HashSet
• HashSet extends AbstractSet and implements the Set interface. It creates a collection
that uses a HashTable for storage. HashTable stores elements by using Hashing
mechanism.
• Hashing: The information about the key value of each and every element is used to
define a hash code. This hash code is used as an index where the data associated with
the key value is stored. Conversion of key value into hashcode is performed
automatically. You can not see the hash code by itself.
• Advantage of hashing is, the execution time of manipulation of elements remains
constant even for large set of elements.
HashSet Constructors:
1. HashSet(): Constructs a default hash set.
2. HashSet(Collection<? extends E> c): Hash set initialization using elements of c.
3. HashSet(int capacity): Initializes the capacity of hash set (Default is 16).
4. HashSet(int capacity, float fillRatio): Initializes capacity and fill ratio. The fill
ratio must be between 0.0 and 1.0. It determines how full the hash set can be before it
is resized upward. Constructors that do not accept fillRatio, default 0.75 fillRatio is
used. Hash set does not provide extra methods other than defined by its super classes
and interfaces. Hash set does not guarantee the order of elements.
Core Java [BBA(CA): Sem. V] 3.63 Inheritance, Package and Collection
Program 3.38: Define an abstract class shape with abstract method area() and volume().
Write a java program to calculate area and volume of cone and cylinder. [S-19]
import java.util.*;
abstract class Shape
{
final float PI=3.14f;
Scanner s=new Scanner(System.in);
abstract void area();
abstract void volume();
}
class Cylinder extends Shape
{
float a,r,h,v;
Core Java [BBA(CA): Sem. V] 3.64 Inheritance, Package and Collection
void accept()
{
System.out.println("Please enter Radius, Height ");
r=s.nextFloat();
h=s.nextFloat();
}
void area()
{
a = (2*PI*r*h)+(2*PI*r*r);
System.out.println("Area of Cylinder :"+a);
}
void volume()
{
v=PI*r*r*h;
System.out.println("Volume of Cylinder :"+v);
}
}
class Cone extends Shape
{
float a,r,h,v;
void accept()
{
System.out.println("Please Radius, Height ");
r=s.nextFloat();
h=s.nextFloat();
}
void area()
{
a=PI*r*(r+(float)Math.sqrt(h*h+r*r));
System.out.println("Area of Cone is :"+a);
}
void volume()
{
v=PI*r*r*(h/3);
System.out.println("Volume of Cone is :"+v);
}
}
Core Java [BBA(CA): Sem. V] 3.65 Inheritance, Package and Collection
class Temp
{
public static void main(String args[])
{
Cylinder s1=new Cylinder();
Cone s2=new Cone();
s1.accept();
s2.accept();
s1.area();
s1.volume();
s2.area();
s2.volume();
}
}
Output:
java Temp
Please Radius, Height
12
23
Please Radius, Height
67
45
Area of Cylinder : 2637.6
Volume of Cylinder : 10399.68
Area of Cone : 31075.094
Volume of Cone : 211431.9
Program 3.39: Write a package for games in java, which have two classes Indoor and
Outdoor. Use a function display() to generate the list of players for specific games.
(Use parameterized constructor, finalize() method and array of objects). [W-18, S-19]
Indoor.java
package games;
public class Indoor
{
protected String player;
public Indoor(){ }
public Indoor(String p)
{
player = p;
}
Core Java [BBA(CA): Sem. V] 3.66 Inheritance, Package and Collection
Output:
java testgame.Games
How many indoor players you want
2
How many outdoor players you want
2
Enter indoor player name :
Shreyas
Enter indoor player name :
Pranay
Enter outdoor player name :
Ira
Enter outdoor player name :
Siddhi
Indoor Players :
Shreyas
Pranay
Outdoor Players :
Ira
Siddhi
Summary
Object Oriented Programming (OOP) allows you to create new class based on a
class that has been already defined using inheritance.
Inheritance is one of the most dominant and vital feature of OOP because it
supports the hierarchical classifications, reusability of class; and defined to
specialization. Types: Single Inheritance, Multilevel Inheritance, Hierarchical
Inheritance, Multiple Inheritance, Hybrid Inheritance
Object oriented programming allows classes to inherit commonly used state and
behavior from other classes.
A subclass inherits the accessible data fields and methods from its superclass, but
the constructors of the superclass are not inherited in the subclass. They can only
be invoked from constructors of the subclass using the keyword super.
'super' keyword is used by subclass to refer its immediate superclass. The word,
'final' is a keyword in Java Language.
The 'final' keyword is used in several different contexts with the variable
declaration, methods and classes as a modifier meaning that what it modifies
cannot be changed in some sense.
Core Java [BBA(CA): Sem. V] 3.69 Inheritance, Package and Collection
If we want the class not be sub-classed (or extended) by any other class, declare it
final.
In Java, if we define any class using final keyword then this type of class is known
as final class in Java. Abstract class is a superclass that only defines a generalized
form which will be shared by all of its subclasses.
An interface in Java is a blueprint of a class. It has static constants and abstract
methods only.
An interface is a way of describing what classes should do, without specifying
how they should do it. Interface is similar to class which is collection of public
static final variables (constants) and abstract methods.
The interface is a mechanism to achieve fully abstraction in Java. If subclass (child
class) has the same method as declared in the parent class, it is known as method
overriding.
Polymorphism in Java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from two Greek words poly and morphs.
The word "poly" means many and "morphs" means forms. Polymorphism means
many forms.
Check Your Understanding
1. Which of these keywords 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 subclass?
(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. Which of the following 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
Core Java [BBA(CA): Sem. V] 3.70 Inheritance, Package and Collection
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
8. Which of the following is true?
1. A class can extend more than one class.
2. A class can extend only one class but many interfaces.
3. An interface can extend many interfaces.
4. An interface can implement many interfaces.
5. A class can extend one class and implement many interfaces.
(a) 1 and 2 (b) 2 and 4
(c) 3 and 5 (d) 3 and 4
9. A _______ is a collection of classes and interfaces.
(a) Object (b) Package
(c) Inheritance (d) Method
10. Final keyword in java is used with _______ .
(a) class attributes (b) class
(c) class functions (d) All of the above
Answers
1. (d) 2. (c) 3. (b) 4. (b) 5. (d) 6. (d) 7. (b) 8. (c) 9. (b) 10. (d) 11. (c)
Practice Questions
Q.I Answer the following questions in short:
1. What is inheritance?
2. What are the types of inheritance?
3. What do you mean by abstract classes and methods?
4. How to override methods in Java?
5. What is final class?
6. What is super class?
8. Give example of hierarchical inheritance.
9. Why abstract class is used?
10. Which keyword is used to define abstract class?
11. By default interface is public and abstract. State True or False.
Core Java [BBA(CA): Sem. V] 3.71 Inheritance, Package and Collection
Winter 2018
1. List the three different uses of final keyword. [2 M]
Ans. Refer to Section 3.5.2.
2. Can interface be final? Justify. [2 M]
Ans. Refer to Section 3.5.2.
3. Explain ArrayList class in Collection Framework. [4 M]
Ans. Refer to Section 3.14.4.2.
4. Explain how multiple inheritance is achieved in Java. [4 M]
Ans. Refer to Section 3.7.1.
5. Write a note on package in Java. [4 M]
Ans. Refer to Section 3.13.
6. Create a package vehicle which will have two classes: Two wheeler and
four-wheeler. Two-wheeler with method display (cc, price), four-wheeler with
method display (reg-no, reg-year). [4 M]
Ans. Refer to Program 3.39.
7. What is Interface? Explain it with example. [4 M]
Ans. Refer to Section 3.7.
Core Java [BBA(CA): Sem. V] 3.72 Inheritance, Package and Collection
8. Define an Interface shape with abstract method area( ). Write a Java program to
calculate an area of Circle and Rectangle (Use final keyword). [4 M]
Ans. Refer to Program 3.14.
Summer 2019
1. How to create and access the package in Java? [2 M]
Ans. Refer to Section 3.13.
2. What is Interface? Why are they used in Java? Explain. [4 M]
Ans. Refer to Section 3.7.
3. Define an abstract class shape with abstract method area() and volume(). Write a
java program to calculate area and volume of cone and cylinder. [4 M]
Ans. Refer to Program 3.38.
4. Write a package for games in java, which have two classes Indoor and Outdoor.
Use a function display() to generate the list of players for specific games.
(Use parameterized constructor, finalize() method and array of objects). [4 M]
Ans. Refer to Program 3.39.
5. Define collection. Explain any two classes used with collection. [4 M]
Ans. Refer to Section 3.14.
6. How to add user defined package in main class? List the steps with suitable
example. [4 M]
Ans. Refer to Section 3.13.2.
7. Write similarities and dissimilarities between Abstract Class and Interface. [4 M]
Ans. Refer to Section 3.5.
8. Explain the use of super and final keyword with reference to inheritance. [4 M]
Ans. Refer to Section 3.11.
4…
File and Exception Handling
Learning Objectives…
▣ To learn Exception and Error.
▣ To understand use of try, catch, throw, throws and finally.
▣ To study Built in Exception and Custom exception.
▣ To understand File Handling.
▣ To learn FileReader and FileWriter class.
(4.1)
Core Java [BBA(CA): Sem. V] 4.2 File and Exception Handling
• The try block can have multiple lines of code that can raise multiple exceptions. Each
of these exceptions is handled by an independent catch block.
• Java Try Catch Example: In the try block, we define a division operation. The divisor
is zero. The statement that divides the two numbers raises an Arithmetic exception.
The catch block defines a handler for Arithmetic exception.
Program 4.1: Program using Try-Catch.
public class Main
{
public static void main(String args[])
{
int i, j;
try
{
//Stmt to Raise Exceptions
System.out.println("Inside Try Block … ");
i = 0;
j = 2078/ i;
System.out.println("\n Value of j: "+j);
System.out.println("Try Block Over …….");
}
catch (ArithmeticException e)
{
// ArithmeticException Handler
System.out.println("Divide by Zero Arithmetic Expression ……");
}
System.out.println("Outside Try-Catch Block ……");
}
}
Output:
Inside Try Block …
Divide by Zero Arithmetic Expression ……
Outside Try-Catch ……
3. Nested Try-Catch/Multiple Catch:
• A try block inside another try block is called a nested try block.
• Syntax of a nested try block is given below:
try
{
//try_block 1;
Core Java [BBA(CA): Sem. V] 4.6 File and Exception Handling
try
{
//try_block 2;
}
catch(Exception e)
{
//exception handler code
}
}
catch(Exception e)
{
//exception handler code
}
4. Finally:
• It follows try block or try-catch block. Some code in our program that needs to be
executed irrespective of whether or not the exception is thrown. The finally block
cannot exist without a try block.
Program 4.2: Program using nested try-multiple catch block with finally.
public class Main
{
public static void main(String args[])
{
//Main try block
try
{
//try block1
try
{
System.out.println("Inside Try Block1 ……");
int num =100/0;
System.out.println(num);
}
catch(ArithmeticException e1)
{
System.out.println("Inside Catch Block1 Exception: e1");
}
Core Java [BBA(CA): Sem. V] 4.7 File and Exception Handling
//try block2
try
{
System.out.println("Inside Try Block2 ……");
int num =200/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e2)
{
System.out.println("Inside Block2 Exception: e2");
}
System.out.println("Block1 and Block2");
}
catch(ArithmeticException e3)
{
System.out.println("Arithmetic Exception ……");
}
catch(ArrayIndexOutOfBoundsException e4)
{
System.out.println("ArrayIndexOutOfBoundsException ……");
}
catch(Exception e5)
{
System.out.println("Main Block Exception");
}
finally
{
System.out.println ("Inside Finally Block …");
System.out.println ("Finally block executed … No Exception…");
}
}
}
Output:
Inside Try Block1 ……
Inside Catch Block1 Exception: e1
Inside Try Block2 ……
Arithmetic Exception ……
Inside Finally Block …
Finally block executed … No Exception…
Core Java [BBA(CA): Sem. V] 4.8 File and Exception Handling
5. Throw: [S-19]
• Java provides a keyword "throw" using which we can explicitly throw the exceptions
in the code or to throw custom exceptions. It can be used to throw the checked or
unchecked exceptions.
• Syntax of the throw keyword is:
throw exception;
or
throw new exception_class("error message");
Program 4.3: Program using throw keyword.
import java.lang.*;
public class Main
{
static void check_sal(int sal)
{
//if specified Salary <200000 , throw ArithmeticException
if(sal < 200000)
throw new ArithmeticException("\n Salary < 2000 not allowed ….");
else //print the message
System.out.println("\n Salary > 20000 .. Enjoy ….");
}
public static void main(String args[])
{
//call Check_sal
check_sal(500000);
System.out.println("\n Be Happy ...");
}
}
Output:
Salary > 20000 .. Enjoy ….
Be Happy ...
6. Throws:
• It is used to declare exceptions but does not throw an exception. It is used to indicate
that an exception might occur in the program or method.
• The declaration of exception using the "throws" keyword tells the programmer that
there may be an exception specified after the "throws" keyword and the programmer
should provide corresponding handler code for this exception to maintain the normal
flow of the program.
Core Java [BBA(CA): Sem. V] 4.9 File and Exception Handling
• Declaring an exception with throws keyword in the method signature and then
handling the method call using try-catch seems to be a viable solution.
• Another advantage of declaring exceptions using throws keyword is that we are
forced to handle the exceptions. If we do not provide a handler for a declared
exception then the program will raise an error.
• Syntax of the throws keyword:
return_type method_name() throws exception_class_name
{
//method code
}
Program 4.4: Program using Throws.
import java.io.IOException;
public class Throws_Eg
{
void music()throws IOException
{
throw new IOException("IO Error");
}
void play()throws IOException
{
music();
}
void enjoy()
{
try
{
play();
}
catch(Exception e)
{
System.out.println("Inside Catch: Exception Handeled ....");
}
}
public static void main(String args[])
{
Throws_Eg t1=new Throws_Eg();
t1.enjoy();
System.out.println("Program End ...");
}
}
Output:
Inside Catch: Exception Handeled ....
Program End ...
Core Java [BBA(CA): Sem. V] 4.10 File and Exception Handling
Exception Error
IOException StackOverflowError
SQLException VirtualMachineError
ClassNot OutOfMemoryError
FoundException
RuntimeException
ArithmeticException
NuIlPointerException
NumberFormat
Exception
IndexOutOf
BoundsException
ArrayIndexOutOf
BoundsException
StringIndexOutOf
BoundsException
catch (Throwable e)
{
System.out.println("\n Inside Throwable Exception:" +
e.toString());
}
}
public static void trial() throws Exception
{
throw new Exception("\n Inside Trial ....... Exception Thrown .....");
}
}
Output:
Inside Throwable Exception: java.lang.Exception:
Inside Trial ....... Exception Thrown .......
InputStream
FileInputStream SequenceInputStream
PipedInputStream ObjectInputStream
ByteArrayInputStream PushBackInputStream
FilterInputStream
BufferedInputStream BufferedInputStream
DataInputStream
DataInput
• The following statement will wrap the FileInputStream to the buffered stream.
o FileInputStream fis = new FileInputStream("test.txt");
o BufferedInputStream bis = new BufferedInputStream(fis);
o bis.read() method will read data from the buffer and not from the file.
(C) DataInputStream:
• This is a high level stream that permits reading of primitive data types. When you
work with byte streams, you have to convert them to characters or strings to
understand their meaning. But this stream provides methods to directly work with
meaningful types.
• DataInputStream implements DataInput interface that defines methods to read the
sequence of bytes and convert them into values of primitive data types.
• The following Table 4.2 shows commonly used methods. All these methods throw
IOException.
Table 4.2: Methods in DataInputStream Interface
Method Description
boolean readBoolean() Reads and returns a boolean value from the stream.
boolean readByte() Reads and returns a byte value from the stream.
boolean readChar() Reads and returns a char value from the stream.
boolean readDouble() Reads and returns a double value from the stream.
boolean readFloat() Reads and returns a float value from the stream.
boolean readInt() Reads and returns a integer value from the stream.
boolean readLong() Reads and returns a long value from the stream.
boolean readshort() Reads and returns a short value from the stream.
void readFully(byte Reads and fills the buffer buff with bytes.
buff[])
void readFully(byte Reads specified number of bytes and fills the buffer
buff[], int index, int from buff[index].
number)
int skip Bytes(int n) Skips n bytes in the stream.
void write (int j) Writes the byte in the lower 8 bits of j.
void write (byte buff[ ]) Writes contents of the buffer to the stream.
void write (byte buff [ ], Writes a portion of the buffer to the stream (starting
int index, int len) from index and of length len).
void close () Writes all data in the stream and closes the stream.
void flush () Flushes (writes) all data from the stream.
Core Java [BBA(CA): Sem. V] 4.18 File and Exception Handling
2. OutputStream:
• OutputStream is an abstract class. Most of the methods of this class return void and
throw IOException in case of errors.
Object
OutputStream
FileOutputStream ObjectOutputStream
PipedOutputStream ByteArrayOutputStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
(C) PrintStream:
• PrintStream extends from FilterOutputStream. PrintStream is one of the most used
Java class. This class provides all of the output capabilities.
• The following are the constructors:
o PrintStream(OutputStream os)
o PrintStream(OutputStream os, boolean flushOnNewLine)
o PrintStream(OutputStream os, boolean flushOnNewLine, String charSet)
throws
• Here,
o os defines the OutputStream that will receive output.
o Unsupported encoding exception flushOnNewLine parameter is true, the output is
automatically flushed every time a newline (\n) character is recognized or when
println is called. If false, it is not flushed automatically.
o charSet specifies character encoding scheme.
(D) DataOutputStream:
• This stream also extends from FilterOutputStream. This writes primitive data to a
byte oriented output stream. It supports all of its methods defined by its superclasses.
• It implements DataOutput interface which define methods that convert values from
primitive data type into a byte sequence and then writes to the underlying stream.
writeDouble(), writeBoolean(), writeInt() are some of the examples of such
methods.
4.6.2 Character Streams
• Character streams can be used to read and write 16 bit unicode characters. Like byte
stream classes, character stream classes are reader stream and writer stream classes.
Reader:
Object
Reader
BufferedReader StringReader
CharArrayReader PipeReader
InputStreamReader FilterReader
FileReader PushbackReader
• Reader class is the base class for all the classes in this group. It is an abstract class.
This class is quite similar to InputStream class in functionality.
• Methods of this class are also identical to those of InputStream class. The only
difference is that the fundamental unit of data is character instead of byte.
Writer:
• Writer class is the base class for all other writer classes in this group. It is an abstract
class. This class is very similar to OutputStream class in functionality.
• Methods of this class are also identical to those of the OutputStream class. The only
difference is that the fundamental unit of data is character instead of byte.
Object
Writer
BufferedWriter PrintWriter
CharArrayWriter StringWriter
FilterWriter PipeWriter
OutputStreamWriter
FileWriter
Program 4.10: A program to illustrate the use of methods of File class that displays
information about the file.
import java.io.*;
public class FileDemo
{
public static void main(String[] args)
{
try
{
File f = new File("DrawApplet.java");
System.out.println("\nCan read? " + f.canRead());
System.out.println("\nCan write? " + f.canWrite());
System.out.println("\nAbsolute path " + f.getAbsolutePath());
System.out.println("\nLength " + f.length());
System.out.println("\nParent " + f.getParent());;
System.out.println("\nIs file? " + f.isFile());
System.out.println("\nIs directory? " + f.isDirectory());
String []list = f.list();
for(int i=0; i<list.length; i++)
System.out.println(list[i]);
}
catch(NullPointerException e) { System.out.println("Error"); }
}
}
Output:
Can read? true
Can write? true
Absolute path D:\Java Programs\DrawApplet.java
Length 888
Parent null
Is file? true
Is directory? false
• Here,
o path refers to the complete path of the file.
o fileObject refers to the object that describes the file.
Program 4.11: A program shows how FileInputStream class is used for reading bytes
from file and FileOuputStream class is used to write bytes to a file.
File: FileRead.java
import java.io.*;
class FileRead
{
public static void main(String[] args) throws IOException,
FileNotFoundException
{
File f = new File("Ball.txt");
FileInputStream fis = new FileInputStream(f);
FileOutputStream fos = new FileOutputStream("NewBall.txt");
int value;
while((value=fis.read()) != -1)
{
System.out.print((char)value);
fos.write(value);
}
fis.close();
fos.close();
}
}
Output:
(Contents of ball.txt - Hello! We are learning Java.)
java FileRead
Hello !
We are learning Java.
• Program reads an existing file and displays its bytes on the screen. It also writes data
to the new file 'NewBall.txt'. We must first create the file named 'Ball.txt' before we
run this program. The new file 'NewBall.txt' is created if it does not already exist. If
the file exists, the previous contents are lost and data is written from the beginning of
the file. In case if the file to be read or new file to be written is not found for any
reason, FileNotFoundException is thrown.
Core Java [BBA(CA): Sem. V] 4.26 File and Exception Handling
FileOutputStream:
• This stream writes bytes to a file. The constructors are as follows:
o FileOutputStream (String path) throws FileNotFound Exception
o FileOutputStream (String path, boolean apppend) throws FileNot Found
Exception
o FileOutputStream (File fileOb)
• All these constructors throw FindNotFoundException. Parameter path indicates
complete path to the file and fileOb indicates file object. Parameter append is true if
the new data should be appended to the existing data and false if the old data should
be overwritten.
Program 4.12: Program using FileOutputStream.
import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[]) throws Exception
{
FileOutputStream fileOut = new FileOutputStream("sample.dat");
int i;
for(i=0;i<10;i++)
fileOut.write(i%5);
fileOut.close();
FileInputStream fin = new FileInputStream("sample.dat");
while ((i = fin.read()) != -1)
System.out.println(i);
fin.close();
}
}
Output:
0 1 2 3 4 0 1 2 3 4
{
char[] arr = new char[50];
try
{
FileInputStream f1 = new FileInputStream("temp.txt");
InputStreamReader i1 = new InputStreamReader(f1);
i1.read(arr);
System.out.println("\n Temp text file..... ");
System.out.println(arr);
i1.close();
}
catch(Exception e)
{
System.out.println("\n Inside Catch Block.... ");
e.getStackTrace();
}
}
}
Output:
Inside Catch Block....
OutputStreamWriter:
• It works with other output streams works as bridge between byte streams and
character streams. It converts its characters into bytes.
Program 4.14: Program using OutputStreamWriter.
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
public class Main
{
public static void main(String args[])
{
String s1 = "aaa bbb ccc ddd eee";
try
{
FileOutputStream f1 = new FileOutputStream("temp.txt");
OutputStreamWriter o1 = new OutputStreamWriter(f1);
o1.write(s1);
o1.close();
}
Core Java [BBA(CA): Sem. V] 4.28 File and Exception Handling
catch (Exception e)
{
System.out.println("\n Catch Block called .... ");
e.getStackTrace();
}
}
}
Output:
aaa bbb ccc ddd eee
Output:
(Contents of in.dat:We are learning File handling.)
out.dat ->
We are learning File handling.
Inside Finally
Program 4.17: Program to Create a File.
import java.io.File;
public class CreateFile
{
public static void main(String[] args)
{
File f1 = new File("newfile.txt");
try
{
// create a file
boolean flag = f1.createNewFile();
if (flag)
{
System.out.println("\n New File created .........");
}
else
{
System.out.println("\n File already exists .........");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
New File created .....
• In addition to the methods defined by the Reader class, this class has a method
readLine() to read a line from the stream. It has two forms of constructors.
1. BufferedReader(Reader inStream): This form creates a buffered character
stream with a default buffer size.
2. BufferedReader(Reader inStream, int buffSize): The size of the buffer is
passed in buffSize.
Program 4.18: Program for BufferedReader.
import java.io.*;
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
// Accepting String value
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
// Accepting integer value
System.out.println("Enter your Roll Number");
int roll_no=Integer.parseInt(br.readLine());
System.out.println("Roll number is "+roll_no);
// Accepting Float value
System.out.println("Enter your Percentage");
float per=Float.parse Float(br.readLine());
System.out.println("Percentage is "+per);
}
}
Output:
Enter your name
Shruti
Welcome Shruti
Enter your Roll Number
101
Roll number is 101
Enter your Percentage
78
Percentage is 78.0
Core Java [BBA(CA): Sem. V] 4.32 File and Exception Handling
Program 4.19: Write a Java program to read the content of Imp.text. Display the content
of file in encoded format. (Use Command Line Argument). [W-18]
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Encod
{
public static void main(String[] args)
{
try
{
File f1 = new File("temp.txt");
Writer w1 = new BufferedWriter(new OutputStreamWriter
(new FileOutputStream(f1), StandardCharsets.UTF_8));
w1.append("\n Make a Great Day Ahead ......").append("\r\n");
w1.append("UTF-8 Demo").append("\r\n");
w1.append("\n Happy Cycling .......").append("\r\n");
w1.flush();
w1.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Core Java [BBA(CA): Sem. V] 4.33 File and Exception Handling
Output:
temp.txt ->
Make a Great Day Ahead ......
UTF-8 Demo
Happy Cycling .......
Program 4.20: Write a Java program to accept string from user, if its length is less than
7, then throw user defined exception ''Invalid String'' otherwise display the string in
upper case. [W-18]
import java .io.*;
class InvalidString extends Exception
{
String str;
InvalidString(String s)
{
this.str=s;
}
public String toString()
{
return "Invalid String !";
}
}
class MyString
{
String str1;
void accept(String s)
{
str1=s;
}
void display()
{
System.out.println("");
}
}
class Temp
{
public static void main(String arg[]) throws Exception
{
System.out.println("Enter String :");
BufferedReader br = new BufferedReader
(newInputStreamReader(System.in));
String str=br.readLine();
Core Java [BBA(CA): Sem. V] 4.34 File and Exception Handling
try
{
if(str.length()<7)
throw new InvalidString(str);
else
str=str.toUpperCase();
System.out.println("String in uppercase :"+str);
}
catch (InvalidString s)
{
System.out.println("Invalid String");
}
}
}
Output:
Enter String :
fabulous
String in uppercase :FABULOUS
Enter String :
Rutu
Invalid String
Program 4.21: Write a java program to accept email address of a user and throw a user
defined exception ''Invalid Email Exception'' if it does not contain '@' symbol. [S-19]
import java .io.*;
class InvalidEmail extends Exception
{
String str;
InvalidEmail(String s)
{
this.str=s;
}
public String toString()
{
return "Invalid Email address as it does not contain @ !";
}
}
class MyEmail
{
String str1;
Core Java [BBA(CA): Sem. V] 4.35 File and Exception Handling
void accept(String s)
{
str1=s;
}
void display()
{
System.out.println("");
}
}
class EMain
{
public static void main(String arg[]) throws Exception
{
System.out.println("Enter Emailaddress :");
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
String str=br.readLine();
try
{
if(str.contains("@"))
System.out.println("Email address is Valid");
else
throw new InvalidEmail(str);
}
catch (InvalidEmail s)
{
System.out.println("Invalid Email");
}
}
}
Output:
Enter Emailaddress :
vedant123@gmail.com
Email address is Valid
java EMain
Enter Emailaddress :
adi.g.com
Invalid Email
Core Java [BBA(CA): Sem. V] 4.36 File and Exception Handling
Program 4.22: Write a java program to display the content of file in reverse order. [S-19]
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try
{
String in = "input.txt";
String out = "output.txt";
File sourceFile=new File(in);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(out);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String ans=buffer.toString();
pwriter.println(ans);
}
content.close();
pwriter.close();
System.out.println("File is copied successfully!");
}
catch(Exception e)
{
System.out.println("Something went wrong");
}
}
}
Output:
input.txt :
Hello We are learning Reversing the file contents
output.txt(reversed)
stnetnoc elif eht gnisreveR gninrael era eW olleH
Core Java [BBA(CA): Sem. V] 4.37 File and Exception Handling
Summary
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may choose
to handle the exception itself, or pass it on. Either way, at some point, the
exception is caught and processed.
All exception types are subclasses of the built-in class Throwable. Immediately
below Throwable are two subclasses that partition exceptions into two distinct
branches.
One branch is headed by Exception. There is an important subclass of Exception,
called RuntimeException. Exceptions of this type are automatically defined for
the programs that you write and include things such as division by zero and
invalid array indexing.
It is used during program development to create an assertion, which is a
condition that should be true during the execution of the program.
We can make use of variables and arrays for storing data in the program. But this
data will be lost if variable goes out of scope or if the program itself is terminated.
Java uses a concept of streams to represent ordered sequence of data. A stream in
java is a path along which data flows. It is like a pipe through which water flows.
This class is extended from FilterInputStream. This enhances the performance
and also supports operations like skipping, marking and resetting.
Although most of the classes defined by java.io operate on streams, File class does
not operate on streams. It directly deals with files and file system.
Only an object that implements the serializable interface can be saved and
restored by the serialization facilities. The Serializable interface defines no
members.
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod() {}
}
(a) AC (b) BC
(c) ACD (d) ABCD
4. Which statement is true?
(a) catch(X x) can catch subclasses of X where X is a subclass of Exception
(b) The Error class is a RuntimeException
(c) Any statement that can throw an Error must be enclosed in a try block
(d) Any statement that can throw an Exception must be enclosed in try block
5. When does Exceptions in Java arises in code sequence?
(a) Run Time (b) Compilation Time
(c) Can Occur Any Time (d) None of the mentioned
6. Which of these keywords must be used to monitor for exceptions?
(a) try (b) finally
(c) throw (d) catch
7. Which Java package must be imported when you use BufferedReader?
(a) java.util package (b) javax.awt package
(c) java.io package (d) java.swing package
8. For reading strings and characters in Java from console which class is used from
following:
(a) OutputStreamReader (b) FileReader
(c) BufferedReader (d) BufferedInputReader
Core Java [BBA(CA): Sem. V] 4.39 File and Exception Handling
Practice Questions
Q.I Answer the following Questions in short:
1. What is a stream?
2. Which are the predefined streams?
3. Describe the term file I/O basic
4. What is Error?
5. When is Exception raised?
6. What is FileReader and FileWriter?
7. When is BufferedReader used?
8. What are different types of Erros?
9. When is FileInputStream and FileOutputStream used?
Q.II Answer the following Questions:
1. What is an exception? In which package exceptions are defined?
2. Can user program throw own exceptions? How?
3. Explain the purpose of throws clause.
4. What is the purpose of finally block in the program?
5. Explain how nested try blocks are handled?
Core Java [BBA(CA): Sem. V] 4.40 File and Exception Handling
Winter 2018
1. Give syntax of two methods used with InputStream class. [2 M]
Ans. Refer to Section 4.6.1.
2. Write a Java program to read the content of Imp.text. Display the content of file in
encoded format. (Use Command Line Argument). [4 M]
Ans. Refer to Program 4.19.
3. Write a Java program to accept string from user, if its length is less than 7, then
throw user defined exception "Invalid String" otherwise display the string in
upper case. [4 M]
Ans. Refer to Program 4.20.
Summer 2019
1. State the purpose of throw keyword. [2 M]
Ans. Refer to Section 4.2.
2. What is Exception? Explain its keyword with example. [4 M]
Ans. Refer to Sections 4.1 and 4.2.
3. Write a java program to accept email address of a user and throw a user defined
exception ''Invalid Email Exception'' if it does not contain '@' symbol. [4 M]
Ans. Refer to Program 4.21.
4. Write a java program to display the content of file in reverse order. [4 M]
Ans. Refer to Program 4.22.
5. Explain any four methods of file class. [4 M]
Ans. Refer to Section 4.8.
5…
Applet, AWT, Event and
Swing Programming
Learning Objectives…
▣ To learn Basic Concepts of Swing
▣ To write Program using Swing.
▣ To learn Applet Programming.
▣ To study AWT in Java.
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
• An Applet does not need to begin its execution with main(). Applets are not stand
alone programs. They can be executed either in any web browser or in an
appletviewer provided by JDK.
How Applet differs from Application?
• As we know that applets and stand-alone applications are Java programs, there are
significant differences between them. Applets are not full-featured application
programs.
• They are usually written to accomplish a small task on the Internet.
1. Applets do not use the main() method for initiating the execution of the code.
Applets, when loaded, automatically call certain methods of Applet class to start
and execute the applet code.
2. Unlike stand-alone applications, applets cannot be run independently. They are
run from inside a Web page using a special feature known as HTML tag.
3. Applets cannot read from or write to the files in the local computer.
4. Applets cannot communicate with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++.
• Comparison between Java Applet and Java Application:
Table 5.1: Comparison between Java Applet and Java Application
Sr.
Java Applet Java Application
No.
1. As applet is downloaded from Application of java has no security
Internet, it provides security features. provided.
2. Applet runs in web pages. It runs on stand alone systems.
3. Parameters are passed by using param String array is used to pass parameter
tag. to main function.
4. Execution starts from init() method Execution starts from main() method.
from main method.
5. Applets are cached in most web browsers, so will be quick to load when returning
to a web page.
6. User can also have full access to the machine if user allows.
7. It works at client side so less response time.
8. It can be executed by browsers running under many platforms, including Linux,
Windows, Mac OSs etc.
9. It is secured.
Disadvantages of Applet:
1. Java plug-in is required to run applet.
2. Java applet requires JVM so first time it takes significant startup time.
3. If applet is not already cached in the machine, it will be downloaded from internet
and will take time.
4. It is difficult to design and build good user interface in applets compared to HTML
technology.
5.2 TYPESAPPLET
• There are two types of applets that a web page can contain.
1. Local Applet
o Local Applet is written on our own, and then we will embed it into web pages.
o Local Applet is developed locally and stored in the local system. A web page
doesn't need the get the information from the internet when it finds the local
Applet in the system. It is specified or defined by the file name or pathname.
o There are two attributes used in defining an applet, i.e., the codebase that
specifies the path name and code that defined the name of the file that contains
Applet's code.
o Example: <applet code = "FirstApplet.class" height = "500" width="500">
</applet>
2. Remote Applet:
o When an applet is created by someone else and we can access it only when we are
connecting with the internet. This type of applet is stored in remote computer and
it is known as remote applet.
o We can download this remote applet from webserver to clients system using
internet connection and can execute it for searching a particular applet we
require to add its URL address into the applet HTML document as the value of
codebase attribute.
o Example: <applet codebase=http://www.abedainamdarcollege.org.in code =
"MyApp.class" width=200 height=200> </applet>
Core Java [BBA(CA): Sem. V] 5.4 Applet, AWT, Event and Swing Programming
start ( )
stop ( )
Exit of Browser
Fig. 5.2: Life Cycle of Applet
1. init () Method:
• The life cycle of an applet is begin on that time when the applet is first loaded into the
browser and called the init() method.
• The init() method is called only one time in the Life cycle of an Applet.
• The init() method is basically called to read the PARAM tag in the HTML file.
• The init() method retrieve the passed parameter through the PARAM tag of HTML file
using get Parameter() method.
• All the initialization such as initialization of variables and the objects like image,
sound file are loaded in the init () method.
• After the initialization of the init() method user can interact with the Applet.
Core Java [BBA(CA): Sem. V] 5.5 Applet, AWT, Event and Swing Programming
• Syntax:
public void init()
{
Statements …
}
2. start () Method:
• The start method of an applet is called after the initialization method init().
• This method may be called multiple times when the Applet needs to be started or
restarted.
• For example, if the user wants to return to the Applet, in this situation the start
Method() of an Applet will be called by the web browser and the user will be back on
the applet. In the start method user can interact within the applet.
• In the start method, user can interact within the applet.
• Syntax:
public void start()
{
Statements …
}
3. stop () Method:
• The stop() method can be called multiple times in the life cycle of applet like the
start() method. Or should be called at least one time.
• There is only miner difference between the start() method and stop() method. For
example, the stop() method is called by the web browser on that time. When the user
leaves one applet to go another applet and the start() method is called on that time
when the user wants to go back into the first program or Applet.
• In the start method, user can interact within the applet.
• Syntax:
public void start()
{
Statements …
}
4. destroy() Method:
• The destroy() method is called only one time in the life cycle of Applet like init()
method.
• This method is called only on that time when the browser needs to Shutdown.
• When the applet programs terminate, the destroy function is invoked which makes
an applet to be in dead state.
• The destroy() method is called only one time in the life cycle of Applet like init()
method.
Core Java [BBA(CA): Sem. V] 5.6 Applet, AWT, Event and Swing Programming
• Syntax:
public void destroy()
{
Statements …
}
5. Display State (paint() Method):
• The applet is said to be in display state when the paint method is called. This method
can be used when we want to display output in the screen.
• This method can be called any number of times. Paint() method is must in all applets
when we want to draw something on the applet window. paint() method takes
Graphics object as argument.
• paint() method is called each time you want to redraw the output of applet. This
situation may occur for various reasons. For example, the window in which the applet
is running may be overwritten by some other window and then uncovered again or
the applet window may be minimized and restored again. This method takes an object
of Graphics class as a parameter. This parameter will contain the graphics context.
This context is used whenever the output to the applet is required.
• Syntax:
public void paint(Graphics g)
{
Statements …
}
• The following is the source code for the Simple applet. This applet displays a
descriptive string whenever, it encounters a major milestone in its life, such as when
Program 5.1: Program for Applet Life Cycle.
import java.applet.*;
import java.awt.*;
/* <applet code = "FirstApplet.class" height = "500" width="500">
</applet> */
public class FirstApplet extends Applet
{
String message = "";
public void init()
{
message = "In init method";
System.out.println(message);
}
Core Java [BBA(CA): Sem. V] 5.7 Applet, AWT, Event and Swing Programming
• Now, we have the following files in the current directory: Hello.java, Hello.class
and Hello.html.
• To run the applet, we should have Java enabled browser or an appletviewer. We will be
able to see the entire webpage if we run the applet in browser. You can use the
appletviewer tool to run the applet as follows:
appletviewer Hello.html
• Please note that the file name used as argument with appletviewer is not the class file
but it is the HTML file.
An Applet Skeleton:
• Applet extends AWT class Panel. Panel extends Container, which in turn extends
Component class. All these classes support Java's window based graphical interface.
• init(), start(), stop() and destroy() apply to all applets. Default implement-
tation for all these methods is provided. Applets do not need to override method if it is
not used.
Program 5.2: Program shows the skeleton of the Applet.
import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkeleton.class" width=300 height=100> </applet> */
public class AppletSkeleton extends Applet
{
public void init()
{
}
public void start()
{
}
}
}
public void paint(Graphics g)
{
}
}
Output:
AppletSkeleton
Core Java [BBA(CA): Sem. V] 5.9 Applet, AWT, Event and Swing Programming
• Although this skeleton does not do anything, it can be compiled and run. When run, it
generates the above window which will be viewed in appletviewer.
• It is important to understand the order in which the methods are called. When an
applet begins, methods are called in sequence like init(), start(), paint(), stop() and
destroy().
5.3.2 Applet Tags
• We have used Applet tag in its simplest form. The syntax of applet tag is a bit
complex. It includes several attributes. The complete tag with all its attributes is
shown below:
<APPLET [CODEBASE = codebase_url] CODE = appletfilename.class
[ALT = alternate_text]
[NAME = appletinstance_name]
WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels]
[HSPACE = pixels] >
[ <PARAM NAME = name1 VALUE = value1> ]
[ <PARAM NAME = name2 VALUE = value2> ]
.......
</APPLET>
• The following table lists all the attributes along with their meaning.
Table 5.2: Applet tag Attributes
Attribute Meaning
CODE=AppletFileName.class Specifies the name of the applet class to be loaded. That
is, the name of the already compiled, class file in which
the executable Java bytecode for the applet is stored.
This attribute must be specified.
CODEBASE=codebase_URL Specifies the URL of the directory in which the applet
(optional) resides. If the applet resides is the same directory as
the HTML file, then the CODEBASE attribute may be
omitted entirely.
WIDTH=pixels These attributes specify the width and height of the
HEIGHT=pixels space on the HTML page that will be reserved for the
applet.
NAME=applet_instance_name A name for the applet may optionally be specified so
(Optional) that other applets on the page may refer to this applet.
This facilitates inter-applet communication.
contd. …
Core Java [BBA(CA): Sem. V] 5.10 Applet, AWT, Event and Swing Programming
Program 5.3: create a small applet to accept two values from the user and display the
product of it in an applet.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ProdDemo extends Applet implements ActionListener
{
TextField tf1, tf2;
int x =0, y = 0, prod = 0;
String s1, s2 , s3;
Button b1;
public void init()
{
tf1 = new TextField(10);
tf2 = new TextField(10);
b1 = new Button("Click");
add(tf1);
add(tf2);
add(b1);
tf1.setText("0");
tf2.setText("0");
b1.addActionListener(this);
}
Core Java [BBA(CA): Sem. V] 5.11 Applet, AWT, Event and Swing Programming
Program Analysis:
• An Applet contains two text fields and a button. User enters two values into the text
fields and when the user clicks on a button, the product of the two values is calculated
and displayed in an applet window.
• Class ProdDemo extends Applet class and it implements ActionListener interaface to
handle the event carried out by a button. It declares all the required variables. Applet's
init() method declares all the GUI controls and it designs GUI for the applet. It also
adds ActionListener interface to the button.
• When the button is clicked, it calls actionPerformed() method to handle the action
event. actionPerformed() method is to be overridden by the code that should be
executed to handle the event. repaint() method calls paint() automatically to
display the updated information in the applet.
• paint() method is called by an Applet which displays initial informatation. It also
displays product of the two numbers entered by the user when called again by
repaint() method.
Passing Parameters to Applet:
• Many times, when we are writing Java applets, we may need to pass parameters. We
can pass these parameters from an HTML page with the help of <param> tag. For
example, we may want to tell the applet, which color should be set as a background to
the applet.
• The benefit of passing parameter from HTML lies in its portability. If you pass
parameters from HTML page, they can be passed from one webpage to the other and
from one website to the other. We can make our applet more flexible and portable
using this technique.
• Parameters are passed by placing them in a <PARAM> tag and placing this tag inside
opening and closing of <APPLET> tag.
• For Example,
<APPLET> <PARAM name = 'name1' value = 'value1'> </APPLET>
Program 5.4: Program for passing parameters to an Applet using <param> tag.
DrawApplet.java
import java.applet.*;
import java.awt.*;
public class ParaApplet extends Applet
{
String name;
int age;
public void init()
{
name = getParameter("nm");
Core Java [BBA(CA): Sem. V] 5.13 Applet, AWT, Event and Swing Programming
try
{
age = Integer.parseInt( getParameter("input_age"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
Font f = new Font("Helvetica", Font.BOLD, 20);
g.setFont(f);
g.setColor(Color.red);
g.drawString("Name is "+ name + " & Age is " + age, 50,25);
}
}
ParaApplet.html
<html>
<body>
This is an Applet...
<applet code = "ParaApplet.class" width = 200 height = 200>
<param name = "nm" value = "Manisha">
<param name = "input_age" value = "50">
</applet>
</body>
</html>
Output:
5.4 APPLETCLASSES
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
5.4.1 Color
• The Color class is a part of Java Abstract Window Toolkit (AWT) package. The Color
class creates color by using the given RGBA values where RGBA stands for RED,
GREEN, BLUE, ALPHA or using HSB value where HSB stands for HUE, SATURATION,
BRI components.
Core Java [BBA(CA): Sem. V] 5.14 Applet, AWT, Event and Swing Programming
• The value for individual components RGBA ranges from 0 to 255 or 0.0 to 0.1.
• The value of alpha determines the opacity of the color, where 0 or 0.0 stands fully
transparent and 255 or 1.0 stands opaque.
Constructors:
1. Color(ColorSpace c, float[] co, float a): Creates a color in the specified
ColorSpace with the color components specified in the float array and the
specified alpha.
2. Color(float r, float g, float b): Creates a opaque color with specified RGB
components(values are in range 0.0 – 0.1)
3. Color(float r, float g, float b, float a): Creates a color with specified
RGBA components(values are in range 0.0 – 0.1)
4. Color(int rgb): Creates an opaque RGB color with the specified combined RGB
value consisting of the red component in bits 16-23, the green component in bits 8
– 15, and the blue component in bits 0-7.
5. Color(int rgba, boolean b): Creates an color with the specified combined RGBA
value consisting of the alpha component in bits 24-31, the red component in bits
16 – 23, the green component in bits 8 – 15, and the blue component in bits 0 – 7.
6. Color(int r, int g, int b): Creates a opaque color with specified RGB
components(values are in range 0 – 255).
7. Color(int r, int g, int b, int a): Creates a color with specified RGBA
components(values are in range 0 – 255).
5.4.2 Graphics
• The Graphics class is the abstract super class for all graphics contexts which allow an
application to draw onto components that can be realized on various devices, or onto
off-screen images as well.
• A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
1. The Component object on which to draw.
2. A translation origin for rendering and clipping coordinates.
3. The current clip.
4. The current color.
5. The current font.
6. The current logical pixel operation function.
7. The current XOR alternation color
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): Is used to draw
the specified string.
2. public void drawRect(int x, int y, int width, int height): Draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): It is
used to fill rectangle with the default color and specified width and height.
Core Java [BBA(CA): Sem. V] 5.15 Applet, AWT, Event and Swing Programming
setBackground(Color.orange);
Font f=new Font("Impact",Font.ITALIC,22);
g.setFont(f);
g.setColor(Color.red);
g.drawString("ABCDEFGHIJ",100,100);
}
}
Output:
Window Panel
2. A container is like a screen wherein we are placing components like buttons, text
fields, checkbox etc. In short, a container contains and controls the layout of
components.
3. A container itself is a component (shown in the above hierarchy diagram) thus we
can add a container inside container.
Types of containers:
• There are four types of containers available in AWT: Window, Frame, Dialog and
Panel. As shown in the hierarchy diagram above, Frame and Dialog are subclasses of
Window class.
1. Window: An instance of the Window class has no border and no title
2. Dialog: Dialog class has border and title. An instance of the Dialog class cannot
exist without an associated instance of the Frame class.
3. Panel: Panel does not contain title bar, menu bar or border. It is a generic
container for holding components. An instance of the Panel class provides a
container to which to add components.
4. Frame: A frame has title, border and menu bars. It can contain several
components like buttons, text fields, scrollbars etc. This is most widely used
container while developing an application in AWT.
• 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.
• The java.awt package provides five layout manager classes as given below:
1. FlowLayout Manager:
• The FlowLayout is one the most popular and simplest layout manager. FlowLayout
Manager places components in a container from left to right in the order in which
they were added to the container.
• When one row is filled, layout advances to the next row. It is analogous to lines of text
in a paragraph. Components managed by a FlowLayout are always set to their
preferred size (both width and height) regardless of the size of the parent container.
• Whenever, the container is resized then the components in the container are also
adjusted from the top-left corner. The FlowLayout is the default layout manager for a
Panel and JPanel.
• Following are Constructors for FlowLayout:
1. FlowLayout(): This constructor centers all components and leaves five pixel
spaces between each component.
2. FlowLayout(int align): This constructor allows to specify how each line of
components is aligned i.e., Flowlayout.LEFT, FlowLayout.CENTER,
FlowLayout.RIGHT.
3. FlowLayout(int align, int hspace, int vspace): This constructor allow to
specify the alignment as well as the horizontal and vertical space between
components.
Program 5.7: Program for flow layout manager.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Example extends JFrame
{
JLabel l1, l2, l3, l4, l5;
public Example()
{
FlowLayout layout = new FlowLayout(FlowLayout.RIGHT);
Core Java [BBA(CA): Sem. V] 5.20 Applet, AWT, Event and Swing Programming
this.setLayout(layout);
l1 = new JLabel("Label 1");
l2 = new JLabel("Label 2");
l3 = new JLabel("Label 3");
l4 = new JLabel("Label 4");
l5 = new JLabel("Label 5");
this.add(l1);
this.add(l2);
this.add(l3);
this.add(l4);
this.add(l5);
}
}
class Main
{
public static void main(String[] args)
{
Example f = new Example();
f.setTitle("Kamil Example of FlowLayout");
f.setBounds(200, 100, 600, 400);
f.setVisible(true);
}
}
Output:
• Five zones, one for each component, as can be seen in Fig. 5.4.
NORTH
SOUTH
(a) (b)
Fig. 5.4: Border Layout Manager
• The constructors defined by BorderLayout as follows:
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)
Where, region specifies any of the following five constants:
1. BorderLayout.CENTER: Places component at center.
2. BorderLayout.EAST: Places component at right border.
3. BorderLayout.WEST: Places component at left border.
4. BorderLayout.SOUTH: Places component at lower border.
5. BorderLayout.NORTH: Places component at upper border.
Program 5.8: Program for border layout.
import java.awt.*;
import javax.swing.*;
public class Main
{
JFrame f;
Main ()
{
f=new JFrame();
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Main ();
}
}
Output:
3. GridLayout Manager:
• GridLayout lays out components in a two-dimensional grid. When we instantiate a
GridLayout, we define the number of rows and columns.
• The GridLayout manager places items in rows (left to right) and columns (top to
bottom). The number of rows and columns is defined when the GridLayout manager
is created.
• The GridLayout manager divides the container into a rectangular grid so that
component can be placed in rows and column. The intersection of each row and
column is known as a cell.
Core Java [BBA(CA): Sem. V] 5.23 Applet, AWT, Event and Swing Programming
• The components are laid out in cells and each cell has the same size, components are
added to a GridLayout starting at the top left cell of the grid and continuing to the
right until the row is full. The process continues left to right on the next row of the
grid and so on.
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new Main();
}
}
Output:
Event Handling:
• An event is a signal to the program that something has happened.
• The code that performs a task in response to an event is called event handler. Event
handling is a process of responding to events that can occur at any time during
execution of a program.
• Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as event
handler that is executed when an event occurs.
• Each event must return a Boolean value (true or false), indicating whether the event
should be made available to other event handlers.
• An Event is an object that describes a state change in a source. It can be generated as a
consequence of a user interacting with the elements in a GUI.
• Any object capable of rising an event is an event source. Event handlers are
procedures that are called when a corresponding event occurs.
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.
5.7.2 Listeners
• It is an object that watch for (i.e. listen for) events and handles them when they occur.
• It is basically a consumer that receives events from the source. To sum up, the job of
an event listener is to implement the interface, register with the source and provide
the event handling.
• The Event listener represent the interfaces responsible to handle events. Java provides
us various Event listener classes but we will discuss those which are more frequently
used.
• Every method of an event listener method has a single argument as an object which is
subclass of EventObject class. For example, mouse event listener methods will accept
instance of MouseEvent, where MouseEvent derives from EventObject.
• EventListner interface is a marker interface which every listener interface has to
extend. This class is defined in java.util package.
• Following is the declaration for java.util.EventListener interface:
public interface EventListener
• Following is the list of commonly used event listeners:
1. ActionListener: This interface is used for receiving the action events.
2. ComponentListener: This interface is used for receiving the component events.
Core Java [BBA(CA): Sem. V] 5.26 Applet, AWT, Event and Swing Programming
f.add(b);f.add(tf);
f.setSize(200,200);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
2. ItemListener:
• The class which processes the ItemEvent should implement this interface.
• The object of that class must be registered with a component.
• The object can be registered using the addItemListener() method.
• When the action event occurs, that object's itemStateChanged method is invoked.
• Method:
void itemStateChanged(ItemEvent e): This method invoked when an item has been
selected or deselected by the user.
Program 5.11: Java program for ItemListener.
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener
{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample()
{
Frame f= new Frame("Kamil CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
Core Java [BBA(CA): Sem. V] 5.28 Applet, AWT, Event and Swing Programming
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
new ItemListenerExample();
}
}
Output:
3. WindowListener:
• The class which processes the WindowEvent should implement this interface.
• The object of that class must be registered with a component.
• The object can be registered using the addWindowListener() method.
Core Java [BBA(CA): Sem. V] 5.29 Applet, AWT, Event and Swing Programming
• Methods:
1. void windowActivated(WindowEvent e): This method invoked when the Window
is set to be the active Window.
2. void windowClosed(WindowEvent e): This method invoked when a window has
been closed as the result of calling dispose on the window.
3. void windowClosing(WindowEvent e): This method invoked when the user
attempts to close the window from the window's system menu.
4. void windowDeactivated(WindowEvent e): This method invoked when a Window
is no longer the active Window.
5. void windowDeiconified(WindowEvent e): This method invoked when a window
is changed from a minimized to a normal state.
6. void windowIconified(WindowEvent e): This method invoked when a window is
changed from a normal to a minimized state.
7. void windowOpened(WindowEvent e): This method invoked the first time a
window is made visible.
4. KeyListener Interface:
• The class which processes the KeyEvent should implement this interface.
• The object of that class must be registered with a component.
• The object can be registered using the addKeyListener() method.
1. void keyPressed(KeyEvent e): This method invoked when a key has been
pressed.
2. void keyReleased(KeyEvent e): This method invoked when a key has been
released.
3. void keyTyped(KeyEvent e): This method invoked when a key has been typed.
5. MouseListener Interface:
• The class which processes the MouseEvent should implement this interface.
• The object of that class must be registered with a component.
• The object can be registered using the addMouseListener() method.
1. void mouseClicked(MouseEvent e): This method invoked when the mouse button
has been clicked (pressed and released) on a component.
2. void mouseEntered(MouseEvent e): This method invoked when the mouse enters
a component.
3. void mouseExited(MouseEvent e): This method invoked when the mouse exits a
component.
4. void mousePressed(MouseEvent e): This method invoked when a mouse button
has been pressed on a component.
5. void mouseReleased(MouseEvent e): This method invoked when a mouse button
has been released on a component.
Core Java [BBA(CA): Sem. V] 5.30 Applet, AWT, Event and Swing Programming
6. 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.
1. void mouseDragged(MouseEvent e): This method invoked when a mouse button
is pressed on a component and then dragged.
2. void mouseMoved(MouseEvent e): This method invoked when the mouse cursor
has been moved onto a component but no buttons have been pushed.
5.7.3 Adapterclasses [W-18]
• Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all
the methods of listener interfaces.
1. Mouse Adapter:
• An abstract adapter class for receiving mouse events. The methods in this class are
empty. This class exists as convenience for creating listener objects.
• Mouse events let you track when a mouse is pressed, released, clicked, moved,
dragged, when it enters a component, when it exits and when a mouse wheel is
moved.
• Extend this class to create a MouseEvent (including drag and motion events) or/and
MouseWheelEvent listener and override the methods for the events of interest. (If you
implement the MouseListener, MouseMotionListener interface, you have to define all
of the methods in it. This abstract class defines null methods for them all, so you can
only have to define methods for events you care about.)
• Create a listener object using the extended class and then register it with a
component using the component's addMouseListener, addMouseMotionListener,
addMouseWheelListener methods. The relevant method in the listener object is
invoked and the MouseEvent or MouseWheelEvent is passed to it in following cases:
1. When a mouse button is pressed, released, or clicked (pressed and released).
2. When the mouse cursor enters or exits the component.
3. When the mouse wheel rotated, or mouse moved or dragged.
Program 5.12: Java Program for Mouse Adapter Class.
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{
Frame f;
MouseAdapterExample()
{
Core Java [BBA(CA): Sem. V] 5.31 Applet, AWT, Event and Swing Programming
2. Key Adapter
• Extend this class to create a KeyEvent listener and override the methods for the events
of interest. (If you implement the KeyListener interface, you have to define all of the
methods in it. This abstract class defines null methods for them all, so you can only
have to define methods for events you care about.)
• Create a listener object using the extended class and then register it with a
component using the component's addKeyListener method. When a key is pressed,
released, or typed, the relevant method in the listener object is invoked, and the
KeyEvent is passed to it.
Core Java [BBA(CA): Sem. V] 5.32 Applet, AWT, Event and Swing Programming
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e)
{
String text=area.getText();
String words[]=text.split("\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args)
{
new KeyAdapterExample();
}
}
Output:
Core Java [BBA(CA): Sem. V] 5.33 Applet, AWT, Event and Swing Programming
Invokes
Event Source
Creates
Registers
Event Object
Listener
Interface Implements
Listener Object
onEvent (EventObj)
onEvent (EventObj)
5.9 SWING
• The swing components are defined in the package javax.swing. This package provides
more powerful and flexible components.
• Swing is a Java foundation class's library and it is an extension to do Abstract
Windowing Toolkit (AWT).
• Swing is an extension to the AWT components which provides feature of pluggable
look and feel for the components. It provides classes to design lightweight
components.
• Swing is the next-generation GUI toolkit which Sun Microsystems is developing to
enable enterprise development in Java.
• Swing is actually part of a large family of Java products which is known as Java
Foundation Classes (JFC).
• Swing is used to create large-scale Java applications with a wide array of powerful
components which can you easily extend or modify these components to control their
appearance and behavior based on the current "look and feel" library that is being
used.
• Swing is a set of classes, this provides more powerful and flexible components than
are possible with the AWT.
• In addition to the familiar components, such as buttons, check boxes, and labels,
Swing supplies several exciting additions, including tabbed panes, scroll panes, trees,
and tables.
• 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 elements.
• The number of classes and interfaces in the Swing packages is substantial. Swing is
the set of packages built on top of the AWT that provide us with a great number of
pre-built classes that is, over 250 classes and 40 UI components.
5.9.1 Swing Features
• Various features of swing are listed below:
1. Light Weight: Swing component are independent of native Operating System's
API as Swing API controls are rendered mostly using pure JAVA code instead of
underlying operating system calls.
2. Rich Controls: Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, color picker, table controls and so on.
Core Java [BBA(CA): Sem. V] 5.35 Applet, AWT, Event and Swing Programming
3. Borders: We can draw borders in many different styles around components using
the setborder() method.
4. Easy Mouseless Operation: It is easy to connect keystrokes to components.
5. Tooltips: We can use the setToolTipText method of JComponent to give
components a tooltip, one of those small windows that appear when the mouse
hovers over a component and gives explanatory text.
6. Easy Scrolling: We can connect scrolling to various components-something that
was impossible in AWT.
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
managers.
5.9.2 Advantages and Disadvantages of Swing
Advantages:
1. Swing provides paint debugging support when you build your own component.
2. Swing components are lightweight.
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:
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.
5.9.3 Introduction to Swing Component and Container Classes
Swing Component:
• Swing components are not implemented by platform specific code. Instead they are
written entirely in Java and therefore, are platform independent.
• Swing component is called lightweight, as it does not depend on any non-java system
classes. Swing components have their own view supported by java's look and feel
classes.
• Swing components have pluggable look and feel so that with a single set of
components you can achieve the same look and feel on any operating system
platform.
• 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.*;
Core Java [BBA(CA): Sem. V] 5.36 Applet, AWT, Event and Swing Programming
• Swing controls or components and their related methods are available in javax.swing
and its subpackages.
• 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.
Program 5.14: Program to demonstrate JLabel.
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class Frame1 extends JFrame
{
private JLabel jLabel1 = new JLabel();
private JLabel jLabel2 = new JLabel();
public Frame1()
{
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Core Java [BBA(CA): Sem. V] 5.38 Applet, AWT, Event and Swing Programming
JIcons:
• Icons are encapsulated by the ImageIcon class, which prints an icon from an image.
• Constructors:
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.
Core Java [BBA(CA): Sem. V] 5.39 Applet, AWT, Event and Swing Programming
{
Container con = getContentPane();
con.setLayout(new FlowLayout());
JLabel j1 = new JLabel ("TextField");
con.add(j1);
JTextField tf1 = new JTextField(40);
con.add(tf1);
setSize(600, 600);
setVisible(true);
}
public static void main(String args[])
{
new TextFieldDemo();
}
}
Output:
• The above program, 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.
5.10.3 JButton
• This class is used to create a push buttons.
• Package: javax.swing
• Constructors:
1. JButton(): Create a empty button having no title and icon.
2. JButton(String str): Create a button having label.
3. JButton(Icon i): Creates a button having icon image.
4. JButton(String str, Icon i): Creates a button having string label and icon
image.
• This class is subclass of Abstract Button class. So it uses following important methods
of abstract button class.
1. void addActionListenerActionListener obj): This method is used to register
the push button to throw an event.
2. String getText(): This method returns the text associated with the button.
Core Java [BBA(CA): Sem. V] 5.41 Applet, AWT, Event and Swing Programming
3. void setText(String s): This method is used to set new Label of the button.
4. void setHorizontalTextPosition(int pos): Sets the horizontal text position
relative to the graphics.
5. void setVerticalTextPosition(int pos): Sets the vertical text position relative
to the graphics.
6. void setIcon( Icon i): This method sets the specified Icon to the button.
7. void setMnemonic(char c): Sets the mnemonic character to the button.
Program 5.17: Program of demonstrate JButton.
import javax.swing.* ;
import java.awt.*;
class JButtonExample extends JFrame
{
JButtonExample()
{
setLayout(new FlowLayout());
JButton btnOk = new JButton("OK");
ImageIcon icon = new ImageIcon("check.png");
JButton btnIcon = new JButton(icon);
JButton btnTxtIcon = new JButton("OK",icon);
add(btnOk);
add(btnIcon);
add(btnTxtIcon);
}
}
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:
Core Java [BBA(CA): Sem. V] 5.42 Applet, AWT, Event and Swing Programming
5.10.4 JToggleButton
• A toggle button is two-state button that allows user to switch on and off. To create a
toggle button in Swing, 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.18: Program to demonstrate JToggleButton.
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class ToggleButtonSample
{
public static void main(String args[])
{
JFrame f = new JFrame("JToggleButton Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = f.getContentPane();
content.add(new JToggleButton("North"), BorderLayout.NORTH);
content.add(new JToggleButton("East"), BorderLayout.EAST);
content.add(new JToggleButton("West"), BorderLayout.WEST);
content.add(new JToggleButton("Center"), BorderLayout.CENTER);
Core Java [BBA(CA): Sem. V] 5.43 Applet, AWT, Event and Swing Programming
5.10.5 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.
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.19: Program to demonstrate JCheckBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Core Java [BBA(CA): Sem. V] 5.44 Applet, AWT, Event and Swing Programming
5.10.6 JRadioButton
• This class is used to create radio button with a text or icon. Radio buttons are
supported by the JRadioButton class, which is a concrete 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.
Core Java [BBA(CA): Sem. V] 5.46 Applet, AWT, Event and Swing Programming
contentPane.add(b3);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}
}
Output:
5.10.8 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 scroll pane.
Core Java [BBA(CA): Sem. V] 5.49 Applet, AWT, Event and Swing Programming
add(s);
}
}
class JScrollPaneJavaExample
{
public static void main(String[] args)
{
JScrollPaneExample frame = new JScrollPaneExample();
frame.setTitle("JScrollPane Java Example");
frame.setBounds(200,250,180,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
5.10.9 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".
• 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);
Core Java [BBA(CA): Sem. V] 5.51 Applet, AWT, Event and Swing Programming
• 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.23: 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);
}
public static void main(String args[])
{
Employees e1 = new Employees ("Editor of Engineering Books");
e1.setSize(500,500);
e1.show();
}
Core Java [BBA(CA): Sem. V] 5.52 Applet, AWT, Event and Swing Programming
4. setValueAt(Object value, int row, int col): Sets the cell value as 'value' for
the position row, col in the JTable.
Program 5.24: Program to display Jtable.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JTableExamples
{
JFrame f;
JTable j;
JTableExamples()
{
f = new JFrame();
f.setTitle("JTable Example");
String[][] data =
{
{ "KAMIL KHAN", "4031", "CSE" },
{ "PRAJAKTA KHATAVKAR", "6014", "IT" },
{ "MANISHA", "7014", "IT" }
};
// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };
// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}
// Driver method
public static void main(String[] args)
{
new JTableExamples();
}
}
Core Java [BBA(CA): Sem. V] 5.54 Applet, AWT, Event and Swing Programming
Output:
5.10.11 JComboBox
• Swing provides a combo box, (a combination of a text field and a dropdown list)
through the JComboBox class, which extends JComponent. A combobox normally
displays one entry.
• However, it can also display a drop-down list that allows a user to select a different
entry. We can also type our selection into the text field.
• The JComboBox component, similar to Choice component in AWT, is a combination of
textfield and drop down list of items. User can make selection by clicking at an item
from the list or by typing into the box.
• 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.
Core Java [BBA(CA): Sem. V] 5.55 Applet, AWT, Event and Swing Programming
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.10.12.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.
• Constructors of JMenu class:
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.26: 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");
Core Java [BBA(CA): Sem. V] 5.58 Applet, AWT, Event and Swing Programming
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setSize(300, 300);
setLocation(200, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit"))
{
System.exit(0);
}
else if (command.equals("Open"))
{
// Open menu item action
System.out.println("Open menu item clicked");
}
else if (command.equals("Save"))
{
// Save menu item action
System.out.println("Save menu item clicked");
}
}
Core Java [BBA(CA): Sem. V] 5.59 Applet, AWT, Event and Swing Programming
myMenu.add(mySubMenu);
JMenuItem myItem = new JMenuItem("Close");
myMenu.add(myItem);
myMenu.addSeparator();
myItem = new JMenuItem("Exit");
myMenu.add(myItem);
return myMenu;
}
private JMenu getColorMenu() {
JMenu myMenu = new JMenu("Color");
JMenuItem myItem = new JMenuItem("Red");
myMenu.add(myItem);
myItem = new JMenuItem("Green");
myMenu.add(myItem);
myItem = new JMenuItem("Blue");
myMenu.add(myItem);
return myMenu;
}
private JMenu getOpenMenu() {
JMenu myMenu = new JMenu("Open");
JMenuItem myItem = new JMenuItem("Java");
myMenu.add(myItem);
myItem = new JMenuItem("HTML");
myMenu.add(myItem);
myItem = new JMenuItem("GIF");
myMenu.add(myItem);
return myMenu;
}
}
Output:
Core Java [BBA(CA): Sem. V] 5.61 Applet, AWT, Event and Swing Programming
5.10.12.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.
• 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:
Table 5.3: JMenuBar Methods
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.
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 = 260;
final int HEIGHT = 220;
frm.setSize(500,500);
frm.setVisible(true);
}
}
Output:
5.10.12.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.
Core Java [BBA(CA): Sem. V] 5.64 Applet, AWT, Event and Swing Programming
5.10.12.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,
you 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.
Program 5.30: Program for JPopMenu.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class PopupSample
{
public static void main(final String args[])
{
JFrame frame = new JFrame("PopupSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create popup menu, attach popup menu listener
JPopupMenu popupMenu = new JPopupMenu("Title");
// Cut
JMenuItem cutMenuItem = new JMenuItem("Cut");
popupMenu.add(cutMenuItem);
// Copy
JMenuItem copyMenuItem = new JMenuItem("Copy");
popupMenu.add(copyMenuItem);
Core Java [BBA(CA): Sem. V] 5.66 Applet, AWT, Event and Swing Programming
// Paste
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
// Separator
popupMenu.addSeparator();
// Find
JMenuItem findMenuItem = new JMenuItem("Find");
popupMenu.add(findMenuItem);
JButton label = new JButton();
frame.add(label);
label.setComponentPopupMenu(popupMenu);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
Output:
Output:
5.10.13 Dialogs
• Dialog windows or dialogs are an indispensable part of most modern GUI
applications.
• A dialog is defined as a conversation between two or more persons. In a computer
application a dialog is a window which is used to "talk" to the application.
• A dialog is used to input data, modify data, change the application settings etc.
Dialogs are important means of communication between a user and a computer
program.
5.10.13.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. You have to close a modal dialog before other windows in the same
application can get focus. A modeless one does not block user input.
• 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 second parameter as '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.
Core Java [BBA(CA): Sem. V] 5.70 Applet, AWT, Event and Swing Programming
Message Dialogs:
• Message dialogs are simple dialogs that provide information to the user. The message
is usually a string constant and represents the text contained in the body.
• If message is an array, it will be interpreted as a series of messages (the interpretation
is recursive - each object will be interpreted according to its type).
• The class JOptionPane is a component which provides standard methods, to pop up a
standard dialog box for a value or informs user of something.
• Following is the declaration for javax.swing.JOptionPane class:
public class JOptionPane
extends JComponent
implements Accessible
• Message dialogs are created with the JOptionPane.showMessageDialog() method. The
messageType defines the style of message. The available options are:
Core Java [BBA(CA): Sem. V] 5.72 Applet, AWT, Event and Swing Programming
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");
Core Java [BBA(CA): Sem. V] 5.74 Applet, AWT, Event and Swing Programming
5.10.14 JColorChooser
• The class JColorChooser provides a pane of controls designed to allow a user to
manipulate and select a color.
Constructors:
1. JColorChooser(): This constructor creates a color chooser pane with an initial
color of white.
2. JColorChooser(Color initialColor): This constructor creates a color chooser
pane with the specified initial color.
3. JColorChooser(ColorSelectionModel model): This constructor creates a color
chooser pane with the specified ColorSelectionModel.
Methods:
1. void addChooserPanel(AbstractColorChooserPanel panel): This method adds a
color chooser panel to the color chooser.
2. static JDialog createDialog(Component c, String title, boolean modal,
JColorChooser chooserPane, ActionListener okListener, ActionListener
cancelListener): This method creates and returns a new dialog containing the
specified ColorChooser pane along with "OK", "Cancel", and "Reset" buttons.
3. AccessibleContext getAccessibleContext(): This method gets the
AccessibleContext associated with this JColorChooser.
4. AbstractColorChooserPanel[] getChooserPanels(): This method returns the
specified color panels.
5. Color getColor(): This method gets the current color value from the color
chooser.
6. boolean getDragEnabled(): This method gets the value of the dragEnabled
property.
7. JComponent getPreviewPanel(): This method returns the preview panel that
shows a chosen color.
8. ColorSelectionModel getSelectionModel(): This method returns the data model
that handles color selections.
9. ColorChooserUI getUI(): This method returns the L&F object that renders this
component.
10. String getUIClassID(): This method returns the name of the L&F class that
renders this component.
11. protected String paramString(): This method returns a string representation of
this JColorChooser.
12. AbstractColorChooserPanel removeChooserPanel(AbstractColorChooserPanel
panel): This method removes the Color Panel specified.
13. void setChooserPanels(AbstractColorChooserPanel[] panels): This method
specifies the Color Panels used to choose a color value.
Core Java [BBA(CA): Sem. V] 5.76 Applet, AWT, Event and Swing Programming
14. void setColor(Color color): This method sets the current color of the color
chooser to the specified color.
15. void setColor(int c): This method sets the current color of the color chooser to
the specified color.
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.34: 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());
Core Java [BBA(CA): Sem. V] 5.77 Applet, AWT, Event and Swing Programming
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);
}
}
Output:
Program 5.35: Program shows the use of Radiobuttons with action listener.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*< applet code="TestRadioButton" width=400 height=200></applet>*/
public class TestRadioButton extends JApplet implements ActionListener
{
public void init()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
JRadioButton fy = new JButton("FYBCA");
JRadioButton sy = new JButton("SYBCA");
Core Java [BBA(CA): Sem. V] 5.78 Applet, AWT, Event and Swing Programming
Program 5.36: An applet which accepts username and password from the user. If the user
is valid, it displays 'Welcome' message. If the user is invalid, it displays 'Invaild' message.
Login.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
public class Login extends JApplet implements ActionListener
{
private JLabel l1, l2, l3;
private JButton ok, cancel;
private JTextField t1, t2;
Core Java [BBA(CA): Sem. V] 5.79 Applet, AWT, Event and Swing Programming
else
{
t1.setText("");
t2.setText("");
l3.setText("");
}
}
}
Login.html
<html>
<body>
<applet code = "Login.class" width = 500 height = 300>
<param name = "htmluser" value = "tybca">
<param name = "htmlpass" value = "tybca">
</applet>
</body>
</html>
Output:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/* <APPLET CODE ="CheckboxAppletExample.class" WIDTH=300 HEIGHT=200>
</APPLET> */
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=" CheckboxAppletExample.class"
height=200 width=400></applet>*/
public class CheckboxAppletExample extends Applet implements ItemListener
{
String msg="Current Selection is:";
Checkbox c1,c2,c3;
CheckboxGroup cbg;
public void init()
{
cbg=new CheckboxGroup();
c1=new Checkbox("java",cbg,true);
c2=new Checkbox("visual basic",cbg,false);
c3=new Checkbox("C",cbg,false);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource()==c1)
{
cbg.setSelectedCheckbox(c1);
}
else if(ie.getSource()==c2)
{
bg.setSelectedCheckbox(c2);
}
Core Java [BBA(CA): Sem. V] 5.82 Applet, AWT, Event and Swing Programming
else
{
cbg.setSelectedCheckbox(c3);
}
repaint();
}
public void paint(Graphics g)
{
msg+=cbg.getSelectedCheckbox().getLabel();
g.drawString(msg,6,130);
}
}
Example 5.38: To creates an applet to handle all mouse movements and print the position
of mouse.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class MouseTest extends Applet implements MouseListener
{
private int x, y = 10;
private String s = " ";
public void init()
{
addMouseListener(this);
}
public void paint(Graphics g)
{
g.drawStrings(s * "at" + "(" + x + ", "+ y + ")"; 50, 50);
}
private void setValues(String event, int x, int y)
{
s = event;
this.x = x;
this.y = y;
repaint(); // This is called, whenever applet needs to update this
information display in its window
}
Core Java [BBA(CA): Sem. V] 5.83 Applet, AWT, Event and Swing Programming
Program 5.39: Write a Java program to display ''Hello World'' with settings font—Times
New Roman, Color–Blue, Background Color–Red on the frame. [W-18]
import java.awt.*;
class Hello extends Frame
{
Label l;
Hello()
{
l=new Label("Hello java");
Core Java [BBA(CA): Sem. V] 5.84 Applet, AWT, Event and Swing Programming
l.setFont(new Font("Georgia",Font.BOLD,14));
l.setForeground(Color.RED);
add(l);
setBackground(Color.BLUE);
setSize(300,300);
setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String a[])
{
new Hello();
}
}
Output:
Program 5.40: Write a applet application in java for designing temple. [S-19]
import java.applet.Applet;
import java.awt.*;
public class Slip10 extends Applet
{
public void paint(Graphics g)
{
Core Java [BBA(CA): Sem. V] 5.85 Applet, AWT, Event and Swing Programming
g.drawRect(100,150,90,120);
g.drawRect(130,230,20,40);
g.drawLine(150,100,100,150);
g.drawLine(150,100,190,150);
g.drawLine(150,50,150,100);
g.drawRect(150,50,20,20);
}
}
Summary
Java AWT stands for Abstract Windowing Toolkit. Java Swing is a part of JFC (Java
Foundation Classes) that is used to create window-based applications. It is built on
the top of AWT API and entirely written in java.
MVC stands for Model View and Controller. MVC is a design pattern that separates
the business logic, presentation logic and data.
The layout managers are used to arrange components in a particular manner. In
layout manager is an interface that is implemented by all the classes of layout
managers. Different classes that represents the layout managers are
BorderLayout, FlowLayout, GridLayout and so on.
The class JComponent is the base class for all Swing components except top-level
containers.
To use a component that inherits from JComponent, you must place the
component in a containment hierarchy whose root is a top-level Swing container.
The JButton class is used to create a button that have platform-independent
implementation.
The class JLabel can display either text, an image, or both.
The class JTextField is a component which allows the editing of a single line of
text.
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.
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options.
The JTextArea class is used to create a text area. It is a multiline area that displays
the plain text only.
The JComboBox class is used to create the combobox (drop-down list). At a time
only one item can be selected from the item list.
In a computer application a dialog is a window which is used to "talk" to the
application.
A dialog is used to input data, modify data, change the application settings etc.
Dialogs are important means of communication between a user and a computer
program.
Core Java [BBA(CA): Sem. V] 5.86 Applet, AWT, Event and Swing Programming
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
An event source is a graphical component that is capable of firing off an event.
Event sources can be any graphical component (e.g., JButton, JList, JComoboBox,
JCheckBox, etc.) the user can interact with.
Event listeners can then be used to handle the events. The Event listener represent
the interfaces responsible to handle events.
Mouse event indicates a mouse action occurred in a component. This low-level
event is generated by a component object for Mouse Events and Mouse motion
events,a mouse button is pressed,a mouse button is released, a mouse button is
clicked (pressed and released), a mouse is moved, the mouse is dragged.
Java allows us to listen for keyboard events.
8. _______ are small Java programs that are mainly used in Internet Applications.
(a) Applets (b) Layouts
(c) Swings (d) All of the Mentioned
Answers
1. (a) 2. (d) 3. (b) 4. (b) 5. (a) 6. (b) 7. (c) 8. (a)
Practice Questions
Q.I Answer the following questions in short.
1. What is swing?
2. What is the purpose of layout manager?
3. List types of layout managers.
4. What do you mean by event listener?
5. How an applet is executed?
6. How events are generated?
7. What is JApplet?
8. What is a listener?
9. What is init?
10. What is component?
11. What is a panel?
12. What is a container?
Q.II Answer the following questions.
1. Explain in brief Delegation Event model for handling events.
2. Enlist the features of swing?
3. Explain in brief the fundamental idea behind MVC architecture?
4. What is difference between Applet and JApplet class?
5. What is Applet? How it is different from application?
6. Write a note on: Applet lifecycle.
7. What is the advantage of using update() method in applet?
8. Which are the various advantages of applet over java application?
9. When start() method is called?
10. To remove applet which method is used?
11. How to compile applet program?
12. Which attributes defines the dimensions of the applet?
13. What repaint method does?
14. How to retrieve parameter in applet?
15. Which swing classes are used to create menu?
16. List layout manager programs.
17. What is event? How to handle events in applets? Explain with example.
Core Java [BBA(CA): Sem. V] 5.88 Applet, AWT, Event and Swing Programming
Winter 2018
1. What is Layout Manager? Explain any one in detail. [4 M]
Ans. Refer to Section 5.6.
2. What is Adapter class? Explain its purpose. [4 M]
Ans. Refer to Section 5.7.3.
3. Write a Java program to display ''Hello World'' with settings font − Times New
Roman, Color–Blue, Background Color–Red on the frame. [4 M]
Ans. Refer to Program 5.39.
4. What is AWT? How to add any component on frame using AWT? [4 M]
Ans. Refer to Section 5.5.
Summer 2019
1. List any two restriction for applet. [2 M]
Ans. Refer to Section 5.1.
2. Which container use border layout as its default layout? [2 M]
Ans. Refer to Section 5.6.
3. What is Applet? Explain life cycle of Applet. [4 M]
Ans. Refer to Section 5.3.
4. Write a java program to accept the details of employee (Eno,Ename, Sal) from the
user and display it on the next frame (Use AWT). [4 M]
Ans. Refer to Program 4.40.
Bibliography
1. https://www.tutorialspoint.com
2. https://www.javatpoint.com
(B.1)