Study Outline of JAVA Programming
Study Outline of JAVA Programming
Study Outline of JAVA Programming
A Guided Book of
A Guidebook
of
JAVA
Engr. Abu Saleh Musa Miah (Abid)
Lecturer(Bangladesh Army University of Science and Technology(BAUST)
B.Sc.Engg. in Computer Science and Engineering(First Class First)
M.Sc.Engg.CSE, University of Rajshahi (First Class First).
Ph.D(Pursuing)
Email:[email protected]
Cell:+88-01734264899
Email : [email protected]
Publisher : Abu Syed Md Mominul Karim Masum.
Chemical Engr.
Chief Executive Officer (CEO)
Swarm Fashion, Bangladesh.
Mohakhali,Dhaka.
Email : [email protected]
Copyright : Writer
Computer Compose : Writer
Print : Royal Engineering Press & Publications.
Meherchandi, Padma Residential Area, Boalia, Rajshahi.
Dedicated
To My Parents and honorable Teachers.
†jL‡Ki K_v
Object Oriented Programming with JAVA †Kvm©wU evsjv‡`‡ki cÖvq mKj wek¦we`¨vj‡qi wm‡jev‡m ¯’vb jvf
K‡i‡Q,evRv‡i †U·UeB _vK‡jI Mfxi fv‡e Abyaveb I cix¶vq fvj gvK©m DVv‡bvi gZ mvRv‡bv †U·UeB mnRjf¨ bq |
cix¶vi cÖ¯‘wZi ¯^v‡_© ZvB, GB MvBWeBwU Avcbv‡K mn‡hvwMZv Ki‡e e‡j Avkv Kiv hvq|
GB eB‡qi cvVK wn‡m‡e, AvcwbB n‡”Qb me‡P‡q ¸iæZ¡c~Y© mgv‡jvPK ev gšÍe¨Kvix| Avi Avcbv‡`i gšÍe¨ Avgvi Kv‡Q g~j¨evb,
Kvib AvcwbB ej‡Z cvi‡eb Avcbvi Dc‡hvMx K‡i eBwU †jLv n‡jv wKbv A_©vr eBwU wKfv‡e cÖKvwkZ n‡j AviI fvj n‡Zv|
mvgwMÖK e¨vcv‡i Avcbv‡`i †h †Kvb civgk© Avgv‡K DrmvwnZ Ki‡e|
ACKNOWLEDGEMENTS
I wish to express my profound gratitude to all those who helped in making this book a reality;
especially to my families, the classmates, and authority of Royal Engineering Publications for
their constant motivation and selfless support. Much needed moral support and encouragement
was provided on numerous occasions by my families and relatives. I will always be grateful, to
the numerous web resources, anonymous tutorials hand-outs and books I used for the
resources and concepts, which helped me build the foundation.
I would also like to express my profound gratitude to Engr. Syed Mir Talha Zobaed for his
outstanding contribution in inspiring, editing and proofreading of this guidebook. I am also
grateful to Omar Faruque Khan (Sabbir) for his relentless support and guideline in making this
book a reality.
I am thankful to the following readers those have invested their valuable times to read this book
carefully and have given suggestion to improve this book:
I wish to express my profound gratitude to the following writers whose books I have used in my
Guidebooks:
…………………….. and Numerous anonymous Power Point Slides and PDF chapters from different
North American Universities.
Object
Oriented
Programming
with JAVA
Syllabus
Section-A:
Concepts of Object Oriented Programming: Class, Object, Abstraction, Encapsulation,
Inheritance,
Polymorphism.
Introduction to Java: History of Java, Java features and advantages, creating classes with Java,
Concept of Constructors, Using JDK, Java application and Applet, Variables, Data types, Arrays,
Operators and control flow.
Methods: Using methods, declaring a class method, Implementation of inheritance, calling a
class method, passing
Parameters, Local variables and variable scope.
Using Standard Java Packages: Creating graphical user interfaces with AWT, Managing graphics
objects with GUI layout managers, Event handling of various components.
Exception Handling: Overview of exception handling, the basic model, Hierarchy of event
classes, Throw clause, Throws statement, try-catch block.
Section-B:
Streams and Input/output Programming: Java’s file management techniques, Stream
manipulation classes.
Thread: Thread, Multithread, Synchronization, Deadlock, Thread scheduling.
Socket Programming: Socket basics, Socket-based network concepts, Client server basics, Client
server algorithm, Socket for client, Socket for server.
Java Database Connectivity: JDBC, JDBC drivers, the JAVA.sql packages, SQL, JDBC connection and
executing SQL, The process of building a JAVA application.
Advanced Java Programming: Java Servlets and Servlets architectures, RMI, Multimedia, Java
Bens, Java server Pages.
Books Recommended:
Index
Chpater 1
Important Concepts of
Question:
Object Oriented
Programming
The virtual machine converts each generalized machine instruction into a specific machine
instruction or instructions that this computer's processor will understand. Bytecode is the
result of compiling source code written in a language that supports this approach. Most
computer languages, such as C and C++, require a separate compiler for each computer
platform- that is, for each computer operating system and the hardware set of instructions that
it is built on. Windows and the Intel line of microprocessor architectures are one platform;
Apple and the PowerPC processors are another. Using a language that comes with a virtual
machine for each platform, your source language statements need to be compiled only once and
will then run on any platform.
Question: What is object oriented language? Briefly discuss about the term Polymorphism? Exam-
2013
Answer:
OOP allows us to decompose a problem into number of entities called objects and then
build data and methods (functions) around these entities.
The data of an object can be accessed only by the methods associated with the object.
An object-oriented programming language provide support for the following object
oriented concepts
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
Question: What is class? Give an example of class. Write down the general form of a class
definition. Exam-2013
Class:
A class can be defined as a template/blueprint that describes the behavior/state that the
object of its type support
Fruits
class classname {
// declare instance variables
type var1;
type var2;
...
type varN;
// declare methods
type method1(parameters)
{ // body of method }
type method2(parameters)
{ // body of method }
// ...
type methodN(parameters)
{ // body of method }
}
Example Program
public class HelloWorld
{
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Object:
An Object is a software entity that models something in the real world. It has two main
Properties:
o State: the object encapsulates information about itself - attributes or fields.
o Behavior: the object can do some things on behalf of other objects – methods
Vehicle minivan = new Vehicle ();
Question: Write down the features of java. Explain any two of them. Exam-2015
Question: Define the terms i) inheritance ii) Encapsulation. Exam-2014
Question: How does java implement polymorphism? Write a Java program that describes
polymorphism.Exam-2015
Question: What are the major C++ features that were intentionally omitted from Java or
significantly modified? Exam-2013
Feature of JAVA/OOP:
Abstraction
Encaptulation
Polymorphism
Enheritence
Abstraction:
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are defined as a
list of abstract attributes. Abstraction is the representation of the essential features of an object
Abstraction means ignoring irrelevant features, properties, or functions and emphasizing the
relevant ones. Abstraction is the concept of describing something in simpler terms i.e
abstracting away the details, in order to focus on what is important
Encapsulation
Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
The technical term for combining data and functions together as a bundle is
encapsulation.
Storing data and functions in a single unit (class) is encapsulation. Data cannot be
accessible to the outside world and only those functions which are stored in the class
can access it.
Polymorphism:
Polymorphism is the attribute that allows one interface to control access to
a general class of actions. The specific action selected is determined by the exact
nature of the situation.
Shape
Draw()
Inheritance
Inheritance is the process by which one object can acquire the properties of
another object. This is important because it supports the concept of classification.
Inheritance is the process by which objects of one class acquire the properties of objects
of another class
This is important because Inheritance support the concept of hierarchical classification
In OOP, the concept of heritance provides the idea of reusability
This means that we can add additional features to an existing class without modifying it
This is possible by deriving a new class from the exiting one
The new class will have the combined features of both the classes
Ca Truck Bus
r
class Vehicle {
int registrationNumber;
Person owner; / / ( Assuming t h a t a Person class has been def
ined ! )
void transferOwnership(Person newOwner) {
. . . …………………………………………..+
...
}
class Car extends Vehicle {
int numberOfDoors;
...
}
class Truck extends Vehicle {
int numberOfAxels;
...
}
class Bus extends Vehicle {
boolean hasSidecar;
...
}
Advantage of Java:
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Chpater
2
Introduction
to Java
Important Question
1. What is Java ?Briefly describe the following features of Java programming language;
Exam-2014
2. Distinguish between JDK and JRE. Exam-2013
3. Platform independent and Portable .ii) Robust and secure. Exam-2014
4. What is an array? Write a Java program that can print the value 0 to10 by using single
dimension array. Exam-2014
5. Write down the name of different primitive data types in java? Exam-2015
6. Explain th structure of java program. Exam-2015
7. What is a static member variable? Using the concept of static variable, write a Java
program that shows the number of objects created from a class. Exam-2013
8. What will be the output of the following program? Identify and correct the errors of the
following program if necessary? Exam-2015
Question: What is Java? Briefly describe the following features of Java programming language;
Exam-2014
Answer:
Java:
Java is a general-purpose computer programming language that is concurrent, class-based,
object-oriented, and specifically designed to have as few implementation dependencies as
possible.
Question: Define i) Platform independent and Portable .ii) Robust and secure. Exam-2014
Answer:
Platform independent:
Platform independence means that the same program works on any
platform (operating system) without needing any modification. In the case of Java the
application runs in a Java Virtual Machine which itself isn't platform independent.
Portable:
. "Java is portable" refers to the SE version. It means that we can run Java bytecode on
any hardware that has a compliant JVM. It doesn't mean that ME is the same as SE is the same as
EE.
Portability is a measure for the amount of effort to make a program run on another
environment than where it originated.
Java goes further than just being architecture-neutral:
Robust:
Robust means reliable and no programming language can really assure reliability. Java puts
a lot of emphasis on early checking for possible errors, as Java compilers are able to detect many
problems that would first show up during execution time in other languages.
Java has been designed for writing highly reliable or robust software:
Language restrictions (e.g. no pointer arithmetic and real arrays) to make it impossible
for applications to smash memory (e.g overwriting memory and corrupting data)
Java does automatic garbage collection, which prevents memory leaks
Extensive compile-time checking so bugs can be found early; this is repeated at runtime
for flexibility and to check consistency
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
make the java language robust.
if (var == true) {
...
} else if (var == false) {
...
} else {
...
}
"robust code" means that our program takes into account all possibilities, and that there is no
such thing as an error - all situations are handled by the code and result in valid state, hence the
"else".
Secure:
Security is an important concern, since Java is meant to be used in networked
environments. Without some assurance of security, you certainly wouldn't want to download an
applet from a random site on the net and let it run on your computer. Java's memory allocation
model is one of its main defenses against malicious code (e.g can't cast integers to pointers, so
can't forge access). Furthermore:
JDK JRE
The JDK is a superset of the JRE, and The Java Runtime Environment (JRE)
contains everything that is in the JRE, plus provides the libraries, the Java Virtual
tools such as the compilers and debuggers Machine, and other components to run
necessary for developing applets and applets and applications written in the Java
applications programming language
JDK is the software development kit for java while JRE is the place where you run your
programs
It's the full featured Software Development Kit Java Runtime Environment. It is basically the
for Java, including JRE, and the compilers and Java Virtual Machine where your Java
tools (like JavaDoc, and Java Debugger) to programs run on. It also includes browser
create and compile programs. plugins for Applet execution.
if we are planning to do some Java when we only care about running Java
programming, you will also need JDK. programs on your browser or computer you
will only install JRE
Sometimes, even though you are not planning The JRE" is, as the name implies, an
to do any Java Development on a computer, environment. It's basically a bunch of directories
you still need the JDK installed with Java-related files.
The JDK is also a set of directories It looks a lot like the JRE but it contains a
directory (called JRE) with a complete JRE, and it
has a number of development tools, most
importantly the Java compiler javac in its bin
directory.
JVM:
The Java Virtual machine (JVM) is the virtual machine that runs the Java bytecodes. The
JVM doesn't understand Java source code, that's why you compile your *.java files to obtain
*.class files that contain the bytecodes understood by the JVM. It's also the entity that allows
Java to be a "portable language" (write once, run anywhere). Indeed, there are specific
implementations of the JVM for different systems (Windows, Linux, MacOS, see the Wikipedia
list), the aim is that with the same bytecodes they all give the same results.
Question: What are the difference between CPP and Java programming language?
Discuss with example?
C++ Java
Compatible with C source code, except for a few No backward compatibility with any previous language.
corner cases.
Write once, compile anywhere (WOCA). Write once, run anywhere / everywhere (WORA /
WORE).
Allows procedural programming, functional Strongly encourages an object-oriented programming
programming, object-oriented programming paradigm.
Allows direct calls to native system libraries. Call through the Java Native Interface and recentlyJava
Native Access.
Exposes low-level system facilities. Runs in a virtual machine.
Only provides object types and type names. Is reflective, allowing metaprogramming and dynamic
code generation at runtime.
Pointers, references, and pass-by-value are Primitive and reference data types always passed by
supported. value.
Supports classes, structs, and unions, and can Only supports classes, and allocates them on
allocate them on heap or stack. theheap. Java SE6 optimizes with escape analysis to
allocate some. objects on the stack.
The C++ Standard Library has a much more The standard library has grown with each release.
limited scope and functionality
Operator overloading for most operators. The meaning of operators is generally immutable, but the
+ and += operators have been overloaded for Strings.
Full Multiple inheritance, including virtual From classes, only single inheritance is allowed.
inheritance. From Interfaces, Multiple inheritance is allowed.
No standard inline documentation mechanism. Javadoc standard documentation.
Third-party software (e.g. Doxygen) exists.
Supports the goto statement. Supports labels with loops and statement blocks.
Java requires that at least one of the classes has a public static method called main. More
precisely we need a method with the following signature:
The word void has the same connotation as in C -- this function does not return a value. The
argument to main is an array of strings (we'll look at strings and arrays in Java in more detail
later)--this corresponds to the argument to the main function in a C program.
We don't need argc because in Java, unlike in C, it is possible to extract the length of an array
passed to a function. Also, unlike C, the argument to main is compulsory. Of course, the name of
the argument is not important: in place of args we could have used xyz or any other valid
identifier.
Here then, is a Java equivalent of the canonical Hello world program.
class helloworld{
public static void main(String[] args){
System.out.println("Hello world!");
}
}
Here println is a static method in the class System.out which takes a string as argument and
prints it out with a trailing newline character.
As noted earlier, we have to save this class in a file with the same name and the extension .java;
that is, helloworld.java.
Variables:
A variable is a name for a location in memory.
Or
A variable must be declared by specifying the variable's name and the type of
information that it will hold
Question: Write down the name of different primitive data types in java? Exam-2015
Data types:
Primitive Data Types
Variables, Initialization, and Assignment
Constants
Characters
Strings
32 bits
Abu Saleh Musa Miah(Abid) 382 6 4 8 9 9
01734 Page 23
+/- 3.4 x 10 with 7 significant digits
November
A GUIDED BOOK OF OBJECT ORIENTED PROGRAMMING JAVA
21, 2017
Operator
An operator is a symbol that operates on one or more arguments to produce a result.
Operands
Operands are the values on which the operators act upon.
An operand can be:
A numeric variable - integer, floating point or character
Any primitive type variable - numeric and Boolean
Reference variable to an object
A literal - numeric value, Boolean value, or string.
An array element, "a,2-“
char primitive, which in numeric operations is treated as an unsigned two byte
integer
Types of Operators
Assignment Operators
Increment Decrement Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Logical Operators
Ternary Operators
Question: What is an array? Write a Java program that can print the value 0 to10 by using single
dimension array. Exam-2014
Arrays:
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Syntax
dataType[] arrayRefVar;
Example
The following code snippets are examples of this syntax −
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −
Example
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList −
double[] myList = new double[10];
Example
Here is a complete example showing how to create, initialize, and process arrays −
Control flow:
The statements inside our source files are generally executed from top to bottom, in
the order that they appear.
Control flow statements, however, break up the flow of execution by employing decision
making, looping, and branching, enabling your program to conditionally execute particular
blocks of code. This section describes the decision-making statements (if-then, if-then-else,
switch), the looping statements (for, while, do-while), and the branching statements (break,
continue, return) supported by the Java programming language.
The If Statement
The if statement executes a block of code only if the specified expression is
true. If the value is false, then the if block is skipped and execution continues with the rest of the
program.
You can either have a single statement or a block of code within an if statement. Note that the
conditional expression must be a Boolean expression.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
Below is an example that demonstrates conditional execution based on if statement condition.
The general form of the for statement can be expressed like this:
for (initialization; termination; increment) {
statement
}
Following is a sample program, SwitchDemo, that declares an integer named month whose
value supposedly represents the month in a date. The program displays the name of the month,
based on the value of month, using the switch statement:
First, the while statement evaluates expression, which must return a boolean value. If the
expression returns true, then the while statement executes the statement(s) associated with it.
The while statement continues testing the expression and executing its block until the
expression returns false.
The example program shown below, called WhileDemo uses a while statement to step
through the characters of a string, appending each character from the string to the end of a
string buffer until it encounters the letter g.
int i = 0;
char c = copyFromMe.charAt(i);
while (c != 'g') {
copyToMe.append(c);
c = copyFromMe.charAt(++i);
}
System.out.println(copyToMe);
}
}
Constructor method has the same name as that of class, they are called or invoked when an
object of class is created and can't be called explicitly. Attributes of an object may be available
when creating objects if no attribute is available then default constructor is called, also some of
the attributes may be known initially. It is optional to write constructor method in a class but
due to their utility they are used.
A constructor has same name as the class in which it resides. Constructor in Java can not be
abstract, static, final or synchronized. These modifiers are not allowed for constructor.
Class Car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Default Constructor
Parameterized constructor
Each time a new object is created at least one constructor will be invoked.
Constructor Overloading
Like methods, a constructor can also be overloaded. Overloaded constructors are differentiated
on the basis of their type of parameters or number of parameters. Constructor overloading is
not much different than method overloading. In case of method overloading you have multiple
methods with same name but different signature, whereas in Constructor overloading you have
multiple constructor with different signature but only difference is that Constructor doesn't
have return type in Java.
Class Language {
String name;
Language () {
System.out.println("Constructor method called.");
}
Language(String t) {
name = t;
}
cpp.setName("C++");
java.getName();
cpp.getName();
}
void setName(String t) {
name = t;
}
void getName() {
System.out.println("Language name: " + name);
}
}
Java Application:
Java application programs run is a standalone environment with the support
of a virtual machine (JVM), where as Java applets run in a browser and are subject to stringent
security restrictions in terms of file and network access, where as an Java application can have
free reign over these resources.
Java Applet:
An applet is a Java™ program designed to be included in an HTML Web document.
We can write your Java applet and include it in an HTML page, much in the same way an image
is included. When you use a Java-enabled browser to view an HTML page that contains an
applet, the applet's code is transferred to your system and is run by the browser's Java virtual
machine.
The HTML document contains tags, which specify the name of the Java applet and its Uniform
Resource Locator (URL). The URL is the location at which the applet bytecodes reside on the
Internet. When an HTML document containing a Java applet tag is displayed, a Java-enabled
Web browser downloads the Java bytecodes from the Internet and uses the Java virtual machine
to process the code from within the Web document. These Java applets are what enable Web
pages to contain animated graphics or interactive content.
You can also write a Java application that does not require the use of a Web browser.
For more information, see Writing Applets , Sun Microsystems' tutorial for Java applets. It
includes an overview of applets, directions for writing applets, and some common applet
problems.
Applications are stand-alone programs that do not require the use of a browser. Java
applications run by starting the Java interpreter from the command line and by specifying the
file that contains the compiled application. Applications usually reside on the system on which
they are deployed. Applications access resources on the system, and are restricted by the Java
security model.
## You can now execute the program, remember to remove the .class extension when running
java HelloWorld
<html>
<head></head>
<body>
<applet code="HelloWorld.class" width=800 height=600></applet>
</body>
</html>
## The Java Applet Code HelloWorld.java, remember you need to compile before
accessing the ## web page
// HelloWorld.java
// A very simple Java Applet
Chpater
3
Important Method
Question
1. Define method? Write down the name of all the parts of method header and explain each
part of it. Exam-2014
2. What are the difference between constructors and methods? Exam-2015
3. What kinf of inheritance support in Java ?Give an example that shows implementation of
inheritance in Java. Exam-2014
4. What is “Called method”and “Calling method”?Give an example to demonstrate calling a
method. Exam-2014
5. Why is the main method declared as static? Exam-2013
6. What is method overriding?Explain with an example. Exam-2013
7. What is Java method ?give a general syntax of it.State how to define a method and
describe each part of method header. Exam-2013
8. What is method overloading? Why is used in Java? Exam-2015
Question: Define method? Write down the name of all the parts of method header and explain
each part of it. Exam-2014 or
Question: What is Java method? Give a general syntax of it. State how to define a method and
describe each part of method header. Exam-2013
Methods:
A Java method is a collection of statements that are grouped together to perform an
operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Creating Method
Considering the following example to explain the syntax of a method −
Method definition consists of a method header and a method body. The same is shown in the
following syntax –
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
Method body − the method body defines what the method does with the
statements.
Example:
public static int methodName(int a, int b) {
// body
}
Question: What is “Called method” and “Calling method”? Give an example to demonstrate calling
a method. Exam-2014
Calling Method: The calling method is the method that contains the actual call.
They are also called the Caller and the Calling methods.
For exampl
// Calling method
void f()
{
g();
}
// Called method
void g()
{
Return 5;
}
Declaring a Method:
A method is a program module that contains a series of statements that carry
out a task. To execute a method, you invoke or call it from another method; the calling method
makes a method call, which invokes the called method.
Passing Parameters:
One of the first things we learn about a programming language we just laid hands on is the
way it manages the parameters when we call a method. The two most common ways that
languages deal with this problem are called “passing by value” and “passing by reference”.
Passing by value means that, whenever a call to a method is made, the parameters are
evaluated, and the result value is copied into a portion of memory. When the parameter is
used inside the method, either for read or write, we are actually using the copy, not the
original value which is unaffected by the operations inside the method.
On the other hand, when a programming language uses passing by reference, the changes
over a parameter inside a method will affect the original value. This is because what the
method is receiving is the reference, i.e the memory address, of the variable.
Some programming languages support passing by value, some support passing by reference,
and some others support both. So the question is, what does Java support
Local variables:
In computer science, a local variable is a variable that is given local scope. Local
variable references in the function or block in which it is declared override the same variable
name in the larger scope.
Variable scope:
A scope is a region of the program and broadly speaking there are three places,
where variables can be declared − Inside a function or a block which is called local variables, In
the definition of function parameters which is called formal parameters. Outside of all functions
which is called global variables
Example:
In Java, when a subclass contains a method that overrides a method of the superclass, it can also
invoke the superclass method by using the keyword super Example:
class Thought {
public void message() {
System.out.println("I feel like I am diagonally parked in a parallel
universe.");
}
}
Question: What is of inheritance support in Java? Give an example that shows implementation of
inheritance in Java. Exam-2014
Implementation of inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object.
Why use inheritance in java
Single Inheritance
Multiple Inheritance (Through Interface)
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance (Through Interface)
The below diagram represents the single inheritance in java where Class B extends only one
class Class A. Here Class B will be the Sub class and Class A will be one and only Super class.
class A
{
public void methodA()
{
System.out.println("Base class
method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits)
more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base
classes.
Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class.
As you can see in below flow diagram C is subclass or child class of B and B is a child class of A.
For more details and example refer – Multilevel inheritance in Java.
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Hierarchical Inheritance
In Hierarchical inheritance one parent class will be inherited by many
sub classes. As per the below example ClassA will be inherited by ClassB, ClassC and ClassD.
ClassA will be acting as a parent class for ClassB, ClassC and ClassD.
In below example class B,C and D inherits the same class A. A is parent class (or base class) of B,C
& D.
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Output:
method of Class A
method of Class A
method of Class A
Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination of
Single and Multiple inheritance. A typical flow diagram would look like below. A hybrid
inheritance can be achieved in the java in a same way as multiple inheritance can be!!
Using interfaces. yes you heard it right. By using interfaces you can have multiple as well
as hybrid inheritance in Java.
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
4
Chpate
r
Important Java
Package
Question
1. What is the difference between container and component in a GUI? Exam-2015
2. Write down the constructors of Flow Layout, Card Layout and GridBag Laoyout
manager. Explain them. Exam-2015
3. Describe how to handle MouseEvent and KeyEvent in Java? Exam-2015
4. Define top-level and secondary container .Write about flow layout with syntex used in
Java. Exam-2014
5. What is an event ?List down the names of some of the Java AWT event listener
interfaces. How to implement a listener interface. Exam-2013
6. Define actionPerfomed().What is the signature of the actionPerfomed method? Exam-
2014
7. What is layout manager? Briefly explain about the basic layout manager in Java and give
the syntax of each layout manager. Exam-2013
AWT Packages
AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with
18 packages of 737 classes as of JDK 1.8). Fortunately, only 2 packages - java.awt and
java.awt.event - are commonly-used.
The java.awt package contains the core AWT graphics classes:
GUI Component classes, such as Button, TextField, and Label,
GUI Container classes, such as Frame and Panel,
Layout managers, such as FlowLayout, BorderLayout and GridLayout,
Custom graphics classes, such as Graphics, Color and Font.
The java.awt.event package supports event handling:
Event classes, such as ActionEvent, MouseEvent, KeyEvent and
WindowEvent,
Event Listener Interfaces, such as ActionListener, MouseListener,
KeyListener and WindowListener,
Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.
AWT provides a platform-independent and device-independent interface
to develop graphic programs that runs on all platforms, including
Windows, Mac OS, and Unixes.
Question: Define top-level and secondary container .Write about flow layout with syntax used in
Java. Exam-2014
Each GUI program has a top-level container. The commonly-used top-level containers in AWT
are Frame, Dialog and Applet:
A Frame provides the "main window" for the GUI application, which has a title bar
(containing an icon, a title, the minimize, maximize/restore-down and close buttons), an
optional menu bar, and the content display area. To write a GUI program, we typically
start with a subclass extending from java.awt.Frame to inherit the main window as
follows:
Basic Terminologies
Term Description
Component is an object having a graphical representation that can be displayed on
Component the screen and that can interact with the user. For examples buttons, checkboxes,
list and scrollbars of a graphical user interface.
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known as
Container container
Examples: panel, box
A Frame is a top-level window with a title and a border. The size of the frame
Frame includes any area designated for the border. Frame encapsulates window. It and
has a title bar, menu bar, borders, and resizing corners.
Panel provides space in which an application can attach any other components,
Panel
including other panels.
Window is a rectangular area which is displayed on the screen. In different window
we can execute different program and display different data. Window provide us
Window
with multitasking environment. A window must have either a frame, dialog, or
another window defined as its owner when it's constructed.
AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.
Sr. No. Control & Description
1 Label: A Label object is a component for placing text in a container.
2 Button: This class creates a labeled button.
Check Box: A check box is a graphical component that can be in either an on (true) or
3
off (false) state.
4 Check Box Group: The CheckboxGroup class is used to group the set of checkbox.
5 List: The List component presents the user with a scrolling list of text items.
Text Field: A TextField object is a text component that allows for the editing of a single
6
line of text.
Text Area: A TextArea object is a text component that allows for the editing of a
7
multiple lines of text.
Choice: A Choice control is used to show pop up menu of choices. Selected choice is
8
shown on the top of the menu.
Canvas: A Canvas control represents a rectangular area where application can draw
9
something or can receive inputs created by user.
Image: An Image control is superclass for all image classes representing graphical
10
images.
Scroll Bar: A Scrollbar control represents a scroll bar component in order to enable
11
user to select from range of values.
Dialog: A Dialog control represents a top-level window with a title and a border used to
12
take some form of input from the user.
File Dialog: A FileDialog control represents a dialog window from which the user can
13
select a file.
Question: What is the difference between container and component in a GUI? Exam-2015
Answer:
Difference between container and component:
Container Component
Label
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we are
showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
Question: What is layout manager? Briefly explain about the basic layout manager in Java and give
the syntax of each layout manager. Exam-2013
Question: Write down the constructors of Flow Layout, Card Layout and GridBag Laoyout
manager. Explain them. Exam-2015
Layout Manager:
A layout manager is an object that implements the LayoutManager interface*
and determines the size and position of the components within a container.
Although components can provide size and alignment hints, a container's layout manager has
the final say on the size and position of the components within the container.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west and center. Each region (area) may contain
one component only. It is the default layout of
frame or window. The BorderLayout provides
five constants for each region:
import java.awt.*;
import javax.swing.*;
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 Border();
} }
Java GridLayout
import java.awt.*;
import javax.swing.*;
JFrame f;
MyGridLayout(){
f=new JFrame();
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another
(in a flow). It is the default layout of applet or panel.
Fields of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b
4);f.add(b5);
f.setLayout(new FlowLayout(FlowLa
yout.RIGHT));
//setting flow layout of right alignme
nt
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Java BoxLayout
import java.awt.*;
import javax.swing.*;
public BoxLayoutExample1 () {
buttons = new Button [5];
}
}
Java CardLayout
The CardLayout class manages the components in such a manner that only
one component is visible at a time. It treats each component as a card that is why it is known as
CardLayout. Constructors of CardLayout class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
public void last(Container parent): is used to flip to the last card of the given container.
public void show(Container parent, String name): is used to flip to the specified card with
the given name.
Example of CardLayout class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space
and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of constraints object we arrange component's display area on the grid. The
FlowLayout
3
The FlowLayout is the default layout.It layouts the components in a directional flow.
GridLayout
4
The GridLayout manages the components in form of a rectangular grid.
GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
5
component vertically,horizontally or along their baseline without requiring the
components of same size.
Depending on your current need, you can choose one of several methods in the Graphics class
based on the following criteria:
Whether you want to render the image at the specified location in its original size or
scale it to fit inside the given rectangle
Whether you prefer to fill the transparent areas of the image with color or keep them
transparent
Fill methods apply to geometric shapes and include fillArc, fillRect, fillOval, fillPolygon.
Whether you draw a line of text or an image, remember that in 2D graphics every point is
determined by its x and y coordinates. All of the draw and fill methods need this information
which determines where the text or image should be rendered.
In this code (x1, y1) is the start point of the line, and (x2, y2) is the end point of the line.
Each Graphics object has its own coordinate system, and all the methods of Graphics including
those for drawing Strings, lines, rectangles, circles, polygons and more. Drawing in Java starts
with particular Graphics object. You get access to the Graphics object through the
paint(Graphics g) method of your applet. Each draw method call will look like
g.drawString("Hello World", 0, 50) where g is the particular Graphics object with which you're
drawing.
For convenience's sake in this lecture the variable g will always refer to a preexisting object of
the Graphics class. As with any other method you are free to use some other name for the
particular Graphics context, myGraphics or appletGraphics perhaps.
These days, the most common programming style among experienced Java programmers is to
assign an individual action listener to each button in the form of an anonymous inner class.
Suppose, for example, that you want the Start and Stop buttons to invoke methods called
startAction and stopAction, respectively. You could do so by changing the initialization code as
follows:
The actionPerformed() method is invoked automatically whenever you click on the registered
component.
The ActionEvent argument e is the object that represents the event. This object contains
information about the event, like which component is the event source. The ActionEvent class
has two methods that you might find beneficial: getActionCommand() and getSource() (which
is actually inherited by the ActionEvent class from the EventObject class). The first method
returns a string that identifies the action. This string is usually set by the event source, using a
method called setActionCommand. The second method returns the event source object
Example:
import java.awt.*;
import java.awt.event.*;
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Question: What is an event? List down the names of some of the Java AWT event listener
interfaces.
Question: What is an Event?
Change button in the state of an object is known as event.
i.e. event describes the change in state of source. Events are generated as result of user
interaction with the graphical user interface components. For example, clicking on a button,
moving the mouse, entering a character through keyboard, selecting an item from list, scrolling
the page are the activities that causes an event to happen.
Types of Event
Interface Summary
Interface Description
ActionListener The listener interface for receiving action events.
AdjustmentListener The listener interface for receiving adjustment events.
The listener interface for receiving notification of events dispatched
AWTEventListener to objects that are instances of Component or MenuComponent or
their subclasses.
ComponentListener The listener interface for receiving component events.
ContainerListener The listener interface for receiving container events.
The listener interface for receiving keyboard focus events on a
FocusListener
component.
The listener interface for receiving ancestor moved and resized
HierarchyBoundsListener
events.
HierarchyListener The listener interface for receiving hierarchy changed events.
InputMethodListener The listener interface for receiving input method events.
ItemListener The listener interface for receiving item events.
KeyListener The listener interface for receiving keyboard events (keystrokes).
The listener interface for receiving "interesting" mouse events
MouseListener
(press, release, click, enter, and exit) on a component.
The listener interface for receiving mouse motion events on a
MouseMotionListener
component.
The listener interface for receiving mouse wheel events on a
MouseWheelListener
component.
TextListener The listener interface for receiving text events.
The listener interface for receiving WindowEvents, including
WindowFocusListener
WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events.
WindowListener The listener interface for receiving window events.
WindowStateListener The listener interface for receiving window state events.
Class Summary
Class Description
A semantic event which indicates that a component-defined action
ActionEvent
occurred.
The adjustment event emitted by Adjustable objects like Scrollbar
AdjustmentEvent
and ScrollPane.
A class which extends the EventListenerProxy specifically for adding
AWTEventListenerProxy
an AWTEventListener for a specific event mask.
ComponentAdapter An abstract adapter class for receiving component events.
A low-level event which indicates that a component moved, changed
ComponentEvent size, or changed visibility (also, the root class for the other
component-level events).
ContainerAdapter An abstract adapter class for receiving container events.
A low-level event which indicates that a container's contents
ContainerEvent
changed because a component was added or removed.
FocusAdapter An abstract adapter class for receiving keyboard focus events.
A low-level event which indicates that a Component has gained or
FocusEvent
lost the input focus.
An abstract adapter class for receiving ancestor moved and resized
HierarchyBoundsAdapter
events.
An event which indicates a change to the Component hierarchy to
HierarchyEvent
which Component belongs.
InputEvent The root event class for all component-level input events.
Input method events contain information about text that is being
InputMethodEvent
composed using an input method.
An event which executes the run() method on a Runnable when
InvocationEvent
dispatched by the AWT event dispatcher thread.
A semantic event which indicates that an item was selected or
ItemEvent
deselected.
KeyAdapter An abstract adapter class for receiving keyboard events.
KeyEvent An event which indicates that a keystroke occurred in a component.
MouseAdapter An abstract adapter class for receiving mouse events.
An event which indicates that a mouse action occurred in a
MouseEvent
component.
MouseMotionAdapter An abstract adapter class for receiving mouse motion events.
An event which indicates that the mouse wheel was rotated in a
MouseWheelEvent
component.
PaintEvent The component-level paint event.
TextEvent A semantic event which indicates that an object's text changed.
At the root of Java event class hierarchy is EventObject which is in java.util. It is a super class for
all events.
Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to its handler. Java provide as with classes for source object.
Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received , the listener process the event an then
returns.
Create the following java program using any editor of your choice in say
D:/ > AWT > com > tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new
AwtControlDemo();
awtControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
but what the selection means is left up to the object responding to the event. For example, a
mouse click could tell the responding object to alter its appearance and then send an action
message. Mouse drags generally indicate that the receiving view should move itself or a drawn
object within its bounds. The following sections describe how you might handle mouse-down,
mouse-up, and mouse-drag events.
Table 4-1 Type constants and methods related to left-button mouse events
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*
HandleMouseListenerInWindowExample(String title){
strEvent = "MouseClicked";
x = e.getX();
y = getY();
repaint();
}
HandleMouseListenerInWindowExample myWindow =
new HandleMouseListenerInWindowExample("Window With Mouse
Events Example");
}
MyWindowAdapter(HandleMouseListenerInWindowExample myWindow){
this.myWindow = myWindow;
}
Example Output
KeyEvent:
Key events indicate when the user is typing at the keyboard. Specifically, key events
are fired by the component with the keyboard focus when the user presses or releases keyboard
keys.
The first kind of event is called a key-typed event. The second kind is either a key-pressed or
key-released event.
In general, you react to only key-typed events unless you need to know when the user presses
keys that do not correspond to characters. For example, to know when the user types a Unicode
character — whether by pressing one key such as 'a' or by pressing several keys in sequence
— you handle key-typed events. On the other hand, to know when the user presses the F1 key,
or whether the user pressed the '3' key on the number pad, you handle key-pressed events.
1. Make sure the component's isFocusable method returns true. This state allows the
component to receive the focus. For example, you can enable keyboard focus for a
JLabel component by calling the setFocusable(true) method on the label.
2. Make sure the component requests the focus when appropriate. For custom
components, implement a mouse listener that calls the requestFocusInWindow
method when the component is clicked.
The following example demonstrates key events. It consists of a text field that you can
type into, followed by a text area that displays a message every time the text field fires a
key event. A button at the bottom of the window lets you clear both the text field and
text area.
Chpater
5
Important
Exception
Question Handling
Exception:
An exception is an indication of a problem that occurs during a program's execution.
The name "exception" implies that the problem occurs infrequently if the "rule" is that a
statement normally executes correctly, and then the "exception to the rule" is that a problem
occurs.
Question: What do you understand by exception handling? Explain with suitable codes?. Exam-
2014
Exception Handling:
Exception handling enables programmers to create applications that can
resolve (or handle) exceptions.
In many cases, handling an exception allows a program to continue
executing as if no problem had been encountered. A more severe problem could prevent a
program from continuing normal execution, instead requiring it to notify the user of the
problem before terminating in a controlled manner
Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.
Program that we want to monitor for exception are written within the try block. If an exception
occurs within the try block, then it is thrown.
Example:
Example of ArithmeticException.
InputMismatchException
import java.util.Scanner;
Result: 100 / 7 = 14
do
{
try // read two numbers and calculate quotient
{
System.out.print( "Please enter an integer numerator: " );
int numerator = scanner.nextInt();
System.out.print( "Please enter an integer denominator: " );
int denominator = scanner.nextInt();
29 int result = quotient( numerator, denominator );
System.out.printf( "\nResult: %d / %d = %d\n", numerator,
denominator, result );
continueLoop = false; // input successful; end looping
} // end try
catch ( InputMismatchException inputMismatchException )
{
System.err.printf( "\nException: %s\n",
inputMismatchException );
scanner.nextLine(); // discard input so user can try again
System.out.println(
"You must enter integers. Please try again.\n" );
} // end catch
catch ( ArithmeticException arithmeticException )
{
System.err.printf( "\nException: %s\n", arithmeticException );
System.out.println(
"Zero is an invalid denominator. Please try again.\n" );
} // end catch
} while ( continueLoop ); // end do...while
} // end main
} // end class DivideByZeroWithExceptionHandling
Result: 100 / 7 = 14
Result: 100 / 7 = 14
Exception: java.util.InputMismatchException
You must enter integers. Please try again.
Result: 100 / 7 = 14
Question: In detail explain the try-catch finally blocks of the exception handling. Exam-2015
Answer:
The try Block
The try block encases any statements that might cause an exception to occur.
For example,
if you are reading data from a file using the FileReader class its expected that you
handle the IOExceptions associated with using a FileReader object (e.g, FileNotFoundException,
IOException). To ensure this happens you can place the statements that deal with creating and
using the FileReader object inside a try block:
public static void main(String[] args){
FileReader fileInput = null;
try
{
//Open the input file
fileInput = new FileReader("Untitled.txt");
}
}
However, the code is incomplete because in order for the exception to be handled we need a
place for it to be caught. This happens in the catch block .
For example,
the FileReader object defined in the code above is capable of throwing a FileNotFoundException
or an IOException. We can specify two catch blocks to handle both of those exceptions:
public static void main(String[] args){
FileReader fileInput = null;
try
{
//Open the input file
fileInput = new FileReader("Untitled.txt");
}
catch(FileNotFoundException ex)
{
//handle the FileNotFoundException
}
catch(IOException ex)
{
//handle the IOException
}
}
In the FileNotFoundException catch block we could place code to ask the user to find the file for
us and then try to read the file again. In the IOException catch block we might just pass on the
I/O error to the user and ask them to try something else. Either way, we have provided a way
for the program to catch an exception and handle it in a controlled manner.
The finally block appears directly after the last catch block:
try
{
//Open the input file
fileInput = new FileReader("Untitled.txt");
}
catch(FileNotFoundException | IOException ex)
{
//handle both exceptions
}
finally
{
//We must remember to close streams
//Check to see if they are null in case there was an
//IO error and they are never initialised
if (fileInput != null)
{
fileInput.close();
}
}
}
Question: Describe the five keywords that manage Java exception handling. Exam-2013
Answer:
try
catch
finally
throw
throws
Although we have covered every keyword individually, let us summarize each keyword
with few lines and finally one example covering each keyword in a single program
Throw clause:
Sometimes, programmer can also throw/raise exception explicitly at runtime on the
basis of some business condition
To raise such exception explicitly during program execution, we need to use throw keyword
Syntax: throw instanceOfThrowableType;
Generally, throw keyword is used to throw user-defined exception or custom exception
whenever exception might thrown from program, then programmer doesn’t necessarily
need to handle that exception using try-catch block instead simply declare that exception
using throws clause next to method signature
But this forces or tells the caller method to handle that exception; but again caller can
handle that exception using try-catch block or re-declare those exception with throws
clause
Note: use of throws clause doesn’t necessarily mean that program will terminate
normally rather it is the information to the caller to handle for normal termination
Any number of exceptions can be specified using throws clause, but they are all need to
be separated by commas (,)
throws clause is applicable for methods & constructor but strictly not applicable to
classes
It is mainly used for checked exception, as unchecked exception by default propagated
back to the caller (i.e.; up in the runtime stack)
Note: It is highly recommended to use try-catch for exception handling instead of
throwing exception using throws clause
The exception is object created at the time of exceptional/error condition which will be thrown
from the program and halt normal execution of the program. Java exceptions object hierarchy is
as below:
checked exceptions are subject to the catch or specify a requirement, which means they require
catching or declaration. This requirement is optional for unchecked exceptions. Code that uses a
checked exception will not compile if the catch or specify rule is not followed.
Name Description
Below example program of reading, file shows how checked exception should be
handled.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CheckedExceptionDemo {
public static void main(String[] args) {
//Below line calls readFile method and prints content of it
String filename="test.txt";
try {
String fileContent = new CheckedExceptionDemo().readFile(filename);
System.out.println(fileContent);
} catch (FileNotFoundException e) {
System.out.println("File:"+ filename+" is missing, Please check file name"
);
} catch (IOException e) {
System.out.println("File is not having permission to read, please check the
permission");
}
}
public String readFile(String filename)throws FileNotFoundException, IOExce
ption{
FileInputStream fin;
int i;
String s="";
fin = new FileInputStream(filename);
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) s =s+(char) i+"";
} while(i != -1);
fin.close();
return s;
}
}
Output: If test.txt is not found:
Running the program after creating test.txt file inside project root folder
Unchecked Exceptions
Unchecked exceptions inherit from the Error class or the RuntimeException
class. Many programmers feel that you should not handle these exceptions in your programs
because they represent the type of errors from which programs cannot reasonably be expected
to recover while the program is running.
When an unchecked exception is thrown, it is usually caused by a misuse of code - passing a null
or otherwise incorrect argument.
RuntimeException
An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime.
I also use Runtime Exception for the default case of a switch statement if there is no better way
of handling it.
RuntimeException is the superclass of those exceptions that can be thrown during the normal
operation of the Java Virtual Machine.
Example;
IoExcepton:
In general, I/O means Input or Output. Those methods throw the IOException whenever
an input or output operation is failed or interpreted.
Note that this won't be thrown for reading or writing to memory as Java will be handling it
automatically. Here are some cases which result in IOException.
Interface Summary
S.N. Interface & Description
CharConversionException
1
This is a base class for character conversion exceptions.
EOFException
2
These are signals that an end of file or end of stream has been reached unexpectedly
during input.
FileNotFoundException
3
These are the signals that an attempt to open the file denoted by a specified
pathname has failed.
InterruptedIOException
4
This is signals that an I/O operation has been interrupted.
InvalidClassException
5
This is thrown when the Serialization runtime detects one of the following problems
with a Class.
InvalidObjectException
6
This indicates that one or more deserialized objects failed validation tests.
IOException
7
These are the signals that an I/O exception of some sort has occurred.
NotActiveException
8
This is thrown when serialization or deserialization is not active.
NotSerializableException
9
This is thrown when an instance is required to have a Serializable interface.
ObjectStreamException
10
This is a superclass of all exceptions specific to Object Stream classes.
OptionalDataException
11
This is an exception indicating the failure of an object read operation due to unread
primitive data, or the end of data belonging to a serialized object in the stream.
StreamCorruptedException
12
This is thrown when control information that was read from an object stream
violates internal consistency checks.
SyncFailedException
13
These are the signals that a sync operation has failed.
UnsupportedEncodingException
14
This character encoding is not supported.
Java Exceptions are divided in two categories RuntimeException also known as unchecked
Exception and checked Exception.
Question: With necessary code snippet, explain the difference between the keywords and throws.
Exam-2015
Code Snipt:
Snippet is a programming term for a small region of re-usable source code, machine code, or
text. Ordinarily, these are formally defined operative units to incorporate into larger
programming modules.
In programming practice, "snippet" refers narrowly to a portion of source code that is literally
included by an editor program into a file, and is a form of copy and paste programming This
concrete inclusion is in contrast to abstraction methods, such as functions or macros, which are
abstraction within the language. Snippets are thus primarily used when these abstractions are
not available or not desired, such as in languages that lack abstraction, or for clarity and absence
of overhead.
Snippets are similar to having static preprocessing included in the editor, and do not require
support by a compiler. On the flip side, this means that snippets cannot be invariably modified
after the fact, and thus is vulnerable to all of the problems of copy and paste programming. For
this reason snippets are primarily used for simple sections of code (with little logic), or for
boilerplate, such as copyright notices, function prototypes, common control structures, or
standard library imports.
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
No. throw throws
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1)
throw an exception. exception.
4) Throw is used within the method. Throws is used with the method signature.
1. Throws clause is used to declare an exception, which means it works similar to the
try-catch block. On the other hand throw keyword is used to throw an exception
explicitly.
2. If we see syntax wise than throw is followed by an instance of Exception class and
throws is followed by exception class names.
For example: