Block 4
Block 4
PGDCA-102
BLOCK 4:
JAVA CLASS LIBRARY, FILE
HANDLING AND GUI
Author
Er. Nishit Mathur
Language Editor
Prof. Jaipal Gaikwad
Acknowledgment
Every attempt has been made to trace the copyright holders of material reproduced
in this book. Should an infringement have occurred, we apologize for the same and
will be pleased to make necessary correction/amendment in future edition of this
book.
The content is developed by taking reference of online and print publications that
are mentioned in Bibliography. The content developed represents the breadth of
research excellence in this multidisciplinary academic field. Some of the
information, illustrations and examples are taken "as is" and as available in the
references mentioned in Bibliography for academic purpose and better
understanding by learner.'
ROLE OF SELF INSTRUCTIONAL MATERIAL IN DISTANCE LEARNING
Contents
UNIT 1 INHERITANCE
Overview of Re-usability, Subclasses, Inheritance and Variables,
Method Overriding, Inheritance and Methods, Inheritance and
Constructors, Class Modifiers, Variable Modifiers, Constructor
Modifiers, Method Modifiers, Object and Class classes, Skills Check,
Exercises
UNIT 2 INTERFACES AND PACKAGES
Interfaces, Interface References, Interface Inheritance, The
instanceof Operator, Packages, The import statement, Access control
and Packages, Skills Check, Exercises
UNIT 3 EXCEPTIONS
Overview of Exceptions, Exception Handling, Catch Block and
searches, The throw statement, Exception and Error classes, The
throws clause, Custom exceptions, Skills check, Exercises
UNIT 1
INTRODUCTION TO JAVA CLASS LIBRARY 03
UNIT 2
FILE HANDLING IN JAVA 20
UNIT 3
BUILDING GRAPHICAL USER INTERFACE (SWING) 41
BLOCK 4: JAVA CLASS LIBRARY, FILE
HANDLING AND GUI
Block Introduction
GUI is a Graphical User Interface that works with icons or indicators along
with electronic devices. Interface is a coordination involved among computer,
program and humans. It is seen that graphical user interface uses visual elements
that will help in showing information which is kept inside computer that is simple
to understand. These elements makes easy for people to work by involving certain
computer software. It is found that in order to design a good user interface it
should allow easy and natural interaction among user and system. File is a mixture
of bytes which are stored in secondary storage device such as disk. So we find that
file handling is applied in order to read, write, append or update a file without
directly opening it.
In this block students will be get knowledge on Java Library Classes with
stress on files handling and its usages. The input and output operation of file along
with process of data entered is well explained. The student will be given
information on Byte oriented stream and Character oriented stream with their
reading writing mechanism.
After this block, student will get knowledge on Scanner and Console classes
with usage on java.util and basic understanding of wrapper class with input stream
stdin. The knowledge about utilities in java.util along with pogramming structures
allow students to work on professional written classes. The idea about Java.util
package will be beneficial to them in longer use.
Block Objective
After learning this block, you will be able to understand:
Concept of Interfacing
Java.util package
1
Java Class Library, Basic of java.lang package
File Handling and
GUI
Block Structure
Unit 1: Introduction to Java Class library
2
UNIT 1: INTRODUCTION TO JAVA CLASS
LIBRARY
Unit Structure
1.0 Learning Objectives
1.1 Introduction
1.2 Classes of Java.util Package
1.7 Exercises
1.10 Glossary
1.11 Assignment
1.12 Activities
3
Java Class Library, 1.1 Introduction
File Handling and
GUI Java is an object oriented programming language, so in java programming,
main two features are supported that is class and object. Basically we know that
class is collection of objects and object is an instance of class. The uses of the java
libraries of class spread the programmer efficiency by allowing computer
programmer to focus on the functionality unique to their job. The library classes
are generally planned with some typical usage pattern in observance, and the
performance may be suboptimal if the actual usage differs. We deliver an
approach for rewriting applications to use different customized versions of library
classes that are generated using a combination of static analysis and profile
information.
4
miscellaneous utility classes. This reference will take you through simple and Introduction
practical methods available in java.util package. to Java Class
Library
It is found that a number of classes in java.util are framed which will
manage a collection of objects. It is seen that a Vector class supports variable-
length arrays of objects, while Hashtable class creates hashtables or associative
arrays which carriers key/value pairs of objects.
Interface Summary
EventListener A tagging interface that all event listener interfaces must extend.
Sorter Map Map that guarantees in ascending key order, sorted as natural
ordering of its keys.
5
Java Class Library,
File Handling and
Check your progress 1
GUI 1. Which of following serves as collection classes?
a. Collection c. HashSet
6
It carries most relevant classes and methods: Introduction
to Java Class
URL Library
String encode(String s)
String decode(String s)
Consider an example:
import java.net.*;
import java.io.*;
try {
7
Java Class Library, // make connection
File Handling and
URL url = new URL(http://www.altavista.com/cgi-bin/query?q=" +
GUI
URLEncoder.encode(args[0]));
connection.setDoInput(true);
InputStream in = connection.getInputStream();
// read reply
String line;
while ((line = r.readLine()).!= null)
b.append(line);
String s = b.toString();
else {
int i = s.indexOf("\"status=”“)+9;
}
catch (Exception e) { e.printStackTrace(); }
Apart from this, there are several useful classes in java.net such as:
8
ProtocolHandler - defines mapping for URL.openConnection() to concrete Introduction
URLConnection to Java Class
Library
ContentHandler - defines mapping for getObject() to Object (based on MIME
type)
a. java.io c. java.net
b. java.util d. java.lang
Annotations
Deprecated Marks program elements which are not used by programmers.
Override Mark methods that override method declaration in superclass.
SafeVarargs Claims to compiler about annotation target without argument.
SuppressWarnings Shows compiler about warnings for program element.
Interfaces
9
Java Class Library, Classes
File Handling and
GUI
10
Exceptions Introduction
to Java Class
Library
CloneNotSupportedException
a. java.lang c. java.io
b. java.util d. java.net
11
Java Class Library, 1.5 Overview of Collection Framework
File Handling and
GUI It is found that collections in java carries a framework which shows
architecture that will store and carry out group of objects. The operations done on
data like searching, sorting, insertion, manipulation, deletion can be done with the
help of Java Collections.
Interfaces:
Set
List
Queue
Deque
Classes:
ArrayList
Vector
LinkedList
PriorityQueue
HashSet
LinkedHashSet
TreeSet
12
The Collections Framework hierarchy comprises of: Introduction
to Java Class
Library
List
ArrayList
LinkedList
Vector
Set
HashSet
TreeSet
LinkedHashSet
HashSet: It stores elements in hash table which is best performing
implementation having no guarantee in relation to iteration.
TreeSet: It stores elements in red-black tree which orders elements as per their
values. It is slower than HashSet.
13
Java Class Library, LinkedHashSet: It is implemented as hash table having a linked list which runs
File Handling and through it.
GUI
Map
HashMap
TreeMap
LinkedHashMap
HashMap: It has no guarantee related to order of iteration
TreeMap: It stores elements in red black tree which is based on values and is
slower than HashMap.
LinkedHashMap: It will order elements as per order in which they were inserted
into set.
Iterator/ListIterator
It is seen that both Iterator and ListIterator are applied to iterate with the
help of elements of collection class. With the help of Iterator, we move in forward
direction with the help of ListIterator.
Iterator
ListIterator
a. TreeMap c. LinkedMap
b. HashMap d. LinkedHashMap
14
1.6 Skills Check Introduction
to Java Class
In Java, skills are required to study about Hash, Tree and LinkedHash maps Library
that stores elements. The detail study of list and set allow us to bifurcate with
related skills that can be used to study them.
a. True
b. False
1.7 Exercises
Example 1:
Let us develop a LinkedHashMap with the help of following code:
15
Java Class Library,
File Handling and
GUI
A1 Nishit
A2 Rohit
A3 Peeyush
A4 Deepak
A5 Ashok
16
It is studied that java.net package provides easy way to access application Introduction
layer, transport layer, and internet layer. The java.lang.Package class contain to Java Class
version information about the implementation and specification of a Java package. Library
Answers: (1-c)
Answers: (1-c)
Answers: (1-a)
Answers: (1-d)
Answers: (1-a)
1.10 Glossary
1. Package - It is a collection of Classes and Interfaces.
1.11 Assignment
Discuss Java Library classes in Detail.
17
Java Class Library, 1.12 Activities
File Handling and
GUI Is the output of this program true? Discuss.
18
Introduction
to Java Class
Library
2. Paul Deitel and Harvey Deitel, "Java How to Program", 9th ed, 2011.
19
Java Class Library,
File Handling and
UNIT 2: FILE HANDLING IN JAVA
GUI
Unit Structure
2.0 Learning Objectives
2.1 Introduction
2.8 Exercises
2.11 Glossary
2.12 Assignment
2.13 Activities
20
2.1 Introduction File Handling
in Java
File is a mixture of bytes which are stored in secondary storage device such
as disk. So we find that file handling is applied in order to read, write, append or
update a file without directly opening it. It is seen that files in Java can be:
Text File
Binary File
As studied, Text File carries information related to only textual data. While
working, you can save the Text files in either a plain text (.TXT) format or rich
text (.RTF) format as like files in Notepad. Binary Files carries both textual data
and custom binary data such as font size, text color and text style.
We see in case of files that are handled in java requires to import package
having the name as java.io that carries all required classes which is required to do
input and output (I/O) operations. So it seen that file handling in java can be done
with the help of two streams:
byte oriented
character oriented
Byte oriented stream: In case of byte oriented stream, the data is written
and read from file using 8-bit bytes. As seen, some common class to do oriented
streaming of data from file uses:
ByteArrayInputStream
FileInputStream
FileOutput Stream
PrintStream
21
Java Class Library, Such type of stream is good for binary data like java .class file where there
File Handling and are images and machine data.
GUI
Character oriented stream: In this case, data is accessed each character
per time. It is used to do character oriented streaming of data that uses files like:
FileReader
FileWriter
InputStreamReader
PrintWriter
Such stream is good for text source like java source file, text document etc.
Consider an example:
22
Check your progress 1 File Handling
in Java
1. Which among the following is a channel by which data flow from source to
destination?
a. String c. Stream
b. Character d. Buffer
b. 2 d. 4
Constructor Description
File(File parent, String child) It creates new File from parent abstract as
pathname and child pathname string.
File(String parent: String child) It creates new File from parent and child
pathname strings.
File(String parent, String child) It creates new File by converting given file
URI into abstract pathname.
23
Java Class Library, Boolean canWrite() It tests for alteration of file shown by abstract
File Handling and pathname.
GUI
int compareTo (File pathname) It compares two abstract pathnames.
24
Boolean isFile() It tests for normality of file as file shown by File Handling
this abstract pathname. in Java
a. get() c. scan()
b. read() d. readFileInput()
The main benefit of character streams is that they make it simple to write a
program which does not depend on particular character encoding. It is found that
Java keeps strings in Unicode, which serves as an international standard character
encoding which is capable of showing written languages. Normally it is seen that
user-readable text files basically uses encodings which does not relates to Unicode
or ASCII. It is sometimes seen that character streams hides dealing with such
complex encodings that shows two classes which acts as bridges between byte
streams and character streams. It is seen that an InputStreamReader class will
25
Java Class Library, work as character-input stream which reads bytes from byte-input stream and
File Handling and converts it into characters as per specific encodings. Also, Output StreamWriter
GUI class will carry out character output stream which alters characters into bytes as
per particular encoding and then writes to byte-output stream.
a. InputStreamReader c. StringStreamReader
b. Output StreamReader d. PrintStreamReader
27
Java Class Library, Input Stream Hierarchy
File Handling and
The input stream classes are collection of several classes which performs
GUI
similar job of opening file in read mode. Apart from this, they require different
needs of programmer where classes exist in java.io package that results in
hierarchical structure as shown:
Further it was observed that the hierarchy has 12 input stream classes where
classes are divided in two categories as high-level streams and low-level streams.
Out of 12 input stream classes, classes of Filter Input Stream are known as high-
level streams having 4 and remaining are known as low-level streams that has 8.
28
In this, every subclasses of Filter Output Stream known as high-level File Handling
streams has 3 streams while balance are known as low-level streams as 6. In this, in Java
1 stream is linked to another to get higher functionality. Consider an example of
java Byte Array Output Stream class where data is written in two files as shown:
29
Java Class Library,
File Handling and
Check your progress 4
GUI 1. Which method of InputStream is used to read integer of next available byte
input?
a. read() c. get()
b. scanf() d. getInteger()
Finally, read and type check lines of user input where every line contains
three fields organized as:
Fields in parentheses shows errors that reports using proper error message.
Here is a sample input file:
30
File Handling
in Java
For this purpose, study the program shown which performs following task:
int lineNum = 0;
while (consolehasNextLine()) {
lineTokenizer = new Scanner(console.nextLine());
lineNum++;
31
Java Class Library, if (lineTokenizer.hasNext()) {
File Handling and
lineTokenizer.next(); {
GUI
// consume the valid token
else {
32
File Handling
in Java
Console Class
In Java, Console class is an easy way to deal with stdio that supports reading
from stdin and writing to stdout. It reads character strings so you do not have to
worry about wrapping System.in inside a Scanner class.
You can obtain the system provide console object from System.console. It is
a good idea to check whether this object exists, since it does not exist for non-
interactive Java programs, which includes program in which stdin is redirected.
For example, the following invocation will not have a console object:
java foo < inputfile // no console object for programs with redirected input
A console object also may not exist for Java programs run with older
versions of the Java virtual machine and some systems will not provide it for
security purposes. In all of these cases you will have to fall back on System.in and
System.out.
import java.util.Scanner;
33
Java Class Library, import java.io.Console; // Console is in the java.io library
File Handling and
class datacheck {
GUI
static public void main(String args[]) {
Scanner lineTokenizer;
String input_line;
if (input_reader == null) {
System.err.println("No console.");
System.exit(1);
}
// because the test expects a boolean and the above assignment returns
// as false, but no so in Java. Hence the infinite loop that I have written
while(true) {
input_line = input_reader.readLine();
int lineNum = 0;
lineNum++;
if (lineTokenizer.hasNext()) {
else {
34
console.printf("Line %d: line must have the format 'name age File Handling
singleness'\n", lineNum); in Java
// determine if the line has a second field, and if so, whether that
// field is an integer
if (lineTokenizer.hasNext()) {
if (lineTokenizer.hasNextInt()) {
}
else
lineNum, lineTokenizer.next());
else {
lineNum);
// determine if the line has a third field, and if so, whether that
// field is a boolean
if (lineTokenizer.hasNext()) {
if (lineTokenizer.hasNextBoolean())
else {
lineNum, lineTokenizer.next());
35
Java Class Library, }
File Handling and
else {
GUI
console.printf("line %d: must have a field for singleness\n", lineNum);
If we form a class called Console Input using main method, then you have
to consider a code shown where comment is to be replaced;
36
The output we get with errors as: File Handling
in Java
a. True
b. False
2.8 Exercises
Exercise 1:
Consider a Java Scanner class which reads int, string and double value as an
input?
Solution:
37
Java Class Library, On running the above program, we get:
File Handling and
Enter your rollno
GUI
10
Anika
Enter
60000
It is seen that working with files uses input and output operation which can
be implement using screen and keyboard. Once the program finished executing,
then all entered data gets lost as primary memory is volatile
It is studied that in Byte oriented stream, data is written and read from file
using 8-bit bytes while in Character oriented stream, data is accessed by character
per time.
In Java, files and directories are carried out and calculated by File class. The
File class will not really show for input and output to files. It shows an identifier
of files and directories.
Further it is studied that Scanner class is obtained from java.util that shows
wrapper class which adds input stream as stdin by giving number of convenience
methods which read lines and breaks line into tokens. While Console class is an
easy way to deal with stdio that supports reading from stdin and writing to stdout.
38
File Handling
2.10 Answers for Check Your Progress
in Java
Answers: (1-b)
Answers: (1-a)
Answers: (1-b)
Answers: (1-a)
2.11 Glossary
1. File - It is a combination of bytes that are placed inside secondary storage
device.
3. Byte oriented stream - In Java, the data in byte oriented stream is written
and read from file using 8-bit bytes.
2.12 Assignment
Discuss Byte oriented steam and Character oriented stream.
39
Java Class Library, 2.13 Activities
File Handling and
GUI Give some examples related class constructor in Java.
2. Paul Deitel and Harvey Deitel, "Java How to Program", 9th ed, 2011.
40
UNIT 3: BUILDING GRAPHICAL USER
INTERFACE (SWING)
Unit Structure
3.0 Learning Objectives
3.1 Introduction
3.2 Building Applications using Classes Related to Graphical Interface
3.6 Exercises
3.9 Glossary
3.10 Assignment
3.11 Activities
3.1 Introduction
GUI also known as Graphical User Interface uses icons or other visual
indicators to work with electronic devices instead of working only with text with
the help of command line. It is found that all versions of Windows use GUI apart
41
Java Class Library, from MS-DOS. The interface was initially developed at Xerox PARC by Alan
File Handling and Kay, Douglas Engelbart. In this, Java Graphics like APIs, AWT and Swing,
GUI delivers high reusable GUI components like button, text field, label, choice, panel
and frame for certain GUI applications. In Java, the classes can be reused again
instead of re-invent the wheels.
The graphical user interface will use visual elements which will help in
showing information that is kept inside computer which is easy to understand.
Such elements make easy for people to work by involving certain computer
software. It is found that a GUI uses windows, icons, and menus to carry out
commands that can be in shape of opening files, deleting files and moving files.
The GUI software is easier to apply as compared to command line software as
there is no need to type and to keep in memory the individual commands.
It is found that the most common graphical elements are shown by WIMP
which is a mixture of window, icon, menu and pointer. In this:
42
Importance of Interface Design Building
Graphical User
To design a good user interface is a difficult task. A good user interface will Interface
allow an easy and natural interaction among user and system. While a slick look (Swing)
interface is cool which concerns with overriding when it comes to user interface
design that is usable. Usability is basically ISO standard to which a product can be
used by specific users having specified goals that works with effectiveness,
efficiency and satisfaction in particular manner. There are certain practical terms
that are well-designed with interface such as:
43
Java Class Library, Fixed Layout makes sense to use when you have a pre-designed interface to
File Handling and work from. Automatic Layout makes sense to use when you don’t know how
GUI many elements you need up front, or don’t want to worry about hand-positioning
each Control. For example, if you are creating a number of different buttons based
on Save Game files, you don’t know exactly how many buttons will be drawn. In
this case Automatic Layout might make more sense. It is really dependent on the
design of your game and how you want to present your interface.
44
Arranging Controls Building
Graphical User
Depends on the type of layout mode, there exists different controls which Interface
can handle and shows grouping. It is found that in Fixed Layout, you will put (Swing)
different Controls into Groups, whereas in case of Automatic Layout, you will be
able to control and handle Areas, Horizontal Groups and Vertical Groups.
Groups are a convention available in Fixed Layout Mode. They allow you to
define areas of the screen that contain multiple Controls. You define which
Controls are inside a Group by using the GUI.BeginGroup() and GUI.EndGroup()
functions. All Controls inside a Group will be positioned based on the Group’s
top-left corner instead of the screen’s top-left corner. It is found that if you reposit
group at runtime, then relative positions of controls in group will be adjusted. As
an example, it’s very easy to center multiple Controls on-screen.
//JavaScript
function OnGUI () {
// All rectangles are now adjusted to the group. (0,0) is the top
left corner of the group.
// we'll make a box so you can see where the group is on-screen
GUI.Box (Rect (0,0,100,100), "Group is here");
// C#
using UnityEngine;
using System.Collections;
void OnGUI () {
45
Java Class Library, // Make a group on the center of the screen
File Handling and
GULBeginGroup (new Rect (Screen.width / 2 - 50, Screen.height ' 2 -
GUI
50, 100, 100));
// All rectangles are now adjusted to the group. (0,0) is the topleft
corner of the group.
You can also nest multiple Groups inside each other. When you do this,
each group has its contents clipped to its parent’s space.
//JavaScript
function OnGUI 0 {
// We want to clip the image and not scale it, which is why we need
the second Group
46
GUI.Box (Rect (0,0,256,32), fgImage); Building
Graphical User
// End both Groups Interface
GUI.EndGroup (); (Swing)
GUI.EndGroup ();
// C#
using UnityEngine;
using System.Collections;
void OnGUI 0 {
47
Java Class Library,
File Handling and
GUI
a. Frame c. Monitor
b. Mouse d. Button
It is seen that if you want your program to calculate geometric objects, then
you have to guide computer about set of 3 numbers and to tell him how to rotate
that point along given axis. Also, if you want to use sphere, then a bit more work
requires your program to function which will create points, spheres, etc. It knows
how to rotate them, to mirror them, to scale them. So in pure procedural
programming you will have procedures to rotate, scale, mirror, each one of your
objects. If you want to rotate an object you will first have to find its type and then
apply the right procedure to rotate it.
48
In object oriented programming, new abstraction just like object carries both Building
data and procedures which is applied and altered data. In this, the data entries are Graphical User
Interface
known as attributes of object and procedures methods. So with the help of object
(Swing)
oriented programming, an object is described to rotate. A point object could be
implemented in python with:
The above program code will form a Point class. Point objects can be
created as instances of the Point class as:
Localizing forms
Previewing Forms
50
Building
3.6 Exercises
Graphical User
Exercise 1: Interface
(Swing)
Consider a Swing application in Java and write a program with the help of
application in Jython?
Solution:
51
Java Class Library,
File Handling and
GUI
It is seen that graphical user interface uses visual elements that will help in
showing information which is kept inside computer that is simple to understand.
These elements makes easy for people to work by involving certain computer
software It is found that in order to design a good user interface it should allow
easy and natural interaction among user and system.
Answers: (1-c)
Answers: (1-a)
52
Building
Check your progress 3
Graphical User
Interface
Answers: (1-a) (Swing)
Answers: (1-d)
3.9 Glossary
1. GUI - It is a Graphical User Interface that works with icons or indicators
along with electronic devices
2. Interface - It is a coordination involved among computer, program and
humans.
3.10 Assignment
Discuss the advantages of GUI?
3.11 Activities
Fill in the blanks so that this program displays a Frame:
53
Java Class Library, 3.12 Case Study
File Handling and
GUI Prepare a report describing about various GUI elements.
54
Block Summary
The block gives detailed explanation to students on Java Library Classes
along with understanding of Graphical User Interface. The concept of files
handling in Java will give more knowledge in terms of how data is kept and work
through these files. The information related to input and output operation of file
with concept of Byte oriented stream and Character oriented stream will really
beneficial to user who has little knowledge about Java programming.
After this block, student will get knowledge about Scanner and Console
classes with usage on java.util and basic understanding of wrapper class with
input stream stdin. The knowledge about utilities in java.util along with
pogramming structures allow students to work on professional written classes.
The idea about Java.util package will be beneficial to them in longer use.
55
Java Class Library, Block Assignment
File Handling and
GUI Short Answer Questions
1. What are wrapper classes?
2. It is possible to use the File class to list the contents of the current working
directory.
3. What is meant by Stream and what are the types of Streams and classes of
the Streams?
56
Enrolment No.
1. How many hours did you need for studying the units?
Unit No 1 2 3 4
Nos of Hrs
2. Please give your reactions to the following items based on your reading of the
block:
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
……………………………………………………………………………………………
57
Education is something
which ought to be
brought within
the reach of every one.
- Dr. B. R. Ambedkar