0% found this document useful (0 votes)
39 views68 pages

Block 4

Uploaded by

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

Block 4

Uploaded by

maulik shah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

OBJECT ORIENTED CONCEPTS

PGDCA-102

BLOCK 4:
JAVA CLASS LIBRARY, FILE
HANDLING AND GUI

Dr. Babasaheb Ambedkar Open University


Ahmedabad
OBJECT ORIENTED CONCEPTS

Knowledge Management and


Research Organization
Pune
Editorial Panel

Author
Er. Nishit Mathur

Language Editor
Prof. Jaipal Gaikwad

Graphic and Creative Panel


Ms. K. Jamdal
Ms. Lata Dawange
Ms. Pinaz Driver
Ms. Tejashree Bhosale
Mr. Kiran Shinde
Mr. Akshay Mirajkar

Copyright © 2015 Knowledge Management and Research Organization.


All rights reserved. No part of this book may be reproduced, transmitted or utilized
in any form or by a means, electronic or mechanical, including photocopying,
recording or by any information storage or retrieval system without written
permission from us.

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

The need to plan effective instruction is imperative for a successful


distance teaching repertoire. This is due to the fact that the instructional
designer, the tutor, the author (s) and the student are often separated by
distance and may never meet in person. This is an increasingly common
scenario in distance education instruction. As much as possible, teaching by
distance should stimulate the student's intellectual involvement and
contain all the necessary learning instructional activities that are capable of
guiding the student through the course objectives. Therefore, the course /
self-instructional material are completely equipped with everything that
the syllabus prescribes.
To ensure effective instruction, a number of instructional design
ideas are used and these help students to acquire knowledge, intellectual
skills, motor skills and necessary attitudinal changes. In this respect,
students' assessment and course evaluation are incorporated in the text.
The nature of instructional activities used in distance education self-
instructional materials depends on the domain of learning that they
reinforce in the text, that is, the cognitive, psychomotor and affective. These
are further interpreted in the acquisition of knowledge, intellectual skills
and motor skills. Students may be encouraged to gain, apply and
communicate (orally or in writing) the knowledge acquired. Intellectual-
skills objectives may be met by designing instructions that make use of
students' prior knowledge and experiences in the discourse as the
foundation on which newly acquired knowledge is built.
The provision of exercises in the form of assignments, projects and
tutorial feedback is necessary. Instructional activities that teach motor skills
need to be graphically demonstrated and the correct practices provided
during tutorials. Instructional activities for inculcating change in attitude
and behavior should create interest and demonstrate need and benefits
gained by adopting the required change. Information on the adoption and
procedures for practice of new attitudes may then be introduced.
Teaching and learning at a distance eliminates interactive
communication cues, such as pauses, intonation and gestures, associated
with the face-to-face method of teaching. This is particularly so with the
exclusive use of print media. Instructional activities built into the
instructional repertoire provide this missing interaction between the
student and the teacher. Therefore, the use of instructional activities to
affect better distance teaching is not optional, but mandatory.
Our team of successful writers and authors has tried to reduce this.
Divide and to bring this Self Instructional Material as the best teaching
and communication tool. Instructional activities are varied in order to assess
the different facets of the domains of learning.
Distance education teaching repertoire involves extensive use of self-
instructional materials, be they print or otherwise. These materials are
designed to achieve certain pre-determined learning outcomes, namely goals
and objectives that are contained in an instructional plan. Since the teaching
process is affected over a distance, there is need to ensure that students actively
participate in their learning by performing specific tasks that help them to
understand the relevant concepts. Therefore, a set of exercises is built into the
teaching repertoire in order to link what students and tutors do in the
framework of the course outline. These could be in the form of students'
assignments, a research project or a science practical exercise. Examples of
instructional activities in distance education are too numerous to list.
Instructional activities, when used in this context, help to motivate students,
guide and measure students' performance (continuous assessment)
PREFACE
We have put in lots of hard work to make this book as user-friendly
as possible, but we have not sacrificed quality. Experts were involved in
preparing the materials. However, concepts are explained in easy language
for you. We have included may tables and examples for easy understanding.
We sincerely hope this book will help you in every way you expect.
All the best for your studies from our team!
OBJECT ORIENTED CONCEPTS

Contents

BLOCK 1: INTRODUCTION TO PROGRAMMING WITH JAVA

