Vous êtes sur la page 1sur 218

Learn Java programming

How do Java front- and back-end skill sets differ?

Is there a tool to type Java code and see what happens?

How can Java restrict viruses?

Can CSS support Java applets?

What is a good beginner's book about Java?

Java jargon

What is the difference between the JVM, JRE and JDK?

What's the difference between JVM and JIT?

What is the difference betwen invoke and call?

Java operators and arithmetic

Does the order of the operands in == matter?

How do I add two numbers in Java?

How can I add two numbers using a method?

How should I round a double up to an int?

How can I calculate minimum, maximum and average using Java?

What are bitwise and bit shift operators?

Variable scope

Why does this for loop instantiation fail to compile?

Class relationships and references

How do I call another class in the same folder?

How do you put both files in the same package to call them?

How do I access a variable declared in another class?

Java design patterns

What is a recursive method?

What is a singleton?

What happens to singletons when two JVMs are running?

How do I format my price correctly?

What is a factory method?

How should I create an immutable class?

What are adapters in Java?

Java application development

How can I sort 3 numbers using Java?

How can I make spelling checker with a LinkedList dictionary?

How can I use SAX to parse a Web page via JTidy?

How can I create a search engine in Java?

Can I get the source code for a Java search engine?

Would a Java search engine be a good final year project?

How can I design my own fonts using Java?

Learn Java programming

Q: How do Java front- and back-end skill sets differ?


A: This is a somewhat arbitrary distinction
to make about Java development, since
applications often have front- and back-end
components

and

understand

how

integrated.

In

it

is

important

both

general

to

aspects

terms,

are

back-end

development is concerned with database


storage

and

retrieval,

servlets,

Web

application frameworks and Enterprise Java


Beans. This requires a good understanding
of SQL and
network

database

principles,

applications, JDBC,
servlet

containers,

theHTTP protocol and an appreciation of


concurrent programming issues.
Front-end

development

for

concerned

with

the

delivery

Web

browsers,

of HTML content

to

servlets

is

especially forms, and touches on most


aspects of markup design, Cascading Style
Sheets and Javascript. Usually, front-end

developers

will

work

to

visual

designs

provided by others, and will implement the


work

using

combination

of

formats

including JSP, JSP tag libraries and other


template frameworks, such as Spring.
Front-end developers may also be involved
in creating pure Java user interfaces for
stand-alone

Swing

applications

or

commonly

these

days)

Abstract

the

(less

Windowing Toolkit (AWT) for applets. In this


case, it is important to have a good
knowledge of the Swing API components,
their intended use, and the data structures
they operate on.

Q: Is there a tool to type Java code and see what happens?


A: Sounds like you're looking for a user
interface

where

statements

you

and

can

enter

execute

Java
them.

The BlueJ interactive Java environment is


designed for people who are new to Java
programming and lets you execute arbitrary
Java statements to see how they work.
You also need to download and install a
recent Java Software Development Kit first,
version 6 is recommended, but all code is
handled through BlueJ.
Start BlueJ, go to the View menu and the
set the Code Pad visible. Type statements
in the Code Pad area and they will be
executed when you press the Enter key. If
you includeSystem.out.println() statements
they

will

automatically

open

a Terminal Window to display the output,


as follows.
full answer hidden, click to get full
answers
Premium members click below for full answer
Is there a tool to type Java code and see what
happens?

Q: How can Java restrict viruses?


A: The Java Runtime Environment (JRE) is
the plug-in software that runs Java applets
in Web browsers. Normally Java applets are
executed

in

so-called

sandbox

environment inside the Web browser that


prevents

direct

computer's

file

access
system

to

the

and

host
blocks

potentially hazardous operations.


The JRE software from Sun, Oracle and other
reputable suppliers is safe to install, but
some versions of the software have been
found to be vulnerable to viruses and
worms. A standard virus checker with up to
date virus signature files should detect
and prevent such problems.
This Virus

found

in

the

Java

cache

directory article explains some typical cases


and

how

to

remove

the

problem.

To

minimise the risk of infections, keep your


JRE software up to date with the latestJava
Downloads.

Q: Can CSS support Java applets?

A: It is possible to control the position and


spacing between Java applets and other
HTML document elements using CSS, but
the CSS associated with the Web page
cannot affect the visual appearance of the
applet embedded in it.

applet, object {

margin: 0.5em;
padding: 0;
}

The appearance of Java applets is controlled


by the Abstract Windowing Toolkit (AWT) or
Swing interface properties defined in the
applet class. It is possible to set the logical
font type, colour and background colour for
applet components, as well as the internal
layout.
Label label = new Label("Example label");
label.setFont(new Font("Serif", Font.BOLD,
14));
label.setForeground(new Color(0, 55, 153));

JavaFX supports a style sheet scheme that


uses a similar syntax to CSS, attached to
the Sceneclass.

Q: What is a good beginner's book about Java?

A: Thinking

In Java by Bruce Eckel is a

good beginner's book on Java, which is


available as a free download too.

Java jargon

Q: What is the difference between the JVM, JRE and JDK?


A: The JDK, also called the Java Software
Development Kit (SDK), is the full suite of
tools required to develop, package and
publish Java applications. The Sun Java SDK
includes the full Java class library, with a
compiler, decompiler, profiler, JAR signer,
key signing tool and many other tools.
full answer hidden, click to get full
answers
Premium members click below for full answer
What is the difference between the JVM, JRE and
JDK?

Q: What's the difference between JVM and JIT?


A: The Java Virtual Machine (JVM) is a
program that runs on a computer operating
system and executes Java program code.
The JVM takes the Java code and compiles it
to a format that can be run directly on the
computer's processor. The JVM controls the
interface between the Java code and the
computer like audio software enables us to
play the same CD on a Windows, Mac or
GNU Linux computer.

In early versions of the JVM, all the Java


code for a program had to be loaded and
compiled before the program could be run.
More recent versions are optimised so that
the Java code is compiled "Just In Time"; just
before it is due to be executed on the
processor.

This

approach

accelerates

program start-up, and overall performance


of the Java program, but requires an extra
level of coordination within the virtual
machine.

Q: What is the difference betwen invoke and call?


A: There is no practical difference in the
meaning of "invoke" versus "call" in Java
programming, both mean that one class
executes a method or constructor on itself
or another class. In general terms the word
invoke means to call upon an agent for help
or guidance, or appeal for confirmation or
corroboration, or summon an entity. Java
programs can also be thought of as a
sequence or network of messages that are
sent between classes to trigger behaviour
and get a response. The metaphor is
basically the same in both cases.

Java operators and arithmetic

Q: Does the order of the operands in == matter?


A: With this sort of question it is often
easiest to try it yourself and see. You will
find that single boolean comparisons are

equivalent whichever way round you have


the values.
From a reader's point of view most people
would put the "unknown" variable first
because it is the subject of the comparison,
but syntactically it does not matter.

if (a == 10) { }

Q: How do I add two numbers in Java?


A: To add two numbers in Java, use the
simple mathematical plus operator, which
may be applied to any numeric variable
type, as below:

int variable1 = 26;


int variable2 = 4;

int result = variable1 + variable2;

The result of the addition does not have to


be assigned to a variable, it can also be
used anonymously in control statements, as
below.
full answer hidden, click to get full
answers
Premium members click below for full answer
How do I add two numbers in Java?

Q: How can I add two numbers using a method?


A: For simple mathematical functions a
method would usually declare the input
variables as method arguments and a
return type that matches the required
numeric type for the result. In the simplest
case an add(int, int) method would return
an int value, as below:
public final int add(final int firstInt,
final int secondInt) {
return firstInt + secondInt;
}

To add two numbers you would call the


method and assign the return value to a
variable so it can be used later.

int sum = add(5, 2);

Q: How should I round a double up to an int?


A: To round a double value up and convert
it to an int value takes two operations. The
staticMath.ceil(double) method

returns

a double value that is equal to the "next


highest" integer. You must then give an
explicit down cast to an int, as below.
full answer hidden, click to get full
answers
Premium members click below for full answer
How should I round a double up to an int?

Q: How

can I calculate minimum, maximum and average using

Java?

A: Assuming

you have data values in a

Java storage structure, the key part of the


process is to iterate through the values,
check

and

store

the

minimum

and

maximum values, the running total and


number of data points. Lets take the simple
case

of

an

iterator

of DataPointobjects

over

that

have

set
an int

getValue() method.
This

example

has int variables

for max, min, count, sum and


temporary dataValue.

The

a
initial

value

for max is set to Integer.MIN_VALUE so that


any given value should exceed it, and min is
set to Integer.MAX_VALUE. A float type is
specified

for

the

mean

variable

since

integer division is likely to result in a


fraction and the decimal part should be
preserved.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I calculate minimum, maximum and
average using Java?

Q: What are bitwise and bit shift operators?

A: Java bitwise operators act on the binary


representation
numbers int and long.

of

primitive
Bitwise

shift

operators perform low level mathematical


actions as if they physically shift binary

10

digits left and right. The bitwise logical


operators compare numbers bit by bit and
transform them according to boolean logic.
The examples below show how the 32 bit
binary values are transformed by each
operator and highlight some significant
exceptions in the the use of shift operators
in mathematics.
full answer hidden, click to get full
answers
Premium members click below for full answer
What are bitwise and bit shift operators?

Variable scope

Q: Why does this for loop instantiation fail to compile?


A: If you declare a variable in a for loop
without braces the Sun compiler will fail
with the message "not a statement", but
the

message

is

misleading.

more

appropriate error message would be "o is


already defined". In this case there is no
contained scope for the variable o, so every
pass through the loop would have the effect
of declaring the variable again and again.
// Does not compile
for ( ; ; ) Out o = new Out();

Without braces its as if you had written a


continuous list of variable declarations:

11

// Does not compile


Out o = new Out();
Out o = new Out();
...

In the example below the for loop statement


is enclosed in curly braces, which gives the
variable declaration more precise scope. In
this case, each pass through the loop
creates a "throw-away" variable which is
local to the statement block.
for ( ; ; ) {
// Compiles
Out o = new Out();
}

This question is not particularly to do with


the for loop and it makes no difference
whether the loop runs once or an infinite
number of times. The significant point is not
to do with assignment, it is about the
declaration of the variable and the scope
the variable has. The annotated example
below continues the case of the for loop,
but the key is to compare the different
syntax that follows the for conditions.
full answer hidden, click to get full
answers
Premium members click below for full answer
Why does this for loop instantiation fail to compile?

Class relationships and references


12

Q: How do I call another class in the same folder?


A: Assuming the Java classes are in the
same package, one class should instantiate
the other to call an instance method, or use
a class name reference to call a static
method, as below.
public class Example {
public static void main(String[] args) {
Other otherInstance = new Other();
otherInstance.instanceMethod();
Other.staticMethod();
}
}

Q: How do you put both files in the same package to call them?
A: If two Java source files are located in
the same directory and neither explicitly
declare a package name, they are implicitly
in

the

same

default

package

explicit import statements

are

and

no

required

between them. Both classes can refer to


each other, instantiate and call methods on
each other directly provided there are no
visibility modifiers that would prevent this.
When you create a package structure for
your classes these relationships get a little
more complicated. In the simplest case you
can declare that both classes belong to the
same

package

by

adding

the

same package statement to the head of


both source files, before the class definition.

13

In this case both classes can refer and call


on each other as with the default package
above, noimport statements are required.
package org.example.packagename;

The convention for package names is to be


the

reverse

associated

of

with

separators.

the
the

The

Internet
project

package

domain
with

dot

names

are

appended with a dot separator all in lower


case.

Q: How do I access a variable declared in another class?


A: The examples below uses three
classes, VariableHost, VariableCaller andVari
ableSubclass,
package

all

in

the

for

The VariableHost class

same

default

simplicity.
has

astatic class

variable and an instance variable and the


cases show how they are accessed from the
host class itself and the other classes.
public class VariableHost {
static int staticInt = 2;
int instanceInt = 4;
public static void main(String[] args) {
// Static reference
int staticAccess = staticInt;
// Object reference necessary for instance
variable
VariableHost hostInstance = new
VariableHost();

14

int
instanceAccess
hostInstance.instanceInt;
}
}

full answer hidden, click to get full


answers
Premium members click below for full answer
How do I access a variable declared in another
class?

Java design patterns

Q: What is a recursive method?


A: A recursive method is

one

whose

method body includes a call to itself, so that


it is called repeatedly until an expected
condition is met or it cannot continue the
recursion any longer. These methods often
take an object or numeric argument that is
subject

to

progressive

mathematical
Recursive

interrogation

processing

methods

must

at

each
be

or

pass.

designed

carefully to ensure that they do not result in


a very deep or endless recursion, which is
likely to cause anOutOfMemoryError.
A simple example of a recursive method is
the getNodeByName(String) method below,
which iterates through all child nodes in an
object structure until it finds one that
matches, or returnsnull.
full answer hidden, click to get full
answers

15

Premium members click below for full answer


What is a recursive method?

Q: What is a singleton?
A: A singleton class

is one in which

instantiation is restricted to ensure that only


one instance is created for the current Java
Virtual Machine. Singletons usually have a
private

default

constructor,

to

prevent

direct instantiation, and a static method to


obtain a "new" reference to the single
instance. On its first call, the static instance
method creates the object using a private
constructor and stores a static reference to
it for all subsequent calls.
full answer hidden, click to get full
answers
Premium members click below for full answer
What is a singleton?

Q: What happens to singletons when two JVMs are running?


A: There is only one instance of a true
singleton in a single virtual machine. If two
virtual machines are running, two separate
and independent instances of a singleton
exist.

If

governing

the

singleton

access to

the

in

question
same

is

system

resource, there may be conflicts between


the two systems, which is why the singleton
design pattern is not ideal in this scenario.

Q: How do I format my price correctly?


A: Whenever you need to represent
quantities that have specific formatting and

16

equivalence requirements, it is best to use


the

Quantity

design

a Money type,

you

pattern.
can

For

associate

aCurrency with the amount and can deal


with all rounding issues in one class. Your
money and currency types can then use
generic rendering methods to show the
amount however you choose.
full answer hidden, click to get full
answers
Premium members click below for full answer
How do I format my price correctly?

Q: What is a factory method?

A: A

factory method is typically used to

obtain a new instance of a class, which may


be

one

of

several

alternate

implementations. The return type of a


factory method is an interface or superclass
type, which gives it the freedom to govern
the actual class that is returned through
polymorphism. This design pattern enables
the factory to control and encapsulate the
logic used to decide which instance to
return.
full answer hidden, click to get full
answers
Premium members click below for full answer
What is a factory method?

Q: How should I create an immutable class?

A: An immutable class is one whose field


values cannot be altered after instantiation,

17

so all variable values must be assigned in


the

constructor

and

may

therefore

be

declared final. By definition an immutable


class

should

not

have

any

modifier

methods, but you must also be careful that


the constructor and accessor methods do
not expose mutable field references.
full answer hidden, click to get full
answers
Premium members click below for full answer
How should I create an immutable class?

Q: What are adapters in Java?

A: An adapter in Java is a design pattern in


which you create a class "wrapper" around
an object of one type so that it can be used
as, and behave like, an object of another
type. The adaptation of classes to the target
interface is often done by composition
rather than inheritance so that the adapter
fully encapsulates the adapted class to
maintain the integrity of both.
To enable a plain Java Person class to be
used in a Swing application, you might
create aSwingPerson adapter. The example
below

encapsulates

private Person instance

in

a
a JPanelwith

labelled text fields to represent the person's


first and last name, with basic getters and
setters

for

each.

The

extension

of

the JPanel class means that the adapter


inherits

all

SwingComponent functionality.

standard
The

18

encapsulation of the Person class "adaptee"


means

that

any

special

behaviour

the Person class has does not have to be


rewritten.
full answer hidden, click to get full
answers
Premium members click below for full answer
What are adapters in Java?

Java application development

Q: How can I sort 3 numbers using Java?


A: Small data sets can be sorted using a
simple bubble sort algorithm that steps
through the sequence, compares adjacent
values and swaps them if necessary. The
example

below

uses

recursive sort(int[]) method

to

re-process

the integer array if the sequence changes.


In the final pass there is no change and the
sorted array is returned.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I sort 3 numbers using Java?

Q: How can I make spelling checker with a LinkedList dictionary?


A: A basic spelling checker that processes
an input stream of some kind might use
aStreamTokenizer to identify the words from
the

input

and

use

the LinkedList class'scontains(Object) metho

19

d to check whether the given word is


recognised. How you deal with un-matched
words is up to the application interface, this
example just lists the line number and word
on the console output.
full answer hidden, click to get full
answers
Premium members click below for full answer
How

can

make

spelling

checker

with

a LinkedList dictionary?

Q: How can I use SAX to parse a Web page via JTidy?


A: The JTidy project help page is not all
that

helpful.

The

original HTML

Tidy

configuration optionsare a better reference


to the equivalent methods in the Java
implementation

and

the Code

StyleJTidy

development notes article should help you


get started.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I use SAX to parse a Web page via JTidy?

Q: How can I create a search engine in Java?


A: This is a big question and there are
many aspects to consider. You may find it
helpful

to

take

the MKSearch system.

This

is

look

at

an

open

source project, so you can review the code


yourself. The project Web site includes Java
documentation,

configuration

notes

and

how to guides to get you started.

20

Q: Can I get the source code for a Java search engine?

A: The
engine

source of the MKSearch search


is

available

from

the MKSearch

Subversion repository, use the trunk path.


The MKSearch Web site has a research
section that includes detailed notes on
several open source spider applications that
can be used to acquire Web content for
indexing.
Another popular open source Java search
engine application is Apache Lucene .

Q: Would a Java search engine be a good final year project?

A: The design and development of a Java

search engine could be suitable for a BSc


final year project. The level of knowledge
required about Web technology in general,
the specifics of the HTTP protocol, how to
spider

Web

pages,

multi-threading

techniques, indexing content, the query


system and results delivery would certainly
give you plenty to work with, possibly too
much. Talk to your tutor about the scope of
the work and perhaps consider working on a
particular aspect of a Java search engine
system.

A: It

Q: How can I design my own fonts using Java?

is puzzling that you would want to

design fonts using Java, the language is not


particularly suited for this purpose. There
are

several

very

good applications for

21

designing

and

converting

fonts

such

as Fontographer for example.

Interface concepts

Why use interfaces to develop Java applications?

I still don't get why I should use interfaces!

What is the difference between interfaces and inheritance?

But interfaces are implemented by classes, why bother?

How come methods in interfaces are not defined?

What is the difference between abstract classes and interfaces?

Why use interfaces instead of abstract classes?

What's the difference between an interface and an API?

Is an API a help document?

Interface use

When should I use an interface?

Where should I use interfaces in my application?

When should I use abstract classes rather than interfaces?

How do we use interfaces as variables?

What are the rules for passing subclasses for method arguments?

Can you give an example of multiple inheritance with interfaces?

How to define an interface

Should I use a public access modifier for interface methods?

Non-public modifiers can be used for nested interfaces!

Can we create a Java class inside an interface?

Can an interface extend a class?

Can an interface extend an abstract class?

Can an interface be declared final?

How to implement an interface

Can we create an object for an interface?

Is more than one interface allowed?

Is it necessary to implement all interface methods?

How is the implements keyword different from extends?

22

Can you show how to implement an interface?

This code seems to be instantiating an interface!

What if two interface methods clash in implementation?

When interfaces clash, which method answers the call?

Marker interfaces

What is a marker interface?

How do marker interfaces affect the behaviour of classes?

Are there any marker interfaces that have methods?

Can we implement a marker interface?

Why do we need to implement the Serializable interface?

Can you show an example marker interface?

Interface constants

Do interfaces have member variables?

Are you sure you can declare member variables in an interface?

Why are interface variables public static final?

Interface variables can be overridden, right?

This interface variable is assigned in a constructor!

What style should I use to declare a member variable in an interface?

Is this interface constant declaration correct?

Interface concepts

Q: Why use interfaces to develop Java applications?


A: It is advisable to design relatively large
applications using interfaces because it
makes the whole system easier to modify,
extend and integrate new features. To start
with you may only have one implementation
of a given interface, but if you find you need
slightly

different

behaviour

in

special

circumstances, you only need write a class


that

conforms

to

one

of

the

existing

23

interfaces and it will drop in place without


major modifications.
Interfaces also allow you to adapt a class
from a different hierarchy to work in an
existing application. The class only needs to
declare it implements the interface, provide
the necessary methods and it can be
integrated directly as if it were created for
the job.

Q: I still don't get why I should use interfaces!


A: When you first start working with Java
interfaces it may seem like extra work
without much pay-back, you have to write
an empty interface definition and also
write concrete methods to implement them.
There is no great advantage when you are
working with relatively small scale, standalone applications for a single purpose.
Most people first recognise the need for
interfaces when they work with Java API
packages

that

implementations
particularly

the

to

require

interface

work

effectively,

old-style

Abstract

Windowing Toolkit (AWT), Swing and Java


threads. With Swing you must implement
theActionListener interface to respond to
button clicks, for example. The more you
implement Java API interfaces for specific
purposes the more you will recognise when
interfaces are appropriate in your own
applications and start to appreciate the
benefits.

24

AWT and Swing are strong examples of Java


interface

use

Interface

(GUI)

because
classes

Graphical
can

User

implement

listener interfaces to handle their own click


or status events. In this case, the use of an
interface means no extra class definition.
public
class
ListeningFrameExample
extends
JFrame
implements
WindowListener {
// Application methods
// Example WindowListener method
public void windowIconified(WindowEvent
e) {
// Handle window minimised events
}
// Other WindowListener methods
}

AWT and Swing event handler interfaces


like ActionListener only have one method,
so

can

easily

be

implemented

by

anonymous inline class definitions, split


over several lines in the example below.
JButton button = new JButton("Example
Button");
button.addActionListener(
new ActionListener() {
actionPerformed(ActionEvent ae) {
// Handle the action
}
}
);

25

The anonymous class is instantiated using


the new keyword followed by the name of
the interfacewith parentheses, as if the
interface name is the name of a concrete
class.

The

declaration

of

single actionPerformed() method


enclosed

in

curly

braces.

the
follows,

The

close

parenthesis on the last line is paired with


the

opening

parenthesis

of

the addActionListener() method call on the


first line; it encloses the whole anonymous
class definition and must be followed by a
semi-colon.

Q: What is the difference between interfaces and inheritance?


A: Interfaces and inheritance are closely
related in Java. In short, when a class
implements an interface it inherits the
essential behavioural characteristics of the
interface. An instance of the class can be
treated the same as any other class that
implements the interface. In this case,
theimplements keyword
inheritance

relationship

creates
between

the
an

interface and a class.


The interface is a largely abstract model, it
defines what is required to be a class of that
type in terms of the methods it must
provide. A class does not inherit any specific
behaviour from an interface, a programmer
is free to implement interface methods as
they choose. So long as they match the
interface method signatures a class inherits

26

the ability to act as or behave like any


other implementation class.
Interface inheritance creates polymorphism
because any class that implements an
interface can be cast to that type and used
interchangeably with any other in variables
and method arguments.

Q: But interfaces are implemented by classes, why bother?


A: When you compare interfaces with
standard class hierarchies there are obvious
similarities, especially compared with an
entirely abstract class. Both interfaces and
abstract classes can be extended and extra
abstract methods added. The nature of
inheritance means that sub-classes and
sub-interfaces

are

type-compatible

with

their parents.
The use of interfaces in Java is partly a
design compromise to support a limited
form of multiple inheritance. Purely abstract
interfaces

enable

classes

to implement

multiple interfaces and extend a superclass


within the general constraints of the Java
language and runtime environment.
The separation of interfaces from classes
means it is also possible to compose Java
types that are loosely coupled or entirely
detached
makes

from

them

example,

class
flexible
class

hierarchies,
to
may

which

change.

For

implement

the java.util.List interface by encapsulating


and adapting a Vector, to make a thin

27

wrapper

around

the Vector without

extending the class. At a later date you can


switch

the

encapsulated Vector to

an ArrayList, LinkedList or

some

other

custom implementation without affecting


clients of the class.

Q: How come methods in interfaces are not defined?

A: An interface

represents a Java type, a

concept of a set of Java classes that behave


in a particular way such that any one could
be used in place of another. It may help to
think of a Java interface as a blueprint, plan
or model that says, write a class that has
these methods.
An interface describes what a Java class
must do, but doesn't say how it should be
done, that's why interface methods have no
code body. A Java programmer is free to
code an interface however they choose, so
long as their methods have the same
names, arguments and return types as the
interface.

That

programmers
different

to

classes

flexibility
write
to

or

fulfil

enables

adapt
a

many

particular

interface.

Q: What is the difference between abstract classes and interfaces?

A: A Java interface is a definition of a class

type without any concrete implementation.


Typically, an interface consists of one or
more method signatures that a subclass
must fulfil to conform to the type. All their

28

methods are abstract and interfaces cannot


be instantiated.
full answer hidden, click for full
answers
Premium members click below for full answer
What is the difference between abstract classes and
interfaces?

Q: Why use interfaces instead of abstract classes?

A: The

key difference between abstract

class and interface based inheritance is that


concrete classes are bound to a single
abstract class hierarchy, they are tightly
coupled and cannot extend any other class.
This makes it difficult to create general
purpose component classes that can be reused in different packages.
Interface based inheritance does not create
a binding to a specific class hierarchy, so
concrete

classes

can

inherit

the

type

characteristics of several interfaces without


limiting their scope for re-use. Concrete
classes can implement multiple interfaces
and extend an abstract class, but it is best
to minimise class inheritance as far as
possible to preserve lexibility.

Q: What's the difference between an interface and an API?


A: An

Application Programming Interface

(API) is the collection of all the public


methods and fields that belong to a set of
classes, including its interface types. The
API defines the way that developers can use

29

the classes in their own Java program, just


by

importing

writing

the

statements

relevant
that

classes

and

instantiate

the

classes and call their public methods and


fields.
A Java interface declares a type of Java
object without a concrete implementation.
Interfaces are defined in a compilation unit
like a standard Java class and the methods
they

declare

are

Application

implicitly

part

Programming

of

an

Interface.

Interfaces are used to help define generic


structural components in an API, a reference
type for concrete implementations, and an
extension mechanism for programmers who
use the API.

A: An

Q: Is an API a help document?


Application Programming Interface

(API) is a way to describe a collection,


library or toolkit of Java software that can
be used as part of new Java programs. The
name Application Programming Interface
refers to the components in a packaged
collection of Java programs and the special
properties and behaviour that they can
provide in a Java program. The classes in
the

Java

networking

package

enable

programmers to get information from the


Internet,
accessible
methods

for

example.

Java
in

classes,

this

The

publicly

properties

collection

are

and

called

the java.netAPI.

30

Ideally a Java software library should be


distributed with a set of help documents
that describe its API and explain how Java
programmers should use the components in
their own programs. These documents can
be

generated

from

specially

formatted

JavaDoc comments embedded in the code


but they only describe the API, they are not
the API itself.

Interface use

Q: When should I use an interface?


A: If you are not used to using interfaces
in your Java programs you are most likely to
recognise

the

need

when

you

are

refactoring an existing application to add a


new feature or support a new input or
output format. When you think about how to
re-organise the program it may be difficult
to see where to make the changes, the
class hierarchy may seem tangled, or it
feels like a new format doesn't fit in neatly.
A strong sign that you need to introduce an
interface is that you have very similar code
in separate classes and you can't re-arrange
the classes to inherit this behaviour from a
common superclass.
When you recognise these characteristics in
a system, you should list the behaviour the
problem objects need to have so that the
main path of the program can process them
in

the

same

way.

Separate

this

31

Processable behaviour in an interface and


keep the type-specific behaviour in the
classes that need to be processed. Where
you see duplicate code in the processable
classes, move it up the hierarchy and
perhaps

head

it

an AbstractProcessable class.

with

That

should

leave the type-specific classes to implement


the Processable interface, possibly extend
theAbstractProcessable class, and focus the
main content of the class on its core,
distinct behaviour.

A Processable interface defines the type of


things that can be processed in a particular
way, a set of data that can be rendered as a
Web page, for example.

An AbstractProcessable superclass

may

implement

and

provide

the Processble interface

some

subclasses

concrete
to

methods

for

such

as

use,

a cleanUpData() method, for example.

Concrete ProcessableSpreadsheet, Processa


bleDocument and ProcessableReportclasses
can extend the AbstractProcessable class
and implement the Processableinterface
methods.

Finally, an HTMLRenderer class can define


a render(Processable) method that accepts
any

of

classes

above

that

implement

the Processable interface to generate HTML


output.
The main path of your application will need
to be adapted to declare and cast these

32

objects asProcessable types, but that will


mean any other Processable type can more
easily be added to the system in future.

Q: Where should I use interfaces in my application?


A: Partly that's a question that depends on
the nature of your application, its overall
structure and how it integrates with the Java
API and third party libraries. Interfaces can
be

used

in

most

areas

of

application

development, so they could be used in any


part of the system. The main things to look
out for are cases where several different
things need to be treated in a similar way,
an interface can consolidate the common
behaviour of a set of classes so that your
application

code

can

process

them

interchangably.

Q: When should I use abstract classes rather than interfaces?


A: Abstract classes are often used to
provide methods that will be common to a
range

of

similar

subclasses,

to

avoid

duplicating the same code in each case.


Each subclass adds its own features on top
of the common abstract methods.
full answer hidden, click for full
answers
Premium members click below for full answer
When should I use abstract classes rather than
interfaces?

Q: How do we use interfaces as variables?

33

A: Java

is a strongly typed language,

which means that all variables and method


arguments

must

be

declared to

be

particular type. The references assigned to


variables and passed to methods must
match their declared type, or be cast to
them, to maintain the type safety of the
system.
Java types fall into 3 categories:

Primitive

types

Including byte, boolean, char, int and other


numerics.

Object

types

Including

built-in

API

classes

and

programmer defined classes.

Interface
Types

types

declared

by

interfaces

and

implemented by concrete classes.


Interfaces cannot be instantiated in their
own right, but the concrete classes that
implement them are type-compatible. That
means that any class that implements
the java.util.List interface can be assigned
to a variable of that type, for example.
// List interface
// Vector implements List
List list = new Vector();

When an instance of a class is assigned to


an interface type variable in this way, you
can safely call any interface methods on the
variable.

This

is

an

example

of

polymorphism in Java. A Vector has its own

34

properties and methods, but when assigned


to a List type variable, it is treated as
a Listand can be passed to other methods
that require a List type argument.

Q: What are the rules for passing subclasses for method arguments?

A: It may help to discuss an example using


birds:

an

interface

called Avian,

superclassFlyingBird that
implements Avian and

two

concrete

classes: Parrot and Penguin. Parrotextends F


lyingBird,

so

is

implicitly

but Penguin does

an Avian type,

not,

it

only

implementsAvian.
full answer hidden, click for full
answers
Premium members click below for full answer
What are the rules for passing subclasses for
method arguments?

Q: Can

you give an example of multiple inheritance with

interfaces?

A: To

illustrate

multiple

inheritance,

consider a Bat, which is a mammal that


flies.

We

might

interfaces: Mammal,

have
which

method suckleInfant(Mammal),

two
has

and Flyer,

which has a method fly(). These types


would be declared in interfaces, as below.
full answer hidden, click for full
answers
Premium members click below for full answer
Can you give an example of multiple inheritance
with interfaces?

35

How to define an interface

Q: Should I use a public access modifier for interface methods?


A: Java interface methods are always
implicitly public, even if they belong to
nested interfaces. Non-public modifiers are
not

valid

or

necessary

for

interface

methods, so the compiler should fail and


warn you in this case. Nested interfaces
may be declared protected or private, but
the methods they define must still follow
this rule, as summarised below.
full answer hidden, click for full
answers
Premium members click below for full answer
Should I use a public access modifier for interface
methods?

Q: Non-public modifiers can be used for nested interfaces!


A: Interface methods must be public, the
compiler will fail and issue a warning if
interface

methods

declared protected or private,


nested

interfaces.

themselves

Nested
may

are
even

in

interfaces
be

declared protected or private.

Q: Can we create a Java class inside an interface?


A: Yes, classes can be declared inside
interfaces. This technique is sometimes
used where the class is a constant type,
return value or method argument in the
interface. When a class is closely associated

36

with the use of an interface it is convenient


to declare it in the same compilation unit.
This

proximity

also

implementation

helps

changes

ensure

to

either

that
are

mutually compatible.
A class defined

inside an

interface is

implicitly public static and operates as a top


level

class.

The static modifier

does not have the same effect on a nested


class as it does with class variables and
methods. The example below shows the
definition of a StoreProcessor interface with
nested StorageUnit class which is used in
the two interface methods.
full answer hidden, click for full
answers
Premium members click below for full answer
Can we create a Java class inside an interface?

Q: Can an interface extend a class?


A: In Java an interface can only extend
another interface, called a super-interface.
This

is

an

inheritance

superclass-subclass;
inherits

all

the

relationship

like

the

sub-interface

constant

variables and

abstract methods defined in the superinterface and can add its own.
Since an interface may have a static class
defined within it, it is possible for a class in
a sub-interface to extend a class in a superinterface, but that is a different thing
entirely. In this case the extension of nested
classes

is

no

different

from

37

standard extends inheritance

except

the

hosts of the classes are interfaces. There is


no mixture of class and interface extension.

Q: Can an interface extend an abstract class?

A: In

Java an interface cannot extend an

abstract class. An interface may only extend


a super-interface. However, an abstract
class can implement an interface. It may
help to think of interfaces and classes as
separate lines of inheritance that only come
together

when

interface,

the

class

implements

relationship

cannot

an
be

reversed.

A: It

Q: Can an interface be declared final?


is

not

permitted

to

declare

an

interface as final, it will cause a compilation


error.

This

is

Java

language

design

decision. Interface types are intended to be


implemented and can be extended without
restriction.

Some

regard

this

free

extensibility as a flaw in the language


design because there are cases where it
would be useful to restrict the broader use
of an interface. In the current scheme it
does not make sense to declare an interface
final because it would imply it could not be
extended and possibly not implemented,
which would not be useful.

How to implement an interface

Q: Can we create an object for an interface?


38

A: Yes,

the most common scenario is to

create an object implementation for an


interface, although they can be used as a
pure reference type. Interfaces cannot be
instantiated in their own right, so it is usual
to

write

class

that

implements

the

interface and fulfils the methods defined in


it.
public
class
Concrete
ExampleInterface {

implements

...
}

Q: Is more than one interface allowed?


A: Yes, a class can implement multiple
interfaces, this is an effective way to
achieve multiple inheritance in Java. A class
can only extend one superclass.

Q: Is it necessary to implement all interface methods?


A: It is not necessary for a class that
implements an interface to implement all its
methods, but in this case the class must be
declared abstract.

In

this

respect

the

implementation of an interface is similar to


the extension of an abstract class. The
implementation of the interface methods
can be deferred through any number of
abstract subclasses, but at some point you
should create concrete implementations. In
fact, its a sign there may be something
wrong with your code design if you defer

39

interface implementation in more than one


or two subclasses.

Q: How is the implements keyword different from extends?


A: The implements keyword is used when
a

class

explicitly

definition

fulfils

with

an

interface

concrete

method

implementations for its abstract method


signatures. A single class can implement
more than one interface, but must be
declared abstract if it does not implement
all interface methods.
The extends keyword
interface

inherits

is

used

the

type

when

an

definition

specified in a super-interface, or a class


inherits from a superclass. A class can only
extend a single superclass but may also
implement one or more interfaces.
When an interface extends a super-interface
it is not required or permitted to implement
any of its abstract methods since the subinterface must be abstract itself.

Q: Can you show how to implement an interface?

A: Simple examples are not always strong


examples,

but

this

an AreaInterface with
method getArea() and

case

shows

single

how

that

is

implemented
in ConcreteCircle, ConcreteSquareand Concr
eteRectangle classes.
public interface AreaInterface {

40

double getArea();
}

full answer hidden, click for full


answers
Premium members click below for full answer
Can you show how to implement an interface?

Q: This code seems to be instantiating an interface!

A: The code you are looking at declares an


inline anonymous class that implements an
interface, which has a similar effect. This
declaration

does

not

instantiate

the

interface, but defines the type of the


anonymous class, which has no name of its
own. This approach is often used in old-style
Abstract Windowing Toolkit (AWT) or Swing
applications where a class is required to
fulfil a minimal interface and it is not
necessary to retain a reference to it by
assignment.
full answer hidden, click for full
answers
Premium members click below for full answer
This code seems to be instantiating an interface!

Q: What if two interface methods clash in implementation?

A: If two interfaces have the same method

signature, they effectively declare the same


method regardless of any other intentions.
Any concrete class that implements both
interfaces

can

implementation

only
of

provide
given

one

method

41

signature, so there is no ambiguity about


how the Java compiler deals with this case,
only a potentially difficult design decision.
If two interface methods have a clash over
their

method

signatures

and

intended

behaviour, it would preferable to rename


one of the interface methods to indicate a
more distinct purpose.

A: In

Q: When interfaces clash, which method answers the call?


this case neither interface answers

the method call, thus it is not a problem.


The

interface

methods

must

be

implemented by a concrete class and it is


the single

concrete

method in

the

implementation class that will handle the


call. The example below shows that the
behaviour defined in the concrete method
will be executed regardless of the reference
type used for its instance.
full answer hidden, click for full
answers
Premium members click below for full answer
When interfaces clash, which method answers the
call?

Marker interfaces

Q: What is a marker interface?


A: Marker interfaces do not

declare any

required methods, but their implementation


signifies

compatibility

with

certain

42

operations. The java.io.Serializable interface


is a typical marker interface, classes must
implement this interface in order for their
instances to be serialized and de-serialized.

Q: How do marker interfaces affect the behaviour of classes?


A: Marker interfaces do not affect the
classes that implement them through their
behaviour, they cannot since there are no
required methods, they only mark the class
by

identifying

it

as

Java

type

that

conforms to the interface. In the classic


example, methods that serialize data can
check that a class can be serialized by its
implementation of the Serializable interface.

Q: Are there any marker interfaces that have methods?


A: No, the definition of a marker interface
is that it contains no behavioural definitions,
so there can be no marker interface that
has

methods.

Marker

interfaces

are

concerned with being a certain type rather


than behaving as a type does.

Q: Can we implement a marker interface?


A: Yes, marker interfaces can be
implemented,

just

add

the implements keyword and the name of


the interface to your class declaration, as
below.
public
class
ExampleSerializable
implements Serializable {
// No interface methods to implement
}

43

Q: Why do we need to implement the Serializable interface?

A: In

some respects marker interfaces

such as Serializable are like a prompt or


reminder to programmers that we must
implement the interface to get the results
we need; most importantly we must ensure
that the class is truly serializable.
A

class

must

implement

the Serializable interface else any attempt


to

serialize

an

instance

will

throw

a NotSerializableException. However, it is
the programmer's responsibility to ensure
that an instance can physically be serialized
and de-serialized in a meaningful way, so
that the object's original state can be fully
restored. That can be a complex task,
especially when a class has field types that
are

final

and

do

not

the Serializable interface,

implement

hence

the

interface is a marker that special measures


need to be taken.

Q: Can you show an example marker interface?

A: An

interface

something

that

typically
is

represents

Processable

in

particular way. Marker interfaces don't have


any interface methods, they usually signify
a property or state that any Java class may
have that cannot be defined by a method
signature.

An

example

would

be

an Immutableinterface, since a fundamental

44

characteristic of immutable classes is the


absence of mutator methods.
full answer hidden, click for full
answers
Premium members click below for full answer
Can you show an example marker interface?

Interface constants

Q: Do interfaces have member variables?


A: Interfaces may have variable fields but
they are implicitly final and static. Interface
variables are inherited by any class that
implements the interface and are also
available

as publicstatic variables

of

the

interface. In effect, interface variables are


constants

that

are

available

to

all

implementations and may be used as key


references

for

method

arguments,

for

example.

Q: Are you sure you can declare member variables in an interface?


A: Yes, it is definitely possible to declare
member variables in an interface, though it
may help to call them static member
variables. Interface variables are implicitly
static, even if you omit thestatic keyword
they will be compiled and treated as public
static final constants. You cannot declare an
instance variable in a Java interface.

Q: Why are interface variables public static final?

45

A: The

short answer is that interface

variables are intended to be Java constants,


which

means

universal

and

they

must

have

un-changable

Interface

these

properties.

variables

are

implicitlypublic because

interfaces

intended

an

to

provide

are

Application

Programming Interface (API) that is fully


accessible
reference

to
and

Java

programmers

implement

in

their

to
own

applications. Since an interface may be


used in Java packages that are different
from their own, public visibility ensures that
program code can access the variable.
Interface variables are static because Java
interfaces cannot be instantiated in their
own right; the value of the variable must be
assigned in a static context in which no
instance exists. The finalmodifier ensures
the value assigned to the interface variable
is a true constant that cannot be reassigned by program code.

Q: Interface variables can be overridden, right?


A: No, interface variables are constants
that

cannot

be

overridden.

They

are

inherited by any class that implements an


interface.

Q: This interface variable is assigned in a constructor!

A: In this case a final instance variable in


a class is declared as an interface type,
which is different from a constant field in
an interface. The example below shows

46

a List type

assigned

afinal variable

in

class constructor. Any object that fulfils


the List interface can be passed to the class
constructor

and

assigned

to

its final instance variable. The final variable


cannot be changed after instantiation.
full answer hidden, click for full
answers
Premium members click below for full answer
This interface variable is assigned in a constructor!

Q: What

style should I use to declare a member variable in an

interface?

A: The

way that interface constants are

declared is arbitrary, whether you use the


full public static final modifiers or none at all
the compiled code will be the same. Java
code style is intended to help the reader
without stopping to think too hard. The
convention

of

setting

constant

variable

names in upper case letters with underscore


separators, CONSTANT_NAME,

is

recommended and likely to be a stronger


guide to the nature of the constant.

Q: Is this interface constant declaration correct?

A: Your
wrong

interface constant declaration is


for

two

reasons.

Firstly,

the

keyword interfacecannot be used in variable


declarations, only in the enclosing interface
declaration itself, as below.
public interface Example {

47

// API declarations
}

Secondly, the type of the variable must


match that of the value that is assigned to
it; an intcannot be assigned a String value.
Standard Java code style is to give your
interface constant an uppercase variable
name with words separated by underscores.
public static final
"Constant example";

String

EXAMPLE

Java inheritance principles

What are the benefits of inheritance?

Is inheritance applicable for beginners in programming?

What forms of inheritance are supported by Java?

Can you show examples of Java inheritance?

Isn't specialization a form of inheritance?

What is the difference between abstract classes and inheritance?

How does inheritance avoid duplication?

How do packages affect inheritance in Java?

Multiple inheritance

Why doesn't Java support multiple inheritance?

Doesn't implicit Object inheritance create multiple inheritance?

Can you prove that Object is the ultimate superclass in Java?

Is multiple interface inheritance better than extending a class?

Can I achieve multiple inheritance without interfaces?

Can we achieve multiple inheritance with the extends keyword?

Extending classes

What's the difference between importing and extending a class?

Can we explicitly inherit from the Object class?

48

How can I use inheritance in graphical user interfaces?

How can I prevent a class from being extended?

The private modifier prevents inheritance too!

Overridden methods

What is overriding?

Can an overridden method return void instead of an object?

Why do overridden methods on a subclass have priority over the superclass?

Can you give an example application that shows overriding?

How do you prevent a method from being overridden?

How can I find the inherited attributes of a class?

Techniques for overridden superclasses

How can I call an overridden method in the superclass?

Can you give an example call to an overridden superclass method?

How can I get the superclass to call back to a method in the subclass?

A superclass can call an overriden method in a subclass too!

Java inheritance principles

Q: What are the benefits of inheritance?


A: One of the key benefits of inheritance is
to minimise the amount of duplicate code in
an application by putting common code in a
superclass and sharing amongst several
subclasses. Where equivalent code exists in
two related classes, the hierarchy can
usually be refactored to move the common
code up to a mutual superclass. This also
tends to result in a better organisation of
code and smaller, simpler compilation units.
Inheritance can also make application code
more flexible to change because classes
that inherit from a common superclass can

49

be used interchangeably. If the return type


of a method is superclass Example, then the
application can be adapted to return any
class that is descended from Example.

Q: Is inheritance applicable for beginners in programming?


A: Inheritance is a good aspect to start
learning in Java because it is fundamental to
the

object

oriented

approach

and

the

concept is relatively easy to understand.


The best way to learn about inheritance in
Java is to write two simple test classes
where one extends the other, compile and
adapt from there to experiment.
public class Superclass {
// Initial implementation empty
}
public class Subclass extends Superclass
{
// Initial implementation empty
}

Make sure these classes compile, then


adapt.

For

example,

add

simple

identification method to the superclass, as


below.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Is

inheritance

applicable

for

beginners

in

programming?

Q: What forms of inheritance are supported by Java?


50

A: There

are two forms of inheritance in

the Java language. The standard form of


inheritance is by extension; a class declares
that

it extends another

class,

or

an

interface extends another interface. In this


case, the subclass or sub-interface inherits
all the fields and methods of its parent.
The second special form of inheritance is
where

classes

they implement an

declare
interface,

that

which

has

more limited consequences. When a class


implements an interface, it inherits any
fields from the parent as final constants,
but must provide its own implementation of
the interface methods.

Q: Can you show examples of Java inheritance?


A: An example of inheritance using
the extends keyword

would

the java.util.Stack class

that

be
extends

the Vector class to provide a last-in-first-out


stack of Objects. The Stack class uses the
same underlying storage facilities provided
by the superclass and adds its own, so it is
a

type

of Vector and

behaves

specialised

wrapper

the Vector class.

The Stack class

like

around
adds

boolean empty() method, peek(), pop() and


push() methods

to

manage

the

stack

contents and a search() method to find the


index of a given object. All the original
methods of the Vector class remain and

51

the Stack can

be

cast

to

a Vector as

necessary.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Can you show examples of Java inheritance?

Q: Isn't specialization a form of inheritance?

A: Specialization
inheritance,

not

is

an

application

particular

of

form

of

inheritance. From a technical point of view


one

can

only

apply

the extends and implements keywords

in

Java to achieve inheritance; the way that a


programmer implements the inheritance
scheme affects the nature of super- and
sub-class

relationships.

For

example,

abstract classes and interfaces are typically


used

to

specify

subclasses,

the

methods

which

is

of

their

specification.

Subclasses often provide special versions of


the

more

general

superclass,

that

is

specialization.
There are no Java keywords to declare
particular applications of inheritance in Java,
they

are

formed

by

of extends, implements and


programming

combination
other

Java
devices

like abstractand final methods,

visibility

modifiers and so on. Really it is the overall


configuration of class, variable and method
hierarchies that

shapes the

inheritance

52

relationships that exist, and classes may


serve more than one role.

Q: What

is

the

difference

between

abstract

classes

and

inheritance?

A: Inheritance
object

is a design principle in

oriented

Inheritance

means

languages
that

like

Java.

classes acquire

methods and properties by declaring that


they are a sub-class of a class that already
has those features. This can significantly
improve the efficiency and management of
code because some methods only need to
be written once and can be used by any
number of sub-classes.
An abstract class is one that is designed to
provide methods or properties to subclasses like a template. Abstract classes
cannot be instantiated in their own right
and usually contain abstract methods that
sub-classes must implement to complete
the intended inheritance program design.
For instance, abstract methods may have a
concrete method that calls an abstract
method, whose implementation varies in
each sub-class.

Q: How does inheritance avoid duplication?

A: To show how Java inheritance can avoid


duplication,

consider

classes: Car andMotorcycle which


implement

an

method moveForward().

two
both
interface

Here's

some

53

example

code

for

the moveForward() method in the Car class.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
How does inheritance avoid duplication?

Q: How do packages affect inheritance in Java?

A: Inheritance

is

properties

behaviour

and

concerned
that

with
a

the
class

aquires by extending a superclass, and the


polymorphic

types

it

acquires

by

implementing interfaces. The package a


class belongs to affects the inheritance
patterns it can adopt and may pass down to
subclasses through its visibility modifiers,
but it is also about assigning a fully qualified
class name.
A

fully

qualified

class

name

like com.example.util.Date distinguishes

non-standard Dateclass from the Java API


class java.util.Date and
the java.sql.Date class for example. That
means you can use all three Date types in
the

same

class

and

refer

to

them

class

specifically without ambiguity.


The

package

combined

with

assignment
the

of

implicit

package

visibility, public,protected or private visibilit


y modifiers on the class overall control
which other classes can extend it. When
those modifiers are applied to a variable or
method they affect which can be accessed

54

by other classes and subclasses. So the


package

assignment

combined

with

visibility modifiers shape the API a class


exposes to the Java environment.

Multiple inheritance

Q: Why doesn't Java support multiple inheritance?


A: The authors of the Java language took a
design decision to compromise multiple
inheritance with interfaces, the specifics of
this decision may be covered in other
sources. Practically, multiple inheritance is
difficult because it creates ambiguity when
a

class

inherits

superclasses

methods

with

the

from

same

two

method

signature: which version should be called?

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Why doesn't Java support multiple inheritance?

Q: Doesn't implicit Object inheritance create multiple inheritance?


A: No, this is a misunderstanding of
implicit object inheritance. Every Java class
is

ultimately

the Object superclass,

descended
whether

from
there

is

an extends Object statement or not. If you


extend

an

Application

Programming

Interface (API) class, the Object inheritance


is passed down through that immediate
superclass, not from

the

superclass and the Object class

too.

55

Implicit inheritance from the Object class


descends through a single line of parent
classes to ensure all user defined classes
have

the

standard toString(), equals() and hashCode(


)methods.

Q: Can you prove that Object is the ultimate superclass in Java?


A: You can prove that the Object class is
the superclass of all others by casting any
class to anObject. If you have a reference to
a

class

instance

variable testInstance then

in
cast

the
it

to

anObject as follows.
Object objectType = null;
try {
objectType = (Object) testInstance;
System.out.println("Instance successfully
cast to an Object.");
}
catch (ClassCastException cce) {
// Should never be thrown
System.err.println("Instance could not be
cast to an Object.");
}

Q: Is multiple interface inheritance better than extending a class?


A: You should make a judgement about
which forms of inheritance are better for a
particular Java application. In many cases
you should use a mixture of inheritance
techniques. The judgement you make will

56

depend on the nature, scale and context of


the solution you are developing.
For most relatively simple, small scale
applications that can operate independently
of other Java systems, class inheritance
works well because of its simplicity and reuse of code. Interface inheritance tends to
be

used

in

applications,

slightly
but

is

larger,

broader

usually

used

incombination with class inheritance, not


separately.
Some Java programmers argue that class
inheritance should be avoided because it
creates a rigid coupling and dependency
between a class and its superclasses. A
class can only have one superclass, so it
can be difficult to extract a class from its
hierarchy for use elsewhere. A more flexible
alternative is to compose a class of one or
more internal class fields and fulfil an
interface by creating a thin wrapper
around them.
The

example

below

implements

standard java.util.List and


example Named interface

the
an

by

adapting

a String and a Vector, not by inheritance.


The String and the Vector are encapsulated
by the host class so it is not tightly coupled.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Is

multiple

interface

inheritance

better

than

extending a class?

57

Q: Can I achieve multiple inheritance without interfaces?

A: The

short answer to your question is

no, this is one of the limitations of the Java


language.

However,

if

you

use

object

composition, it can be relatively easy to


fulfil two or more interfaces with adaptor
code that passes calls through to the
underlying objects.

Q: Can

we

achieve

multiple

inheritance

with

the extends keyword?

A: No, it is not possible to achieve multiple


inheritance

in

Java

using

the extends keyword alone. A Java class


may only extend one superclass. A limited
form of multiple inheritance can be created
where a class extends a superclass and
implements one or more interfaces. The
subclass would be type-compatible with the
superclass and the interfaces, though it
would not inherit any concrete behaviour
from the interfaces.

Extending classes

Q: What's the difference between importing and extending a class?


A: When a Java class is imported, the type
it represents is made available to the host
class to use as if it were contained within
the host. The imported class is not visible
through the public interface of the host
unless it is declared to extend it.

58

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
What's

the

difference

between

importing

and

extending a class?

Q: Can we explicitly inherit from the Object class?


A: Whenever we declare a new class
without an explicit extends keyword, the
class

implicitly

extends

fundamental Object class.

the

When

you

explicitly extend a different class, that will


be

descended

from

the Object class

at

some point in its hierarchy. It may help to


understand the inheritance structure more
clearly

if

you

explicitly

extend

the Object class and it would not be an


error to do so.
public class Example1 {
// Implicitly extends Object
}
public class Example2 extends Object {
// Explicitly extends Object
}
public class Example3 extends Example1 {
// Ultimately extends Object
}

Q: How can I use inheritance in graphical user interfaces?


A: Java inheritance has been designed to
be universal; any non-final Java class can be
extended without any special handling for

59

graphical user interface types. Child classes


will directly inherit all non-private fields and
methods of the parent, which can be
overridden

and

extended

however

you

choose.
Having said that, graphical user interface
classes can be quite complex and rely upon
specific method calls to maintain their
integrity.

Be

cautious

if

you

override

methods and make sure you check there


are no unintended side effects of your
changes. If you are not certain of the
consequences of your overrides, call the
overridden superclass method before your
own method statements.
In general, it is safest only to add features
to GUI classes or build new structures by
composition.

Q: How can I prevent a class from being extended?


A: To prevent a class from being extended
or subclassed include the final modifier in
the class declaration statement, as below.
public final class FinalClass {
// Class definition
}

Q: The private modifier prevents inheritance too!

A: The final keyword


concerned

with

blocking

is

primarily
any

subclass

override of a method, while the method


remains accessible by its subclasses and

60

possibly other classes too. If a method is


marked private it

is

not

visible

to

the

subclass, so cannot be overridden, but no


other class can call the method either.
If you use the private modifier to prevent
overrides it can also lead to confusing cases
where the subclass defines a method with
the same signature as its superclass. The
compiler will not issue a warning in this
case.

Overridden methods

Q: What is overriding?
A: So long as a class and its methods are
not marked final, a subclass can declare a
method with the same signature as one in a
superclass and its own implementation. A
typical

example

toString() method,

is

which

is

the String
declared

in

the Object class. All objects implicitly inherit


this method. The default implementation is
to output the class name combined with its
hash code in hexadecimal. The String class
overrides the toString() method to give a
Unicode representation of string content of
the

object.

Any

other

override toString() with

its

object
own

may

method

body, to return its own custom output.


public String toString() {
return "All classes may override non-final
methods.";

61

Q: Can an overridden method return void instead of an object?


A: It will often help to understand the Java
language if you create small test classes,
compile and run them. If you try to compile
this test case, you will find it fails because
the method signatures have different return
types: void and

an

object

reference.

In

Java, void is a return type and voidmethods


must not return object references.
To override a method, the subclass method
must have the same signature as the
superclass: return type, method name and
arguments.

If

the

return

type

of

the

subclass method is different it will fail to


compile, attempting to use incompatible
return type.

Q: Why

do overridden methods on a subclass have priority over the

superclass?

A: An

overridden method in a subclass

must take priority over the superclass


implementation because a class can only
expose one implementation of a particular
method

signature

through

its

public

Application Programming Interface (API).


The technique of overriding effectively says
use this special implementation of the
method instead of the superclass version.

Q: Can you give an example application that shows overriding?


62

A: The

method override example below

shows several aspects of inheritance. Both


classes

implement

the ObjectRenderer interface,


one

method, void

which

has

render(Object).

The

superclass BasicObjectRenderer has


default

constructor

and

the System.outPrintStream to

uses

render

object,

the
the

subclass HTMLObjectRenderer has


constructor

that

takes

an OutputStream argument to render the


object with HTML formatting.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Can you give an example application that shows
overriding?

Q: How do you prevent a method from being overridden?

A: To

prevent a specific method from

being

overridden

the final modifier

in
on

subclass,
the

use

method

declaration, which means this is the final


implementation of this method, the end of
its inheritance hierarchy.
public final void exampleMethod() {
// Method statements
}

Q: How can I find the inherited attributes of a class?


63

A: It

is possible to deduce the inherited

fields and methods of a Java class using


reflection through a recursive process that
uses

the Class method getSuperclass().

The Class methodgetFields() returns

an

array of Field objects for public fields only.


The getDeclaredFields()returns an array of
all declared fields in the current class,
including

private

fields,

but

not

inherited

the

fields.

The getMethods() and getDeclaredMethods(


) methods

return

equivalent

arrays

of Method objects.
To obtain a list of all inherited fields or
methods, a program would need to get the
superclass of the object in question, store
the

return

value

for

its getDeclaredFields() method then process


each of its superclasses in turn. The simple
example below prints out all the inherited
fields in its immediate superclass Thread.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
How can I find the inherited attributes of a class?

Techniques for overridden superclasses

Q: How can I call an overridden method in the superclass?


A: To call a superclass method that has
been overridden in a subclass, you must
either call the method directly through a

64

superclass instance, or use the super prefix


in the subclass itself. From the point of the
view

of

provides

the
an

subclass,
explicit

the super prefix

reference

to

the

superclass' implementation of the method.


// From subclass
super.overriddenMethod();

Q: Can you give an example call to an overridden superclass method?


A: The example below shows a general
class GeneralNotifier with

method printMessage()which is overridden


in

the

subclass SpecialNotifier.

The SpecialNotifier also

has

methodprintParentMessage() that calls the


superclass version of printMessage().

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Can you give an example call to an overridden
superclass method?

Q: How can I get the superclass to call back to a method in the subclass?
A: This type of call to a method in the
superclass chained to a call in the subclass
can be done if the superclass calls an
abstract method that is overridden in the
subclass, see the example below.

full

answer

hidden, click

for

complete answers

65

Premium members click below for full answer


How can I get the superclass to call back to a
method in the subclass?

Q: A superclass can call an overriden method in a subclass too!


A: Yes, you can also have a superclass call
custom methods in a subclass when the
subclass

overrides

concrete

method.

However, in this case, there is no contract


between the superclass and the subclass,
no

guarantee

that

actually does override


implementation.

The

the

subclass

the

superclass

implied

override

approach may work if a single programmer


writes the superclass and all subclasses, but
cannot ensure that another programmer
would complete the design pattern.
The advantage of the abstract method
approach is that subclass programmers
must discover the intended purpose of the
method

and

write

an

appropriate

implementation. This requires extra effort


and puts a greater responsibility on the
implementor,

but

should

enforce

the

contract established by the superclass.

Abstract class design and use

When should I use abstract methods?

Why use an abstract class instead of an interface?

Why do we need abstract classes with no abstract methods?

What's the use of concrete methods in abstract classes?

How many abstract subclasses can I create?

Understanding abstract classes


66

Must a superclass be abstract or concrete?

Must abstract classes contain at least one abstract method?

You're wrong, abstract classes must have an abstract method!

How can an abstract method be inherited?

Do I have to implement all abstract methods?

Abstract method design constraints

Can a static method be abstract?

Can you show some static calls to abstract classes?

Why can't abstract methods be declared static?

Why can't an abstract method be declared private?

We can have private abstract methods in some cases, can't we?

Abstract classes and methods

How can I call a concrete instance method on an abstract class?

Can you give an example of an abstract class?

Can I call a static method on an abstract class?

Can I declare a constructor for an abstract class?

Abstract class design and use

Q: When should I use abstract methods?


A: Abstract methods are usually declared
where two or more subclasses are expected
to fulfil a similar role in different ways. Often
the subclasses are required to the fulfil an
interface, so the abstract superclass might
provide several of the interface methods,
but leave the subclasses to implement their
own variations of the abstract methods.
Abstract classes can be thought of as partcomplete templates that make it easier to
write a series of subclasses.

67

For example, if you were developing an


application for working with different types
of

documents,

you

might

have

a Document interface that each document


must

fulfil.

You

might

then

anAbstractDocument that

create
provides

concrete openFile() and closeFile() methods,


but

declares

an

abstract displayDocument(JPanel) method.


Then
separate LetterDocument,StatementDocum
ent or InvoiceDocument types
have

to

implement

their

would
own

only

version

of displayDocument(JPanel) to

fulfil

the Document interface.

Q: Why use an abstract class instead of an interface?


A: The main reason to use an abstract
class rather than an interface is because
abstract classes can carry a functional
payload that numerous subclasses can
inherit and use directly. Interfaces can
define the same abstract methods as an
abstract

class

but

cannot

include

any

concrete methods.
In a real program it is not a question of
whether abstract classes or interfaces are
better, because both have features that are
useful. It is common to use a mixture of
interface and abstract classes to create a
flexible and efficient class hierarchy that
introduces concrete methods in layers. In
practical terms it is more a question of the
appropriate point in the hierarchy to define

68

empty

abstract

methods

and

methods,

combine

concrete

them

through

the extends and implementskeywords.


The example below compares a Spectrum
type

defined

by

an

interface

and

an

abstract class and shows how the abstract


class can provide protected methods that
minimise the implementation requirements
in its subclasses.
full answer hidden, click here for all
answers
Premium members click below for full answer
Why use an abstract class instead of an interface?

Q: Why do we need abstract classes with no abstract methods?


A: An abstract class without any abstract
methods should be a rare thing and you
should always question your application
design if this case arises. Normally you
should refactor to use a concrete superclass
in this scenario.
One specific case where abstract class may
justifiably have no abstract methods is
where it partially implements an interface,
with the intention that its subclasses must
complete the interface. To take a slightly
contrived motoring analogy, a Chassis class
may partially implement a Vehicle interface
and provide a set of core methods from
which a range of concrete Vehicletypes are
extended. Chassis is

not

viable

implementation of a Vehicle in its own right,


so a concrete Car subclass would have to

69

implement interface methods for functional


wheels, engine and bodywork.

Q: What's the use of concrete methods in abstract classes?


A: One of the design principles of Java
inheritance is to create superclass methods
that

can

be

used

by

one

or

more

subclasses, this avoids duplication of code


and makes it easier to amend. The same
principle holds with abstract classes that
are fulfilled by numerous subclasses.
One useful technique with abstract classes
is that a concrete method may be defined in
anticipation

of

abstract

methods

being

fulfilled in its subclasses. In the example


below

theAbstractShape class

has

concrete printArea() method that calls the


abstract getArea()method.

Subclasses

inherit

and

the printArea() method

must

implement the getArea() method to stand


as concrete classes.
full answer hidden, click here for all
answers
Premium members click below for full answer
What's the use of concrete methods in abstract
classes?

Q: How many abstract subclasses can I create?

A: Inheritance is fundamental to the Java


programming language and it is vital that
any class should be able to extend another,
no matter how many superclasses it has.
Abstract classes should be no different, so
long as the subclass is abstract too you can

70

have very extended hierarchies of abstract


classes. Though it is possible to have many
levels of inheritance, you should question
your application design if you have more
than 2 or 3 successive abstract classes
without a concrete implementation.

Understanding abstract classes

Q: Must a superclass be abstract or concrete?


A: A superclass may be abstract or
concrete, provided the concrete class is not
declared final. In both cases, you can add
supplementary methods to those inherited
from the superclass. To extend abstract
classes

you

must

fulfil

any abstract methods that are declared by


the superclass.

Q: Must abstract classes contain at least one abstract method?


A: No, abstract classes are not required to
have any abstract methods, they can simply
be marked abstract for general design
reasons. An abstract class may contain a
full set of functional, integrated methods
but have no practical use in its basic form,
for example. In other words, they may
require extension with additional methods
to fulfil a range of different purposes. If the
purpose is not specified by abstract method
signatures,

the

range

of

potential

applications for subclasses can be very


broad.

71

Q: You're wrong, abstract classes must have an abstract method!


A: The answer given is definitely correct. It
is not common, but an abstract class may
have nomethods at all and still compile
successfully, such as the example below.

public abstract class AbstractNoMethods {

// Empty
}

Q: How can an abstract method be inherited?


A: A subclass inherits all non-private fields
and methods of its superclass whether the
methods are abstract or have concrete
implementations. If a subclass does not
implement

an

abstract

method,

the

subclass must be declared abstract itself.


That means that an abstract method can be
inherited
classes

through
without

numerous

abstract

any

concrete

implementation.
A common use of abstract methods is the
template

design

pattern,

where

the

common behaviour of a class hierarchy is


defined in a set of concrete methods in an
abstract superclass. Those core methods
include calls to abstract template methods
which must be implemented in concrete
subclasses. This makes it relatively easy to

72

implement subclasses and produce typespecific behaviour in each.

Q: Do I have to implement all abstract methods?

A: Yes, it is possible to extend an abstract

class without implementing its abstract


methods, but in this case the subclass must
also be declared abstract. If the subclass is
not declared abstract, the compiler will
throw an error. So ultimately it is necessary
for any concrete subclass to implement the
abstract methods.

Abstract method design constraints

Q: Can a static method be abstract?


A: The abstract keyword cannot be applied
to static method declarations. The compiler
will reject the class with the error "illegal
combination of modifiers". However, an
abstract class can have static variables and
methods, which can be accessed directly
using

the

standard

dot

notation,

e.g. AbstractExample.staticMethod().
follows

that

static

methods

must

It
be

concrete.

Q: Can you show some static calls to abstract classes?


A: Yes, the examples below show how a
static field and a static method in an
abstract superclass are called in a concrete
subclass

using

the

dot

notation.

The

subclass inherits the NULL_KEY field so the

73

dot notation is not strictly necessary for this


public field reference but shows the syntax
that should be used in unrelated classes.
full answer hidden, click here for all
answers
Premium members click below for full answer
Can you show some static calls to abstract classes?

Q: Why can't abstract methods be declared static?


A: The rule against static abstract
methods is fundamentally a Java language
design decision, which is not explained in
the

Java

Language

Specification.

The

abstract inheritance and implementation


scheme

is

structured

concerned
collaboration

with

forming

of classes with

deferred implementation of its abstract


instance methods. This scheme can be
verified at compile time to ensure it is safe
at runtime.
Static methods must be concrete because
they are attached to a specific host class
and must be available to execute in a static
context, when no object instance exists. It is
not possible to assign an implementation to
a static method at runtime, there is no
mechanism to do that in Java.
It is also worth noting that static methods
cannot be overridden by a subclass in Java.
Static methods with the same signature
effectively hide the superclass method. The
concept of implementing a static method in
a subclass would fail for the same reason,

74

the

concrete

implementation

would

be

attached to the wrong host.

Q: Why can't an abstract method be declared private?


A: The private and abstract method
modifiers do not make sense in combination
and the compiler should normally fail with a
warning in this case. An abstract method
must be overridden by any subclass, but
subclasses do not have access to their
superclass'

private

fields,

so

private

abstract method could never be fulfilled.

Q: We can have private abstract methods in some cases, can't we?

A: If you attempt to compile a class with


a private abstract method it will fail with the

message illegal combination of modifiers:


abstract and private. An abstract method
must be declared with implicit package
visibility

or

with

the protected or public keywords.

The

fundamental principle is that an abstract


method must be visible to any potential
subclass. If an abstract method was private
it would not be visible to any subclass and
could not be implemented.
The

concrete

implementation

of

the

abstract method in a subclasses must have


the same level of visibility or greater. If an
abstract method has package visibility, its
subclass implementations must have the
same, protected or public visibility.
abstract

method

If

an

has protectedvisibility,

concrete implementations must have the

75

same

or public visibility.

If

an

abstract

method has public visibility the

concrete

versions must also be public.

Abstract classes and methods

Q: How can I call a concrete instance method on an abstract class?


A: It is only possible to call a concrete
method of an abstract class when the
method is instantiated through a concrete
subclass. The method must also have a
public or package visibility modifier that
makes it accessible to the calling class.
When you call the method on the subclass,
it

implicitly

invokes

superclass

implementation, as in the example below.


full answer hidden, click here for all
answers
Premium members click below for full answer
How can I call a concrete instance method on an
abstract class?

Q: Can you give an example of an abstract class?


A: Yes, this example of an abstract class
hierarchy

has

superclass AbstractShape that

includes

concrete moveTo(int, int) method that will


be

inherited

includes

by

any

subclass.

an

getArea() method

It

also

abstract double
that

must

be

implemented by any concrete subclass. The


implementation of the getArea() method is

76

different

in

the Circle and Square subclasses.


full answer hidden, click here for all
answers
Premium members click below for full answer
Can you give an example of an abstract class?

Q: Can I call a static method on an abstract class?


A: In Java it is possible to execute the
static methods of abstract classes, since an
object instance is not required in this
context.

public abstract class AbstractStaticMethod {

public static void doSomething() {

System.out.println("Static method
called.");
}

public static void main(String[] args) {

doSomething();
}
}

Since

abstract

classes

cannot

be

instantiated in their own right, no instance

77

methods can be called except through their


subclasses.

Q: Can I declare a constructor for an abstract class?


A: This may sound odd, but an abstract
class may have constructors, but they
cannot be used to instantiate the abstract
class. If you write statements to call the
constructor the compiler will fail and report
the

class

is

"abstract;

cannot

be

instantiated".

public abstract class AbstractConstructor {

public AbstractConstructor() {

// Statements
}

public AbstractConstructor(final int size)


{

// Statements
}

public static void main(String[] args) {

// Not permitted
// AbstractConstructor instance1 = new
AbstractConstructor();

78

// Not permitted either


// AbstractConstructor instance2 = new
AbstractConstructor(4);
}
}

Constructors
designed

in

only

abstract
to

be

classes

used

by

are
their

subclasses using a super()call in their own


constructors. Though the abstract class
cannot stand as an instance in its own right,
when its abstract methods are fulfilled by a
subclass, its constructors can be called
upon

to

deliver

stock

template-like

initialisation behaviour, for example.

public
class
ConcreteSubclassSuperconstructor extends
AbstractConstructor {

private static final int INDEX = 4;

public
ConcreteSubclassSuperconstructor() {

super(INDEX);
}
}

79

Concurrent programming features

Can a class have more than one thread?

What is threaded programming and when is it used?

What is a thread?

How do Java threads make the environment asynchronous?

Threads and runnable types

What's the difference between Thread and Runnable types?

What is a Runnable object and a Runnable argument?

How does the run() method in Runnable work?

A Thread is runnable, how does that work?

Do Thread and Runnable types have their own run() methods?

Why not override Thread to make a Runnable?

When could I adapt the Thread class though?

The start() method

What's the difference between a thread's start() and run() methods?

Can I implement my own start() method?

Thread management methods

Which class is the wait() method defined in?

Which class is the sleep(long) method defined in?

Why are wait(), notify() and notifyAll() methods defined in the Object class?

Why are there separate wait() and sleep() methods?

Multi-threaded design questions

If all methods are synchronized, is a class thread safe?

Do I need to use synchronized on setValue(int)?

How do I create a Runnable with inheritance?

What is the volatile modifier for?

What is the SwingUtilities.invokeLater(Runnable) method for?

Which has priority with a static synchronized thread?

Multi-threaded design patterns


80

What is a working thread?

Thread programming jargon

What is a green thread?

What are native operating system threads?

Thread programming problems

I get incompatible return type for my thread's getState() method!

Apache Log4J has thrown a ThreadDeath error!

Concurrent programming features

Q: Can a class have more than one thread?


A: Any Java class may be loaded and
instantiated as part of a multi-threaded
program. Since Java is fundamentally a
multi-threaded programming language all
classes

should

possibility
whether

in
it

be

designed

mind,
is

with

likely

with

this

judgement

and

what

its

consequences would be.


You

should

normally

have

enough

information to judge whether your own


classes are likely to be used in a multithreaded

context.

immediate

If

there

requirement,

is

avoid

the

no

thread-

proofing your class until that time comes.


The

Java

API

programming

is

used

purposes

for

that

general

cannot

be

anticipated in advance, so thread safety


considerations are usually noted in classes'
API documentation. Many data storage and
management

classes

in

81

the java.util package are distinguished by


their thread safety status because safety is
usually

trade-off

against

the

time-

performance of key operations.

Q: What is threaded programming and when is it used?


A: Threaded programming is normally
used when a program is required to do more
than one task at the same time. Threading
is often used in applications with graphical
user interfaces; a new thread may be
created to do some processor-intensive
work while the main thread keeps the
interface responsive to human interaction.
The

Java

programming

language

has

threaded programming facilities built in, so


it is relatively easy to create threaded
programs.

However,

multi-threaded

programs introduce a degree of complexity


that

is

not

justified

for

most

simple

command line applications.

Q: What is a thread?
A: In Java the Thread class

represents a

single independent path of execution in a


Java Virtual Machine. When you run a Java
program it implicitly starts a single thread of
execution.

The Threadclass

enables

programmers to create additional threads


and set them running. A number of threads
may run in parallel, but only one is actively
executed at a given moment.
The

Java

runtime

system

uses

fairly

complex thread scheduling mechanisms to

82

coordinate the execution of threads, but this


does not require privileged knowledge or
detail level intervention by programmers.
Programmers can manage the high level
creation, initiation and distribution of tasks
amongst threads through simple Application
Programming Interface (API) methods.
The example below shows the simplest
approach
execution;

to

thread

construct

creation
a

and

task

new Thread with

a Runnable argument and start it.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
What is a thread?

Q: How do Java threads make the environment asynchronous?


A: The thread mechanism in Java begins
with

the

main

entry

point

thread

the

runtime environment creates to start a Java


program. When you use that initial thread
create secondary threads, each one runs
independently of the other. The Java virtual
machine manages the execution of the
threads so they behave as if they all run at
the same time, in fact each thread briefly
takes turns at execution.
In its simplest form there may be no
communication or synchronization between
multiple threads in a Java program and they
each run to completion independently of
each other. In this respect Java threads are
fundamentally asynchronous, there is no

83

master clock that governs when threads will


run and when they synchronize variables to
catch-up with each other.
It is often necessary and more useful if
threads do check

ready

states

before

progressing, synchronize read and write


access to shared variables and call-back to
each other when their work is done. This is
where the synchronized keyword and the
various sleep(), wait() andnotify() methods
are used to more closely schedule the
interaction between asynchronous threads.

Threads and runnable types

Q: What's the difference between Thread and Runnable types?


A: A Java Thread controls the main path of
execution in an application. When you
invoke

the

Java

Virtual

Machine

with

the java command, it creates an implicit


thread

in

which

themain() method.

to

execute

The Thread class

provides a mechanism for the first thread to


start-up other threads to run in parallel with
it.
The Runnable interface defines a type of
class that can be run by a thread. The only
method it requires is run(), which makes the
interface very easy to fulfil by extending
existing classes. A runnable class may have
custom constructors and any number of

84

other

methods

for

configuration

and

manipulation.

Q: What is a Runnable object and a Runnable argument?


A: A Runnable object is one that
implements the Runnable interface, which is
the type used to execute new threads.
The Runnable interface

only

has

one

method, run(), which must be implemented


by a Runnable class.
In Java an argument is a primitive value or
object

reference

constructor
method

or

that

is

method,

signature.

passed
defined

to
in

a
the

A Runnable argument

would be a constructor or method argument


that is declared to be a Runnable type. The
constructor of the Thread class is the most
obvious example.
public Thread(Runnable target);

This constructor requires a Runnable type


argument to be passed when a Thread is
instantiated.

Q: How does the run() method in Runnable work?


A: It may help to think of the run method
like the main method in standard single
threaded applications. The run method is a
standard entry point to run or execute a
class.

The run method

executed

in

the

independent Thread,

is

normally

context
but

is

of
a

only
an

normal

method in all other respects.

85

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
How does the run() method in Runnable work?

Q: A Thread is runnable, how does that work?


A: The Thread class' run() method
normally

invokes

the Runnable type


constructor.

the run() method


it

is

However,

it

passed
is

in

of
its

possible

to

override the thread's run method with your


own.
It

is

more

common

to

implement

the Runnable interface in a separate class


and

pass

it

to

standard Thread constructor. This approach


usually requires less coding and allows
yourRunnable class

to

inherit

application-specific

behaviour

useful
from

separate class hierarchy.

Q: Do Thread and Runnable types have their own run() methods?

A: The Runnable interface

defines

an

abstract run() method and the Thread class


implements the interface, so has its own
concrete run() method.

However

the Thread class implementation ofrun() is


different from most others because of its
special use in the creation of new threads.
In a typical Runnable class the run() method
contains code that does the main work of a
thread. It may complete one long-running
process or set up a loop that repeats a
series

of

actions,

for

example.

86

The Thread run() method has no worker


code of its own, it just calls the run()method
of the Runnable object that was passed to
its constructor.
To instantiate a Thread object you normally
pass a Runnable class to the constructor as
the target of the thread. When you call
the Thread's start() method it creates a new
thread whose first and only action is the to
call Thread class'

own run() method

once.

The Thread class run()calls


the run() method on the target Runnable,
which does the work of the thread.

Q: Why not override Thread to make a Runnable?

A: There

is little difference in the work

required

to

override

compared

with

the Runnable interface,


body

the Thread class

of

implementing
both

require

the run() method

the

to

be

implemented. However, it is much simpler


to

make

an

existing

class

hierarchy

runnable because any class can be adapted


to implement the run() method. A subclass
of Thread cannot extend any other type, so
application-specific code would have to be
added to it rather than inherited.
Separating

the Thread class

the Runnable implementation

also

from
avoids

potential synchronization problems between


the

thread

and

the run() method.

separate Runnablegenerally gives greater


flexibility in the way that runnable code is
referenced and executed.

87

A: It

Q: When could I adapt the Thread class though?


is

always

a Runnable type

best
rather

to

implement

than

extend

a Thread. On that basis, the extension of


the Thread class should only be considered
in

exceptional

circumstances

when

the

application is very simple, composed of few


classes, where the interaction of threads is
minimal and requires only minimal control
over thread execution.

The start() method

Q: What's the difference between a thread's start() and run() methods?


A: The separate start() and run() methods
in the Thread class provide two ways to
create

threaded

programs.

The start() method starts the execution of


the new thread and calls therun() method.
The start() method returns immediately and
the new thread normally continues until
the run() method returns.
The Thread class' run() method

calls

the run() method of the Runnable type class


passed

to

its

constructor.

Subclasses

of Thread should override the run() method


with their own code to execute in the
second thread.
Depending on the nature of your threaded
program,

calling

the Thread run() method

directly can give the same output as calling


via the start() method. Howevever, the code

88

will only be executed in a new thread if


the start() method is used.

Q: Can I implement my own start() method?


A: The Thread start() method is not
marked final, but should not be overridden.
This method contains the code that creates
a

new

executable

specialised.

Your

thread

and

threaded

is very

application

should either pass a Runnable type to a


new Thread, or extend Thread and override
the run() method.

Thread management methods

Q: Which class is the wait() method defined in?


A: The wait() method is defined in
the Object class,

which

is

the

ultimate

superclass of all others. So the Thread class


and

any Runnable implementation

inherit

this method from Object.


The wait() method is normally called on an
object in a multi-threaded program to allow
other threads to run. The method should
only

be

called

by

thread

that

has

ownership of the object's monitor, which


usually

means

it

is

in

a synchronized method or statement block.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Which class is the wait() method defined in?

89

Q: Which class is the sleep(long) method defined in?


A: The sleep(long) method is defined as a
static method of the Thread class for two
reasons. First, it is responsible for delaying
the execution of threads rather than any
other objects, soThread is the logical host
for

the

method.

Secondly,

it

is

static

because it suspends the currently executing


thread, which is implicitly the thread that
called the method. The programmer does
not need to know which other threads are
alive.
The sleep(long) method

retains

the

synchronization locks of the current thread,


so it can have a significant effect on the
behaviour of multi-threaded applications. If
the exact period of the delay you require is
not important, it may be better to use
the wait(long) method.

Q: Why

are wait(), notify() and notifyAll() methods

defined

in

the Object class?

A: The

purpose

of

the wait(), notify() and notifyAll() methods is


to

temporarily

pause

and

resume

the

execution of code in an object. Typically the


host object is not in a state where it can
proceed with a method call it has been
given and the thread of execution must
literally wait for the object to return to a
ready state. A common example would be a
limited pool or store of objects where you
must wait for a storage slot to be released

90

or an object to be returned to the pool


before you can use it.
public synchronized Object getNextObject()
{
// Waiting loop
while (! objectAvailable()) {
try {
wait();
}
catch (InterruptedException e) {
// Handle exception
}
}
// No longer waiting, get the return object
Object returnObject;
// Assign the returnObject from store
// Notify state change for other waiters
notify();
return returnObject;
}

The

act

of

waiting

is

associated

with

the Object class because any subclass may


need to wait for a ready state to occur (Java
is

fundamentally

multi-threaded

language). The waiting process acts on a


single thread of execution, but the wait
mechanism expects that multiple threads
may

be

waiting

for

the

same

object.

The wait() and notify() methods are hosted


by the Object class so that the Java Virtual
Machine can manage the wait set of
threads through the objects they are waiting
for.

91

Q: Why are there separate wait() and sleep() methods?


A: The static Thread.sleep(long) method
maintains control of the thread execution
but delays the next action until the sleep
time expires. The wait() method gives up
control over thread execution indefinitely so
that other threads can run.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Why are there separate wait() and sleep() methods?

Multi-threaded design questions

Q: If all methods are synchronized, is a class thread safe?


A: Even if all the methods of a class are
synchronized, it may still be vulnerable to
thread safety problems if it exposes nonfinal fields or its methods return mutable
object references that could be manipulated
by multiple threads. Non-final fields should
be declared private and encapsulated with
synchronization.

Rather

than

return

references to internal object fields, create


an independent copy that has no relation to
the original, known as a deep copy.
A deep copy of an object duplicates the
content and state of the original object and
all its constituent fields in such a way that
none of its properties refer to instances in
the original at any level.

92

These

measures

will

help

prevent

uncontrolled access to the internal state of


objects,

but

you

must

also

ensure

synchronization techniques are applied in a


robust, consistent manner that will not
cause deadlock or race conditions. It is
generally better to use synchronized blocks
than synchronized methods for performance
reasons. Limit the extent of synchronized
blocks and ensure they all use the same
object monitor.

Q: Do I need to use synchronized on setValue(int)?


A: It depends whether the method affects
method

local

variables,

class

static

or

instance variables. If only method local


variables are changed, the value is said to
be confined by the method and is not
prone to threading issues.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
Do I need to use synchronized on setValue(int)?

Q: How do I create a Runnable with inheritance?


A: To introduce a Runnable type to an
existing class hierarchy, you need to create
a

sub-class

that

declares

that

it implements the Runnable interface,

and

provide

This

a run() method

to

do

so.

combination of interface and inheritance


means that runnable implementations can
be

very

minor

extensions

of

existing

classes, as in the example below.

93

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
How do I create a Runnable with inheritance?

Q: What is the volatile modifier for?


A: The Java language specification allows
the runtime system to keep a local copy of a
variable in each thread that refers to it.
These thread-local copies of a variable act
like a cache to improve the performance of
multi-threaded programs, they avoid having
to check the true master value of the
variable every time it is needed.
One consequence of this thread cache
behaviour

is

that

at

the

moment

of

execution the value of thread-local variables


may be different from the true master value
of the variable. For variables whose value
does not change frequently and would not
critically affect the behaviour of a program,
thread-local cached values are a tolerable
compromise of precision for the sake of
better performance, if not they should be
controlled.
You can use synchronized blocks to ensure
the true master value of a variable is used,
but at the cost of excluding all other thread
access

to

those

code

blocks.

The volatile modifier ensures the integrity of


a variable value without the performance
impact of full synchronization, it means that
any thread that sets or gets the variable

94

must

use

the

The volatile modifier

true

master

value.

effectively

disables

thread-local caching of values for specific


variables.

Q: What is the SwingUtilities.invokeLater(Runnable) method for?

A: The

static

utility

method invokeLater(Runnable) is

intended

to execute a new runnable thread from a


Swing application without disturbing the
normal sequence of event dispatching from
the Graphical User Interface (GUI). The
method places the Runnable object in the
queue of Abstract Windowing Toolkit (AWT)
events that are due to be processed and
returns

immediately.

The

runnable

object's run() method is only called when it


reaches the front of the queue.
The

deferred

effect

of

the invokeLater(Runnable) method ensures


that any necessary updates to the user
interface can occur immediately, and the
runnable work will begin as soon as those
high priority events are dealt with. The
invoke later method might be used to start
work in response to a button click that also
requires a significant change to the user
interface,
activities,

perhaps
before

to
the

restrict

other

runnable

thread

executes.

Q: Which has priority with a static synchronized thread?

A: A synchronized method

uses what is

called an intrinsic lock to control thread

95

execution, an object reference that is used


as a monitor for the lock. Synchronized
instance methods implicitly use their own
object instance as the monitor. Only one
thread can hold the monitor object at a
given

moment

and

execute

the

may

be

synchronized code.
Static synchronized methods

executed when there is no instance of the


class to serve as a lock monitor, so must
use a different lock object. When class
methods are invoked the Java runtime
system automatically creates an object of
the

type Class as

the

context

for

the

method to be executed. If the class method


happens

to

be synchronized,

this Class instance is the intrinsic lock used


as the monitor object for synchronization.
Since

synchronized

instance

and

class

methods have different monitor objects,


there is no effective synchronization control
between them and no guarantee to their
sequence of execution. If a closer level of
control is required, it may be necessary to
remove the synchronized modifier from the
instance

method

and

create

a synchronized block inside the method that


uses theClass instance as its monitor, as in
the example below.

full

answer

hidden, click

for

complete answers

96

Premium members click below for full answer


Which has priority with a static synchronized
thread?

Multi-threaded design patterns

Q: What is a working thread?


A: A working thread, more

commonly

known as a worker thread, is the key part of


a design pattern that allocates one thread
to execute one task. When the task is
complete, the thread may return to a thread
pool for later use. In this scheme a thread
may execute arbitrary tasks, which are
passed in the form of a Runnable method
argument, typically execute(Runnable). The
runnable tasks are usually stored in a queue
until a thread host is available to run them.
The worker thread design pattern is usually
used to handle many concurrent tasks
where it is not important which finishes first
and no single task needs to be coordinated
with another. The task queue controls how
many threads run concurrently to improve
the overall performance of the system.
However,

worker

thread

framework

requires relatively complex programming to


set up, so should not be used where simpler
threading techniques can achieve similar
results.

97

Thread programming jargon

Q: What is a green thread?


A: A green thread refers

to a mode of

operation for the Java Virtual Machine (JVM)


in which all code is executed in a single
operating system thread. If a Java program
has

any

concurrent

manages
internally

threads,

multi-threading
rather

than

the

JVM

behaviour

use

additional

operating system threads.


There is a significant processing overhead
for the JVM to keep track of thread states
and swap between them, so green thread
mode has been deprecated and removed
from more recent Java implementations.
Current JVM implementations make more
efficient use of native operating system
threads. These days there is no case where
the green thread approach is useful except
on

systems

where

this

is

the

only

concurrency scheme that is available for


Java,

on

old

operating

systems

and

hardware platforms.

Q: What are native operating system threads?


A: Native operating system threads are
those provided by the computer operating
system that plays host to a Java application,
be it Windows, Mac or GNU/Linux. Operating
system threads enable computers to run
many programs simultaneously on the same

98

Central

Processing

Unit

(CPU)

without

clashing over the use of system resources


or

spending

program

at

lots

of

time

the

expense

running
of

one

another.

Operating system thread management is


usually optimised to specific microprocessor
architecture and features so that it operates
much

faster

than

Java

green

thread

processing.

Thread programming problems

Q: I get incompatible return type for my thread's getState() method!


A: It sounds like your application was built
for a Java Software Development Kit (SDK)
before

Java

Programming

1.5.

The

Interface

method getState() was

Java

Application

(API) Thread class


introduced

in

version 1.5. Your thread method has the


same name but different return type. The
compiler assumes your application code is
attempting to override the API method with
a different return type, which is not allowed,
hence the compilation error.
You have two main options; compile your
program with a Java SDK before version 1.5,
or rename your method and adapt any
client classes to the new name.

Q: Apache Log4J has thrown a ThreadDeath error!


A: The java.lang.ThreadDeath type signals
a serious Error in the execution of a Java
program and should not normally be caught

99

by applications, it should be left to escalate


and

terminate

the

application. ThreadDeath is
a Throwable type, so the Apache logging
package may blindly catchThrowable rather
than

an Exception,

which

is

not

recommended. More likely ThreadDeath is


caught so that other asynchronous threads
may be

cleaned

up

before

logging

is

terminated.
Since this ThreadDeath instance is wrapped
in the commons LogConfigurationException,
the root cause of the problem is most likely
that a suitable LogFactory or Log instance
cannot be created by the corresponding
factory methods. In other words, your
logging configuration declares a type that
cannot be instantiated, possibly because of
bad spelling, ultimately because the named
class

is

not

available

to

the

relevant

classloader.

The static main method

How can I write a program that takes command line input?

Why is the main method declared public static void?

What does public static void main(String[]) mean?

In which class is the main() method declared?

Why do we only use the main() method to start a program?

Why don't all classes need a main() method?

Overloading the main method

Can the main() method be overloaded?

Can you give an example of overloading the main()?

How can the JVM identify the main() method when its overloaded?

100

Main method arguments

What do the arguments in the main() method mean?

Which is the right syntax for the main() method?

Can I name the main() argument argf?

Why does the main() method take a String array argument?

Why are command line arguments passed as a String?

Why doesn't the main() method throw an error with no arguments?

How can I print the main method arguments in reverse order?

Main method modifiers

Can the main() method be declared final?

I get an exception if I remove the static modifier from main()!

What happens when I remove the static modifier from main()?

Calling the main() method

Can I call the main() method with a String argument?

How many arguments can be passed on the command line?

When I pass *.java as an argument I get a list of all my source files!

How can I make an interactive command line interface?

Application start up

How can the static main method use instance variables?

Can I invoke the main method from another class?

The static main method

Q: How can I write a program that takes command line input?


A: Java programs that take input from the
command

line

declare

method

calledmain,

special
which

static
takes

a String array as an argument and returns


void. The example program below loops
through

any

arguments

passed

to

the

program on the command line and lists their


values.

101

full answer hidden, click for full


answers
Premium members click below for full answer
How can I write a program that takes command line
input?

Q: Why is the main method declared public static void?


A: The main method is declared public so
that it is accessible as part of the public
interface

of

the

program.

It

is static because it must be called before


the

class

instantiated.

that
It

hosts

the

method

returns void because

is
the

Java interpreter does not expect to receive


or process any output from the class; any
output intended for end users will normally
be sent to the system output and error
streams, or via a graphical user interface or
supplementary logging systems.

Q: What does public static void main(String[]) mean?


A: This is a special static method
signature that is used to run Java programs
from a command line interface (CLI). There
is nothing special about the method itself, it
is a standard Java method, but the Java
interpreter is designed to call this method
when a class reference is given on the
command line, as below.
full answer hidden, click for full
answers
Premium members click below for full answer
What does public static void main(String[]) mean?

102

Q: In which class is the main() method declared?


A: The static void main(String[]) method
can be declared in any Java class to create a
running Java application. Where you choose
to place the main method will depend on
the nature and structure of your application.
It is possible for numerous classes to have
their own main entry point methods, but
only one entry point can be used to start
the program. An application will typically
have a top level application class, an
"Editor", "Viewer", "Server" or "Monitor"
type that will be used to start and run the
program, for example.

Q: Why do we only use the main() method to start a program?

A: The entry point method main() is used


to the provide a standard convention for
starting Java programs. The choice of the
method name is somewhat arbitrary, but is
partly

designed

to

avoid

clashes

with

the Thread start() and Runnable run() meth


ods, for example.

Q: Why don't all classes need a main() method?

A: Java

classes do not necessarily need

a main() method because not all classes are


used as the entry point to start a Java
program, or the execution of the code is
activated through a higher level service, like
a servlet container. Java class code is
usually executed in the context of a larger
Java application composed of lots of classes

103

that interact together to provide the overall


functionality of the system. It is rare that a
single class would comprise a stand-alone
application, but of course this can be the
case with small utilities, test programs and
experimental work.
The main() method is used to start a Java
program, so is only necessary where the
host class serves that purpose in a Java
application.
include

Java

developers

a main() method

sometimes

to

run

simple

configuration or diagnostic tests on a class,


where you might feed in arbitrary input
parameters.

Overloading the main method

Q: Can the main() method be overloaded?


A: Yes, any Java method can be
overloaded

including

the main() method.

The Java interpreter will only invoke the


standard

entry

the main() method,

point
with

signature
a

string

for
array

argument, but your application can call its


own main() method as required.

Q: Can you give an example of overloading the main()?


A: To overload the main() method you
would

have

the

modifier, staticmethod

same public visibility


type, void return

type and main method name but the type


or number of arguments must vary.

104

Overloaded methods can provide versatility


in a class and group similar behaviour with
a common name. You may want to chain the
standard main() method with an overloaded
version that takes a conditional variable,
key value or reference to signal further
processing. This approach breaks down the
program

logic

and

overloaded main() method

indicates
is

the

associated

with the standard version. The example


below

passes

the

original String[] arguments

to

an

overloadedmain(String[], int) method where


the int argument is a key value for further
processing.
full answer hidden, click for full
answers
Premium members click below for full answer
Can you give an example of overloading the main()?

Q: How can the JVM identify the main() method when its overloaded?
A: An overloaded main() method must
have

different

number

and

type

of

arguments from the standard entry point


method, otherwise it would be identical and
the

class

would

not

compile.

The

standard public static void main() method


has

single

argument

which

is

of

type Stringarray, written String[].


public static void main(String[] args) {}

The main() method

below

is

overloaded

because it has the same method name and

105

return

type

but

two

arguments.

The

first String[] argument is the same as the


standard main() entry point method, but
the second int argument makes it different.
public static void main(String[] args, int
index) {}

The final example below has the same


method name and return type with one
argument, like the standard main() method.
In this case the type of the argument
is String rather than String[]which makes it
different.
public static void main(String arg) {}

Main method arguments

Q: What do the arguments in the main() method mean?


A: You can think of the arguments in the
main method as a special set of variables
that are fed into the program at start-up.
The main arguments can be used to pass
runtime

configuration

values

for

the

program, such as the path to a properties


file, or input values for the program to
process. The arguments may also serve as
commands to the application that invoke
different operations.

Q: Which is the right syntax for the main() method?


106

A: The

way the Java compiler interprets

the syntax for the main method is evidently


quite

loose.

The

main

method

takes

a String array as an argument, which is


written

as String[].

The

name

of

the

argument is usually given as args, so the


proper method declaration is:

public static void main(String[] args)

However, you will often see this method


written with the square brackets next to the
argument name main(String args[]) and this
is

also

accepted

by

the

compiler.

And main(String []args) is also accepted by


the Sun Java compiler, which has been
written to be fault tolerant.

Q: Can I name the main() argument argf?


A: Yes, the variable name you give to
the String[] parameter in the public static
main()method is up to you, the class will
compile and run provided it is a valid Java
variable name. You must be careful to
reference the variable correctly throughout
the method though. Unless you have good
reason to change, it is worth sticking to
convention and name the parameter args to
avoid confusion for yourself, and other
people who may read your code.

Q: Why does the main() method take a String array argument?


107

A: The static

main() method

takes

a String array as an argument to provide a


best match with the way that command line
arguments are fed into a Java program. A
Java program may be started with no
command line arguments, in which case
the String array is zero length, or it may
have one or more arguments. The Java
runtime

system

passes

an

array

that

matches the number of command line


arguments that are given, so there is a
direct correspondence between the program
input and the data received by the main
method.
Each storage slot in the String array passed
to

the main() method

contains

the String value of the relevant command


line argument, indexed from zero. The
example

program

below

repeats

the

command line arguments in the order they


are given.
full answer hidden, click for full
answers
Premium members click below for full answer
Why does the main() method take a String array
argument?

Q: Why are command line arguments passed as a String?

A: Command line arguments are passed to


the

application's public

static

void

main()method by the Java runtime system


before

the

application

class

or

any

supporting objects are instantiated. It would

108

be much more complex to define and


construct arbitrary object types to pass to
the main() method, and primitive values
alone are not versatile enough to provide
the range of input data that strings can.
String

arguments

can

be

parsed

for

primitive values and can also be used for


arbitrary text input, file and URL references.

Q: Why

doesn't the main() method throw an error with no

arguments?

A: When

you

invoke

the

Java

Virtual

Machine on a class without any arguments,


the

class' main()method

receives

a String array of zero length. Thus, the


method signature is fulfilled. Provided the
main method does not make any reference
to elements in the array, or checks the
array length before doing so, no exception
will occur.

Q: How

can I print the main method arguments in reverse

order?

A: Command line arguments are passed to


the main method as a string array, each
argument is an item in the array. To print
the submitted arguments in reverse order,
use a for loop but start from the highest
index and decrement the index value, as
below.
full answer hidden, click for full
answers

109

Premium members click below for full answer


How can I print the main method arguments in
reverse order?

Main method modifiers

Q: Can the main() method be declared final?


A: Yes,
the static
void
main(String[]) method

can

be

declared

final.

Q: I get an exception if I remove the static modifier from main()!


A: The static void main(String[]) method is
a basic convention of the Java programming
language that provides an entry point into
the

runtime

system.

The main() method

must be declared static because no objects


exist when you first invoke the Java Virtual
Machine (JVM), so there are no references to
instance methods. The JVM creates the
initial runtime environment in which this
static method can be called, if you remove
the static modifier,

it

will

throw

aNoSuchMethodError.

Q: What happens when I remove the static modifier from main()?


A: If you remove the static modifier from
the

standard main() method

it

becomes

an instancemethod. If you then try to


execute class the Java runtime system will
fail and report:

110

Exception
in
thread
"main"
java.lang.NoSuchMethodError: main.

If

you

restore

the static modifier

and

change the return type to int, for example,


you get the same error. The runtime system
expects

a static main() method

with

the void return type, if you change either of


these properties you may create a valid
method but it will not be executed by
the java command.

Calling the main() method

Q: Can I call the main() method with a String argument?


A: It is possible to change the name of
the

argument

in

the public

static

void

main(String[]) method, but the argument


type must be a String array. If you declare
a Stringargument,

it

will

make

valid

method, but it cannot not be used as the


standard entry point for your program, the
Java runtime system would report an error.

Q: How many arguments can be passed on the command line?


A: The number of arguments that may be
passed to a Java program will vary from one
interpreter to another and will also be
affected

by

the

operating

system's

command interpreter. In a simple test, 169


arguments were passed to the Sun Java
interpreter via a Windows batch script

111

before it reported "The input line is too


long". If your program requires a great
number of input parameters, it would be
better to pass a reference to a Java
properties file on the command line and
extract the input from that, as below.
full answer hidden, click for full
answers
Premium members click below for full answer
How many arguments can be passed on the
command line?

Q: When I pass *.java as an argument I get a list of all my source files!


A: The behaviour you are seeing is a
consequence of the way the system shell
interprets

the

asterisk

as

so

called

"wildcard" operator that represents a set of


files. This is intended as a convenience
because it is an easy way to pass a series of
file names as arguments to a program such
as the Java interpreter. Putting a partial file
path before the asterisk, or a file extension
after it makes the file listing more specific,
but

you

cannot

alter

the

fundamental

behaviour.
To

limit

argument

this

behaviour,

that

contains

enclose
an

asterisk

any
in

double quotes, to ensure it is not expanded


to a series of file names. An alternative is to
omit the asterisk in the command line and
write your program in such a way that the
asterisk is implicit and add it to the input
arguments where applicable.

112

Q: How can I make an interactive command line interface?


A: The key to creating an interactive
command line interface in Java is to set up a
continuous loop that reads the system input
one line at a time. The example below
captures

the

system

input

stream

in

an InputStreamReader and wraps that in


a BufferedReader to read the input lines. It
uses System.out to create a prompt and
watches for a "quit" message to exit the
loop.
full answer hidden, click for full
answers
Premium members click below for full answer
How can I make an interactive command line
interface?

Application start up

Q: How can the static main method use instance variables?


A: For very simple programs it is possible
to write a main method that only uses static
variables and methods. For more complex
systems, the main method is used to create
an instance of itself, or another primary
class, as the basis of the application. The
primary application object reference uses
instance methods to create and interact
with other objects, do the work and return
when the application terminates.

113

public class SimpleClass {

public void doSomething() {

// Instance method statements


}

public static main(final String[] args) {

SimpleClass
SimpleClass();

instance

new

instance.doSomething();
}
}

Q: Can I invoke the main method from another class?


A: Yes, the main method can be called
from a separate class. First you must
prepare the string array of arguments to
pass to the method, then call the method
through a static reference to the host class,
MaxFactors in the example below.

String[] arguments = new String[] {"123"};

114

MaxFactors.main(arguments);

The String class

Why is the String class declared final?

So the String class is final because its methods are complex?

How many objects are created for identical strings?

What's the use of the String constructor?

How should I use the String constructor?

String methods and operators

One case prints a Java code, another a literal string!

The == operator doesn't match strings correctly!

Is the + operator overloaded?

How can you say the + operator is not overloaded in Java!

How can I reverse the characters in a string?

String buffers and tokenizers

What is the difference between String and StringBuffer?

When should I use a StringBuffer instead of a String?

Why don't two StringBuffers match?

What's the difference in the memory allocation for StringBuffers?

How can I pad a StringBuffer?

What is a StringTokenizer for?

How can I get a person's initials from their full name?

Regular expressions

How can I check a string has no numbers?

The String class

Q: Why is the String class declared final?


115

A: The short answer is that any class may


be declared final if it is not considered
suitable for extension, particularly if it is a
highly

specialised

Application
class

is

class.

Programming
very

When

Interface

specialised,

its

an
(API)

internal

behaviour may be quite complex and pose


un-seen problems for anyone who would
create a subclass.
full answer hidden, click here for all
answers
Premium members click below for full answer
Why is the String class declared final?

Q: So the String class is final because its methods are complex?


A: Yes, it is partly because the String class
implementation

is

so

complex

that

overriding the class would very likely cause


problems. A subclass would have to take
account

of

lots

of

internal

code

that

maintains the integrity of the String data


representation,

such

as

the

representation,

locale-specific

Unicode
features,

upper and lower case schemes and byte


conversion.
A high level of complexity and compatibility
constraints are the most typical reasons you
would

mark any class final,

but

the

integrity of the String class is also critical to


many Java security mechanisms. A custom
class

that

could

stand

in

place

of

a String could be mis-used.

Q: How many objects are created for identical strings?


116

A: Two identical string literal assignments


would

create

two

separate

string references, but they would both


refer to the same string object. This is a
special optimisation case that is supported
by

the

fact

immutable

that
in

string
Java.

objects
Once

are
a

Java String object is created it cannot be


changed, so it is safe for any number of
identical string literal references to point to
a singleString object.
The Java compiler marks string literals in a
way that the Java Virtual Machine can
identify and add to its String Literal Pool, a
collection

of

references

to

Java

string

objects. If identical string literals are found


at runtime the String Literal Pool provides a
reference to the first instance of the string,
and no duplicate String object is created.
That means that two identical string literals
refer to the same Java object.
This optimisation does not apply to strings
declared with the new String() constructor,
as the examples below demonstrate.
full answer hidden, click here for all
answers
Premium members click below for full answer
How many objects are created for identical strings?

Q: What's the use of the String constructor?


A: The explicit String constructor has the
same result as using double quotes to
implicitly create a string reference, in both

117

cases the given string is assigned to the


reference
double

variable.
quoted

However,
string

passing

argument

a
to

the String constructor actually makes two


strings; the argument string is implicitly
created inline and then its contents are
copied to the new Stringinstance. For this
reason this constructor is largely redundant
and

not

recommended

purposes.

for

general

The String constructor

with String argument is rarely used except


to

create

an

independent

copy

of

an

existing string variable.


// Creates one string implicitly
String s = "This is a test string";
// Creates two string instances
String s = new String("This is a test string");

Q: How should I use the String constructor?

A: The String class

does

have

constructor but it should not be used unless


you have a very clear and definite purpose
for it. In most cases a new String should be
declared by enclosing the relevant text in
double quotes assigned to a String variable,
or passed directly into a method.
String
myString
creation.";

"Efficient

System.out.println("Anonymous
instance.");

String
string

118

There

are

number

of

specialist String constructors that can be


used to create strings from character and
byte
arrays, StringBuffer and StringBuilder refere
nces, see the Java API documentation for
full details.
public String(char[] value);
public String(char[] value, int offset, int
count);
public String(byte[] value);
public String(byte[] value, int offset, int
count);
public String(StringBuffer buffer);
public String(StringBuilder builder);

The int arguments above operate like a


substring method parameters, to select only
the characters from the offset index of the
array onwards by count characters.

String methods and operators

Q: One case prints a Java code, another a literal string!


A: Your sample code shows some
confusion between reference values and
literal strings. Whenever an object reference
is

passed

to

the System.out.println(Object) method,


itstoString() method is used to provide the
output.

119

a a1 = new a();
out.println("a");

In this case, the instantiation of the class a,


referenced by the variable a1 is legitimate,
but the second line completely disregards it
and

will

print

the

string

literal

"a".

Whenever you put characters in double


quote marks like this, the Java interpreter
will

treat

it

as

a String object,

not

reference to the class a or instance a1.


try {
...
}
catch(Exception e) {
out.println(e);
}

In the second case the reference to the


exception e will

be

printed

its toString()method.

The

by

calling
default

implementation of toString() inherited from


the Object class

will

output

coded

reference to the object in the Java Virtual


Machine. If the toString() method has been
overridden by the exception class, it may
provide

human

readable

diagnostic

information.

Q: The == operator doesn't match strings correctly!


A: Java strings are stored as an immutable
sequence of Unicode characters and the
class'equals() method

is

overridden

to

120

compare

that

character

content,

so

standard logical comparison operators will


not give the result one might expect. If you
use the simple comparison operator on two
string objects that represent the same
string,

it

will

return false.

Always

use

theequals(Object) method to compare the


contents of two strings, as below.
full answer hidden, click here for all
answers
Premium members click below for full answer
The == operator doesn't match strings correctly!

Q: Is the + operator overloaded?


A: Java does not have operator
overloading, but string concatenation is a
special case. When the +operator is applied
to a String, the two values are appended as
a new String. If you use the +operator with
a String and a primitive value, such as
an int or long, the Java interpreter implicitly
converts

the

primitive

value

string

representation and concatenates them.

Q: How can you say the + operator is not overloaded in Java!


A: The plus operator for Java strings is a
limited exceptional case that is practically
the same as operator overloading. Its a fine
distinction but using + to append object
contents is not a general case in Java, it
only applies to String objects. An equivalent
append operation may be meaningful and
useful for data storage types but does not

121

have a general application and is not


implemented in Java.
// Compiler error: "operator + cannot be
applied to java.util.Vector"
// Vector vector = new Vector() + new
Vector();

full answer hidden, click here for all


answers
Premium members click below for full answer
How can you say the + operator is not overloaded
in Java!

Q: How can I reverse the characters in a string?

A: This

example code gets a char array

from the input string and loops through it to


populate a second char array. The for loop
uses two variables, i is incremented and j is
decremented at each pass. The output array
could be used to create a new string or
output directly, as in this case.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I reverse the characters in a string?

String buffers and tokenizers

Q: What is the difference between String and StringBuffer?


A: The main difference is that in
Java Strings are immutable, which makes
them quite inefficient for concatenating
large

amounts

of

text,

especially

in

122

extensive

loops.

each Stringconcatenation

For

statement

the

Java runtime system must instantiate at


least one additional Stringobject and then
dispose

of

it. StringBuffer is

designed

exactly to overcome this problem, to build


string content in an editable internal buffer
without

generating

lots

of

additional

objects.StringBuffer has many convenience


methods to append all Java primitive types,
character arrays and objects, and to check
and manipulate characters in the buffer.

Q: When should I use a StringBuffer instead of a String?


A: In most cases you should use
a StringBuffer rather

than

string

concatenation. The character content of


Java String objects is immutable. Whenever
you concatenate two String instances you
actually create a third String object for the
result. This implicit String object creation
can slow down your program, increase the
number of objects in the runtime system
and the garbage collection required to
dispose of the temporary strings.
On a small scale, string concatenation is
unlikely to have a significant performance
impact, but if you are building strings in
a for or while loop, or over many statement
lines it is better to use aStringBuffer,
or StringBuilder in

single

threaded

applications.

Q: Why don't two StringBuffers match?


123

A: The String class

overrides the default

implementation

of

the equals(Object) method to compare the


string contents of each object. In this case
equivalent string contents are considered
equal.

The StringBuffer class

does not override

the

superclass Object equals(Object)method,


which tests whether the argument refers to
the same object reference.
full answer hidden, click here for all
answers
Premium members click below for full answer
Why don't two StringBuffers match?

Q: What's the difference in the memory allocation for StringBuffers?


A: The key difference between
a String and

a StringBuffer in

terms

of

memory allocation is that String objects are


immutable; once the string contents are set
they cannot be changed, so the virtual
machine can optimise memory use on this
basis. The content of StringBuffers can be
expanded beyond their initial buffer size, so
the memory allocation needs to be variable
and must be managed by the Java runtime
system.

The StringBuffer class

automatically adjusts its buffer size to fit


the string content it is given, but you should
instantiate the class with an explicit buffer
size large enough to avoid the performance
overhead associated with such resizes.

124

StringBuffer
buffer
StringBuffer(1024);

new

Java programmers should not be concerned


with detailed level memory management
for Stringoperations, which will be handled
and optimised by the runtime system. The
key

things

are

to

choose String or StringBuffer types


appropriate to the task and set an adequate
buffer size.

Q: How can I pad a StringBuffer?

A: The StringBuffer insert(int,

String) method can be used to pad the


buffer at specific locations. The method
inserts the given string at the offset position
indicated by the int value and shifts the
original buffer contents right. The original
string contents are preserved and the buffer
length is increased by the length of the
inserted string.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I pad a StringBuffer?

Q: What is a StringTokenizer for?

A: The
standard java.util.StringTokenizer class is a
special type of Enumeration that represents
segments

of

string,

which

may

be

separated by one or more "delimiters".

125

When you construct a StringTokenizer with


a comma delimiter, it will identify each word
in a comma separated list for instance.
full answer hidden, click here for all
answers
Premium members click below for full answer
What is a StringTokenizer for?

Q: How can I get a person's initials from their full name?

A: The

simplest way to extract single

words from a string like a full name is to use


aStringTokenizer.
The String method charAt(int) can then be
used to get the first character of each word,
as below.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I get a person's initials from their full
name?

Regular expressions

Q: How can I check a string has no numbers?


A: The simplest way to check that
a String does not contain any numbers is to
use the regular expression class Pattern in
the java.util.regex package.

The

method

below uses the regular expression [^09]+ to check that none of the characters in
the input string is a number. The square
brackets define a character class. The

126

negation

modifier ^ followed

by

the

number range 0-9 means "not a number".


The + quantifier

asks

the

regular

expression to match the character class one


or more times.
full answer hidden, click here for all
answers

Static design principles

When should I use static operations?

Static variables

What is special about static variables?

I get "non-static variable this cannot be referenced from a static context"!

How can I call static class members from a different class?

Static method calls

What's the difference in calling a method from a class or an object?

How do I call a static method in a separate class?

Can I call a static method from an object reference?

Can I call super() from a static context?

Can I call the superclass version of an overridden static method?

This static method sure looks like it overrides the superclass!

The static modifier

What is the difference between static and final keywords?

Static design principles

Q: When should I use static operations?


A: Java is an object oriented language, so
the first principle is to implement the
majority of your program through object
instances, instance variables and methods.
One

area

where

static

context

is

127

necessary

is

during

program

start-up

because the Java entry point method is


static:public static void main(String[]). This
means that variables and methods required
during start-up may need to be static too,
but the principle should be to create a
primary core object for your program early
and use that to instantiate and interact with
other object components of the system.
As a rule, static variables and methods
should

be

kept

to

minimum.

Static

variables are generally used for values that


belong to, or represent some state of the
class as a whole, where all instances would
have the same value. The most obvious
examples

are

constants

like Integer.MAX_VALUE, where the value is


fixed and standard whatever instance of
an Integer you have, or a counter that
keeps track of a value across all instances.
Static methods are often used as utilities
that are not associated with a particular
instance of a class. For example, static
utility methods may be used to parse an
input

value

to

another

type,

the Integer.valueOf(String) method,

as

with

or

as

so-called factory methods to acquire a preconfigured

instance

of

type,

like

the Calendar.getInstance() method.

Static variables

Q: What is special about static variables?


128

A: A

static

variable

is

shared

by

all

instances of a class. Every instance has a


reference to the same variable and can
modify

it

directly.

Static

instances

are

declared with the static modifier.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
What is special about static variables?

Q: I get "non-static variable this cannot be referenced from a static context"!


A: The main method must be
declared public static void because it is
invoked when the Java Virtual Machine first
starts up, before any Java object instances
exist. The main method may reference any
number of static variables and call static
methods. Any series of calls to other static
methods only extends this original static
context.

To

reference

or instance variable

from

non-static
the

main

method, you must first instantiate the


relevant object, even if it is the host of the
main method itself, as below.

full

answer

hidden, click

for

complete answers
Premium members click below for full answer
I get "non-static variable this cannot be referenced
from a static context"!

Q: How can I call static class members from a different class?


A: Calling static members in a separate
class is very similar to calling a static

129

method

in

separate

class.

Most

importantly, the static member must have


a public, package or protectedmodifier that
makes it accessible to the calling class. Use
the class name, a dot separator and the
name of the member variable, as with
the AWT Color class properties below:

Color textColor = Color.black;


Color panelColor = Color.lightGray;

Static method calls

Q: What's the difference in calling a method from a class or an object?


A: The only way that a class can call a
method without an object reference is in a
static

context.

For

example,

the

static main() method is invoked in a static


context, before any instance is created, so
any methods it calls must also be static.
The main() method may call static methods
of its own, or of other classes.
One key thing about static methods is that
they

must

not

reference

any

instance

variables or call any instance methods


because there may not be any instance of
an object in the static context.
When you call a method from an object
(more precisely from a reference to an
instance of an object), it ensures that an

130

instance exists and means that all instance


variables
referenced,

are

initialised

and

instance

and

can

methods

be
can

safely be called. The compiler ensures these


conditions. An instance can also call a class
or static method and variables of its own or
other classes.

Q: How do I call a static method in a separate class?


A: To call a static method in a separate
class

you

should

prefix

the

method

reference with the name of the class it


belongs to, known as the host class. For
example,

the String class

hasvalueOf() methods to convert primitive


values to strings:

String booleanString = String.valueOf(true);

Q: Can I call a static method from an object reference?


A: Yes, it is possible to call a static method
from

an

object

reference.

The

object

reference must be the host of the static


method. The example below constructs a
new instance of itself, but any other class
could instantiate the class and call its static
method.
public class StaticMethodExample {
public static void staticMethod() {

131

System.out.println("Static method call.");


}
public static void main(String[] args) {
StaticMethodExample object = new
StaticMethodExample();
object.staticMethod();
}
}

Unless you happen to have an instance of a


class for other purposes, it is generally
simpler, clearer and preferable to use a
static reference to the host class.

StaticMethodExample.staticMethod();

Q: Can I call super() from a static context?


A: The super() method can only be called
in an object's constructor, it cannot be
called in a static context. The only way to
invoke the super() method is to place this
statement in the first line of an object's
constructor and instantiate the object. You
can then invoke this method via thestatic
void main(String[]) method, as below.
public class
Superclass {

SuperConstructor

extends

public SuperConstructor() {
super();
}

132

public static void main(String[] args) {


SuperConstructor
SuperConstructor();
}
}

object

new

Q: Can I call the superclass version of an overridden static method?

A: Static

methods

cannot

truly

be

overridden, if you create static methods


with the same signature as those in a
superclass

it

will

lead

to

confusing

behaviour and is not recommended. It is not


possible to use the super keyword in the
static context of a subclass because it refers
to a instance. Just use the standard static
method

reference

scheme

for

the

superclass; the superclass name, a dot


separator,

the

method

name

and

arguments, as below.
public class ExampleSubclass
ExampleSuperclass {

extends

public static void main(String[] args) {


ExampleSuperclass.testMethod();
}
}

Q: This static method sure looks like it overrides the superclass!

A: Creating a static method with the same


signature

as

superclass

version

effectively hides the superclass method, it


does not override it. This is a difficult

133

distinction to understand and to detect


because in several contexts the methods
behave as if they were overridden. The
difference

becomes

apparent

when

an

instance of the subclass is assigned to a


superclass type, as below.
public class SuperclassStatic {
public static void testMethod() {
System.out.println("Superclass
message");
}
}
public
class
SubclassStatic
SuperclassStatic {

extends

public static void testMethod() {


System.out.println("Subclass
message");
}
public static void main(final String[] args)
{
System.out.println("Calling subclass
method...");
testMethod();
System.out.println("Calling superclass
method...");
SuperclassStatic.testMethod();
// Subclass type
SubclassStatic subStatic = new
SubclassStatic();
System.out.println("Calling static
method on subclass type...");
subStatic.testMethod();
// Superclass type
SuperclassStatic superStatic = new
SubclassStatic();

134

System.out.println("Calling static
method on superclass type...");
superStatic.testMethod();
}
}

The

subclass'

local

call

to

the

static testMethod() executes its own version


and you get the subclass message. The call
to
the SuperclassStatic.testMethod() executes
the superclass version and you get the
superclass message.
When

you

assign

an

instance

of

the

subclass to a SubclassStatic type variable,


the

runtime

system

the testMethod() version


the variable type,

executes

associated
so

with
gives

thesubclass message. In the last case a


subclass instance is assigned to a variable
declared

as

aSuperStatic type,

so

the testMethod() defined in the superclass


is

executed

and

gives

thesuperclass message.
The Java compiler does not fail or warn
about static method name clashes, so it is
important to be aware of this scenario and
avoid it.

The static modifier

Q: What is the difference between static and final keywords?

135

A: The static and final modifiers

have

quite distinct purposes in Java, though they


can be used in combination to declare class
constants.

When

the static modifier

is

applied to a variable or method it belongs to


all instances of the class and can be
referenced in a static context. In other
words, the class does not have to be
instantiated before the variable can be read
or the method called. That means that
static variables must be assigned at compile
time and static methods cannot reference
instance variables or call instance methods.
The final modifier can be applied to a class
definition or method to prevent extension or
overriding

respectively.

This

helps

the

compiler optimise byte code for the class.


When the finalmodifier is declared on a
variable it means that its initial assignment
will not change during the execution of the
code. Final instance variables must be
assigned at compile time or in the class'
constructor, as in the example below.
full answer hidden, click for complete answers

Language features

Is Java a fully object oriented language?

What are keywords and reserved words?

How can I develop in my local language in Java?

Java data types

What Java types are available?

What is the return type in Java?

What's the difference between primitive types and arrays?

136

Java language design concepts

What's the difference between abstraction and encapsulation?

Is println() overloading or overriding?

What is the difference between static and dynamic polymorphism?

What is dynamic method dispatch?

What is polymorphism?

Why do we overload methods in Java?

Java memory allocation

What part of memory is used for interfaces and abstract classes?

Language features

Q: Is Java a fully object oriented language?


A: Java is an object oriented language, but
there is no standard that defines a "fully"
object oriented language, it is a matter of
definition and opinion.
full answer hidden, click to get full
answers
Premium members click below for full answer
Is Java a fully object oriented language?

Q: What are keywords and reserved words?


A: Java keywords are standard English
words that have a special meaning in the
Java programming language. Keywords
include class, interface, abstract, public, st
atic and final, which are used to declare the
type and nature of Java compilation units.
The statements used to define variables
and method bodies include
keywords new, return, if, while and throws.

137

These words are interpreted by the Java


compiler and used to produce byte code
that can be run as a program.
full answer hidden, click to get full
answers
Premium members click below for full answer
What are keywords and reserved words?

Q: How can I develop in my local language in Java?


A: Java programming
language keywords must be used literally
in their standard English form, there are no
alternative language equivalents for
the new, extends and public keywords, for
example. Primitive numeric values must be
represented by standard ASCII numeric
characters and syntax elements like
comment markers and curly braces must be
represented by the conventional ASCII
characters.
Beyond such
fundamental syntax constraints, Java class
files can be created with alternative
character encodings so you can type
comments, class and variable names
and String literals directly in your preferred
language. Java also supports UTF-8 class file
names.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I develop in my local language in Java?

138

Java data types

Q: What Java types are available?


A: There are two main divisions of data
types in Java: object and primitive types.
Object types are declared according to their
class.
Object object = new Object();

Objects can also be cast to a more general


superclass or interface type. Java type cast
behaviour is part of a general scheme of
object substitution called polymorphism, in
which an object behaves like and can be
treated as an instance of another type.
// Implicit cast to object type
Object object = new
StringBuffer("Example");
// Implicit cast to interface type
Comparable object = new
File("c:\Example.txt");

full answer hidden, click to get full


answers
Premium members click below for full answer
What Java types are available?

Q: What is the return type in Java?


A: All Java methods must declare a return
type, which may be an object reference,
primitive value or void. The void return

139

declaration means that no value is returned,


control is simply returned to the calling
class. Methods with non-void return types
must ensure that the appropriate object
reference or primitive value is returned
when the method completes. The method
return value is like a message and often
represents a property of the object, the
product of a calculation or algorithm or a
text output for instance.

Q: What's the difference between primitive types and arrays?


A: Primitive data types are containers that
hold references to fundamental numeric,
logical, byte and character literal data and
are built-in to the Java language and
runtime system. They are called primitive
because they have a relatively simple
physical storage format and size. Primitives
are not Java objects and objects cannot be
cast to a type that could be stored in a
primitive variable.
// incompatible types, does not compile
long l = new Object();

full answer hidden, click to get full


answers
Premium members click below for full answer
What's the difference between primitive types and
arrays?

Java language design concepts


140

Q: What's the difference between abstraction and encapsulation?


A: Abstraction and encapsulation are two
quite separate concepts in Java. Abstraction
is a technique that is used to represent
common functionality amongst a set of
classes. An analogy is to look at a set of
vehicles: Car, Truck and Bus have some
common features that all road vehicles
share. From a Java perspective, the
mechanics of turning four wheels, an
engine, could be handled in abstract form
through a common superclass. Abstraction
allows subclasses to share common code
without duplication.
full answer hidden, click to get full
answers
Premium members click below for full answer
What's the difference between abstraction and
encapsulation?

Q: Is println() overloading or overriding?


A: The PrintWriter println() method is an
example of overloading because several
methods in the class have the same name
and return the same type. In this
case, println(boolean),println(int) and printl
n(String) all have the same basic method
name, "println", and all return void. The
only part of the method signature that
varies is the type of the argument (including
none), which is enough for the Java
interpreter to identify the appropriate
method to call at runtime.

141

full answer hidden, click to get full


answers
Premium members click below for full answer
Is println() overloading or overriding?

Q: What is dynamic method dispatch?


A: Dynamic method dispatch is the
process the Java runtime system uses to
determine which method implementation to
call in an inheritance hierarchy. For
example, the Object class has
atoString() method that all subclasses
inherit, but the String class overrides this
method to return its string content. If
a String or other object type is assigned to
an Object reference using application logic,
the Java compiler cannot know in advance
where a call to the toString()method will be
resolved, it must be determined
dynamically at runtime.
full answer hidden, click to get full
answers
Premium members click below for full answer
What is dynamic method dispatch?

Q: What is the difference between static and dynamic polymorphism?


A: The term static polymorphism is
associated with overloaded methods
because it gives the impression that a
single named method will accept a number
of different argument types.
TheSystem.out.println() method is an
example that may

142

take String or Object references,boolean an


d other primitive types as an argument. In
fact, each overloaded method is separate
and the compiler can see the difference
between them. In this case, the argument
types are fixed at compile time and are
considered static. This has nothing to do
with the Java keyword static.
Dynamic polymorphism is where a class
overrides a superclass method or
implements an interface. For example, any
class may override
the Object.toString() method and provide its
own implementation, and this is known at
compile time. However, for a simple Java
program that instantiates a series of objects
and calls their toString() method, the
compiler does not consider the object
references differently. Any differences in the
objects' toString()implementations are only
seen at runtime, so they are considered
dynamic.

Q: What is polymorphism?

A: The key to understanding the principle


of polymorphism is the phrase behaves
like. In Java you can say that
a FileInputStream class behaves like
an InputStream. It means that wherever you
require an InputStream you can use
a FileInputStream.
Java defines the behaves like relationship
in a formal way with
the extends and implementskeywords. This

143

technical detail doesn't alter the nature of


the relationship, it just lays down the rules
to follow when you write a program.
The poly aspect of the name
polymorphism means that a class may
behave like more than one thing, which
makes it more versatile. First, a class
behaves like itself. It must also behave like
at least one superclass, the Object class. If
a class extends another class it will behave
like at least three things: itself, Object and
its superclass.
A Java class may also implement an
interface, which is another way to say
behaves like. When an interface has a
super-interface a class implementation
behaves like both types.
The great advantage of polymorphism is
that it allows you to create flexible, well
structured Java programs where the
concrete behaviour of the system is generic
at a high level and specific at appropriate
levels lower down. If an application is coded
at the top level using interfaces and generic
superclasses like InputStream,
polymorphism allows you to use an input
stream from a URL connection,
a FileInputStream,
or StringBufferInputStream to handle
different input sources, for example.
The Java API is the ultimate example of the
strength and necessity of polymorphism.
The API defines many high level generic

144

interfaces and classes for application


programmers to build upon. Polymorphism
is what makes the system extensible,
modular and versatile.

Q: Why do we overload methods in Java?

A: Method overload is a design pattern


that creates the illusion of a general

purpose method that will accept a range of


argument types. For example,
the java.io.PrintStream attached
toSystem.out has a range of
overloaded print() and println() methods
that each take a single argument, a
primitive type, char[], Object or String.
Since the overloaded methods have the
same void return type and method name,
they give the appearance that you can pass
almost any variable type to
the print() method.
void print(boolean b);
void print(char c);
void print(char[] c);
void print(Object o);

Overloading gives the appearance of


handling method arguments in a
polymorphic way, including primitives, but
in fact each overloaded method is typespecific and its implementation is separate
and different. The print(Object) method can
be truly polymorphic because any object

145

type can be passed and implicitly cast.


Overloading makes methods easier to learn
and avoids the need to cast or convert
variables to a particular type before they
are passed as arguments. However, it can
also make code difficult to read because it is
less clear which overloaded method is
called.

Java memory allocation

Q: What part of memory is used for interfaces and abstract classes?


A: Interfaces and abstract classes are part
of the application programming interface for
the Java language, but are never
instantiated in their own right when a Java
program is run. Only objects are
instantiated in the Java Runtime
Environment (JRE) and held in a division of
the program's memory allocation called the
heap. Stack memory holds primitive values
and the memory addresses of objects on
the heap.

Object concepts

What is an object in Java?

What's the difference between a class and an object in Java?

What's the difference between an instance and an object?

What is a concrete object?

Which is the object in test t1 = new test()?

Understanding constructors

What is a constructor?

What is the difference between a constructor and an object?

146

What is the difference between a method and a constructor?

How do I invoke a constructor?

How can I call a constructor from a constructor?

Is it OK to tag inline method calls on constructors?

What does the statement super($anonymous0) mean in Java?

Why do we use static initializer blocks?

Object design

How can I count the number of instances of an object?

Can objects be used in place of arrays?

What's the difference between equals and ==?

Object methods

Can I use the same variable name in two methods?

Is it possible to use the same variable name in the same method?

What is the syntax for methods with no argument?

How can I get the caller of a method?

How does an object call an inner class method?

What is the difference between a method header and its signature?

Object comparison methods

When is hashCode() used?

How can I create a constructor to equate two other objects?

Object concepts

Q: What is an object in Java?


A: In Java the Object class is the ultimate
superclass of every other object type. All
objects are extended from the Object class,
either directly or by inheritance through any
number of parent classes. If a class does not
explicitly extend any named class, it
implicitly extends the Objectclass. An object

147

with a small o is the word used to describe


an instance of a Java class.

Q: What's the difference between a class and an object in Java?


A: A Java class is a definition or model of
an object type. A class has a specific set of
fields, methods and constructors with
distinct argument types. Any object that
fulfills a class definition directly or by
inheritance has a set of properties and
behaviour that is common to all instances of
the class. In this sense, a class is a set of
things that are alike.
In Java concrete classes also provide a code
implementation that can be instantiated to
create an object reference. An instance of a
class directly fulfills its own definition, it also
fulfills any superclass definitions too.
The Java Virtual Machine creates static
references to classes when it runs a Java
program. Classloaders make the public
static fields and methods of classes
available to the runtime system whether
any instance exists or not. When a
constructor is called, the class returns an
instance of the object it represents.

Q: What's the difference between an instance and an object?


A: When you create a Java object by
calling its constructor, the object reference
that is returned is called an instance. This
means there is little difference between the
two terms. The word instance is usually

148

used when we talk about the process of


object creation or instantiation, it is a single
reference to an object. The word object can
also be used to talk collectively about the
general properties and behaviour of a Java
object.

Q: What is a concrete object?


A: The term concrete class is used to
describe a class that can be instantiated to
form an object instance in the Java Runtime
Environment (JRE). A concrete object would
be an instance of a concrete class and
makes better sense in contrast with
abstract classes and interfaces, which
cannot be instantiated in their own right,
only by extension or implementation by a
concrete class.

Q: Which is the object in test t1 = new test()?

A: In this example the variable t1 holds a


reference to an object of the class test,
which is also known as an instance of the
class test.

Understanding constructors

Q: What is a constructor?
A: A constructor is a special class method
that is used to create an instance of the
class. A constructor method is named after
the class it belongs to and may have
arguments. The constructor returns an

149

instance of the class, which is an object you


can use in your Java program.
The constructor is called without referring to
an instance of the class. When you use
the newkeyword followed by the name of
the class with parentheses, the Java
compiler knows this is a constructor call for
the class. The class instance it returns is
normally assigned to a variable with an
appopriate type, as below. You can call the
constructor as many times as you like and it
should always return an instance.
Object objectInstance = new Object();

full answer hidden, click to get full


answers
Premium members click below for full answer
What is a constructor?

Q: What is the difference between a constructor and an object?


A: A constructor is a special type of
method that you use to create an instance
of a class. An object is another name for an
instance of a class. If you think of a Java
source file as a plan or design for a
component in a larger machine, when you
call a class constructor it is like an
instruction to the Java runtime system to
say make one of these. The runtime
system returns an object based on that
design which you can use in your Java
program. You can call a constructor as many
times as you want to get multiple instances

150

of an object, which each exist


independently but can also have linked
behaviour and properties.
The Java statements in a constructor are
intended to prepare a new object for the
work it will do in a Java program. The
constructor should ensure that the object
has all necessary input arguments,
configure itself for use and set up any
linkages and dependencies with other Java
objects.

Q: What is the difference between a method and a constructor?


A: Methods and constructors are quite
similar in nature, you can think of a
constructor as a special type of static
method that implicitly returns an instance of
the relevant class. Methods have an explicit
return type in their signature that tells you
what type of object or primitive the method
will return, or void if none. A constructor
has no explicit return type because it
always returns an instance of the class. In
most other ways constructors are like
methods, they have the same visibility
modifiers and may have zero, one or more
arguments.
One notable property of constructors is that
the Java compiler will automatically insert a
call to the no-argument superclass
constructor unless you explicitly add a
superclass constructor statement. This
arrangement will create a compilation error

151

if the superclass does not have a visible noargument constructor, in which case you
must make the superclass constructor
visible or add call to an alternative
superclass constructor.
public class Example extends Superclass {
public Example() {
// Implicitly calls the superclass
constructor Superclass()
}
public Example(final int param) {
// Supersedes implicit call to superclass
constructor
super(param);
}
}

Q: How do I invoke a constructor?


A: Java object constructors are invoked by
putting the new operator before the class
name and enclosing any constructor
argument references in parentheses after it.
A fundamental case is theObject class,
which is invoked as follows.
full answer hidden, click to get full
answers
Premium members click below for full answer
How do I invoke a constructor?

Q: How can I call a constructor from a constructor?

A: When you have a number of


constructors in a class you can call them
using this() in a similar way to the

152

superclass constructor super(). For instance,


if you have a "good citizen" constructor that
takes a String and a boolean, and a
shorthand version that only takes a String,
you may pass a default value to the two
argument constructor, as below.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I call a constructor from a constructor?

Q: Is it OK to tag inline method calls on constructors?

A: Using a dot separator to call a method


on a new instance is a convenience
technique that combines two statements in
one. There is no practical difference in the
method invocation, in both cases a new
instance is created and the method is
executed, but in practice the code can
create unnecessary anonymous instances
and confuse the assignment of the return
value. For clarity it is better to use two
separate statements with obvious
assignments, as the series of examples
below illustrate.
full answer hidden, click to get full
answers
Premium members click below for full answer
Is it OK to tag inline method calls on constructors?

A: The

Q: What does the statement super($anonymous0) mean in Java?

statement super($anonymous0) would be

153

used as the first statement of a class


constructor, it passes the
variable $anonymous0 to the superclass
constructor. It may be necessary to store or
read configuration details from the variable
to properly prepare the class for use, for
example. That means that the superclass
must have a constructor with a single
argument that matches the type of the
variable $anonymous0. The
variable $anonymous0 must be passed as
an argument to the subclass constructor or
be a static variable of the subclass because
its reference must be defined before the
superclass constructor is called.

Q: Why do we use static initializer blocks?

A: Static initializer blocks tend to be used


in classes that have important properties
and behaviour that are accessed in a static
context and may require some runtime
configuration. A static initializer block is
similar in nature to a class constructor,

except it is executed when the class is first


loaded by the Java runtime system, before
any instance is created. Static initialization
blocks may set the initial value of static
variables using relatively complex logic,
execute Java statements and call other
methods. Since this code runs before any
instance of the host class exists, it cannot
work with instance variables or methods of
its own.

154

Static initializer blocks enable programmers


to run relatively complex code during class
loading to prepare a class for use in a purely
static context, or when it would be too
late to run the code in a constructor call.
static {
// Execute statements during class loading
}

Object design

Q: How can I count the number of instances of an object?


A: To count all instances of a class you
should create a static int variable to store
the number of instances and include an
increment statement in all constructors. You
must also implement
afinal finalize() method that is called upon
garbage collection to decrement the count.
And since multiple instances may increment
and decrement the static value in separate
threads, these statements should be
enclosed in a synchronized block, as in the
example below.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I count the number of instances of an
object?

Q: Can objects be used in place of arrays?


155

A: Yes, sometimes it is sensible to use an


object to carry other object references
instead of an array. For instance, you could
issue an object as the return value of a
method that must return multiple object
references.
full answer hidden, click to get full
answers
Premium members click below for full answer
Can objects be used in place of arrays?

Q: What's the difference between equals and ==?


A: The Java == operator is used to
compare primitive values such
as int, long and boolean for equality;
whether the variables, values or expression
on either side of the operator equate to the
same value.
full answer hidden, click to get full
answers
Premium members click below for full answer
What's the difference between equals and ==?

Object methods

Q: Can I use the same variable name in two methods?


A: It is possible to use the same variable
names for method local variables in two
separate methods, and in separate
statement blocks, enclosed by curly
braces, { and }. Methods and statement
blocks have their own variable scope, so the

156

Java compiler and interpreter can maintain


a distinction between the variables they
contain. Generally it is preferable for
variables that represent different properties
to have different names to avoid confusion,
but it is likely that several methods may use
an index named i in a for loop for example.

public class MethodLocalVariables {

void testOne() {

int test;
}

void testTwo() {

int test;
}
}

Q: Is it possible to use the same variable name in the same method?


A: It is technically possible to use the
same variable name in separate statement
blocks because the variables are localised;
the compiler can deduce from their context
that they are different things, see the
working example below. However, it is not

157

advisable to use the same variable name in


multiple places, especially within the same
method, because it is confusing and can
lead to bugs.

public class RepeatLocalVariables {

public final void doSomething(final String


thing) {

if ("thing one".equals(thing)) {

int a;
// Other statements
}
if ("thing two".equals(thing)) {

int a;
// Other statements
}
}
}

If both variables in this example are actually


used for the same purpose, a single variable
declaration should be made in the main
body of the method. If the variables are for

158

different purposes, it would be better to


name them differently.

Q: What is the syntax for methods with no argument?


A: The syntax for methods with no
arguments is to follow the method name
with open and close brackets with nothing
in between. This syntax applies to static and
instance methods, and those with void,
primitive or object return types.

public final void noArguments() {

// Method statements
}

Q: How can I get the caller of a method?


A: In most cases it is not relevant or
necessary for a Java method to know the
object that called it. If your code needs to
know the origin of a method call it is likely
the method is located in the wrong host
class, or your overall program structure
does not follow good object oriented
principles. Consider whether you can move
the method to a different host class or
refactor to place class-specific code in the
relevant classes.
If you find there really is good reason to
know the origin of method calls, add

159

an Object argument to the method and use


the getClass() method to test.

Q: How does an object call an inner class method?

A: Host classes call methods on inner

classes in exactly the same way as they


would on a separate class defined in its own
compilation unit. To call an inner class'
instance method it is necessary to
instantiate the class first, as below.
full answer hidden, click to get full
answers
Premium members click below for full answer
How does an object call an inner class method?

Q: What is the difference between a method header and its


signature?

A: A Java method header is the whole


declaration statement for a method before
its curly braces. The header includes the
method's visibility modifier, return type,
arguments and exceptions, as below.

public final String getDetails(final File file,


final String key) throws
IOException

A Java method signature is the method


name and parameters only. The order of the
parameters is significant because they may
distinguish overloaded methods by the
same name.

160

getDetails(File, String)

Object comparison methods

Q: When is hashCode() used?


A: The hashCode() method is used in
hash-based data stores to get a "nearly
unique" identifier for each object. The hash
code is used to speed up the search
process, so should have a high probability of
being different from any other instance. It is
possible for two hash codes to be the same,
so the equals method is used to make an
exact match.
full answer hidden, click to get full
answers
Premium members click below for full answer
When is hashCode() used?

Q: How can I create a constructor to equate two other objects?


A: Normally when we compare two objects
we use the
fundamental equals(Object) method.
Conceptually, the equals method "belongs"
to the objects you are comparing and
returns aboolean to indicate whether they
are passed a reference to themselves.
Its not obvious why you would choose to
make that comparison in the constructor of
another class, which may only return a

161

reference to the new instance, not a simple


boolean response. In any case, the example
below shows how you can compare method
arguments and return a boolean, which
could be refactored for use in a constructor.
full answer hidden, click to get full
answers

Getting started with JDBC

What's the difference between a data store and a database?

Where can I find a JDBC driver for my database?

How does Class.forName(dbDriver) work with DriverManager.getConnection()?

Why not statically import a database driver class?

How do I use JDBC with Microsoft SQLServer?

Java SQL API

What's the difference between Driver and DriverManager?

What is the driver manager?

Is the DriverManager thread safe?

How do I implement the interfaces Statement and PreparedStatement?

What's the difference between Statement and PreparedStatement?

How can I insert multiple records at a time?

Why it is better to use PreparedStatement?

JDBC techniques

How can I insert records in multiple tables?

How do you make a database insert using JDBC?

How can I use system variables to make a database connection?

How can I create a connection pool?

JDBC problems

I get "cannot find symbol" for my executeUpdate(String) call!

My JSP throws "Error establishing socket" when I migrate to Linux!

SQL queries

How can I insert a new row between two others?

162

So a new row will be sorted in the last position, right?

How can I select records between two dates?

What is a database view?

Getting started with JDBC

Q: What's the difference between a data store and a database?


A: A data store is a general term for a
storage system like a relational database
that may be used to store and retrieve
information. For example, the Enterprise
Java Beans (EJB)specifications use the term
data store throughout to allow application
server vendors to implement storage
however they choose. In most cases a data
store is implemented in the form of a
relational database, but it could take other
forms too.

Q: Where can I find a JDBC driver for my database?


A: This will depend on the database you
use and the JDBC version you require. To
find the latest versions, search Google
for JDBC driver and add your database
name.

Q: How does Class.forName(dbDriver) work


with DriverManager.getConnection()?

A: The static Class.forName() method is a


way to instantiate a class that minimises
hard coded dependencies in your Java
applications. You may well know the
database driver you intend to use when you

163

first write your code, but if you use


a String variable for the driver class name
you can re-configure for a different
database product without re-writing your
client application.
full answer hidden, click for
complete answers
Premium members click below for full answer
How does Class.forName(dbDriver) work
with DriverManager.getConnection()?

Q: Why not statically import a database driver class?


A: The standard Java import statement
makes a class available to the importing
class to use its public variables and method
calls. It is certainly possible to import
specific JDBC driver implementations and
use them in the same way, provided they
are available on the application's classpath.
However, the Java SQL package and JDBC
scheme has been designed to deal with
database interfaces in a generic way that is
not tied to any single driver
implementation. In fact, it is possible to load
multiple drivers in a single application.
Though it may be possible to load a specific
driver and invoke its connect(String,
Properties) method directly, it is far
preferable to use the
static Class.forName(String)method and get
connections through
the DriverManager's getConnection() metho
ds. This allows you to configure your

164

application's database driver using external


configuration or properties, rather than hard
code class references. You only need
declare the Java interface types for the
driver, connection, statements, rather than
vendor-specific classes.

Q: How do I use JDBC with Microsoft SQLServer?

A: One of the great strengths of

the JDBC API is that the Java code required


to load and use a database driver from one
vendor is the same as that for any other.
The key differences between one vendor's
driver and another will be the class name of
the driver, and the JDBC URL used to
identify it through the DriverManager class.
Both of these variables should be set in the
application's configuration properties rather
than hard coded Java statements. Provided
the necessary database driver class
packages are available on the application's
classpath, the runtime system will be able
to load and the run the driver classes.
For Microsoft SQLServer, the database
driver class name
iscom.microsoft.jdbc.sqlserver.SQLServerDri
ver, the connection URL has the following
scheme:
full answer hidden, click for
complete answers
Premium members click below for full answer
How do I use JDBC with Microsoft SQLServer?

165

Java SQL API

Q: What's the difference between Driver and DriverManager?


A: Driver is a Java interface that declares
a standard set of methods that a database
server is expected to provide. A database
vendor must supply their own serverspecific JDBC code that implements
the Driver interface and a number of
supporting types,
including Connection,Statement and Result
Set. Since all these key Java DataBase
Connectivity (JDBC) components are defined
as Java interfaces, the vendor-specific
implementations can dynamically be loaded
at runtime without hard coded references to
their fully qualified class names.
A database vendor's JDBC implementation
code is usually distributed in the form of a
Java Archive (JAR) file that you include in
your application's classpath at runtime.
DriverManager is one of the few concrete
implementation classes built into
the java.sqlpackage and serves as a static
registry of the JDBC Drivers available to the
Java runtime system. As a Driver class is
loaded it is expected to register itself with
the DriverManager class by calling its
static DriverManager.registerDriver(Driver)
method, passing an instance of itself as an
argument.

166

JDBC application code should call one of


several
static DriverManager.getConnection()metho
ds to get a connection to the relevant
database. All the getConnection() methods
include a connection URL argument that is
used to look-up the
appropriate Driver implementation and get
a connection through its
own connect(String, Properties) method.

Q: What is the driver manager?


A: The DriverManager class is a core part
of the java.sql package for Java database
connectivity, it provides a registry
of JDBC drivers that are loaded and
available for use, and methods to get
database connections using those drivers.
The JDBC specification requires
implementations of
the java.sql.Driver interface to register
themselves with
theDriverManager method registerDriver(Dr
iver) when their class is loaded through
theClass.forName(String) method.
Once the driver class is loaded and
registered, connections can be obtained
from the staticgetConnection() methods of
the DriverManager class. The
basic getConnection(String)method requires
a URL string in the
form jdbc:subprotocol:subname, which the
driver manager will use to identify the
relevant driver and get a connection.

167

Overloaded versions of this method also


accept database user name and password
strings, or a Properties object containing
these details and any other connection
details that may be necessary for a specific
driver.

Q: Is the DriverManager thread safe?


A: Yes,
the DriverManager getConnection() method
is thread safe. However, it is not very
efficient for multiple threads to request their
own connections from the driver manager,
so it is recommended you use a connection
pool in a production environment. A
connection pool will acquire database
connections on behalf of an application;
when one thread has finished with a
connection it is returned to the pool for reuse and this minimises the new connection
time overhead.
The Apache Commons Database Connection
Pool (DBCP) library is a robust open source
implementation of a connection pool that is
widely used. A little extra effort is required
to set up, but this will pay off in more rapid
database connectivity.

Q: How do I implement the


interfaces Statement and PreparedStatement?

A: These SQL package interfaces are


declared in the Java API so that your

applications do not have to rely on a single


specific implementation. The JDBC scheme

168

requires database vendors to provide


concrete implementations of these
interfaces, and these are obtained via
the DriverManagerclass. When the database
driver is registered,
the DriverManager accessor methods return
database-specific implementations
of Driver and Connection, which issue
custom Statement,PreparedStatement and
ResultSet instances in turn.

Q: What's the difference


between Statement and PreparedStatement?

A: A standard Statement is used to create


a Java representation of a
literal SQL statement and execute it on the
database. The statement input may be any
valid SQL, but the class has different
methods for inert queries and update
statements that change the contents of the

database:executeQuery(String) and execute


Update(String) respectively.
full answer hidden, click for
complete answers
Premium members click below for full answer
What's the difference
between Statement and PreparedStatement?

Q: How can I insert multiple records at a time?

A: From a data management point of view,


it does not seem necessary or sensible to
make multiple inserts to a database with a
single SQL statement. The nature of
the INSERT statement is to create records,

169

and records should be distinct from each


other else they would be redundant and
inefficient use of storage.
An UPDATE statement on existing records
can affect multiple records through a single
statement, and that is more likely to be an
appropriate way to manage your data.
Having said that, a PreparedStatement that
is used to iterate through a series of insert
statements is a perfectly good way to add
multiple different records to your database,
as below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I insert multiple records at a time?

Q: Why it is better to use PreparedStatement?

A: Prepared statements are more efficient


for managing database actions because
they give the driver and the database
system itself the opportunity to optimise the
queries, and to re-use them. Although the
parameters of the query, update or insert
may change, the more often the prepared
statement is used, the greater the potential
saving.
full answer hidden, click for
complete answers
Premium members click below for full answer
Why it is better to use PreparedStatement?

170

JDBC techniques

Q: How can I insert records in multiple tables?


A: The approach to insert simple
independent records in multiple tables
would be to prepare the two
insert Statement objects and call
the executeUpdate() method on them one
after the other. Depending on your
application it may also be appropriate to
commit a transaction for these inserts.

Q: How do you make a database insert using JDBC?


A: Java database programming requires
some relatively complicated classpath and
database-specific configuration and class
loading which are explained elsewhere. This
example focuses on creating and executing
an SQL insert statement using
a PreparedStatement, with values taken
from command line parameters. It uses a
fixed database driver class name, database
URL, user name and password for simplicity.
full answer hidden, click for
complete answers
Premium members click below for full answer
How do you make a database insert using JDBC?

Q: How can I use system variables to make a database connection?


A: The variables available through the
standard system Properties set do not
include any custom environment variables
stored by the operating system. However, it

171

is possible to add custom variables to this


property set with the Java command line
flag -D and pass these properties to the
database driver manager. With variable
substitution, it is then possible to use
operating system variables for these values,
as detailed below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I use system variables to make a database
connection?

Q: How can I create a connection pool?


A: Developing a database connection pool
is a relatively advanced project. You should
consider using an existing open source tool
like the Apache Commons database
connection poolcomponent.

JDBC problems

Q: I get "cannot find symbol" for my executeUpdate(String) call!


A: The Statement executeUpdate(String)
method takes a single string argument. The
string concatenation syntax you have used
is incorrect and represents multiple comma
separated string arguments, not a single
string. The error "cannot find symbol"
means that the Java compiler cannot find
a Statement method that has this number
of string arguments.

172

This case highlights one of the hazards of


concatenating SQL statements in method
calls, it can be difficult to see where the
Java syntax ends and the SQL syntax
begins. It would be much clearer and
simpler to use a PreparedStatement in this
case and substitute the variables explicitly,
as below.
full answer hidden, click for
complete answers
Premium members click below for full answer
I get "cannot find symbol" for
my executeUpdate(String) call!

Q: My JSP throws "Error establishing socket" when I migrate to Linux!


A: This exception explains itself; your Web
application could not get a connection to
the Microsoft SQL Server service. There are
many possible causes for a connection
failure. Most simply the database server
may not be running or there may be no
network connection to the machine the
database is running on, or it is operating on
a different port, for example.
It may help to write a small JDBC utility to
test the database connection problem
independently from your Web application. It
can be easier to produce diagnostic
information from a command line
application, re-configure and re-deploy than
to do the same with a Web application. You
will likely find a small but significant
configuration difference between your

173

development environment and production


environment that can easily be corrected.

SQL queries

Q: How can I insert a new row between two others?


A: There is no need to insert relational
database records in any particular
sequence. When you insert a record the
database application will typically add the
record to the end of the table. If it is
important for your database application to
list data in a particular sequence, you would
normally use a data field to determine the
sort order. For example, you might use
the SQL ORDER BYstatement to sort the
data by a customer's last name and first
name:

SELECT * FROM customer ORDER BY


last_name, first_name;

Q: So a new row will be sorted in the last position, right?


A: If your database table has an
automatically generated serial ID field, new
records will normally adopt the next ID
value in the series and that creates a
natural sequence of record values. A serial
ID field allows you to sort database records
by their serial value to re-create the
chronological insert sequence for the table.

174

Database concurrency controls may mean


that the insert sequence for database
transactions is slightly out of the step with
the "real time" activity of people using a
Web front end to the database, and may
create gaps in the sequence.
The design of database tables may not
require a serial ID field. Some tables may
have a different field type that can be
guaranteed unique and used as a primary
key, or a combination of fields can be used
as a primary key. It is best not to think of
data rows in a specific physical location or
sequence. Use your database structure and
query design to get a specific sort order.

Q: How can I select records between two dates?


A: To select records by date, your
database table must have
a DATE or TIMESTAMP field to use in
the WHERE condition of the query
statement. For example, for a product order
table you might have a date_ordered field
that is a DATE data type. Secondly, since
the SQL query input is submitted as a
string, you must cast the two dates
to DATE data types, as below, split over
several lines for clarity.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I select records between two dates?

175

Q: What is a database view?


A: A database view is a temporary,
selective representation of database fields
from one or more tables. The view data is
held in a structure that behaves like, and
can be treated as, a standard database
table. The field values held in a view are
dynamically updated as the tables they
refer to are changed, so the view is always
current.
Database views are created by assigning
the results of a standard SQL query to a
named view, as in the simple example
below. Views are typically used to make a
simplified extract from a complex data set,
so the queries used to create them tend to
be relatively complex. View selections may
also cast data from one type to another for
convenience.
full answer hidden, click for
complete answers

Java API versions

What's the difference between the Java versions?

What are legacy classes?

What is the difference between API and help in Java?

Where can I find out more about the Java API?

Java system integration

How do I get the name of the operating system?

What is System.out?

Are the Java console streams subclasses of System?

How do I find the size of an object in Java?

176

How can I copy process information from Windows task manager?

Java exceptions

What's the difference between checked and un-checked exceptions?

What is a NullPointerException in Java?

What's the best way to handle a NullPointerException?

Can you give an example of catching an exception?

How can I throw a NumberFormatException back to the main() method?

Class loading

How can I get a class reference without using new operator?

What's the difference between the Class.forName() method and the new operator?

What is the return type for the Class.forName(String) method?

How can I implement the Class.forName() scheme?

How can I cast an unknown sub-class returned by newInstance()?

Is Class.forName() runtime polymorphism?

Java Abstract Window Toolkit classes

How do I draw a Rectangle on a Graphics instance?

What is the difference between heavyweight and lightweight components?

Java API versions

Q: What's the difference between the Java versions?


A: The major release versions of the Sun
Java Software Development Kit (SDK, also
known as the Java Development Kit, JDK)
include significant Application Programming
Interface (API) changes that provide extra
programming features built upon the core
Java software platform. That means that the
basic features of the Java language do not
change from one release to the next, so

177

most existing programs will run successfully


when compiled with the new SDK.
Some core packages may gain additional
features in new Java releases, but it is very
rare for established API features to be
removed, which would break backwards
compatibility. Superseded or problematic
API methods are usually
marked deprecated before they are
removed altogether, to give programmers
the chance to upgrade their code to the
new standard. Deprecated classes and
methods can still be used to develop and
run Java programs, but the compiler will
issue warnings.
Oracle publish a set of release notes for
each SDK release with their archive
of previous Java SDK releases.

Q: What are legacy classes?


A: The term legacy has a similar meaning
to its everyday usage; something that is left
behind from an earlier time or passed down
from one's ancestors.
In Java, legacy classes are system
components that we continue to work with,
even though they may be deprecated, use
deprecated methods or sub-optimal
programming techniques, for example.
Systems may use legacy classes from third
party suppliers that are no longer
maintained, for which no source code is
available.

178

Ideally, one would replace such legacy


classes with contemporary
implementations, but sometimes the extent
of a system's dependence on legacy classes
makes them difficult or un-economical to
replace. In this case, it is often necessary to
use adapter classes that enable legacy
classes to work with new programming
interfaces.

Q: What is the difference between API and help in Java?


A: A Java Application Programming
Interface (API) is a packaged set of classes,
interfaces, variables and methods that a
programmer can use to write their own Java
programs. The Java language has a syntax
to include documentation comments
amongst the code of a program to explain
its purpose, example usage and advisory
notes. The Java Software Development Kit
(SDK) includes a JavaDoc tool to
automatically generate HTML format API
documentation from these embedded
documentation comments, which are a form
of online help.
Many Java Integrated Development
Environments (IDE) also include code
completion as you type, based on the API
packages used in a project. When the IDE
recognises the start of a method name
associated with a known Java type it may
prompt to complete the statement. This
type of context-aware help is based on the

179

contents of a Java API but is not part of the


API itself.

Q: Where can I find out more about the Java API?


A: You should download the Java SDK API
documentation or read online. The standard
Java documentation gives full details of all
public methods and usage guidelines for all
classes and is an excellent place to start,
and for quick reference.

Java system integration

Q: How do I get the name of the operating system?


A: To get the operating system name in
Java use the
static System.getProperty("os.name")metho
d, which returns a string. Other operating
system property keys include os.arch for
the hardware architecture
and os.version for the version number, as
below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How do I get the name of the operating system?

Q: What is System.out?
A: System.out is a static variable that
refers to the console output. The object type
ofSystem.out is PrintStream,
not PrintWriter, but it has similar
overloaded println methods. These print

180

methods can be called by any class using


the static System.out reference.

Q: Are the Java console streams subclasses of System?


A: System.out is a static variable of
the System class that holds a reference to
a PrintStreamused to channel output to the
host system's console. System.err is also
a PrintStream andSystem.in is
an InputStream. When the Java runtime
system starts up it automatically hooks-up
these object references to the host system's
output, error and input streams.
The PrintStream and InputStream types
used to interface with the host system are
not subclasses of the System class, they are
a subclasses of
the java.io.OutputStream andInputStream h
ierarchy. Notably the PrintStream class
never throws IOException, though you can
use the checkError() method to discover
any problems.
The common technique of making print calls
with System.out.println() gives the
impression that println() may be a method
of the System class but it is not, it is a
method of thePrintStream class.

Q: How do I find the size of an object in Java?


A: There is no direct management of the
storage size of code that is held in memory
by the Java Virtual Machine (JVM). The
virtual machine manages the allocation and
de-allocation of storage through an integral

181

garbage collection system. The JVM keeps


track of all object references and
periodically disposes of de-referenced
objects to free memory.
It is possible to check the overall memory
use of a Java application with methods in
thejava.lang.Runtime class.
The freeMemory() method returns the spare
memory available to the runtime system,
the totalMemory() method reports the total
memory allocated to the virtual machine, so
you can deduce the memory in use, as
below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How do I find the size of an object in Java?

Q: How can I copy process information from Windows task


manager?

A: Getting information from Windows


system applications relies on the programs
having command line interfaces that a Java
program can read from. Windows Task
Manager program does not seem to support
command line arguments to interrogate
running processes, nor standard output, so
you may need to interface with a different
program to get the information you seek.
The example below uses the
Java ProcessBuilder class to create
a Process that opens the Task Manager
graphical user interface application. The

182

same approach can be used to run other


system tools or installed applications,
provided you know the path to the
executable program and can supply any
appropriate arguments.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I copy process information from Windows
task manager?

Java exceptions

Q: What's the difference between checked and un-checked exceptions?


A: A Java checked exception represents a
problematic case that can be anticipated
when one instantiates an object or calls a
method. A typical example is when you
attempt to create a file or open a URL
connection, which may fail for many
reasons. Checked exceptions must be
declared in the throws statement of a
method header, and any class that calls the
method must ensure that it handles all
checked exceptions that may occur.
full answer hidden, click for
complete answers
Premium members click below for full answer
What's the difference between checked and unchecked exceptions?

Q: What is a NullPointerException in Java?


183

A: A NullPointerException is a runtime
exception that indicates the Java Virtual
Machine attempted to call a method on an
object, but the object reference was null.
This case may occur when a reference is
assigned from another method call that may
return a null value, such as
aHashtable look-up.
full answer hidden, click for
complete answers
Premium members click below for full answer
What is a NullPointerException in Java?

Q: What's the best way to handle a NullPointerException?


A: The best way to handle
a NullPointerException is to prevent one
being thrown to begin with.
A NullPointerException happens when
a null value is assigned to an object type
variable, then a method is called on that
variable. The variable is expected to hold a
pointer or reference to an object, but
actually holds a null value, hence null
pointer.
This type of exception can also happen
when you try to get or set a field on
a null object reference, operate on the
reference as if it was an array, or throw it as
if it was an exception.
A NullPointerException is a runtime
exception that you should not try to catch.
Avoid the exception by checking the value
before a call, as in the example below with

184

theSystem.getProperty(String) method.
The getProperty() method is expected to
return aString value for a given system
property, or null if the property does not
exist.
full answer hidden, click for
complete answers
Premium members click below for full answer
What's the best way to handle
a NullPointerException?

Q: Can you give an example of catching an exception?


A: One common example of catching an
exception is when you try to read from a file
that may not exist. You may enter a file
name as the first argument on the
command line, for example:
full answer hidden, click for
complete answers
Premium members click below for full answer
Can you give an example of catching an exception?

Q: How can I throw a NumberFormatException back to


the main() method?

A: NumberFormatException is an unchecked exception. That means that the


compiler will not enforce that your
application catches the exception and
handles the case. For example, users may
enter an invalid number at runtime and the
application would throw an exception and
crash.

185

If you want to handle runtime exceptions it


is important to handle them in the methods
in which they may occur. The callers of such
methods cannot be expected to know that
they would throw a runtime exception and
handle them. Your methods should include
validation and handling for specific,
anticipated runtime exceptions.
If you want to signal a problem that cannot
be handled locally by your method, you
should catch the runtime exception and
throw a checked exception, as below. This is
a typical case for creating your own
checked exception type, though rather
heavyweight for this simple example.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I throw a NumberFormatException back to
the main() method?

Class loading

Q: How can I get a class reference without using new operator?


A: There are two questions here, first why
would you want to get a class reference
without using the new operator? Often this
is the case when you need to load a class at
runtime, but you do not know in advance
what class it is. In this case, you might
configure the class name in a properties file
and load it using the

186

static Class.forName(String) method, as


below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I get a class reference without
using new operator?

Q: What's the difference between the Class.forName() method and


the new operator?

A: The Class.forName() method is


different from invoking the new operator for
a class because it does not return an
instance of the class.
The forName() method initialises a class
and returns aClass object.
full answer hidden, click for
complete answers
Premium members click below for full answer
What's the difference between
the Class.forName() method and the new operator?

Q: What is the return type for the Class.forName(String) method?


A: The return type for the
static Class.forName(String) method is
a Class object reference for the class
named in the string argument. This is not
the same as an instance of the class itself.
You must use the newInstance() method on
the class reference to obtain an instance of
the named class. You can also create an
instance indirectly by obtaining
a Constructor reference from the class and
call its newInstance(Object[]) method.

187

Q: How can I implement the Class.forName() scheme?


A: To use this method of class loading, the
dynamically loaded class only requires a
default constructor, with no arguments, and
be a known type. Once the class is loaded,
then use
theClass object's newInstance() method to
get a new object reference for the class. You
must also handle a number of exceptions
that may be thrown if the class is not found,
cannot be loaded, etc. The example below
expects to load a class that implements
the Shape interface and has a default
constructor.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I implement the Class.forName() scheme?

Q: How can I cast an unknown sub-class returned by newInstance()?

A: When you want to instantiate one of


several possible sub-classes at runtime it is
best to create an interface type that defines
the common behaviour of those classes. For
instance, you might define
a Processor interface with one common
method, as shown below.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I cast an unknown sub-class returned
by newInstance()?

188

Q: Is Class.forName() runtime polymorphism?

A: The Class.forName() scheme is

an application of polymorphism that is


applied at runtime, so can be regarded as
an example of runtime polymorphism.
However the Class.forName()scheme has to
be designed into an application in advance,
the polymorphic aspect is not createdat
runtime, it is only expressed at runtime.
full answer hidden, click for
complete answers
Premium members click below for full answer
Is Class.forName() runtime polymorphism?

Java Abstract Window Toolkit classes

Q: How do I draw a Rectangle on a Graphics instance?


A: When you have a method that takes an
object as an argument, you must pass an
object of the specified type in the method
call. There is no Graphics method that
accepts a Rectangle to draw, nor
a Rectangle method that accepts
a Graphics object to render to.
Since Graphics is an abstract class, you
must obtain a concrete implementation. You
can then use its drawRect(int x, int y, int
width, int height) method to draw an outline
of your rectangle, as below.
full answer hidden, click for
complete answers

189

Premium members click below for full answer


How do I draw a Rectangle on a Graphics instance?

Q: What is the difference between heavyweight and lightweight


components?

A: Java Graphical User Interface (GUI)


components are called heavyweight when
they rely on components from the
underlying operating system to be
displayed. This is because these native
peers have a relatively heavy processing
demand to render on screen and maintain
their state representation. Thus applications
composed of many heavyweight
components can become slow to render on
screen.
full answer hidden, click for
complete answers

Java Web clients

How can I download a Web page and write it to a file?

My Java Web client gets the wrong site!

How can I set a code name identifier for my feed reader?

Java networking API

How do I get the domain name from a URL?

How do I get the registered domain name from a URL?

How do I get a domain name from an IP address?

Java Web clients

Q: How can I download a Web page and write it to a file?


A: The standard Java input/output and
network APIs make it quite easy to acquire

190

content from the Internet and write files.


Writing from a stream input to a file output
is the slightly complex part. The example
below uses a copy(InputStream,
OutputStream) method adapted from a
version in Java I/O by Elliotte Rusty Harold.
full answer hidden, click for
complete answers
Premium members click below for full answer
How can I download a Web page and write it to a
file?

Q: My Java Web client gets the wrong site!


A: Many Web sites use virtual hosting,
which requires you send
an HTTP Host header with your request.
full answer hidden, click for
complete answers
Premium members click below for full answer
My Java Web client gets the wrong site!

Q: How can I set a code name identifier for my feed reader?


A: Your application should pass a UserAgent header in the HTTP request with the
code name of your application as the
header value. Web browser user agents
often include the full version and build
number for the application and the software
platform it was built for. Feed readers tend
to use simpler name and version number
combination. See the Java example below.
full answer hidden, click for
complete answers

191

Premium members click below for full answer


How can I set a code name identifier for my feed
reader?

Java networking API

Q: How do I get the domain name from a URL?


A: If you want to extract a domain name
from an existing URL object, use the
URL's getHost()method.

String urlString =
"http://www.test.example/path/page.htm";

URL url = new URL(urlString);

String domain = url.getHost();

Q: How do I get the registered domain name from a URL?


A: The URL getHost() method returns the
fully qualified domain name (FQDN). To get
the registered domain name you would
need to break the FQDN further to remove
any subdomains. The example below uses
the String lastIndexOf() method to get the
index of the dot separators
and substring() to
extract codestyle.org from www.codestyle.o
rg.

192

full answer hidden, click for


complete answers
Premium members click below for full answer
How do I get the registered domain name from a
URL?

Q: How do I get a domain name from an IP address?


A: It is possible to do a reverse name lookup for an IP address using
thejava.net.InetAddress class. The example
below first gets an instance of the class
using the static getByName(String) method,
then applies the getHostName() method to
it. The method will only resolve a domain
name if there is one configured for the host,
otherwise the method returns the original IP
address.
full answer hidden, click for
complete answers

Read and write files

How can I divert console output to a file?

How can I generate an array from a list?

File system navigation

How can I get the full path of Explorer.exe?

How can I get the path to an installed program?

How do I limit the scope of a file chooser?

Is it possible to convert a string to an abstract file path?

Input and output streams

Why are streams used in Java?

What does "broken pipe" mean?

Is it best to customise state with Serializable or Externalizable?

193

Read and write files

Q: How can I divert console output to a file?


A: The java.lang.System class holds a
static reference to the console output
stream in itsSystem.out field, which is an
instance of java.io.PrintStream.
TheSystem.setOut(PrintStream) method
allows you to assign a different output to
the reference. In this case you can construct
a PrintStream from a FileOutputStream, as
below.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I divert console output to a file?

Q: How can I generate an array from a list?


A: The answer to your question would
depend on the format of the list, which is
perhaps stored in a file? If there is a
consistent character pattern that separates
the list items, you might use
aStringTokenizer to capture them. The
example below creates
a BufferedReader from aFileReader and
uses the readLine() method to acquire the
data.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I generate an array from a list?

194

File system navigation

Q: How can I get the full path of Explorer.exe?


A: Firstly, you cannot generally obtain this
reference from an applet loaded via the
Internet because the Java sandbox will not
permit this type of system access.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I get the full path of Explorer.exe?

Q: How can I get the path to an installed program?


A: You can check for programs added to
the host system's path environment
variable through
thejava.lang.System class' getenv() method
, or getenv(String), provided the application
has the necessary security permission.
The getenv() method returns a map of all
environment variables in the current user
session, getenv(String) returns
the String value of the variable named by
the argument, if it exists. You can extract all
the paths in the path environment variable
using a StringTokenizer using the system
specific path separator as the delimiter, as
below.
full answer hidden, click here for all
answers
Premium members click below for full answer
How can I get the path to an installed program?

195

Q: How do I limit the scope of a file chooser?


A: The general mechanism for limiting file
selection is to use a FileFilter. You could
write a custom filter that only accepts files
in a specified directory for instance. This
would not stop users from browsing the file
system, but would ensure that no other files
could be selected.
full answer hidden, click here for all
answers
Premium members click below for full answer
How do I limit the scope of a file chooser?

Q: Is it possible to convert a string to an abstract file path?


A: The java.io.File class has various
methods for creating abstract file paths,
which can then be created on the file
system or used to test whether the actual
file paths exist. The simple
constructor File(String) takes an argument
that is a complete abstract path name. In
theFile(File, String) constructor,
the File argument is a parent directory
reference and theString is a path name
under that directory. See the Java
Development Kit Application Programming
Interface (API) documentation for further
details about listing, creating, testing,
comparing, deleting and setting the
properties of files.

Input and output streams


196

Q: Why are streams used in Java?


A: In Java streams are used to process
input and output data as a sequence of
bytes, which does not assume a specific
character content or encoding. Byte content
can be read from network sources, files and
other sources, and bytes copied between
multiple inputs and outputs.
Streams types can be sub-classed to add
filtering, to mark a point in the stream and
re-read those bytes, or to skip a number of
bytes. Streams also enable serlializable
objects to stored and re-constructed
using ObjectInputStream and ObjectOutput
Stream types.

Q: What does "broken pipe" mean?


A: A pipe is an input/output link between
two programs, commonly where you use the
output from one program as the input for
another program. A broken pipe means that
the linkage between the output and input is
interrupted, the reasons vary. For example,
the feeder program may throw an error and
terminate unexpectedly, intermediate
source or output files may not be created
successfully, or key resources become
unavailable during the process. You may
also get problems with the amount of swap
file storage or overall memory usage
approaches its limits.

Q: Is it best to customise state with Serializable or Externalizable?


197

A: When a class is the marked


as Serializable it signifies that it is suitable
for object serialization using the builtin ObjectOutputStream writeObject(Object)
method without modification. It is the
programmer's responsibility to ensure this is
the case and that it can be restored by the
inverse readObject(Object) method.
Default object serialization methods have a
great advantage because they take care of
the whole process without special
programming. The state of superclass fields
are automatically discovered and
incorporated in serial data streams using
reflection, which can affect performance but
is normally a great convenience.
If a Serializable class requires special
measures to properly save and restore its
internal state, it should define special
read/write methods, as below.
full answer hidden, click here for all
answers

Storage structures

What is the first argument in the Hashtable put() method?

What is the difference between Hashtable and HashMap?

How do I get the keys from a Map?

Why is Vector a legacy class?

Working with dates and calendars

How do I insert slashes in a date?

How can I convert a String into a Date object?

How can I get the difference between two dates in days?

Why isn't my custom Calendar class called?

198

Why do we use Calendar.getInstance()?

Storage structures

Q: What is the first argument in the Hashtable put() method?


A: You should download the Java API
documentation, which details all standard
classes and their method parameters. The
first parameter in a Hashtable's put method
is the key by which the value in the second
argument will be stored.
To retrieve the stored value, use
the get(Object) method, where the object
parameter is a reference to the key.

Q: What is the difference between Hashtable and HashMap?


A: In Java 2 Hashtable fulfills
the Map interface like HashMap. The main
difference
betweenHashtable and HashMap is
that HashMap is not synchronized and
allows a null key to be used and null values
to be stored.
full answer hidden, click to get full
answers
Premium members click below for full answer
What is the difference
between Hashtable and HashMap?

Q: How do I get the keys from a Map?


A: To get the keys in a map rather than
the values, use the keySet() method, which
returns ajava.util.Set object that contains all

199

the keys. You can then get an Iterator from


the key set, or process the keys using
other Set methods.

Q: Why is Vector a legacy class?


A: Vector is a legacy class that was
adapted in Java Software Development Kit
version 1.2 to integrate it with the more
contemporary collections
framework. Vector now implements
theCollection interface.

Working with dates and calendars

Q: How do I insert slashes in a date?


A: To format Date types in Java, you

should use a java.text.SimpleDateFormat.


This class takes a time pattern string and
applies it to the given date like a template.
To create a date with slashes, you might use
the pattern "dd/MM/YYYY" for instance.
full answer hidden, click to get full
answers
Premium members click below for full answer
How do I insert slashes in a date?

Q: How can I convert a String into a Date object?


A: The recommended way to parse
a String representation of a date to
a Date object is to use
the java.text.SimpleDateFormat class parse
(String) method. In its simplest form, the
class is instantiated with a String pattern

200

argument that defines the general syntax of


the date to be parsed. In the example
below, the World Wide Web Consortium
(W3C) date time format for year, month and
day is represented by the pattern yyyy-MMdd and is used to parse the date
string2008-09-20.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I convert a String into a Date object?

Q: How can I get the difference between two dates in days?


A: To compare dates by day, deduct the
millisecond time of the earlier date from the
later one and divide the result by the
number of milliseconds in a day. This
method checks the dates are not the same
and uses the after(Date) method to check
the deduction is the right way round. For
finer comparisons by hour or minute, it is
important to check any possible timezone
offset too.
full answer hidden, click to get full
answers
Premium members click below for full answer
How can I get the difference between two dates in
days?

Q: Why isn't my custom Calendar class called?


A: If you have a broad import statement
like import java.util.*;, the Java Virtual
Machine will adopt the standard distribution

201

version of any named class, such


as java.util.Calendar. You should limit the
scope of your import statements and use
the fully qualified name of the
customCalendar class.
full answer hidden, click to get full
answers
Premium members click below for full answer
Why isn't my custom Calendar class called?

Q: Why do we use Calendar.getInstance()?

A: The Calendar class is abstract and


instances must be obtained from the
staticgetInstance() method so that they are
created with an appropriate locale.
Calendars must be created with a
specific Locale reference to take account of
regional time zones and any seasonal
daylight saving changes when getting
dates, including AM or PM values and time
relative to Greenwich Meantime (GMT).

Compiler concepts

What is the source code for the compiler?

Why is the source file named after the class?

Which class should be compiled first?

Compiler commands

What are the steps in compiling a class?

What do I type at the command line to compile Hello.java?

Where is my compiled class file?

How can I compile Java classes with packages on the command line?

How can I ensure my compiler will locate the SAX package?

Compiler diagnostics
202

I get javac not recognised!

I get cannot find symbol, what's wrong?

What does this deprecation message mean?

What are undefined and undeclared variables?

Why doesn't the compiler warn about stack overflow problems?

Development environment

What Java compilers are there?

How do I set the compiler path?

The DOS command cd doesn't go to the Java directory!

How do I set environment variables on Windows XP?

How do I configure EditPlus to compile Java and capture output?

Compiler concepts

Q: What is the source code for the compiler?


A: The source code for a Java program is
also known as a compilation unit, which
contains the code for a top level Java class
or interface. A Java compilation unit is
usually created in the form of a file with
a .java extension and is passed to the
compiler as a file path reference.
The Java source file contains a header that
declares the type of class or interface, its
"visibility" with respect to other classes, its
name and any superclass it may extend, or
interface it implements. The body of the
class contains variable declarations and
methods that define the behaviour of the
class, and any constructors used to create
an instance of the class. A compilation unit
may also contain nested inner classes.

203

Q: Why is the source file named after the class?


A: The Java source file naming convention
is not a standard specified by the Java
language but is a common feature of Java
compilers, such as javac, to help locate
source code. The source content of a Java
class is known as a compilation unit. By
storing the compilation unit in a file that is
named after the class, the compiler can
locate any supporting classes by name and
compile those too.
This convention also extends to package
names. Most Java compilers expect source
code to be stored in directories whose
names match their package hierarchy. Thus
the source code for a class
named Example in the
package com.domain.util might be stored in
a file with the
pathc:\src\com\domain\util\Example.java

Q: Which class should be compiled first?


A: Sometimes you will find that trial and
error will give you the answer you need. If
you are using the Sun compiler, javac, the
compiler will compile any other classes that
your target class depends on, provided the
other source files are in the same directory
hierarchy as the first and the sub-directory
names reflect the package hierarchy of the
classes.
full answer hidden, click for full
answers

204

Premium members click below for full answer


Which class should be compiled first?

Compiler commands

Q: What are the steps in compiling a class?


A: Once you have written the Java source
code file, there is only one step required to
compile it. To compile the class from the
command line, you need to give the path to
the compiler program, such as Sun javac,
and the path of the source code file, like
this:
full answer hidden, click for full
answers
Premium members click below for full answer
What are the steps in compiling a class?

Q: What do I type at the command line to compile Hello.java?


A: In the simplest case, type cmd in the
Windows Run dialogue (on
the Start menu) and change to the source
directory then run the javac command, as
below.
full answer hidden, click for full
answers
Premium members click below for full answer
What do I type at the command line to
compile Hello.java?

Q: Where is my compiled class file?

205

A: If you are sure your class is being


compiled, then the class file should be
output somewhere! Without any directory
argument, your compiler should place the
class file in the same directory as your
source file. Use the output directory
argument to specify where the class files
are generated, as below.
full answer hidden, click for full
answers
Premium members click below for full answer
Where is my compiled class file?

Q: How can I compile Java classes with packages on the command


line?

A: When you plan to compile Java classes


into a package hierarchy it is best to
organise your Java source files in a folder
hierarchy that matches your packages and
use the compiler's -classpathor cp argument and output directory
parameter -d to keep the class file output
organised in a separate equivalent
structure.
package one;
public class ExamplePackageOne {
public static void main(String[] args) {
System.println.out("Example output");
}
}
package two;

206

public class ExamplePackageTwo {


// Empty
}

Add the -d command before the Java source


file reference, followed by the path for the
output folder, and the -cp command
followed by the common root directory for
your source files. The examples below are
split over several lines for clarity, it may
help to put the commands in a batch script
to experiment with.
full answer hidden, click for full
answers
Premium members click below for full answer
How can I compile Java classes with packages on
the command line?

Q: How can I ensure my compiler will locate the SAX package?

A: One way to ensure your compiler can


locate any package it may require is to
pass its path to the compiler explicitly using
the -classpath argument, see the exmaple
below.
full answer hidden, click for full
answers
Premium members click below for full answer
How can I ensure my compiler will locate
the SAX package?

Compiler diagnostics
207

Q: I get javac not recognised!


A: This error means that the Windows
command shell cannot find the path to your
Java Software Development Kit installation
where the javac program is installed. One
way to solve this is to add
the javac program to the system
environment variable named PATH. You can
also give the full path to the javac program
in the Windows shell, e.g.

c:\JavaSDK\bin\javac
c:\projects\java\MyClass.java

To add to your PATH variable, open


the System Properties applet in the
Windows Control Panel, click
the Advanced tab, then the Environment
Variables button. In the System
Variables list select the PATH variable and
then the Edit button. Type a semicolon
separator followed by the path to
your javac program then click OK to save
the changes and back-out. Now you should
be able to use the javac program without
specifying its path.

javac c:\projects\java\MyClass.java

208

Q: I get cannot find symbol, what's wrong?


A: There is nothing wrong with the Java
source you have given. Provided the two
Java source files are in the same folder and
it is the current working folder, when you
compile the HelloApp.javaclass the Java
compiler should find the source of
the Hello.java class and compile it too.
The cannot find symbol error suggests
that your Java source folder is not the
current working folder, or you have given
a -classpath argument that does not match
the source folder. The first case is the most
likely. For example, if your source files are
at C:\Documents and Settings\Test and your
command prompt is C:\> the implicit
classpath is the root folder of theC: drive.
This is where the compiler will look for any
supporting classes and won't find them
there.
To solve this problem add an explicit
classpath argument for your test folder,
split over two lines below for clarity. Enclose
file paths with spaces in quotes.
C:\> javac -cp "C:\Documents and
Settings\Test"
"C:\Documents and
Settings\Test\HelloApp.java"

Q: What does this deprecation message mean?


A: The deprecation message you have
seen means that the methods you are

209

calling have been marked with a JavaDoc


deprecation comment. When a method or
class is marked @deprecated it is only
advisory, not mandatory, but the advice is
given for good reason and should be
followed. So long as deprecated methods
remain in the public API it is possible to use
them, so this approach supports legacy
code and gives developers time to amend
their applications as necessary.
full answer hidden, click for full
answers
Premium members click below for full answer
What does this deprecation message mean?

Q: What are undefined and undeclared variables?


A: One gets warning messages about
undefined and undeclared variables when
compiling Java classes that have
programming errors, as in the example
below.
full answer hidden, click for full
answers
Premium members click below for full answer
What are undefined and undeclared variables?

Q: Why doesn't the compiler warn about stack overflow problems?

A: There are many cases of poor runtime


programming that could potentially be
identified at compile time, but the number

and subtlety of the cases gets increasingly


difficult to address. The main purpose of a
compiler is to produce executable byte code

210

that is valid according to the rules of the


programming language, not to guard
against poor programming. Hence most
compilers only validate the syntax of the
language and the most obvious logical
errors in the code at compile time.

Development environment

Q: What Java compilers are there?


A: There are many Java compiler
implementations. The one most developers
start with is that provided with the Sun Java
Software Development Kit (JSDK),
named javac. Alternative implementations
include the free open source GNU Compiler
for Java (GCJ) and the Eclipse Compiler for
Java, which is part of the Eclipse integrated
development environment (IDE).

Q: How do I set the compiler path?


A: The Java compiler is a program like any
other and your operating system needs to
know where to find the executable file. The
simplest way to do this is to give the full
path to the Java compiler in the command,
as below for Windows...
full answer hidden, click for full
answers
Premium members click below for full answer
How do I set the compiler path?

Q: The DOS command cd doesn't go to the Java directory!


211

A: The Windows command line


program cd is to change directory, the
present working directory for subsequent
commands, and requires a space between
program name cd and the directory path
you want. The examples below show three
main ways to change directory starting from
the root of the C: drive.
REM Change to the root of the C: drive
c:
cd \
REM Relative path with leading slash
cd \jdk1.5\bin
REM Return to root of C:
cd \
REM Relative path, no leading slash
cd jdk1.5\bin
REM Return to root of C:
cd \
REM Absolute path
cd c:\jdk1.5\bin

Q: How do I set environment variables on Windows XP?


A: For Windows 2000/XP systems, the
environment settings are edited in a
special Control Panelapplet
called System.
full answer hidden, click for full
answers
Premium members click below for full answer
How do I set environment variables on Windows XP?

Q: How do I configure EditPlus to compile Java and capture output?


212

A: These instructions on configuring


the NSGMLS markup validator for
EditPlus will help you get started. For Java,
the Command field will be the path to
your javac.exe program (or java.exe to
run). The Argument should contain any
parameters you want to pass to the
compiler and should end with the $
(FilePath) variable that substitutes the
current file name. Check the Capture
output box to get feedback from the
compiler.
full answer hidden, click for full
answers

The final modifier

How can I prevent inheritance without marking a class final?

What's the difference in using a final keyword and an abstract class?

Java visibility modifiers

I assume inherited fields and members are non-private, are they?

What is the protected modifier for?

So protected methods don't have to call super?

What visibility modifiers can I use to override a protected method?

Can constructors have visibility modifiers?

How should I use visibility modifiers with interfaces?

Which modifiers can I combine with the abstract keyword?

The static modifier

How does the static modifier apply to the main() method?

How do I work with static variables and methods?

Thread programming modifiers

How do the synchronized and volatile modifiers work?

The final modifier


213

Q: How can I prevent inheritance without marking a class final?


A: Declaring a class final is the simplest
way to prevent extension. A more limited
way to control overrides without preventing
extension is to declare individual
methods final. If all methods are declared
final but not the class, the class may be
extended but none of its methods
overridden.

Q: What's the difference in using a final keyword and an abstract class?


A: The final keyword is a modifier that can
be applied to classes, methods and
variables to control how they are used in a
Java program. Final classes cannot be
extended, final methods cannot be
overridden, final variables can only have a
value assigned once and not modified. For
example, if you declare a method argument
as final, the object reference passed into
the method cannot be assigned a different
reference. A final method implementation
cannot be changed by subclasses.

public final void doSomething(final Object


argument) {

// Not possible with a final argument


// argument = new Object();

// OK

214

System.out.println(argument.toString());

// Also OK
try {
Object clone = argument.clone();
}
catch (CloneNotSupportedException cnse)
{

// Handle exception
}
}

An abstract class may be used to define a


core set of methods for use by subclasses,
and may also define abstract methods that
act like a template for subclasses to
implement. Abstract classes often represent
a concept in a program that isn't a
meaningful thing in its own right. For
example, the concept of a "pedal vehicle
with wheels" might be represented by
an AbstractCycle class with
concrete crank() and changeGear(int) meth
ods. It might also have an abstract Wheel[]
getWheels() method that
subclasses MonoCycle, BiCycle and TriCycle
would implement by returning the
appropriate number of wheels in the array.

215

Java visibility modifiers

Q: I assume inherited fields and members are non-private, are they?


A: The Java visibility modifiers are firstly
concerned with which classes can access
the variables and methods, and secondly
with inheritance. If a field or method is
marked public or protectedit will be
accessible in sub-classes too. If it has no
explicit visibility modifier, it has
implicitpackage visibility status, which is
accessible to sub-classes in the same
package, but not to sub-classes in a
different package.
The private visibility keyword means only
accessible from the host class, so will not be
accessible in any subclass.
The public means any class can read a
variable or call a method.

Q: What is the protected modifier for?


A: The Java visibility modifiers are
concerned with data hiding and
encapsulation, they control which classes
and sub-classes can read and write variable
values and call methods.
Theprotected visibility modifier means that
the field or method is accessible from within
the host class itself, and internally to other
classes in the same package and subclasses
that may be in a different package.
Protected fields cannot be accessed through
the public API of a class.

216

The protected modifier is usually used to


develop the features of an inheritance
hierarchy by sharing access to common
variables and methods with subclasses. It
offers greater scope for extension
than package visibility without creating a
public API.

Q: So protected methods don't have to call super?


A: The use of the protected modifier on a
superclass method means that any subclass
can call that method on the superclass
through itself. Such calls are made with an
implied "this" reference with the same
syntax as a call to one of their own instance
methods, they do not require an
explicit super. prefix.

int example = protectedGetInt();

In this respect protected method


inheritance is the same as public method
inheritance, but theprotected modifier
means that the method is not part of the
class' public API; other classes cannot call
the method on an instance of the class.
Typically another class may call a public
method that internally calls the protected
method to complete the request.

Q: What visibility modifiers can I use to override a protected method?

217

A: With this type of question it is often


easiest to create a minimal test case and
attempt to compile it. In this case you will
find that the compiler will fail and issue a
warning if you attempt to assign "weaker"
access privileges to the overridden methods
using private or implicit package private
modifiers. The term weaker is slightly
misleading in this context; it means that the
private and package access modifiers are
more restrictive than the parent classes'
method, which is not permitted. In short,
only protected or public visibility modifiers
can be used to override protected methods.

Q: Can constructors have visibility modifiers?

A: Yes, Java class constructors are


assigned access modifiers. If none is
explicitly declared, the constructor will
implicitly have package visibility, which
means it is accessible by the class itself and
other classes in the same package only.
Constructors may also be
assigned private,protected or public access.
The choice of constructor visibility modifiers
will depend on the nature of your
application, but the notes below give some
broad principles in each case.
full answer hidden, click for
complete answers

218

Vous aimerez peut-être aussi