UNIT 1 PROBLEM SOLVING WITH COMPUTERS


Need of programming, Algorithms, Flowcharts, Pseudo-Code,
Programming Languages Overview, and Overview of Object
Oriented Concepts, Skills check, Exercises
UNIT 2 INTRODUCTION TO JAVA
History, Overview of JVM & Bytecode, Java versions (J2me etc.), Java
class library, JDK, Your First Java Application, Skills check, Exercises
UNIT 2 BEGINNING WITH JAVA PROGRAMMING
Java Keywords, Comments in Java, Variables and Assignments,
Strings and Characters, Arithmetic Operators and Expressions, Type
Conversion in Expressions, Type Conversion, Skills check, Exercises

BLOCK 2: JAVA CONTROL STATEMENTS, OPERATORS AND CLASSES

UNIT 1 JAVA CONTROL STATEMENTS


The if statement, The if-else statement, Blocks of Code, The for
statement, Increment & Decrement operators, Backslash codes,
Relational and Boolean logical operators, Ternary operators, Skills
check, Exercises
UNIT 2 MORE ABOUT CONTROL STATEMENTS AND OPERATORS
Nested if statement, Variations of the for loop, The while loop, The
do loop, Nested loops, The break statement, The continue statement,
The switch statement, The bitwise operators, Skills check, Exercises
UNIT 3 CREATING CLASSES
The General form of a class, Creating Simple Classes, Adding
Constructors, Constructor Overloading, The this keyword, Instance
variables and methods, Static variables and methods, Local
variables and its scope, Method overloading, Argument Passing,
Wrapper Classes, System Class, Garbage Collection, Skills check,
Exercises

BLOCK 3: INHERITANCE, INTERFACE, PACKAGES AND EXCEPTIONS IN


JAVA

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

BLOCK 4: JAVA CLASS LIBRARY, FILE HANDLING AND GUI

UNIT 1 INTRODUCTION TO JAVA CLASS LIBRARY


Classes of java.util package, Classes of java.net package, Classes of
java.lang package, Overview of Collection Framework, Skills check,
Exercises
UNIT 2 FILE HANDLING IN JAVA
Overview of File Handling, File Class in Java, Using Character Stream
Classes, Using Byte Stream Classes, Using Scanner and Console
Classes in Java, Skills check, Exercises
UNIT 3 BUILDING GRAPHICAL USER INTERFACE (SWING)
Building applications using classes related to Graphical Interface,
Creating Layouts in GUI, Using Events in GUI applications, Skills
check, Exercises
Dr. Babasaheb PGDCA-102
Ambedkar
Open University

OBJECT ORIENTED CONCEPTS

BLOCK 4: JAVA CLASS LIBRARY, FILE HANDLING AND GUI

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:

 Graphical User Interface

 Concept of Interfacing

 File handling system

 Byte oriented and Character oriented streams

 Scanner and Console classes

 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

Unit 2: File Handling in Java

Unit 3: Building Graphical User Interface (Swing)

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.3 Classes of Java.net Package

1.4 Classes of Java.lang Package

1.5 Overview of Collection Framework

1.6 Skills Check

1.7 Exercises

1.8 Let Us Sum Up

1.9 Answers for Check Your Progress

1.10 Glossary

1.11 Assignment

1.12 Activities

1.13 Case Study


1.14 Further Readings

1.0 Learning Objectives


After learning this unit, you will be able to understand:

 The Classes of java.util package

 The Classes of java.net package

 The Classes of java.lang package

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.

The java programming supports different type of classes as User defines


class and also there are some classes available with java system that provide some
important support to the java programmer for developing their programming logic
as well as their programming architecture with very smooth and very fine way.
These classes are called Library Classes. In Java support thousands of library
classes and also each class contains various types of functions. The availability of
a large numbers of libraries of standardized classes is a vital reason for popularity
of Java as a standard programming language in modern software world. The use
of class libraries grows for the programmer productivity by allowing programmers
to focus on the characteristics for that are unique to their application without being
burdened with the unexciting task of building and debugging of the standard
infrastructure. This java library classes are often designed and executed with some
typical usage pattern in real life job profile.

1.2 Classes of Java.util package


One of the fundamental packages which uses simplest of Java applications
is Java utility package java.util. Java.util package exists since beginning of Java
which was one of the original packages available in Java.

Utilities in java.util will show complex programming structures that are


used to use in certain professional written classes. The majority of utility classes
are related with collections of such package which will include classes for date
and time, resource bundle handling, parsing a string and Timer API.

Java.util package contains the collections framework, legacy collection


classes, event model, date and time facilities, internationalization, and

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.

The java.util package contains a number of new classes in Java 1.1 to


support internationalization. Many of these classes work in conjuction with the
classes defined in the new java.text package. The most important new class is the
Locale class, which represents a particular locale, or country and language, for
internationalization purposes.

Interface Summary

Collection The root interface in the collection hierarchy.

Comparator Comparison fimction that imposes total ordering on collection


of objects.

Enumeration Object that implements Enumeration interface that generates


series of elements at a time.

EventListener A tagging interface that all event listener interfaces must extend.

Iterator An iterator over a collection.

List An ordered collection.

Listlterator Iterator for lists which allows programmer to traverse list in


either direction and modify list during iteration.
Map An object that maps keys to values.

Map.Entry A map entry.

Observer Class implementation that observer interface when informed of


changes in observable objects.

Set A collection that contains no duplicate elements.

Sorter Map Map that guarantees in ascending key order, sorted as natural
ordering of its keys.

SortedSet Set that guarantees its iterator to traverse set in ascending


element order and sorted as per natural ordering of elements.

5
Java Class Library,
File Handling and
Check your progress 1
GUI 1. Which of following serves as collection classes?

a. Collection c. HashSet

b. Iterator d. None of above

1.3 Classes of Java.net Package


The java.net package provides easy way to access application layer,
transport layer, and internet layer.

Fig 1.1 java.net package

6
It carries most relevant classes and methods: Introduction
to Java Class
URL Library

 URL(String spec) - constructor

 URLConnection openConnectiono - creates TCP connection of type given


by the protocol

URL Connection (interface) / HttpURLConnection (subclass) - for


making HTTP requests

 void setRequestMethod(String method) - set method (GET/POST/... -default


is GET)

 void setDoOutput(boolean dooutput) - intend to use connection for output

 void setDoInput(boolean doinput) - intend to use connection for input

 Output Stream getOutput Stream() - output stream

 InputStream getInputStream0 - input stream

 void setRequestProperty(String key: String value) - set request header

 Hashtable getHeaderFieldsO - read response header

 Object getContento - read input and convert to an object

URLEncoder / URLDecoder - for encoding/decoding special chars in


URLs (application/x-www-form-urlencoded)

 String encode(String s)

 String decode(String s)
Consider an example:

import java.net.*;

import java.io.*;

public class AltaVista {

public static void main (String args[])

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]));

URLConnection connection = url.openConnection();

connection.setDoInput(true);

InputStream in = connection.getInputStream();

// read reply

StringBuffer b = new StringBuffer();

BufferedReader r = new BufferedReader(new InputStreamReader(in));

String line;
while ((line = r.readLine()).!= null)

b.append(line);

String s = b.toString();

// look for first search result, if any

if (s.indexOf(">We found 0 results").!= -1)

System.out.println("No results found.");

else {

int i = s.indexOf("\"status=”“)+9;

int j = s.indexOf("”, i);

System.out.println("First result: " + s.substring(i, j));

}
catch (Exception e) { e.printStackTrace(); }

Apart from this, there are several useful classes in java.net such as:

InetAddress - IP addresses (DNS lookup, etc.)

Socket,ServerSocket - TCP sockets (as in example client and server)

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)

Check your progress 2


1. Which among the following package has classes and interfaces for
networking?

a. java.io c. java.net

b. java.util d. java.lang

1.4 Classes of Java.lang package


The java.lang.Package class contain version information about the
implementation and specification of a Java package. The java.lang package carries
class for each Java primitive type such as Boolean, Byte, Short, Character,
Integer, Float, Long, Double, Void.

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

Check your progress 3


1. The wrapper classes are found in _____ package

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.

It is applicable for single unit of objects. Such framework will provide:

Interfaces:

 Set
 List
 Queue
 Deque
Classes:

 ArrayList
 Vector
 LinkedList
 PriorityQueue
 HashSet
 LinkedHashSet
 TreeSet

The idea of collections framework is to:

 Create high performance framework to implement highly efficient


collections of dynamic arrays, linked lists, trees and hashtables.
 Make framework that will allow several types of collections that will work
in similar manner with high degree of interoperability.
 Ease the extend and/or adapting collection.

12
The Collections Framework hierarchy comprises of: Introduction
to Java Class
Library

Fig 1.2 Collections Framework

List

It is an ordered Collection or sequence which carries duplicate elements that


can put or accessed by their position in list having zero-based index. It contains:

 ArrayList
 LinkedList
 Vector
Set

It is a Collection or sequence of non-duplicate elements that has three main


implementations of Set interface which are:

 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

Map is an object which maps keys to particular values. It has no duplicate


keys. There are three important Map implementation interfaces as:

 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

Check your progress 4


1. Which among the following stores elements in insertion order?

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.

Check your progress 5


1. In Java, skills are required to study about Hash, Tree and LinkedHash maps
that stores elements

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

On running the above program, we get an output as:

A1 Nishit

A2 Rohit

A3 Peeyush
A4 Deepak

A5 Ashok

1.8 Let Us Sum Up


In this unit we have learnt that Java is an object oriented programming
language which supports two features class and object. In this, class is collection
of objects and object is an instance of class.

In Java, utilities such as java.util will show complex programming structures


which can be used further in many professional written classes. This package
contains collection of framework, legacy collection classes, event model, date and
time facilities.

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

1.9 Answers for Check Your Progress

Check your progress 1

Answers: (1-c)

Check your progress 2

Answers: (1-c)

Check your progress 3

Answers: (1-a)

Check your progress 4

Answers: (1-d)

Check your progress 5

Answers: (1-a)

1.10 Glossary
1. Package - It is a collection of Classes and Interfaces.

2. List - It is a collection or sequence having duplicate elements that access by


position in list with zero index.

3. Map - In programming, map shows an object that describes about particular


values.

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.

1.13 Case Study


Discuss the output of the program?

18
Introduction
to Java Class
Library

1.14 Further Readings


1. The online Java tutorial @ http://docs.oracle.com/javase/tutorial/.

2. Paul Deitel and Harvey Deitel, "Java How to Program", 9th ed, 2011.

3. Y. Daniel Liang, "Introduction to Java Programming", 9th ed, 2012.

4. Bruce Eckel, "Thinking in Java", 4th ed, 2007.

19
Java Class Library,
File Handling and
UNIT 2: FILE HANDLING IN JAVA
GUI
Unit Structure
2.0 Learning Objectives

2.1 Introduction

2.2 Overview of File Handling


2.3 File Class in Java

2.4 Using Character Stream Classes

2.5 Using Byte Stream Classes

2.6 Using Scanner and Console Classes in Java

2.7 Skills Check

2.8 Exercises

2.9 Let Us Sum Up

2.10 Answers for Check Your Progress

2.11 Glossary

2.12 Assignment

2.13 Activities

2.14 Case Study


2.15 Further Readings

2.0 Learning Objectives


After learning this unit, you will be able to understand:

 The File Class in Java

 The Character Stream Classes

 The Byte Stream Classes

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.

2.2 Overview of File Handling


Working with files uses input and output operation that we have done
through the use of screen and keyboard. Once the program finished executing,
then all entered data gets lost as primary memory is volatile. If you want to use the
data for later use then it is required to keep it as permanent storage device. It is
found that Java language will provide concept of file with which data can be
stored on disk or secondary storage device. It is found that the data stored can be
read or of any use whenever it is required.

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

2. In Java, Stream classes are categorised into _______ groups:


a. 1 c. 3

b. 2 d. 4

2.3 File Class in Java


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. As file object are created, it does not show that really they
present on disk file with identifier which carries file object. To defining file in File
Class, you need several types of constructors.

File Class constructors:

Constructor Description

File(File parent, String child) It creates new File from parent abstract as
pathname and child pathname string.

File(String pathname) It creates new File by altering required


pathname string into abstract pathname

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.

File class methods:


Method Description

Boolean canExecute() It test for execution of file shown by abstract


pathname.

Boolean canRead() It tests for reading of file shown by 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.

Boolean createNewFile() It creates new from abstract pathname when


file with such name does not exist yet.

Boolean delete() It deletes file or directory shown by abstract


pathname.

Long getFreeSpacet() It returns number of unallocated bytes in


partition named by abstract path name.

String getName() It returns name of file or directory shown by


abstract pathname.

String getParent() It returns pathname string of abstract


pathname's parent, if pathname have no parent
directory.

File getParentFileQ It returns abstract pathname of abstract


pathname's parent. if pathname have no parent
directory.

String getPath() It converts abstract pathname into pathname


string.

String toStringQ It returns pathname string of abstract


pathname.

Boolean mkdir() It creates directory name by abstract


pathname.

Long getTotalSpace() It returns size of partition name by abstract


pathname.

Long getUsableSpace() It returns number of bytes present to virtual


machine on partition name by abstract
pathname.

int hashCodeQ It finds a hash code for abstract pathname.

Boolean isAbsoluteO It tests for this abstract pathname absoluteness.

Boolean isDirectory() It tests for directory containing a file from


abstract pathname.

24
Boolean isFile() It tests for normality of file as file shown by File Handling
this abstract pathname. in Java

Boolean isHidden() It tests if file named by this abstract pathname


is hidden file.

long lastModifiedO It returns time that file shows by this abstract


pathname that was last changed.

Long length() It returns length of file shown by this abstract


pathname

String[] list() It returns array of strings naming files and


directories in directory shown by this abstract
pathname

Check your progress 2


1. Which among the following method will be helpful to read from file?

a. get() c. scan()

b. read() d. readFileInput()

2.4 Using Character Stream Classes


In Java, character streams classes are like byte streams as they have 16-bit
Unicode characters instead of 8 bit bytes. Such type of stream classes is
implemented by Reader and Writer classes along with their subclasses. It is seen
that Readers and Writers classes support similar operations like Input Streams and
Output Streams rather than byte-stream methods that works on bytes or byte
arrays. The character stream methods works with characters and character arrays
or strings.

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.

Another benefit of character streams is that it potentially becomes efficient


as compared to byte streams. The working of many Java original byte streams is
oriented around byte-at-a-time read and writes operations. Character-stream
classes are oriented around buffer-at-a-time read and write operations. With such
type of difference in combination with efficient locking scheme makes the
character stream classes to add overhead of encoding conversion that exists in
several cases.

Character-stream Description Corresponding byte


class class
Reader Abstract class/character-input Input Stream
streams
BufferedReader Buffers input, parses lines BufferedlnputStream
LineNumberReader Keeps track of line numbers LineNumberInputStream
CharArrayReader Reads from a character array ByteArrayInputStream
InputStreamReader Translates byte stream into (none)
character stream
FileReader Translates bytes from file into FileinputStream
character stream
FilterReader Abstract class for filtered Filter Input Stream
character input
PushbackReader Allows characters to be PushbacklnputStream
pushed back
PipedReader Reads from a PipedWriter PipedlnputStream
StringReader StringBufferInputStream
Reads from a String

Writer Abstract class for character- Output Stream


output streams
BufferedWriter Buffers output, uses BufferedOutput Stream
platform's line separator
CharArrayWriter Writes to a character array ByteArrayOutput
Stream

FilterWriter Abstract class for filtered Filter Output Stream


26
character output File Handling
Output Translates character stream (none) in Java
StreamWriter into byte stream
FileWriter Translates character stream FileOutput Stream
into byte file
PrintWriter Prints values and objects to a PrintStream
Writer
PipedWriter Writes to a PipedReader PipedOutput Stream
StringWriter (none)
Writes to a String

Check your progress 3


1. _________ is used to convert byte oriented data into character oriented data
in Java.

a. InputStreamReader c. StringStreamReader
b. Output StreamReader d. PrintStreamReader

2.5 Using Byte Stream Classes


As studied earlier, the file copying is achieved in JDK 1.0 along with byte
streams. It is found that the Byte streams will able to read or write files that carries
ASCII characters which ranges from 0 to 255. So, byte streams will only be able
to copy files having only English alphabets and no other language alphabets.
It is found that classes which supports byte streams is categorised as input
stream classes and output stream classes. The only difference among them
depends on type of job they do. Further, the input stream classes open the file in
read mode whereas output stream classes opens file in write mode. Also, the
character stream classes divide these into reader classes and writer classes. So the
job of input stream classes and reader classes along with job of output stream
classes and writer classes results in similar in spite of different divisions.

Fig 2.1 I/O Stream

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:

Fig 2.2 Input Stream hierarchy

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.

Output Stream Hierarchy


Just like input stream hierarchy, the output stream hierarchy also deals with
output stream classes.

Fig 2.3 Output Stream hierarchy

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:

Fig 2.4 Output of program

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()

2. Which data type is returned by every method of Output Stream?


a. int c. byte

b. float d. None of above

2.6 Using Scanner and Console Classes in Java


Scanner Class
The Scanner class is obtained from java.util which shows a wrapper class
that adds up input stream as stdin giving number of convenience methods that will
read lines and breaks line into tokens. Such set of notes covers set of Scanner a
method which is frequently used.

It is observed that a constructor for Scanner class takes Java InputStream,


File or String as parameter which forms a Scanner object. Normally, Scanner class
works with all which supports iterator that done through collection of tokens.

In Java, the variable System.in is declared as an InputStream and it points to


stdin. System.in is a byte stream so you can't read from it directly if you want to
read character strings, which is what you normally want to do. So it is better to
wrap a Scanner object around System.in so as to take care about string oriented
I/O. The following statement accomplishes this task:

To illustrate the use of a Scanner, consider the following problem:

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

The output of the program shows:

For this purpose, study the program shown which performs following task:

int lineNum = 0;

while (consolehasNextLine()) {
lineTokenizer = new Scanner(console.nextLine());

lineNum++;

// determine if the line has a name field

31
Java Class Library, if (lineTokenizer.hasNext()) {
File Handling and
lineTokenizer.next(); {
GUI
// consume the valid token

else {

System.out.printf("Line %d: line must have the format 'name age


singleness'\n", lineNum);

continue; // proceed to the next line of input

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.

Consider a sample code:

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;

Console input_reader = System.console();

// I'm just going to exit if the console is not provided

if (input_reader == null) {

System.err.println("No console.");

System.exit(1);
}

// you cannot use the C/C++ idiom of

// while (input_line = input_reader.readLine())

// because the test expects a boolean and the above assignment returns

// a String reference. In C/C++ the return of null would be interpreted

// as false, but no so in Java. Hence the infinite loop that I have written

// with a break statement for when readLine returns null

while(true) {

input_line = input_reader.readLine();

if (input_line == null) break;

line_scanner = new Scanner(input_line);

int lineNum = 0;
lineNum++;

// determine if the line has a name field

if (lineTokenizer.hasNext()) {

lineTokenizer.next(); // consume the valid token

else {

34
console.printf("Line %d: line must have the format 'name age File Handling
singleness'\n", lineNum); in Java

continue; // proceed to the next line of input

// determine if the line has a second field, and if so, whether that

// field is an integer

if (lineTokenizer.hasNext()) {

if (lineTokenizer.hasNextInt()) {

lineTokenizer.nextInt(); // consume the valid token

}
else

console.printf("line %d - %s: age should be an integer\n",

lineNum, lineTokenizer.next());

else {

console.printf("line %d: must have fields for age and singleness\n",

lineNum);

continue; // proceed to the next line of input

// determine if the line has a third field, and if so, whether that

// field is a boolean

if (lineTokenizer.hasNext()) {
if (lineTokenizer.hasNextBoolean())

lineTokenizer.nextBoolean(); // consume the valid token

else {

console.printf("line %d - %s: singleness should be a boolean\n",

lineNum, lineTokenizer.next());

continue; // proceed to the next line of input

35
Java Class Library, }
File Handling and
else {
GUI
console.printf("line %d: must have a field for singleness\n", lineNum);

continue; // proceed to the next line of input

lineTokenizer.close(); // discard this line

Check your progress 5


1. Which among the following Scanner class is used to scans the next token as a
byte?

a. public String nextLine() c. public short nextShort()

b. public byte nextByte() d. public int nextInt()

2.7 Skills Check


There are lots of skills required to read Java’s input from System.in console.
It can be done by consider following two ways to read input from console such as:

a. Input Stream Reader wrapped in a Buffered Reader

b. Scanner classes in JDK1.5

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

Check your progress 6


1. If we form a class called Console Input using main method, then we have to
consider a code shown where comment is to be replaced

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

Enter your name

Anika

Enter

60000

Rollno:10 name:Anika fee:60000

2.9 Let Us Sum Up


It is learnt in this unit that file is a mixture of bytes that are stored in
secondary storage device which can be applied to read, write, append or update
data.

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

Check your progress 1

Answers: (1-c), (1-b)

Check your progress 2

Answers: (1-b)

Check your progress 3

Answers: (1-a)

Check your progress 4

Answers: (1-a), (1-d)

Check your progress 5

Answers: (1-b)

Check your progress 6

Answers: (1-a)

2.11 Glossary
1. File - It is a combination of bytes that are placed inside secondary storage
device.

2. Stream - It is a channel through which data flow from source to destination

3. Byte oriented stream - In Java, the data in byte oriented stream is written
and read from file using 8-bit bytes.

4. Character oriented stream - In Java, data in character oriented stream is


accessed each character per time.

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.14 Case Study


Discuss the output of this program?

2.15 Further Readings


1. The online Java tutorial @ http://docs.oracle.com/javase/tutorial/.

2. Paul Deitel and Harvey Deitel, "Java How to Program", 9th ed, 2011.

3. Y. Daniel Liang, "Introduction to Java Programming", 9th ed, 2012.

4. Bruce Eckel, "Thinking in Java", 4th ed, 2007.

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.3 Creating Layouts in GUI

3.4 Using Events in GUI Applications

3.5 Skills Check

3.6 Exercises

3.7 Let Us Sum Up

3.8 Answers for Check Your Progress

3.9 Glossary

3.10 Assignment

3.11 Activities

3.12 Case Study

3.13 Further Readings

3.0 Learning Objectives


After learning this unit, you will be able to understand:

 The applications using classes.

 The Layouts in GUI.

 The Events in GUI applications.

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.

3.2 Building Applications using Classes Related to


Graphical Interface
The computer systems require some form of user interface which will help
to communicate among human beings. Out the whole, the commonly used
interface as of today is graphical user interface which are used in most computers.

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:

 Window: It is a space on the screen which shows information. The contents


here are displayed irrespective from rest of the screen.
 Icon: An icon is small picture which shows objects like program or file
which can be easily carried out in different ways.
 Menu: It shows a list of choices to users. In this, the options are selected
with the use of mouse or other pointing device. It shows the possibility
inside a software which is in terms of commands and functions.
 Pointer: It is an onscreen symbol which shows movement of device which
is controlled by the user in order to select windows, icons and menus.
These four elements have dominated user interface design since they were
first introduced in the mid-1980s. Most recently, mobile devices, such as
smartphones and tablets, have starting using these elements in new ways due to
constraints in space and available input devices. Touchscreen technology has
introduced new interactions such as pinching and rotating, which are not
supported by traditional input devices.

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:

 Leamability: How easy is it for users to accomplish basic tasks?

 Efficiency: How quickly can they perform tasks?

 Memorability: How easily can users establish proficiency?

 Errors: How many errors do users make?

 Satisfaction: How pleasant is it to use the design?


User interface design is critical to the success of a system, and it should be
part of the original design concepts for the system.

Check your progress 1


1. Identify the three software parts of GUI program?

a. Windows, Buttons, Mice

b. GUI Components, Graphics, Code

c. GUI Components, Event Listeners, Application Code

d. Frames, Code, Events

3.3 Creating Layouts in GUI


There are two different modes you can use to arrange and organize your
GUIs: Fixed and Automatic. Up until now, every Unity GUI example provided in
this guide has used Fixed Layout. To use Automatic Layout, write GUI Layout
instead of GUI when calling control functions. You do not have to use one Layout
mode over the other, and you can use both modes at once in the same On GUI()
function.

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.

There are two key differences when using Automatic Layout:

GUI Layout is used instead of GUI

No Rect() function is required for Automatic Layout Controls

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.

Fixed Layout - 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.

/* Center multiple Controls on the screen using Groups */

//JavaScript

function OnGUI () {

// Make a group on the center of the screen

GULBeginGroup (Rect (Screen.width 2 - 50, Screen.height / 2 -


50, 100, 100));

// 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");

GUI.Button (Rect (10,40,80,30), "Click me");

End the group we started above. This is very important to


remember! GUI.EndGroup 0;

// C#

using UnityEngine;

using System.Collections;

public class GUITest : MonoBehaviour {

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.

/* Using multiple Groups to clip the displayed Contents */

//JavaScript

var bgImage : Texture2D; // background image that is 256 x 32

var fglmage : Texture2D; // foreground image that is 256 x 32

var playerEnergy = 1.0; //a float between 0.0 and 1.0

function OnGUI 0 {

// Create one Group to contain both images

// Adjust the first 2 coordinates to place it somewhere else on-screen


GUI.BeginGroup (Rect (0,0,256,32));
// Draw the background image

GUI.Box (Rect (0,0,256,32), bglmage);

// Create a second Group which will be clipped

// We want to clip the image and not scale it, which is why we need
the second Group

GUI.BeginGroup (Rect (0,0,p1ayerEnergy * 256, 32));

// Draw the foreground image

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;

public class GUITest : MonoBehaviour {

// background image that is 256 x 32


public Texture2D bglmage;

// foreground image that is 256 x 32

public Texture2D fglmage;

// a float between 0.0 and 1.0

public float playerEnergy = 1.0f;

void OnGUI 0 {

// Create one Group to contain both images

// Adjust the first 2 coordinates to place it somewhere else on-screen

GUL.BeginGroup (new Rect (0,0,256,32));

// Draw the background image

GULBox (new Rect (0,0, 256,32), bgImage);

// Create a second Group which will be clipped


// We want to clip the image and not scale it, which is why we need the
second Group

GUI.BeginGroup (new Rect (0,0,playerEnergy * 256, 32));

47
Java Class Library,
File Handling and
GUI

Check your progress 2


1. Which among the following component exists in all GUI programs?

a. Frame c. Monitor

b. Mouse d. Button

3.4 Using Events in GUI Applications


To design an interactive Graphical User Interfaces is a difficult task,
especially for those who have no experience. Creating user interfaces with the
help of toolkit is time consuming process as it does not integrate in scientific-
computing work-flow during explanation of algorithms and data-flow where
objects shown by GUI are likely to change.

Visual computing, where the programmer creates first a graphical interface


and then writes the callbacks of the graphical objects, gives rise to a slow
development cycle, as the work-flow is centered on the GUI, and not on the code.

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:

To carry out objects, developer requires no knowledge about internal


details of their procedures. It is seen that as long as object has rotate method, the
developer knows how to rotate it.
49
Java Class Library,
File Handling and
Check your progress 3
GUI 1. A Graphics object is:

a. object showing part of Frame which can be drawn.

b. object that shows whole Frame.

c. object that shows full monitor.

d. object that shows graphics board.

3.5 Skills Check


In Java GUI programming, lot of skills are used to interface icons and
elements with electronic devices.. The knowledge about Automatic Layout and
Fixed Layout will allow user to design a program which supports several
elements.

In order to design a graphical user interface, you require following steps:

 Creating a new form or dialog

 Placing and arranging components in the form

 Defming properties of the components

 Binding components to the source code

 Making forms functional

 Localizing forms

 Previewing Forms

Check your progress 4


1. In order to design a graphical user interface, it require

a. Creating a new form of dialogue

b. Placing and arranging components in the form

c. Defining properties of the components

d. All of the above

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:

This simple application draws a JFrame that is completely filled with a


JButton. When the button is pressed, “Click Me!” prints to the command line.

51
Java Class Library,
File Handling and
GUI

Fig 3.1 Java

3.7 Let Us Sum Up


In this unit we have learnt that GUI is a Graphical User Interface that uses
icons or visual indicators to work with electronic devices rather than working with
text along with command line.

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.

3.8 Answers for Check Your Progress

Check your progress 1

Answers: (1-c)

Check your progress 2

Answers: (1-a)

52
Building
Check your progress 3
Graphical User
Interface
Answers: (1-a) (Swing)

Check your progress 4

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.

3.13 Further Readings


1. The online Java tutorial @ http://docs.oracle.com/javase/tutorial/.
2. Paul Deitel and Harvey Deitel, "Java How to Program", 9th ed, 2011.

3. Y. Daniel Liang, "Introduction to Java Programming", 9th ed, 2012.

4. Bruce Eckel, "Thinking in Java", 4th ed, 2007.

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 the purpose of the File class?

4. Explain Java.util package with examples?

Long Answer Questions


1. Explain in detail about GUI in Java?
2. Compare among Character oriented stream and Byte oriented stream?

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:

3. Any Other Comments


………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

……………………………………………………………………………………………

57
Education is something
which ought to be
brought within
the reach of every one.

- Dr. B. R. Ambedkar

Dr. Babasaheb Ambedkar Open University


Jyotirmay’ Parisar, Opp. Shri Balaji Temple, Sarkhej-Gandhinagar Highway, Chharodi,
Ahmedabad-382 481.

You might also like