Java Programming
Java Programming
Published by:
Global Media
1819, Bhagirath Palace,
Chandni Chowk, Delhi-110 006
Email: globalmedia@dkpd.com
Table of Contents
1. Introduction
2. History
5. Installation
6. Compilation
7. Execution
10. Syntax
11. Statements
13. Packages
16. Methods
18. Java.Lang.String
19. Arrays
24. Types
Java Overview
The Java Platform
Java Programming Environment
Getting Started
This section is a quick start to using Java: installing Java software, compiling and running
programs, and some small sample programs to illustrate the basics of getting started with Java.
Language Fundamentals
This section introduces the fundamental elements of the Java programming language.
Syntax
Keywords
Statements
Classes and objects and types
Packages
Nested classes
Nesting classes inside another class
Nesting classes inside a method
Add additional classes to a Java source file
Anonymous classes
Access modifiers
Methods
Primitive types
Types
String
Arrays
Data and variables
Generics
Classes and Objects
Defining classes
Creating objects
Interfaces
Using static members
Destroying objects
Overloading methods and constructors
Collections
Introduction
Arrays
Collection Classes
Collection or Map
Collection
Map
Set or List or Queue
Set
List
Queue
Map Classes
Thread Safe Collections
Classes Diagram (UML)
Exceptions
Throwing and catching exceptions
Handling exceptions
Application exceptions
Runtime exceptions
NullPointerException
Main Exception classes
Checked exceptions
Unchecked exceptions
Preventing NullPointerException
1. REDIRECT Template:Java Programming:Concurrent Programming
Template:Streams
Reflection
Reflection Overview
Dynamic Class Loading
Dynamic Method Invocation
Accessing Private Features with Reflection
Applets
Overview
User Interface
Applying styles and adding content
Font
Button
Label
TextField
Layout
Panel
Event Listeners
ActionListener
MouseListener
MouseMotionListener
Analyzing User Input
Graphics and Media
Drawing
Painting
Sound
HTML Implementation
JavaBeans
Introduction to JavaBeans
There are some useful templates which aid in creating content for the book, especially in code
samples. The book prefix “Java” is a redirect to “Java Programming”, so we also use “Java” as a
prefix for some templates (following the templates defined for Ada):
{{Java://|comment}}
For // comments in a code block. Sample use: {{Java://|Check for a null value}}
yields // Check for a null value
{{Java:kw|keyword}}
For marking a Java keyword. This will also create a link to the keyword’s page in the
book. Sample use: {{Java:kw|for}} yields for
{{Java:int}}
Use for the int keyword. Each Java keyword has a corresponding Java: template; see
Keywords.
{{Java:string|string content}}
For marking a Java String literal. The Java:String template adds the opening and
closing double quote for you. This is purely a formating template and does not create
any links. Sample use: {{Java:string|Cafe, Babe}} yields “Cafe Babe”. Don’t
confuse with {{Java:String}} below.
{{Java:null}}
Use for the null literal.
{{Java:true}}
Use for the Boolean literal true.
{{Java:false}}
Use for the Boolean literal false.
{{Java:npe}}
Use for referring to NullPointerException.
{{Java:Object}}
Use for referring to Object (the page for java.lang.Object)
{{Java:jlObject}}
Use for referring to java.lang.Object (two links: one for java.lang and one for
java.lang.Object)
{{Java:Class}}
Use for referring to Class (the page for java.lang.Class)
{{Java:jlClass}}
Use for referring to java.lang.Class (two links: one for java.lang and one for
java.lang.Class)
{{Java:String}}
Use for referring to String (the page for java.lang.String). Don’t confuse with
{{Java:string|string content}} above.
{{Java:jlString}}
Use for referring to java.lang.String (two links: one for java.lang and one for
java.lang.String)
{{Java:pkg|package}}
Use to link to the category for a Java package. For example, {{Java:pkg|java.util}}
links to java.util
{{Java:pkgcat|package}}
Use to put a page in the category for a Java package. For example, use
{{Java:pkgcat|java.util}} on a page to add it to the category, Category:java.util
{{Java:api|package-name|class-name}}
Use this to link to a page which describes one of the classes documented in this book.
The above {{Java:Object}} and similar templates are implemented with this template.
The first parameter is the package name; the second is the class name. Sample use:
{{Java:api|java.io|IOException}} yields IOException
{{Java:qapi|package-name|class-name}}
Use this for qualified package names which create two links: one to a category for the
Java package, and one to a page which describes the class. The above
java.lang.Object and similar templates are implemented with this template. The
first parameter is the package name; the second is the class name. Sample use:
{{Java:qapi|java.io|IOException}} yields java.io.IOException
Innovative help
Points to ponder
Common mistakes and
For your information
Please add your name here if you have contributed to Java Programming
djb
Ervinn
rappo
Malfist
deva
Arun Reginald
History
The Java programming language was created by James Gosling and other engineers at Sun
Microsystems. It was developed in 1991, as part of the Green Project, and officially announced
on May 23, 1995, at SunWorld; being released in November. Java was initially designed as a
replacement to C++ (although the feature set is more similiar to Objective C) and known as Oak
(in honour of a tree outside Gosling’s office); however, Oak was previously copyrighted. More on
the history of Java can be found in the article about the Java platform, which includes the
language, the Java virtual machine, and the Java API. Java is owned by Sun Microsystems; the
term Java is a trademark of Sun Microsystems.
Versions
The Java platform is the name for a computing environment, or platform, from Sun
Microsystems which can run applications developed using the Java programming language and
set of development tools. In this case, the platform is not a specific hardware or operating system,
but rather an execution engine called a virtual machine, and a set of standard libraries which
provide common functionality.
The platform is properly called the Java 2 Platform (although the “2” is to be dropped ), and
includes a Standard Edition or J2SE (now Java SE), an Enterprise Edition or J2EE (now Java
EE), and a Micro Edition or J2ME (now Java ME). The current version of the Java 2 platform is
alternatively specified as version 1.5 or version 5 (both refer to the same version). A good
overview of the myriad of technologies that makes up the Java 2 Platform can be found on the
JDK Documentation Page.
Java technologies
The Java platform consists of a wide array of technologies, each of which provides a distinct
portion of the overall development or runtime environment. For example, end-users typically
interface with the Java virtual machine and the standard set of class libraries. In addition, there
are numerous ways for Java applications to be deployed, including being embedded into a web
page. Lastly, developers who are creating applications for the platform use a set of development
tools called the Java Development Kit.
The heart of the Java platform is the concept of a common “virtual” processor that executes Java
bytecode programs. This bytecode is the same no matter what hardware or operating system the
program is running under. The Java platform provides an interpreter called the Java virtual
machine (JVM), which translates the Java bytecode into native processor instructions at run-time.
This permits the same application to be run on any platform that has a virtual machine available.
Since JRE version 1.2, Sun’s JVM implementation has also included a just-in-time compiler.
Instead of interpreting the bytecode one instruction at a time, this converts the bytecode for a
program into equivalent native machine code as the program is loaded into the virtual machine,
causing it to execute much faster at the cost of a small delay whenever new bytecode is loaded.
This allows the JIT compiler to target a specific host platform and hardware, even potentially
optimizing the output code in different ways based on observations of the program’s behaviour.
This is not to say that one can truly compile Java code to its fullest extent (in order to reap the
benefits of speedy native machine code). Yes, there are “compilers” available that will attempt
this feat, but not all Java libraries have a machine code equivalent. For instance, the “reflect”
library, which allows Java programmers to delve into instructions only available at runtime, is not
well represented (if at all) by machine code.
Java was not the first virtual-machine-based platform, though it is by far the most successful and
well-known. Previous uses for virtual machine technology primarily involved emulators to aid
development for not-yet-developed hardware or operating systems, but the JVM was designed to
be implemented entirely in software, while making it easy to efficiently port an implementation to
hardware of all kinds.
Class libraries
In most modern operating systems, a large body of reusable code is provided to simplify the
programmer’s job. This code is typically provided as a set of dynamically loadable libraries that
applications can call at runtime. Because the Java platform is not dependent on any specific
operating system, applications cannot rely on any of the existing libraries. Instead, the Java
platform provides a comprehensive set of standard class libraries, containing much of the same
reusable functions commonly found in modern operating systems.
The Java class libraries serve three purposes within the Java platform. Like other standard code
libraries, they provide the programmer with a well-known set of functions to perform common
tasks, such as maintaining lists of items or performing complex string parsing. In addition, the
class libraries provide an abstract interface to tasks that would normally depend heavily on the
hardware and operating system. Tasks such as network access and file access are often heavily
dependent on the native capabilities of the platform. The Java java.net and java.io libraries
implement the required native code internally, then provide a standard interface for the Java
applications to perform those tasks. Finally, some underlying platforms may not support all of the
features a Java application expects. In these cases, the class libraries can either emulate those
features using whatever is available, or provide a consistent way to check for the presence of a
specific feature.
Languages
The word Java, by itself, usually refers to the Java programming language which was designed
for use with the Java platform. Programming languages are typically outside of the scope of the
phrase “platform”. However, Sun does not encourage the use of any other languages with the
platform, and lists the Java programming language as a core part of the Java 2 platform. The
language and runtime are therefore commonly considered a single unit.
Nevertheless, third parties have produced a number of compilers which target the JVM. Some of
these are for existing languages, while others are for extensions to the Java language itself. These
include:
Groovy
Pizza
GJ (Generic Java), which was incorporated into official Java as of Sun’s version
1.5.
NetREXX
Similar Platforms
The success of Java and its write once, run anywhere concept has also led to other similar efforts.
The most notable of these is the Microsoft .NET platform, which borrows many of the concepts
and innovations of Java; in fact, it has an implementation of a Java-like language called Visual J#
(formerly known as J++). (It is Java-like in that J# is not the Java language. Instead, J# contains
non-standard extensions of the language.)
Later Microsoft stoped, withdrew its J# support, and created a new language called C#. C# is very
similar to J# and Java, but not compatible with them. The differences between Java and C# can be
read at w:Comparison of C Sharp and Java.
Concurrent
Collections Exceptions Reflection
Programming
Applets JavaBeans Libraries
Java Programming Environment
To compile Java programs, you will need to download and install the Java Development Kit
(JDK). This is available from Sun’s website. Other hardware and operating system vendors also
supply Java Development Kits for their platforms, although they may change the name of the kit.
Sun produces JDKs for Windows, Linux, and Solaris.
There are numerous environments you can use to develop your Java programs. You can choose to
write your programs in a text editor and then compile them using the command line, or you can
use an integrated development environment (IDE). IDEs like NetBeans and Eclipse provide many
useful functions such as syntax error checking, code completion, automatic compilation and
debugging, which you may find useful, especially if this is your first foray into programming.
javac compiles Java source files into executable Java class files. Source files are text files with a
.java file name extension. You can create such files with a text editor, like Notepad, or an IDE.
javac then compiles these files into loadable and executable class files, using the .class
extension. For example, if you create a Java class org/yahoos/util/PrintDate.java
package org.yahoos.util;
import java.util.Date;
public class PrintDate
{
public void main(String[] args)
{
System.out.println(new Date());
}
}
You would normally invoke this in a shell whose working directory is the root directory
containing all of your source files resides. (The Java package statement, package
org.yahoos.util, corresponds to the directory structure org/yahoos/util see Java packages.)
javac will create the file PrintDate.class in the same directory where the source file is
located. If there are syntax errors, javac will print those to the shell. The PrintDate.class file
contains the byte code, that will run under all hardware where the Java runtime is installed. Even
if the PrintDate.class file was created in Windows operating system, you can copy this file
to unix and it will be executed fine.
Usually there is more than one class file created and those files are packaged to a
application_name.jar file to distribute to run in any hardware.
IDEs may manage this process automatically. For example, Eclipse contains its own Java
compiler and thus does not use javac directly. It automatically compiles the Java source files
when you save them. The use of IDE’s such as Eclipse are beyond the scope of this module,
however, so consult the IDE’s tutorials and help to see how they provide a Java programming
environment.
The bytecode
It is clear from the above paragraph that the Java compiler compiles source code text files with
the extension .java into executable code usually confined into a class file with the .class
extension. Such code is called Bytecode.
In many languages prior to Java, the source code would generally compile into the machine-code
for the particular machine the program was compiled upon. Therefore, if a program was compiled
on an X86 machine, it would run only on an X86 machine and no other. Java, on the other hand,
produces a bytecode - an intermediate binary form of code that is a portable representation of the
Java class. Any Java Virtual Machine on any hardware/operating system platform can then
execute this same bytecode. There are some restrictions to this portability. For example, a Java
ME system cannot execute all programs compiled for the Java SE environment because Java ME
is pared down to small devices. But in general, a Java SE program can run unmodified on any
Java SE virtual machine.
Being compiled halfway through, it is the job of the Java Virtual Machine to compile the rest of
the program to native code at the time of its execution making Java code follow the “Write Once,
Run Anywhere” (WORA) policy. The compiler used to compile bytecode into machine-code at
runtime is called the Just-In-Time or JIT compiler. Once a piece of code is compiled by the JVM
to execution code, the code is used and re-used again and again, to speed up execution.
The class is hence said to have a main entry point defined and is usually called a Java program.
The method described above as the main entry point is usually nicknamed the main method. Java
classes without main methods are simply classes, although they may be part of a program.
If a class which you compile with javac has a main entry point, you can execute the class by
specifying the class name as an argument to the java program.
This will run the main method in the PrintDate class in the org.yahoos.util package.
(Packages provide a convenient way to provide namespaces and organization of Java classes.
We’ll use org.yahoos.util as a parent package in this module. More on packages.)
Your program will begin execution in the shell window. Inputs and outputs will be gathered from
and to your shell window. On a Windows platform, you can use a DOS command window as the
command shell program for the execution of Java programs. The JRE is normally called java
because the java program is the most widely used program to execute Java programs.
On the Windows platform, there is an alternate JRE executable called javaw.exe or javaw
which runs Java programs as a Windows native application - that is, with no console for standard
input or output.
Rather than executing in the console, the Java program would be executed in a separate Windows
native process. This is typically done for Java applications which create their own graphical user
interface (GUI) windows. The above-mentioned org.yahoos.util.PrintDate program,
which prints output to the standard output stream, is not appropriate for use with javaw as there
is no console output. Instead, org.yahoos.util.ViewDate would be a program which creates
its own windows to display the date.
As with java, IDE’s also manage the execution of Java programs in slightly different ways. They
may provide shortcuts for running programs and windows for capturing the output.
On UNIX/Linux this does not matter. If the program is launched graphically (by file association
in a file manager) a console is not shown. GUI programs will have the titlebars following the look
and feel of your desktop (KDE, GNOME, Fluxbox, XFCE) theme.
Other JDK tools
Apart from the tools specified above in detail, the JDK has matured over the years and has
included in itself several other tools. Where some of these tools are no longer used, others offer a
far greater deal of capability to the Java Development Kit. Below is a list of some of the tools
available for the JDK.
In Java 1.5 (alias Java 5.0) Sun added a mechanism called annotations. Annotations allow to add
meta-data to Java source code, and even provide mechanisms to carry that meta-data forth into a
compiled class files.
Also starting with Java 1.5 Sun added the apt tool to the JDK. apt works on Java source code. It
is an annotation processing tool which digs through source code, finds annotation statements in
the source code and executes actions if it finds known annotations. The most common task is to
generate some paticular source code.
The actions apt performs when finding annotations in the source code are not hard-coded into apt.
Instead, one has to code particular annotation handlers (in Java). These handlers are called
annotation processors.
The most difficult thing with apt is that Sun decided to use a whole set of new terminology. apt
can simply be seen as a source code preprocessor framework, and annotation processors are
typically just code generators.
Java applets require a particular environment to execute. Typically, this environment is provided
by a browser with a decend Java plug-in, and a web server serving the applet. However, during
development and testing of an applet it might be more convenient to start an applet without the
need to fiddle with a browser and a web server. In such a case Sun’s appletviewer from the JDK
can be used to run an applet.
A Java class can call native, or non-Java, code that has been prepared to be called from Java. The
details and procedures are specified in the JNI (Java Native Interface). Commonly, native code is
written in C (or C++). The JDK tool javah helps to write the necessary C code, by generating C
header files and C stub code.
Security Tools
The JDK comes with a large number of tools related to the security features of Java. Usage of
these tools first requires study of the particular security mechanisms.
keytool
To manage keys and certificates
jarsigner
To generate and verify digital signatures of JARs (Java ARchives)
policytool
To edit policy files
kinit
To obtain Kerberos v5 tickets
klist
To manage Kerberos credential cache and key table
ktab
To manage entries in a key table
Such files can contain only ASCII and Latin-1 characters, but international programmers need a
full range of character sets. Text using these characters can appear in properties files and resource
bundles only if the non-ASCII and non-Latin-^1 characters are converted into Unicode escape
sequences (\uXXXX notation).
The task of writing such escape sequences is handled by native2ascii. You can write the
international text in an editor using the appropriate character encoding, then use native2ascii to
generate the necessary ASCII text with embedded Unicode escape sequences. Despite the name,
native2ascii can also convert from ASCII to native, so it is useful for converting an existing
properties file or resource bundle back to some other encoding.
native2ascii makes most sense when integrated into a build system to automate the conversion. ğ
RMI Tools
TODO
Java IDL and RMI-IIOP Tools
TODO
TODO
With Java 1.5 a set of monitoring and management tools have been added to the JDK, in addition
to a set of troubleshooting tools.
The monitoring and management tools are intended for monitoring and managing the virtual
machine and the execution environment. They allow, for example, monitoring memory usage
during the execution of a Java program.
The troubleshooting tools provide rather esoteric insight into aspects of the virtual mashine.
(Interestingly, the Java debugger is not categorized as a troubleshooting tool.)
All the monitoring and management and troubleshooting tools are currently marked as
“experimental” (which does not affect jdb). So they might disappear in future JDKs.
Jar is short for Java archive. It is a tool for creating Java archives or jar files - a file with .jar
as the extension. A Java archive is a collection of compiled Java classes and other resources
which those classes may require (such as text files, configuration files, images) at runtime.
Internally, a jar file is really a .zip file.
Jdb is short for Java debugger. The Java debugger is a command-line console that provides a
debugging environment for Java programs. Although you can use this command line console,
IDE’s normally provide easier to use debugging environments.
As programs grow large and complex, programmers need ways to track changes and to
understand the code better at each step of its evolution. For decades, programmer have been
employing the use of special programming constructs called comments - regions that help declare
user definitions for a code snippet within the source code. But comments are prone to be verbose
and incomprehensible, let alone be difficult to read in applications having hundreds of lines of
code.
Java provides the user with a way to easily publish documentation about the code using a special
commenting system and the javadoc tool. The javadoc tool generates documentation about the
w:application programming interface (API) of a set of user-created Java classes. javadoc reads
source file comments from the .java source files and generates HTML documents that are easier
to read and understand without looking at the code itself.
Where Javadoc provide a detailed view into the API and documentation of a Java class, the
javap tool prints information regarding members (constructors, methods and variables) in a
class. In other words, it lists the class’ API and/or the compiled instructions of the class. javap is
a formatting disassembler for Java bytecode.
Concurrent
Collections Exceptions Reflection
Programming
javac -version
command. If the JDK is installed and on your executable path, you should see some output which
tells you the version that is running. The output will vary depending on which version is installed
and which vendor provided the Java installation.
$ java -version
Eclipse Java Compiler 0.548, pre-3.1.0 milestone-6, Copyright IBM Corp 2000, 2005. All
rights reserved.
You may have other versions of Java installed; this command will only show the first in your
PATH.
then the JDK may not be installed or it may not be in your path. You can use your system’s file
search utilities to see if there is a javac or javac.exe executable installed. If it is, and it is a
recent enough version (Java 1.4.2 or Java 1.5, for example), you should put the bin directory that
contains javac in your system path. The Java runtime, java, is often in the same bin directory.
If the installed version is older (i.e. it is Java 1.3.1 or Java 1.4.2 and you wish to use the more
recent Java 5 release), you should proceed below wth downloading and installing a JDK.
For example for Linux running on the x86 architecture, you can download an RPM (RedHat
Package Manager) file or a self extracting .bin binary (such as jdk-1_5_0_06-linux-
i586.bin for Intel Pentium compatible machines) to get Java SE release 5. (Note: The file name
changes as new versions of Java are released.)
You may also have to modify your path so that it includes the bin</bin> subdirectory of
your JAVA_HOME. You should put the JAVA_HOME/bin directory before other directories
where Java is installed. The above installations may put the JRE, java (or java.exe) in a
system bin directory, but they may not put all of the JDK executables in your path.
You may need to restart your command shell in order to pick up environment variable changes
for JAVA_HOME and PATH.
Install an IDE
You may optionally choose to install an IDE. There are many free and commercial IDE’s
available. For example, the Eclipse IDE found at http://www.eclipse.org includes many of the
tools necessary to build Java programs (such as a Java compiler, debugger, Javadoc, etc.) and
thus you do not need to install a JDK if you opt to use Eclipse. However, Eclipse does require
you to install a JRE - Eclipse is a Java program that runs within the JRE. The JDK download sites
mentioned above also include JRE downloads, and installation instructions are similar.
Another Popular IDE for the Windows platform is Borland’s JBuilder from
http://www.borland.com
And a popular Free IDE is JCreator LE from XINOX Software found at http://www.jcreator.com
However, even if you choose to use Eclipse, it is recommended that you download and install the
JDK. This will allow you to use scripts to build and test your Java software from outside the IDE
environment.
If you download Java from Sun’s site, you also have the option of installing the NetBeans IDE +
JDK 5.0 Update 6 bundle.
Install Validation
When you are done with the above JDK download and install instructions, repeat the
javac -version
command to verify that your path picks up the correct version of the JDK.
Concurrent
Collections Exceptions Reflection
Programming
Compiling to bytecode
In Java, programs are not compiled into executable files; they are compiled into Bytecode (as
discussed earlier), which the JVM then executes at runtime. Java source code is compiled into
bytecode when we use the javac compiler. The bytecode gets saved on the disk with the file
extension .class. When the program is to be run, the bytecode is converted, using the Just-In-
Time(JIT) compiler. The result is machine code which is then fed to the memory and is executed.
The Java classes/Byte Codes are compiled to machine code and loaded into memory by the JVM
when needed the first time. This is different than other languages like C/C++ where the whole
program had to be compiled to machine code and linked to create an executable, before the
program could start.
JIT compilers compile byte-code once and the compiled machine code are re-used again and
again, to speed up executations. A better name for JIT would be “Compile only once” compilers,
COO, or “Just-one-time” compilers, JOT. Early Java compilers compiled the byte-code to
machine code each time it was used, that was slow. It was still faster than an “interpreter-
language”, where code is compiled from high level language, not from byte-code each time it
was used.
The best way is to use a build tool to build your application. The build tool would check all the
needed dependencies and compile only the needed class for the build. The Ant tool is the best and
the most popular build tool currently available. Using Ant you would build your application from
the command line by typing:
ant build.xml
The xml file contains all the information needed to build the application.
The next most popular way to build applications are using an IDE. IDE stands for Intergated
Development Environment. Some of them are listed below.
For compilation, the file must be in the right directory structure. A file containing a class in the
unnamed package must be in the current-root directory; if the class belongs to a package, it must
be in a directory with the same name as the package.
The convention is that package names and directory names coresponding to the package consist
of only lower case letters.
Examples
package example;
Subpackages
package org.yahoos.en;
en
yahoos
org
resulting in
org/yahoos/en
Filename Case
The Java source file name must be the same as the public class name, the file contains. There can
be only one public class defined per file. The Java class name is case sensitive, as is the source
file name.
The naming convention for the class name is for it to start with a capital letter.
Compiler Options
Debugging and Symbolic Information
Additional Tools
IDEs
This section contains a little about the different IDEs available and their strengths and
weaknesses.
JBuilder
JBuilder is a IDE with proprietary source code, sold by Borland. One of the advantages in
integration with togheter, a modelling tool.
JCreator
There’s info at: http://www.apcomputerscience.com/ide/jcreator/index.htm
Eclipse
Eclipse is a free IDE, plus a developer tool framework that can be extended for a particular
development need. IBM was behind this free software development and it replaced IBM Visual
Age tool. The idea was to create a standard look and feel that can be extended. The extendibility
is distinguish Eclipse from any other IDE tools. Eclipse also meant to compete with Microsoft
Visual Studio tools. Microsoft tools give a standard way of developing code in the Microsoft
world. Eclipse gives simular standard way of developing code in the Java world, with a big
success so far. With the online error checking only, coding can be speed up by at least
50%(coding does not include programming).
IBM’s WSAD, and later IBM Rational Software Development Platform are built on Eclipse.
NetBeans
The NetBeans IDE is a free, open-source Integrated Development Environment for software
developers. The IDE runs on many platforms including Windows, Linux, Solaris, and the
MacOS. It is easy to install and use straight out of the box. The NetBeans IDE provides
developers with all the tools they need to create professional cross-platform desktop, enterprise,
web and mobile applications.
BlueJ
BlueJ is an IDE that includes templates and will compile and run the applications for you. BlueJ
is often used by classes because it is not necessary to set classpaths. BlueJ has it’s own sets of
Library’s and you can add your own under preferances. That sets the classpath for all
compilations that come out of it to include those you have added and the BlueJ libraries.
BlueJ offers an intresting GUI for creation of packages and programs. Classes are represented as
boxes with arrows running between them to represent inheratance/implementation or if on is
constructed in another. BlueJ addes all those classes (the project) into the classpath at compile
time.
BlueJ Homesite
Kawa
Kawa was developed by Tek-Tools. It is basically a Java editor, It does not include wizards, and
GUI tools, best suited to experienced Java programmers in small and midsized delelopment
teams.
Ant
Ant is a build management tool designed to replace MAKE as the tool for automated builds of
large Java applications. Like Java, and unlike MAKE, Ant is designed to be platform
independent.
Building a Java application requires certain tasks to be performed. Those tasks may include not
only to compile the code, but also to copy code, to package the code to Jar, to create EJBs, to run
automated tests, to ftp the code to remote site, and so on. For some tasks a condition can be
assigned, for example a compile only changed code, or do the task if that was not already done
so. Tasks dependency can also be specified, that will make sure that the order of executions of the
tasks are in the right order. For example compile the code before package them to jar, the
package-to-jar task depend on the compilation task.
The tasks and their dependencies are defined in a “build.xml” file. The Ant program will parse it
and do whatever it describes. The Ant tool much more powerful than the MAKE tool. Because of
the java codes are spread out in the file system according the java package(name space), the use a
MAKE tool feels very awkward.
Also the Ant tool is written in Java and can be extended, so if there is a task you’d like to be done
during the build, and the task is not in the pre-defined tasks list, you can write it yourself. It is
very easy to hook your ant task code to the other tasks, you code only needs to be in the classpath,
and the Ant tool will load it during runtime. Your ant task code has to follow the Ant framework,
that’s all.
Concurrent
Collections Exceptions Reflection
Programming
Applets JavaBeans Libraries
Execution
There are various ways Java code can be executed. A complex Java application are usually using
third party APIs or services. In this section we list the most popular way a piece of Java code may
be packed together and/or executed.
JINI
After J2EE Sun had a vision about the next step of network computing. That is JINI. The main
idea is that in a network environment, there would be many independent services and consumers.
JINI would allow these services/consumers to interact dynamically with each other in a robust
way. The basic features of JINI are:
JINI is not widely used at the current writing (2006). There are two possible reasons for it. One is
JINI a bit complicated to understand and to set it up. The other reason is that Microsoft pooled
out from Java, which caused the industry to turn to the use of proprietary solutions.
First Java Program
Hello World
Generally when you first start programming in any language, you’ll start with the traditional
Hello World example. That said, let’s start building your first Java program. You guessed it, it’s
Hello World! Before starting this exercise, make sure you know how to Compile and run Java
programs.
Open your IDE and write the following text. Pay close attention to capitalization, as Java is case
sensitive
Save it as HelloWorld.java. Again, make sure that the filename is the same case as the class
name. Compile and run it:
javac HelloWorld.java
java HelloWorld
Hello, world!
Line-by-line Analysis
declares a Java class named HelloWorld. This class is declared public - it is available to any
other class. The next line,
The
System.out.println(“Hello, world!”);
statement sends the text Hello, world! to the console (with a line terminator). The final two
braces mark the end of the main method and the end of the class.
it will print
Hello, yahoos!
Hello, yahoos!
or, if you do not pass a command line parameter, it will simply print
Hello, World!
Common Problems
If the program does not work as you expect, check the following common errors.
Are you sure all words are spelled correctly and with the exact case as shown?
Are there semicolons and brackets in the appropriate spot?
Are you missing a quote?
Concurrent
Collections Exceptions Reflection
Programming
At this point, you may wish to review the source to see how much you might be able to
understand. While perhaps not being the most literate of programming languages, someone with
understaning of other procedural languages such as C, or other OO languages such as C++ or C#,
will be able to understand most if not all of the sample program.
javac Distance.java
(If the javac command fails, review the Java installation instructions.)
To run the program, you supply it with the x and y coordinates of two points on a plane. (For this
version of Distance, only integer points are supported.) The command sequence is
java Distance x0 y0 x1 y1
to compute the distance between the points (x0, y0) and (x1, y1)
java Distance 0 3 4 0
will compute the distance between the points (0,3) and (4,0) and print the following:
The command
java Distance -4 5 11 19
will compute the distance between the points (-4,5) and (11,19):
The syntax of a Java class is the characters and symbols and their structure used to code the class
using Unicode characters. A fuller treatment of the syntax elements of Java may be found at
Syntax. We will provide here only enough description of the syntax to grasp the above program.
Java programs consist of a sequence of tokens. There are different kinds of tokens. For example,
there are word tokens such as class and public which represent keywords - special words with
reserved meaning in Java. Other words (non keywords such as Distance, point0, x1, and
printDistance) are identifiers. Identifiers have many different uses in Java but primarily they
are used as names. Java also has tokens to represent numbers, such as 1 and 3; these are known as
literals. String literals, such as “Distance between “, consist of zero or more characters
embedded in double quotes, and operators such as + and = are used to express basic computation
such as addition or String concatenation or assignment. There are also left and right braces ({ and
}) which enclose blocks. The body of a class is one such block. Some tokens are punctuation,
such as periods . and commas , and semicolons ;. You use whitespace such as spaces, tabs, and
newlines, to separate tokens. For example, whitespace is required between keywords and
identifiers: publicstatic is a single identifier with twelve characters, not two Java keywords.
Sequences of tokens are used to construct the next building blocks of Java classes: declarations
and definitions. A class declaration provides the name and visibility of a class. For our example,
is the class declaration. It consists (in this case) of two keywords, public and class followed
by the identifier Distance.
This means that we are definining a class named Distance. Other classes, or in our case, the
command line, can refer to the class by this name. The public keyword is an access modifier
which declares that this class and its members may be accessed from other classes. The class
keyword, obviously, identifies this declaration as a class. Java also allows declarations of
interfaces and (as of Java 5) annotations.
The class declaration is then followed by a block (surrounded by curly braces) which provides the
class’ definition. The definition is the implementation of the class - the declaration and definitions
of the class’ members. This class contains exactly six members, which we will explain in turn.
The declaration
declares two instance fields. Instance fields represent named values that are allocated whenever
an instance of the class is constructed. When a Java program creates a Distance instance, that
instance will contain space for point0 and point1. When another Distance object is created,
it will contain space for its own point0 and point1 values. The value of point0 in the first
Distance object can vary independently of the value of point0 in the second Distance
object.
1. The private access modifier, which means these instance fields are not visible to
other classes.
2. The type of the instance fields. In this case, the type is java.awt.Point. This the
the class Point in the java.awt package.
3. The names of the instance fields in a comma separated list.
These two fields could also have been declared with two separate but more verbose declarations,
Since the types of these fields is a reference type (i.e. a field that refers to or can hold a reference
to an object value), Java will implicitly initialize the values of point0 and point1 to null when
a Distance instance is created. The null value means that a reference value does not refer to an
object. The special Java literal, null is used to represent the null value in a program. While you
can explicitly assign null values in a delcaration, as in
Example: Constructor
A constructor is a special method in a class which is used to construct an instance of the class.
The constructor can perform initialization for the object, beyond that which the Java VM does
automatically. For example, Java will automatically initialize the fields point0 and point1 to
null.
1. The optional access modifier(s). In this case, the constructor is declared public
2. The constructor name, which must match the class name exactly: Distance in
this case.
3. The constructor parameters. The parameter list is required. Even if a constructor
does not have any parameters, you must specify the empty list (). The parameter
list declares the type and name of each of the method’s parameters.
4. An optional throws clause which declares the exceptions that the constructor may
throw. This constructor does not declare any exceptions.
5. The constructor body, which is a Java block (enclosed in {}. This constructor’s
body contains two statements.
public Distance(int x0, int y0, int x1, int y1)
{
point0 = new java.awt.Point(x0, y0);
point1 = new java.awt.Point(x1, y1);
}
This constructor accepts four parameters, named x0, y0, x1 and y1. Each parameter requires a
parameter type declaration, which in this example is int for all four parameters. Java integer
values are signed, 32 bit twos complement integers. The parameters in the parameter list are
separated by commas.
The two assignments in this constructor use Java’s new operator to allocate two
java.awt.Point objects. The first allocates an object represeting the first point, (x0, y0),
and assigns it to the point0 instance variable (replacing the null value that the instance variable
was initialized to). The second statement allocates a second two java.awt.Point instance with
(x1, y1) and assigns it to the point1 instance variable.
This is the constructor for the Distance class. Distance implicitly extends from
java.lang.Object. Java inserts a call to the super constructor as the first executable statement
of the constructor if there is not one explicitly coded. The above constructor body is equivalent to
the following body with the explicit super constructor call:
{
super();
point0 = new java.awt.Point(x0, y0);
point1 = new java.awt.Point(x1, y1);
}
While it is true that this class could be implemented in other ways, such as simply storing the
Example: Methods
Methods are the third and most important type of class member. This class contains three methods
in which the behavior of the Distance class is defined: printDistance(), main(), and
intValue()
The printDistance() method prints the distance between the two points to the standard output
(normally the console).
This instance method executes within the context of an implicit Distance object. The instance
field references, point0 and point1, refer to instance fields of that implicit object. You can also
use the special variable this to explicitly referene the current object. Within an instance method,
Java binds the name this to the object on which the method is executing, and the type of this is
that of the current class. The body of the printDistance method could also be coded as
This method both computes the distance and prints it in one statement. The distance is computed
with point0.distance(point1); distance() is an instance method of the
java.awt.Point class (of which point0 and point1 are instances. The method operates on
point0 (binding this to the object that point0 refers to during the execution of the method)
and acceping another Point as a paramemer. (Actually, it is slightly more complicated than that,
but we’ll explain later.) The result of the distance() method is a double precision floating
point number.
The main() method is the main entry point which Java invokes when you start a Java program
from the command line. The command
java Distance 0 3 4 0
instructs Java to locate the Distance class, put the four command line arguments into an array of
String values, then pass those arguments the public static main(String[]) method of the
class. (We will introduce arrays shortly.) Any Java class that you want to invoke from the
command line or desktop shortcut must have a main method with this signature.
The main() method invokes the final method, intValue(), four times. The intValue() takes
a single string parameter and returns the integer value represented in the string. For example,
intValue(“3”) will return the integer 3.
The intValue() method delegates its job to the Integer.parseInt() method. The main
method could have called Integer.parseInt() directly; the intValue() method simply
makes the main() method slightly more readable.
return Integer.parseInt(data);
This method is private since, like the fields point0 and point1, it is part of the internal
implementation of the class and is not part of the external programming interface of the
Distance class.
Both the main() and intValue() methods are static methods. The static keyword tells the
compiler to create a single memory space associated with the class. Each individual object
instantiated has its own private state variables and methods but use the same static methods and
members common to the single class object created by the compiler when the first class object is
instantiated or created. This means that the method executes in a static or non-object context -
there is no implicit separate instance available when the static methods run from various objects,
and the special variable this is not available. As such, static methods cannot access instance
methods or instance fields (such as printDistance()) or point0) directly. The main()
method can only invoke the instance method printDistance() method via an instance
reference such as dist.
Data Types
Most declarations have a data type. Java has several categories of data types: reference types,
primitive types, array types, and a special type, void.
Reference Types
A reference type is a Java data type which is defined by a Java class or interface. Reference types
derive this name because such values refer to an object or contain a reference to an object. The
idea is similar to pointers in other languages like C.
Java represents sequences of character data, or String, with the reference type
java.lang.String which is most commonly referred to as String. String literals, such as
“Distance between “ are constants whose type is String.
Primitive Types
In addition to object or reference types, Java supports primitive types. The primitive types are
used to represent Boolean, character, and numeric values. This program uses only one primitive
type explicitly, int, which represents 32 bit signed integer values. The program also implicitly
uses double, which is the return type of the distance() method of java.awt.Point.
double values are 64 bit IEEE floating point values. The main() method uses integer values 0,
1, 2, and 3 to access elements of the command line arguments. The Distance() constructor’s
four parameters also have the type int. Also, the intValue() method has a return type of int.
This means a call to that method, such as intValue(args[0]), is an expression of type int.
This helps explain why the main method cannot call
Since the type of the args array element is String, and our constructor’s parameters must be int,
such a call would result in an error because Java cannot automatically convert values of type
String into int values.
Java’s primitive types are boolean, byte, char, short, int, long, float and double, each
of which are also Java language keywords.
Array Types
Java supports arrays, which are aggregate types which have a fixed element type (which can be
any Java type) and an integral size. This program uses only one array, String[] args. This
indicates that args has an array type and that the element type is String. The Java VM
constructs and initializes the array that is passed to the main method. See arrays for more details
on how to create arrays and access their size.
The elements of arrays are accessed with integer indices. The first element of an array is always
element 0. This program accesses the first four elements of the args array explicitly with the
indices 0, 1, 2, and 3. (This program does not perform any input validation, such as verifying that
the user passed at least four arguments to the program. We will fix that later.)
void
void is not a type in Java; it represents the absense of a type. Methods which do not return values
are declared as void methods.
Concurrent
Collections Exceptions Reflection
Programming
Unicode
Java source code are built by Unicode characters.
Tokens
Java programs consist of a sequence of different kinds of tokens. For example, there
are word tokens such as class and public which are keywords.
Keywords
Those are special words with reserved meaning in Java. Those words can not be used
by the programers to name identifiers.
Identifiers
Other words (non keywords) are identifiers. Identifiers have many different uses in
Java but primarily they are used as names, class names, method names, and variable
names... .
literals
Java also has tokens to represent numbers, such as 1 and 3; these are known as
literals.
String literals, such as “http://en.yahoos.org/Java_Programming”, consist of zero
or more characters embedded in double quotes.
Operators
And operators such as + and = are used to express basic computation such as addition
or String concatenation or assignment.
Blocks
There are also left and right braces ({ and }) which enclose blocks. The body of a
class is one such block.
Statements
A Block contains one or more Java statement(s), separated by semicolons. A
statement is the smallest building block of Java.
Separators
Some tokens are punctuation, such as periods . and commas , and semicolons ;.
whitespace
You use whitespace such as spaces, tabs, and newlines, to separate tokens. For
example, whitespace is required between keywords and identifiers: publicstatic is
a single identifier with twelve characters, not two Java keywords.
Comments
Comments are not part of the exacuting code. Comments are used to document the
code.
Unicode
Java source files consist of Unicode text files written in UTF-16 encoding. Most Java program
text consists of ASCII characters, but Unicode escape sequences may be used to express any
Unicode character when needed.
For example, Π (which is the Greek Capital Letter Pi) is a valid Java identifier. Π may also be
represented in Java as the Unicode escape sequence \u03A0. Thus, the following is a valid, but
not very readable, declaration and assignment:
The following demonstrate the use of Unicode escape sequences in other Java syntax:
Keywords
Keywords are special tokens in the language which have reserved use in the language. Keywords
may not be used as identifiers in Java - you cannot declare a field whose name is a keyword, for
instance.
Examples of keywords are the primitive types, int and boolean; the control flow statements
for and if; access modifiers such as public, and special words which mark the declaration and
definition of Java classes, packages, and interfaces: class, package, interface.
It declares a class abstract, not all its methods are defined/implemented. Objects can not be
created from an abstract class. It needs to have a non abstract subclass in order to create an
object.
It also declares a method abstract, that is not implemented in the abstract class. A method can not
be declared abstract in a non abstract class.
Syntact:
For Example:
// --- This method does have a body, it is implemented in the abstarct class, gives a
default behavior ---
public void normalMethod()
{
...
}
}
assert is a Java keyword used to define an assert statement. An assert statement is used to
declare an expected boolean condition in a program. If the program is running with assertions
enabled, then the condition is checked at runtime. If the condition is false, the Java runtime
system throws a AssertionError.
An example:
Assertions are usually used as a debugging aid. They should not be used instead of validating
arguments to public methods.
Assertions are enabled with the Java -ea or -enableassertions runtime option. See your
Java environment documentation for additional options for controlling assertions.
boolean is a keyword which designates the boolean primitive type. There are only two
possible boolean values: true and false. The default value for boolean fields is false.
The following is a declaration of a private boolean field named initialized, and its use in
a method named init()
Note that there is no automatic conversion between integer types (such as int) to boolean as is
possible in some languages like C. Instead, one must use an equivalent expression such as (i !=
0) which evaluates to true if i is not zero.
For Example:
for ( int i=0; i < maxLoopIter; i++ )
{
System.println(“Iter=” +i);
if ( i == 5 )
{
break; // -- 5 iteration is enough—
}
}
byte is a keyword which designates the 8 bit signed integer primitive type.
The java.lang.Byte class is the nominal wrapper class when you need to store an int value
but an object reference is required.
Syntact:
For Example:
byte b = 65;
or
byte b = ‘A’;
catch is a keyword.
It’s part of a try block. If an exception is thrown inside a try block, the exception will be
compared to any of the catch part of the block. If the exception match with one of the exception
in the catch part, the exception will be handled there.
For example:
try {
...
char is a keyword.
The java.lang.Character class is the nominal wrapper class when you need to store an char
value but an object reference is required.
Syntact:
For Example:
System.out.println( oneChar );
Output:
class is a Java keyword which begins the declaration and definition of a class.
The extends word is optional, if omitted, the class extends the Object class, as all Java class
inherited from it.
Skip the reminder of the loop and ‘continue’ with the next iteration.
For Example:
do is a Java keyword.
It starts a do-while looping block. The do-while loop is functionally similar to the while loop,
except the condition is evaluated AFTER the statement executes
Syntax:
do{
statement;
} while (condition);
For Example:
do ( i < maxLoopIter )
{
The java.lang.Double class is the nominal wrapper class when you need to store an double
value but an object reference is required.
Syntact:
For Example:
double d = 65.55;
For Example:
if ( boolean Expression )
{
System.println(“’True’ statement block”);
}
else
{
System.println(“’False’ statement block”);
}
For Example:
enum Grade { A, B, C, D, F };
...
private Grade gradeA = Grade.A;
student.assigneGrade( gradeA );
...
public void assignGrade(Grade grade)
{
this.grade = grade;
}
Used in class and interface definition to declare the class or interface that is to be extended.
Syntact:
final is a keyword.
It has more then one meaning depending whether it used for a class, a method, or for a variable.
For Example
Access Modifiers
finally is a keyword.
It is an optional part of a try block. The code inside the finally block will always be executed,
even if there is an exception in the try block.
Note: in that third and final case, NO CODE after the try-catch block is executed.
For Example:
Note: if there is an exception that happens before the try-catch block, the finally block is not
executed.
Keywords/try
Keywords/catch
Throwing and Catching Exceptions#Catching Rule
The java.lang.Float class is the nominal wrapper class when you need to store an float
value but an object reference is required.
Syntact:
float f = 65.55;
Primitive Types
For Example:
Keywords/while
Keywords/do
if is a Java keyword.
if ( boolean Expression )
{
System.println(“’True’ statement block”);
}
else
{
Keywords/else
Used in class definition to declare the Interfaces that are to be implemeted by the class.
Syntact:
Creating Objects
Keywords/class
It declares a Java class to use in the code below the import statement. Once a Java class is
declared, then the class name can be used in the code without specifying the package the class
belongs to.
Use the ‘*’ character to declare all the class belonging to the package.
Syntax:
import package.JavaClass;
import package.*;
Packages
instanceof is a keyword.
It checks an object reference if that defined by a class or its subclasses and returns a boolean
value;
The <object-reference> instanceof Object will return true for all object references, since all
Java objects are inherited from Object
Syntact:
For example:
class Fruit
{
...
}
class Apple extends Fruit
{
...
}
class Organge extends Fruit
{
...
}
public class Test
{
public static void main(String[] args)
{
Collectiom coll = new ArrayList();
Apple app1 = new Apple();
Apple app2 = new Apple();
coll.add(app1);
coll.add(app2);
printColl(coll);
}
java Test
The output:
int is a keyword which designates the 32 bit signed integer primitive type.
The java.lang.Integer class is the nominal wrapper class when you need to store an int
value but an object reference is required.
Syntact:
int i = 65;
Primitive Types
For example:
public interface
{
public void method1();
...
}
Keywords/new
long is a keyword which designates the 64 bit signed integer primitive type.
The java.lang.Long class is the nominal wrapper class when you need to store an long value
but an object reference is required.
Syntact:
For Example:
long l = 65;
Primitive Types
It marks a method, that it will be implemented in other languages, not in Java. It works together
with JNI(Java Native Interface)
Syntact:
Syntact:
Creating Objects
It declares a ‘name space’ for the Java class. It must be put at the top of the Java file, it should be
the first Java statement line.
To make the package name to be unique across vendors, usually the company url is used stating
in backword.
Syntact:
package package;
For Example:
package com.mycompany.myapplication.mymodule;
Packages
Keywords/import
private is a Java keyword which declares a members access as private. That is, the member is
only visible within the class, not from any class (including subclasses). The visibility of private
members extends to nested classes.
Syntact:
It is an access modifier, it is used before a method, to indicate that the method can be accessed
only by the class subclasses.
Syntact:
Access Modifiers
public is a Java keyword which declares a member’s access as public. Public members are
visible to all other classes. This means that any other class can access a public field or method.
Further, other classes can modify public fields unless the field is declared as final.
A best practice is to give fields private access and reserve public access to only the set of
methods and final fields that define the class’ public constants. This helps with encapulation
and information hiding, since it allows you to change the implementation of a class without
affecting the consumers who use only the public API of the class.
Below is an example of an immutable public class named Length which maintains private
instance fields named units and magnitude but provides a public constructor and two public
accessor methods.
package org.yahoos.java;
public class Length {
private double magnitude;
private String units;
public Length(double magnitude, String units) {
if (units == null || units.trim().length() == 0)
throw new IllegalArgumentException(“non-null, non-empty units
required.”);
this.magnitute = magnitude;
this.units = units;
}
public double getMagnitude() {
return magnitude;
}
public String getUnits() {
return units;
}
}
Syntax:
short is a keyword.
Syntact:
For Example:
Primitive Types
static is a keyword that states that all instances of a given class are to share the same
variable/method. This is used for a constant variable or a method that is the same for every
instance of a class, such as the methods in the Math class. The main method of a class is
generally labelled static
No object needs to be created to use static variables or call static methods. Just put the class name
before the static variable or method to use them.
Static methods can not call non static methods. The this current object reference is also not
available in static methods.
Syntact:
To access them :
ClassName.variableName = 10;
ClassName.methodName();
For Example:
It makes sure that floating point calculations result precisely the same regardless of the
underlying operating system and hardware platform, even if more precision could be obtained.
This is compatible with the earlier version of Java 1.1 . If you need that use it.
Syntact:
Used inside a sub-class method definition to call a method defined in the super class. Private
methods of the super-class can not be called. Only public and protected methods can be called by
the super keyword.
Syntact:
super.<method-name>();
For Example:
Java SubClass
The output:
It is a branching operation, based on a number. The ‘number’ must be either char, byte, short,
or int primitive type.
Syntact:
switch ( <integer-var> )
{
case <label1>: <statements>;
case <label2>: <statements>;
...
case <labeln>: <statements>;
default: <statements>;
}
When the <integer-var> value match one of the <label>, then: The statements after the matched
label will be executed including the following label’s statements, until the end of the switch
block, or until a break keyword is reached.
For Example:
int var = 3;
switch ( var )
{
case 1: System.out.println( “Case: 1” );
System.out.println( “Execute until break” );
break;
case 2: System.out.println( “Case: 2” );
System.out.println( “Execute until break” );
break;
case 3: System.out.println( “Case: 3” );
System.out.println( “Execute until break” );
break;
case 4: System.out.println( “Case: 4” );
System.out.println( “Execute until break” );
break;
default: System.out.println( “Case: default” );
System.out.println( “Execute until break” );
break;
}
int var = 3;
if ( var == 1 )
{
System.out.println( “Case: 1” );
System.out.println( “Execute until break” );
}
else if ( var == 2 )
{
System.out.println( “Case: 2” );
System.out.println( “Execute until break” );
}
else if ( var == 3 )
{
System.out.println( “Case: 3” );
System.out.println( “Execute until break” );
}
else if ( var == 4 )
{
System.out.println( “Case: 4” );
System.out.println( “Execute until break” );
}
else // -- This is the default part—
{
System.out.println( “Case: default” );
System.out.println( “Execute until break” );
}
Keywords/if
synchronized is a keyword.
It marks a ‘critical section’. A ‘critical section’ is where one and only one thread is executing. So
to enter into the marked code the threads are ‘synchronized’, only one can enter, the others have
to wait. For more information see Syncronizing Threads Methods.
Syntact:
this.method();
For Example:
throw is a keyword.
Syntact:
throw <Exception Ref>;
For Example:
return custRet
}
Keywords/throws
Syntact:
It flags a field as something that should not be considered part of an objects persistent state.
It marks a member variable not to be serialized, when it is persisted to streams of bytes. When an
object is transferred through the network, the object needs to be ‘serialized’. Serialization
converts the object state to serial bytes. Those bytes are sent over the network and an the object is
recreated from those bytes. Member variables marked by the java transient keyword are not
transferred, they are lost on purpose.
Syntact:
For example:
try is a keyword.
It starts a try block. If an Exception is thrown inside a try block, the Exception will be compared
any of the catch part of the block. If the Exception match with one of the Exception in the catch
part, the exception will be handled there.
No exception is thrown:
the code in the try block
plus the code in the finally block will be executed
plus the code after the try-catch block is executed
An exception is thrown and a match is found among the catch blocks:
the code in the try block until the exception occured is executed
plus the matched catch block is executed
plus the finally block is executed
plus the code after the try-catch block is executed
An exception is thrown and no match found among the catch blocks:
the code in the try block until the exception occured is executed
plus the finally block is executed
NO CODE after the try-catch block is executed
For Example:
} catch ( MyException_1 e ) {
Keywords/catch
Keywords/finally
Throwing and Catching Exceptions#Catching Rule
Used at method declaration and defination to specify that the method does not return any type, the
method returns void. It is not a type and there is no void references/pointers as in C/C++.
For example:
Keywords/return
volatile is a keyword.
It marks a member variable not to be used in optimization, during compilation. The compiler may
rearange code to gain performance, this can cause problems when a member variable can be
changed by many threads. Those member variables that can be changed by more then one thread
should be set to volatile.
Syntact:
For example:
Keywords/synchronized
For Example:
Statements
Keywords/for
Keywords/do
Literals
Java Literals are syntactic representations of boolean, character, numeric, or string data. Literals
provide a means of expressing specific values in your program. For example, in the following
statement, an integer variable named count is declared and assigned an integer value. The literal
0 represents, natually enough, the value zero.
int count = 0;
The following method call passes a String literal “int count = 0;” the boolean literal true
and the special null value null to the method parse():
Boolean Literals
Numeric Literals
Character Literals
Integer Literals
Floating Point Literals
String Literals
null
Concurrent
Collections Exceptions Reflection
Programming
After a block is executed all local variables defined inside the block is discarded, go out of scope.
{
...
// -- This is a block ---
}
{
...
{
// -- This is a nested block ---
}
}
Whitespaces
Whitespace in Java is used to separate the tokens in a Java source file. Whitespace is required in
some places, such as between access modifiers, type names and Identifiers, and is used to
improve readability elsewhere.
Wherever whitespace is required in Java, one or more whitespace characters may be used.
Wherever whitespace is optional in Java, zero or more whitespace characters may be used.
Line separators are special whitespace characters in that they also terminate line comments,
whereas normal whitespace does not.
Other Unicode space characters, including vertical tab, are not allowed as whitespace in Java.
Required Whitespace
Below is the declaration of an abstract method taken from a Java class
Whitespace is required between public and abstract, between abstract and Distance,
between Distance and distanceTo, and between Destination and dest.
because whitespace is required between keywords and identifiers. The following is lexically valid
but means something completely different: it declares a method which has the return type
publicabstractDistance It is unlikely that this type exists, so the above would result in a
semantic error.
Indentation
Java ignores all whitespace in front of a statement. As this, these two code snippets are identical
for the compiler:
void printMessage() {
System.out.println(“Hello World!”);
}
public static void main(String[] args) {
printMessage();
}
void printMessage() {
System.out.println(“Hello World!”);
}
However, the first one’s style (with whitespace) is preferred, as the readability is higher. (The
method body is easier to distinguish from the head, even at a higher reading speed.)
Statements
In Java programming, instructions are referred to as statements. A clear indicator that a line of
code is a statement is its termination with an ending semicolon (;). For instance, consider the
following statement.
If one were to write multiple statements, it is recommended that each statement be entered on a
separate line and should end with a semicolon (;).
The former code gathers appeal in the developer circles. Writing statements as in the second
example only makes your code look more complex and incomprehensible.
The C Programming yahoo describes very well how and why we should ident our code. That also
applies to Java code. For details see C Programming/Structure and style.
Java is an Obejct Oriented language, and such it is built on the structural programming paradime,
where code consists of:
Sequences
Branches
Loops(Iterations)
{
int a = 10;
int b = 20;
int result = a + b;
}
Branching Statements
Program flow can be affected using function declaration, loops and iterations. Of various types of
branching constructs, we can easily pick out two generic branching methods.
Unconditional Branching
Conditional Branching
If you’d closely look at a method, you’ll see that a method is a named statement block that is
executed by calling that particular name. An unconditional branch is created either by invoking
the method or by calling break, continue, return or throw, all of which are described in
below.
When a name of a method is encountered in a flow, it stops execution in the current method and
branches to the newly called method. After returning a value from the called method, execution
picks up at the original method on the line below the method call.
Running the above code would provide us with this screen of information.
Inside main method. Invoking aMethod
Inside aMethod
Back in main method
The program flow begins in the main method. Just as aMethod is invoked, the flow travels to the
called method. At this very point, the flow branches to the other method. Once the method is
completed, the flow is returned to the point it left off and resumes at the next statement after the
call to the method.
Conditional branching is attained with the help of the if...else and switch statements. A
conditional branch occurs only if a certain condition expression evaluates to true.
Conditional Statements
Also referred to as if statements, these allow a program to perform a test and then take action
based on the result of that test.
if (condition){
do statements here if condition is true
} else {
do statements here if condition is false
}
The condition is a boolean expression which can be either true or false. The actions performed
will depend on the value of the condition.
Example:
if ( i > 0 ){
System.out.println(“value stored in i is greater than zero”);
}
else {
System.out.println(“value stored is not greater than zero”);
}
If statements can also be made more complex using the else if statement
if (condition 1){
do statements here if condition 1 is true
}
else if (condition 2){
do statements here if condition 1 is false and condition 2 is true
} else {
Example:
if ( i > 0 ){
System.out.println(“value stored in i is greater than zero”);
}
else if (i < 0){
System.out.println(“value stored in i is less than zero”);
}
else {
System.out.println(“value stored is equal to 0”);
}
If there is only one statement to be executed after the condition, as in the above example, it is
possible to omit the curly braces, however Sun’s Java Code Conventions explicitly state that the
braces should always be used.
There is no looping involved in an if statement so once the condition has been evaluated the
program will continue with the next instruction after the statement.
If...else statements
The if ... else statement is used to conditionally execute one of two blocks of statements,
depending on the result of a boolean condition.
Example:
if (list == null) {
// this block of statements executes if the condition is true
}
else {
// this block of statements executes if the condition is false
}
Sun’s Java Code Conventions explicitly state that the braces should always be used.
if (boolean-condition)
statement1
and
if (boolean-condition)
statement1
else
statement2
Use the second form if you have different statements to execute if the boolean-condition is true or
if it is false. Use the first if you only wish to execute statement1 if the condition is true and you do
not wish to execute alternate statements if the condition is false.
The following example calls two int methods, f() and f(), stores the results, then uses an if
statement to test if x is less than y and if it is, the statement1 body will swap the values. The end
result is x always contains the larger result and y always contains the smaller result.
int x = f();
int y = y();
if ( x < y ) {
int z = x;
x = y;
y = z;
}
if...else statements also allow for the use of another statement, else if. This statement is used
to provide another if statement to the conditional that can only be executed if the others are not
true. For example:
if (x == 2)
x = 4;
else if (x == 3)
x = 6;
else
x = -1;
The else if statement is useful in this case because if one of the conditionals is true, the other
must be false. Keep in mind that if one is true, the other will not execute. For example, if the
statement contained in the first conditional, if(x == 2), were changed to x = 3;, the second
conditional, the else if, would still not execute. However, when dealing with primitive types in
conditional statements, it is more desirable to use switch statements rather than multiple
else if statements.
Switch statements
The switch conditional statement is basically a shorthand version of writing many if...else
statements. The syntax for switch statements is as follows:
switch(<variable>)
This means that if the variable included equals one of the case results, the statements following
that case, until the word break will run. The default case executes if none of the others are
true. Note: the only types that can be analysed through switch statements are char, byte,
short, or int primitive types. This means that String variables can not by analysed through
switch statements.
int n = 2, x;
switch(n)
{
case 1: x = 2; break;
case 2: x = 4; break;
case 3: x = 6; break;
case 4: x = 8; break;
}
return x;
In this example, since the integer variable n is equal to 2, case 2 will execute, make x equal to
4. Thus, 4 is returned by the method.
Iteration Statements
Iteration Statements are statements that used to iterate a block of statements. Such statements are
often referred to as loops. Java offers four kinds of iterative statements.
The while loop iterates a block of code while the condition it specifies is true.
Here the condition is an expression. An expression as discussed earlier is any statement that
returns a value. While condition statements evaluate to a boolean value, that is, either true or
false. As long as the condition is true, the loop will iterate the block of code over and over and
again. Once the condition evaluates to false, the loop exits to the next statement outside the
loop.
The do-while loop is functionally similar to the while loop, except the condition is evaluated
AFTER the statement executes
do{
statement;
} while (condition);
The for loop is a specialized while loop whose syntax is designed for easy iteration through a
sequence of numbers Example:
If you compile and run the statement above, the program will print the numbers 0 to 99 and their
squares
0 0
1 1
2 4
3 9
...
100 10000
int i = 0;
while (i < 100){
System.out.println(i + “\t” + i * i);
i++;
}
The foreach statement allows you to iterate through all the items in a collection, examining
each item in turn while still preserving its type. The syntax for the foreach statement is:
For an example, we’ll take an array of Strings denoting days in a week and traverse through the
collection, examining one item at a time.
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Notice that the loop automatically exits after the last item in the collection has been examined in
the statement block.
Where there is an ability to re-iterate the loop, there is an ability to exit the loop when required.
At any given moment, if you’d like to exit a loop and end all further work within the loop, the
break ought to be used.
Also, the continue and break statements can be used with a label like follows:
String s = “A test string for the switch!\nLine two of test string...”;
outer: for (int i=0;i<s.length();i++) {
switch(s.charAt(i)) {
case ‘\n’: break outer;
case ‘ ‘: break;
default: System.out.print(s.charAt(i));
}
Ateststringfortheswitch!
Concurrent
Collections Exceptions Reflection
Programming
For example, a sports car is an object. Some of its members might be its height, weight,
acceleration, and speed. An object’s members just hold data about that object. Some of the
methods of the sports car could be “drive”, “park”, “race”, etc. The methods really don’t mean
much unless associated with the sports car, and the same goes for the members.
The blueprint that lets us build our sports car object is called a class. A class doesn’t tell us how
fast our sports car goes, or what color it is, but it does tell us that our sports car will have a
member representing speed and color, and that they will be say, a number and a word (or hex
color code), respectively. The class also lays out the methods for us, telling the car how to park
and drive, but these methods can’t take any action with just the blueprint - they need an object to
have an effect.
This instantiation is brought about by one of the class’s methods, called a constructor. As its
name implies, a constructor builds the object based on the blueprint. Behind the scenes, this
means that computer memory is being allocated for the instance, and values are being assigned to
the data members.
A default constructor will build the most basic instance. Generally, this means assigning all the
members values like null, zero, or an empty string. Nothing would stop you, however, from your
default sports car color from being red, but this is generally bad programming style. Another
programmer would be confused if your basic car came out red instead of say, colorless.
A non-default constructor is designed to create an object instance with prescribed values for
most, if not all, of the object’s members. The car is red, goes from 0-60 in 12 seconds, tops out at
190mph, etc.
A copy constructor is generally not seen in the Java language, but it’s important to understand
what it is. As the name implies, a copy constructor creates a new instance to be a duplicate of an
already existing one. In Java, this is usually accomplished by creating the instance with the
default constructor, and then using the assignment operator to equivicate them. This is not
possible in all languages though, so just keep the terminology under your belt.
Type
When an object is created, a reference to the object is also created. The object can not be accessed
directly in Java, only through this object reference. This object reference has a Type assigned to
it. We need this Type when passing the object reference to a method as a parameter. Java does
strong Type checking.
Type is basically a list of features/operations, that can be performed through that object reference.
The object reference Type basically is a contract that guarantees that those operations will be
there at run time.
When a car is created, it comes with a list of features/operations listed in the user manual that
guarantees that those will be there when the car is used.
When you create an object from a class by default its Type is the same as its class. It means that
all the features/operations the class defined are there and available, and can be used. See below:
(new ClassName()).operations();
You can assign this to a variable having the same Type as the class:
You can assign the created object reference to the class super class, or to an interface the class
implements:
In the car analogy, the created car may have different Type of drivers. We create separate user
manuals for them, Average user manual, Power user manual, Child user manual, or Handicaped
user manaul. Each type of user manual describes only those feathers/operations appropriate for
the type of driver. The Power driver may have additional gears to swith to higher speeds, that are
not available to other type of users...
When the car key is passed from an adault to a child we replacing the user manuals, that is called
Type Casting.
In java:
Type and Type Casting will be covered in more details later at ‘Types’ module.
Packages
Java Package / Name Space
Usually a Java application is built by many developers and it is common that third party
modules/classes are integrated . The end product can easily contain hundreds of classes. Class
name collision is likely to happen. To avoid this a Java class can be put in a “name space”. This
“name space” in Java is called the package.
The Java package needs to be unique across Vendors to avoid name collisions. For that reason
Vendors usually use their domain name in reverse order. That is guaranteed to be unique. For
example a company called ‘Your Company Inc.’, would use a package name something like this:
com.yourcompany.yourapplicationname.yourmodule.YourClass.
To put a class in a package, the package keyword is used at the top of each class file. For
Example,
package com.yourcompany.yourapplication.yourmodule;
When we want to reference a Java class that is defined outside of the current package, “name
space”, then we have to specify which pacake,name space that class at. So we could reference
that class something like this: com.yourcompany.yourapplication.yourmodule.YourClass . To
avoid to type in the package name each time when we want to reference an outside class, we can
declare which package the class belongs by using the import Java keyword at the top of the file.
For Example,
import com.yourcompany.yourapplication.yourmodule.YourClass;
Then we can refer to that class by just using the class name : YourClass .
In rare cases it can happen that you need to reference two classes having the same name in
different packages. In those cases you can not use the import keyword for both classes. One of
them needs to be referenced by typing in the whole package name. For Example,
package com.mycompany.myapplication.mymodule;
...
import com.yourcompany.yourapplication.youmodule.SameClassName;
...
SameClassName yourObjectRef = new SameClassName();
com.hercompany.herapplication.hermodule.SameClassName herObjectRef = new
com.hercompany.herapplication.hermodule.SameClassName();
The Java package has one more interesting characteristics; the package name corresponds where
the actual file is stored on the file system. And that is actually how the compiler and the class
loader find the Java files on the file system. For example, the class
com.yourcompany.yourapplication.yourmodule.YourClass, is stored on the file system in the
corresponding directory : com/yourcompany/yourapplication/yourmodule/YourClass. Because of
this package names should be lower case, since in some operating systems the directory names
are not case sensitive.
Nested Classes
In Java you can define a class inside an other class.
The inner class has the access of the outer class instance variable, even private, as seen above.
This makes it very different from the nested class in C++, where nesting is simple a name-hidding
mechanism.
The created inner object has the reference of the outer object. The nested object can only be
created through the ‘outer’ object. See below.
}
}
}
Anonymous Classes
In Java a class defination and its instantiation can be combined into a single step. By doing that
the class does not require to have a name. Those classes are called anonymous classes. An
anonymous class can be defined and instantiated in contexts where a reference can be used, and it
is a nested class to an existing class.
Anonymous classes are most useful to subclass and upcast to an ‘Adapter Class’ or to an
interface.
Access Modifiers
Access modifiers
You surely would have noticed by now, the words public, protected and private at the
beginning of class declarations used in this book. These keywords are called the access modifiers
in the Java language syntax, and can be defined as...
.. keywords that help set the visibility and accessibility of a class, its member
variables, and methods.
The following table shows what Access Modifiers are appropriate for classes, nested classes,
member variables, and methods:
Interface
Nested Member
Class Method Interface method
class variable
signature
visible visible
same as its same as its same as its visible from
public from from
class class class anywhere
anywhere anywhere
Points to ponder
Note that Inteface method visibility is public by default. You do not need to specify the
access modifier it will default to public. For clarity it is considered a good practise to
put the public keyword.
The same way all member variables defined in the Interface by default will become
static final once inherited in a class.
If a class has public visibility, the class can be referenced by anywhere in the program. If a class
has package visibility, the class can be referenced only in the package where the class is defined.
If a class has private visibility, (it can happen only if the class is defined nested in an other class)
the class can be accessed only in the outer class.
If a variable is defined in a public class and it has public visibility, the variable can be reference
anywhere in the application througth the class it is defined in. If a variable has package visibility,
the variable can be referenced only in the same package througth the class it is defined in. If a
variable has private visibility, the variable can be accessed only in the class it is defined in.
If a method is defined in a public class and it has public visibility, the method can be called
anywhere in the application througth the class it is defined in. If a method has package visibility,
the method can be called only in the same package througth the class it is defined in. If a method
has private visibility, the method can be called only in the class it is d
Methods
Method Definition
Method is an operation on a particular object. An object is an instance of a class. When we define
a class we define its member variables and its methods. For each method we need to give a name,
we need to define its input parameters and we need to define its return type. We also need to set
its visibility(private, package, or public). If the method throws an Exception, that needs to be
declared as well. The syntact of defining a method is:
class MyClass
{
...
public ReturnType methodName( ParemOneType param1, ParamTwoType param2 ) throws
ExceptionName
{
ReturnType retType;
...
return retType;
}
...
}
We can declare that the method does not return anything using the void java keyword. For
example:
When the method return nothing, the return keyword at the end of the method is optional. The
return keyward can be used anywhere in the method, when the executation flow reach the
return keyword, the method execution is stoped and the execution flow returns to the caller
method.
Method Overloading
For the same class we can define two methods with the same name. However the parameter types
and/or the number of parameters must be different for those two methods. In the java
terminology, this is called method overloading. It is useful to use method overloading when we
need to do something different based on a parameter type. For example we may have the
operation : runAroundThe. We can define two methods with the same name, but different input
parameter type:
public void runAroundThe( Building block )
{
...
}
public void runAroundThe( Park park )
{
...
}
Related terminology is the method signature. In java the method signature contains method
name and the input parameter types. The java compiler takes the signature for each method and
makes sure that each method signature is unique for a class. For example the following two
method defininations are valid:
Because the type order is different. If both input parameters were type String, that would be a
problem again since the compiler would not be able to distinguish between the two:
The compiler would give and error for the following method definations as well:
{
logIt( msg );
}
Method Overriding
Obviously a method signature has to be unique inside a class. The same method signature can be
defined in different classes. If we define a method that exsist in the super class then we override
the super class method. The terminology for this is method overriding. This is different from
method overloading. Method overloading happens with methods with the same name different
signature. Method overriding happens with same name, same signature between inhereted classes.
The return type can cause the same problem we saw above. When we override a super class
method the return type also must be the same. In fact if that is not the same, the compiler will
give you an error.
Method overriding is related dynamic linking, or runtime binding. In order to the Method
Overriding to work, the method call that is going to be called can not determined at compilation
time. It will be decided at runtime, and will be looked up in a table.
{
1 MyClass obj = new SubOfMyClass();
2
3 MyClass obj = new MyClass();
4
5 obj.myMethod(); // -- During compilation, it is not known what reference the ‘obj’
has, MyClass or SubOfMyClass
}
In the above example ‘obj’ reference has the type MyClass on both line 1 amd line 3. However
the ‘obj’ reference points two different objects. On line 1 it references SubOfMyClass object, on
line 3 it references MyClass object. So on line 5 which method will be called, method define in
MyClass, or the method that defined in its subclasses. Because the ‘obj’ reference can point to
object and all its sub object, and that will be known only at runtime, a table needs to be kept with
all the possible method address to be called.
Also an other rule is that when you do an override, the visibility of the new method that overrides
the super class method can not be reduced. The visisbility can increased, however. So if the super
class method visibility is public, the override method can not be package, or private.
In the case of the exception the override method may throw can be the same as the super calss or
it can be one of that exception inhereted class. So the common rule is that the override method
must be throw the same exception or its any of its subclasses.
NOTE: Common mistake to think that as we can override methods, we should be overrired
member variables. This is not the case however. Member variables are not overriden.
{
1 MyClass obj = new SubOfMyClass();
2
3 MyClass obj = new MyClass();
4
5 String var = obj.myMemberVar; // -- The myMemberVar is defined in the MyClass object
}
In the above example, it does not count what object the ‘obj’ reference point at, because it was
declared MyClass type on both line 1 and line 3, the variable in the MyClass object will be
referenced. In real file we rarely use public variables, but if you do keep in mind that variable can
not be overriden. I wonder if that can be done in C++ or not. <If someone knows could add it
here>
Parameter Passing
We can pass in all the primitive data types or any object references to a method. An object cannot
be passed to a method, only its references. All parameters (those are primitive types and object
references) are passed by value. In other words if you change the passed in parameter values
inside the method, that will have no effect on the original variable that was passed in. When you
pass in an object reference to a method and then you change that inside the method, that will have
no effect on the original object reference. However if you modify the object itself, that will stay
after the method returns. Think about the object reference as a pointer to an object. If you change
the object the reference points at, that will be permanent. For example:
1 {
2 int var1 = 10;
3 int var2 = 20;
4 ...
5 myMethod( var1, var2 );
6 ...
7 System.out.println( “var1=”+var1 +”var2=”var2 ); // -- The variable values did not
change
8 }
9 ...
10 void myMethod( int var1, int var2 )
11 {
12 ...
13 var1 = 0;
14 var2 = 0;
15 ...
16 }
On line 7 the value of var1 is 10 and the value of var2 is 20. When the variables were passed in to
the methods their values were copied. This is called passing the paramater by value. In java we do
not represent an object directly, we represent an object throught an object reference. You can
think of an object reference as a variable having the address of the object. So the object reference
passed in by value, but the object itself is not. For example:
1 {
2 MyObjOne obj = new MyObjOne();
3 obj.setName(“Christin”);
4 ...
5 myMethod( obj );
6 String name = obj.getName(); // --- The name attribute was changed to ‘Susan’ inside
the method
7 }
8 void myMethod( MyObjOne obj )
9 {
10 obj.setName(“Susan”);
11 ...
12 obj = new MyObjOne();
13 obj.setName(“Sonya”);
14 ...
15 }
On line 2, we created an object, on line 3 we set its name property to ‘Christin’. On line 5 we
called the myMethod( obj ). Inside the method, we changed the name to ‘Susan’ through the
passed in object reference. So that change will stay. Note however that after we reassigned the obj
reference to a new object, that is no effect whatsoever on the passed in object.
Return Parameter
A method may or may not return a value. If the method does not return a value we use the void
java keyword. Same as the parameter passing, the method can return a primitive type or an object
references. So a method can return only one value. What if you want to return more than one
value from a method. You can always pass in an object reference to the method, and let the
method modify the object properties. The modified values can be considered as an output value
from the method. However better option, and cleaner if you create an Object array inside the
method, assign the return values and return the array to the caller. You could have a problem
however, if you want to mix primitive data types and object references as the output values from
the method. There is a better approach. Define s special return object with the needed return
values. Create that object inside the method, assign the values and return the reference to this
object. This special object is “bound” to this method and used only for returning values, so do not
use a public class. The best way is to use a nested class, see example below:
public class MyObject
...
return ret;
}
}
In the above example the ‘getPersonInfoById’ method returns an object reference that contains
both values the name and age. See below how you may use that object:
{
...
MyObject obj = new MyObject();
MyObject.ReturnObj person = obj.getPersonInfoById( 102 );
System.out.println( “Person Name=” + person.getName() );
System.out.println( “Person Age =” + person.getAge() );
...
}
Special method, the Constructor
There is a special method for each class that will be executed each time an object is created from
that class. That is the Constructor . Constructor does not have a return value and its name is the
same as the class name. The Constructor can be overloaded; you can define more than one
constructor with different parameters. For example:
In the above example we defined two constructors, one with no input parameter, and one with one
input parameter. You may ask which constructor will be called. Its depends how the object is
created with the new keyword. See below:
{
...
MyClass obj1 = new MyClass(); // The constructor with no input parameter
will be called
MyClass obj2 = new MyClass(“Init Value”); // The constructor with one input param. will
be called
...
}
In the above example we created two objects from the same class, or we can also say that obj1
and obj2 both have the same type. The difference between the two is that in the first one the
memberVar field is not initialized, in the second one that is initialized to ‘Init Value’. obj1, and
obj2 contains the reference to the object. Each class must have a constructor. If we do not define
one, the compiler will create a default so called empty constructor automatically.
The Constructor is called automatically when an object is created with the new keyword. A
constructor may also be called from an other constructor, see bellow:
In the above example, the constructor with no input parameter calls the other constructor with the
default initial value. This gives an option to the user, to create the object with the default value or
create the object with a specified value.
Static Method
We defined method above as an operation on an object. Static Methods are defined inside a class,
but they are not an operation on an object. No object needs to be created to execute a Static
Method, they are simply global functions, with input parameters and a return value.
Static Methods can be referenced anywhere prefixed by the class name. See below:
{
...
// --- Call myStaticMethod ---
...
}
You can write a non object oriented program by using only Static Methods in java. Because java
evolved from theC programming language, Static Method is a left over from a non object oriented
language.
You write Static Method the same way as normal method, the only difference is that you can not
reference any member variables and any object methods. Static Methods can reference only Static
variables and call only other Static Methods. However you can create an object an use it inside a
Static Method.
Arrays can be defined using Java primitive types, but because they are not objects, they can not
be put in a collection.
For this reason object wrappers are defined in JDK ‘java.lang.*’ package for all the primitive
types.
double 64
double d =
Double
65.55d;
boolean 1
boolean b =
Boolean
true;
void -- -- -- -- Void
The numeric types like short, int, long, float, and double are used in arithmetic operations.
The character types like char, and byte are used in file input output operations.
Representing literal character strings, however, the String object is defined, in the java.lang.*
package. The java.lang.String is not a primive type, rather it is a special object built into the Java
language. For further info. see String.
Implicit : casting operation is not required; no data precision is lost due to the
conversion
Explicit : casting operation required; data precision may be lost due to the
conversion
int i = 65;
long l = i; // --- int is converted to long, casting is not needed
long l = 656666l;
int i = (int) l; // --- long is converted to int, casting is needed
The following table shows the conversions between primitive types, it shows the casting
operation for explicit conversions:
to - N/A
double
Autoboxing/unboxing
Autoboxing/unboxing
Autoboxing and unboxing, language features since Java 1.5, make the programmer’s
life much easier when it comes to working with the primitive wrapper types. Consider
this code fragment:
Primitive wrapper objects were Java’s way of allowing one to treat primitive data types as though
they were objects. Consequently, one was expected to ‘wrap’ one’s primitive data type with the
corresponding primitive wrapper object, as shown above.
Autoboxing
Since Java 1.5, one may write as below and the compiler will automatically create the
wrap object. The extra step of wrapping the primitive is no longer required. It has
been ‘automatically boxed up’ on your behalf.
Points to ponder
Keep in mind that the compiler still creates the missing wrapper code, so one doesn’t
really gain anything performance-wise. Consider this feature a programmer convenience,
not a performance booster.
Unboxing
Uses the same process in reverse. Study the following code for a moment. The if
statement requires a boolean primitive value, yet it was given a Boolean wrapper
object. No problem! Java 1.5 will automatically ‘unbox’ this.
Keywords
java.lang.String
java.lang.String
String is a special class built into the Java language defined in the java.lang.* package.
The String class represents character strings. String literals in Java programs, such as “abc”, are
implemented as instances of this class. Strings are constant; their values cannot be changed after
they are created.
For Example:
On the right hands side a String object is created representing the string literal and its object
reference is assigned to the str variable.
The Java language provides special support for the string concatenation operator ( + ), and for
conversion of other objects to strings. For example:
Each Java object has the String toString() inherited from the Object class. So it cen be
over ridden to convert the object to String.
The String class provides a nice set of methods for string manipulation. Since String objects
are immutable (constants), all methods return a new String object. For example:
name = name.trim();
The trim() method returns a copy of the string with leading and trailing whitespace removed.
Note that the following would do nothing useful:
name.trim(); // wrong!
This would create a new trimmed string and then throw it away. Study the String class and its
methods carefully. Strings are ubiquitous in Java; it will serve you well to know how to
manipulate them skillfully.
On the ( + ) operation a new String object is created at each iteration. Do not use it. Instead use
Template:Java:StringBuffer, see below, only one StringBuffer object is created:
Since Java 1.5, a new StringBuilder class was introduced. Performancewise StringBuilder class
is preferable, however it is not thread safe. So if only one thread is accessing your StringBuffer
object and performance may be an issue, consider to switch to StringBuilder.
Compare Strings
Compare two strings: Comparing strings is not as easy as it may first seem. We cannot just use
a simple equality statement such as:
We must instead use a method built into java.String class itself, the compareTo() method, which
can be accessed wherever we use a String datatype. Lets take a look at an example:
This snippet of code is comparing the String variable myString to “Hello World”. If the two
strings match exactly the toString method will return “0”, i.e. that there is no variance between
the two strings, and the statement body will run. However if myString was to be different, even in
the slightest manner we will get a value above or below 0 depending on the exact difference. The
result is a negative integer if this String object lexicographically precedes the argument string.
The result is a positive integer if this String object lexicographically follows the argument string.
Take a look at the Java API for more details.
To compare for exact match the equals() method can also be used.
...
An other usefull application could be to ‘split’ the String text based on the ‘new line’ character,
so you could process the text line by line.
Creating Substrings
It may also be sometimes useful to create substrings, or strings using the order of letters from an
existing string. This can be done in two methods.
The first method involves creating a substring out of the characters of a string from a given index
to the end.
For example:
In this example, substr would return “fee”. As previously discussed, the index of the first
character in a string is 0. By counting from there, it is apparent that the character in index 3 is the
second “f” in “coffee”. This is known as the beginIndex. All characters from the beginIndex
until the end of the string will be copied into the new substring.
The second method involves a user-defined beginIndex and endIndex. For example:
The string returned by substr would be “port”. Please note that the endIndex is not inclusive.
This means that the last character will be of the index endIndex-1. Therefore, in this example,
every character from index 3 to index 6, inclusive, was copied into the substring.
Note: “Substring” is considered to be one word. This is why the method name does not seem to
follow the common syntax of Java. It is easy to mistake the method substr() for subStr()
(which does not exist and would return with a syntax error on compilation). Just remember that
this style only applies to methods or other elements that are made up of more than one word.
Modifying String cases
The String Class also allows for the modification of cases. The two methods that make this
possible are toLowerCase() and toUpperCase(). These methods are useful, for example, in
the typical programming classroom assignment of evaluating whether or not a string is a
palindrome.
String a = “YAHOOS”;
String b = “google”;
import java.io.*;
public class ArrayExample {
static BufferedReader kbRead = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) throws IOException {
int numNames = getInt(“Number of names? “);
String[] names = new String[numNames];
for (int i = 0; i < names.length; i++) {
names[i] = getString(“Enter name #” + i);
}
Copy the code and compile it. The program will ask you to enter some names then reprints the
names in order. It demonstrates three major aspects of arrays: how to define an array, how to set
data, and how to access it. The code String[] names = new String[numNames]; tells
Java to create an array of size numNames that will store Strings. To set data, use names[x] =
data where x is the index to access. Note that all Java arrays start at 0 and go to array size - 1.
Thus, if you dimension an array to size 10, the highest index is 9.
Array Fundamentals
To create an array, use the syntax DataType[] variable = new
DataType[ArraySize]. Alternatively, if you know the data beforehand, you can
write DataType[] variable = {item 1, item 2,...item n}
To access an item, use the syntax variable[i] where i is the index
To set an item, use the syntax variable[i] = data
To find the length of an array, use the syntax variable.length
Two-Dimensional Arrays
Two dimensional array is represented by array of an array. Beacuse an array is also an object like
any other object having the Object as the super class, it can be used to create an array where the
element of the array are also an array. In this way any number of dimensional array can be
created. See below how two create two dimentional arrays with the initializer blocks:
In the above example we defined an array which has three elements, each elements contains an
array having 5 elements. We could create the array having the 5 elements first and use that one in
the initialize block.
Multidimensional Array
Going futher any number of dimentional array can be defined.
<elementType>[][]...[] <arrayName>
or
<elementType><arrayName>[][]...[]
For example, to create an int primitive type value, named yr that stores 2006;
int yr = 2006;
To access the data in yr, use the variable in place of the number.
System.out.println(yr);
Produces
2006
The value of yr is passed to the print method by value. It means that the yr variable value can not
be changed inside the print method. All variables in Java are passed to methods by value. The
content of the varaiable will be copied, and actually the copied value is passed to methods. So if
the passed in value changes inside the method, that change will be lost when the method returns.
When the variable contains a reference to an object, the object reference is passed in by value, the
same way as primitive type variables. The value of the object reference can not be changed by the
method, but the object itself can.
Scope
Variables only exist within the structure in which they are defined. For example, if a variable is
created within a method, it cannot be accessed outside the method. In addition, a different method
can create a variable of the same name which will not conflict with the other variable.
Generics
Generics were added to the Java language syntax in version 1.5. This means that code using
Generics will not compile with Java 1.4 and less.
Java was long criticized for the need to explicitly type-cast an element when it was taken out of a
“container/collection” class. There was no way to enforce that a “collection” class contains only
one type of object. This is now possible since Java 1.5.
In the first couple of years of Java evolution, Java did not have a real competitor. This has
changed by the appearance of Microsoft C#. With Generics Java is better suited to compete
against C#. Similar constructs to Java Generics exist in other languages, see w:Generic
programming for more information.
When an object is created, parameters can be passed to the created object, through the
constructor. Now with Generics, we can also pass in Types. The type-place-holders will be
replaced with the specified type, before the object is created.
for a class
When an object is created from that class the type-parameter-argument will be
replaced with the actual Type.
...
}
...
// --- Create an Employee person ---
Person<Employee> emplPerson = new Person<Employee>();
...
// --- Create a Customer person ---
Person<Customer> custPerson = new Person<Customer>();
for a method
Just like class declarations, method declarations can be generic—that is,
parameterized by one or more type parameters.
Introduction
Java is a “strongly” typed language. That’s why it is so easy to use. Many potential problems are
caught by the compiler. One area where Java was criticized was regarding the
“Container/Collection” objects. Container objects are objects that contain other objects. Before
Generics were introduced there was no way to ensure that a container object contains only one
type of objects. When an object was added to a container, it was automatically cast to Java
Object. When it was taken out an explicit cast was needed. Normaly an excplicit cast is checked
by the compiler.
But in the case of container classes, the compiler was not able to catch an invalid type casting.
collString is a container object, that can contain only String objects, nothing else, so when we get
out an element it can be casted only to class that normaly a String can be casted.
With Generics, Java strict type checking can be extended to container objects. Using Generics
with container classes, gives an impression that a new container type is created, with each
different type parameter. Before Generics:
With generics:
Both collObject and collCustomer have the same type, BUT it is against the Generic rule, that
is collCustomer can contain only Customer objects, and collObject can contain only Object
object. So there is an additional check to the normal type checking, the type of the parameter type
has to be matched too.
There are some differences however. The C++ template can be seen as a kind of macro, that
generates code before compilation. The generated code depends on how the Template class is
referenced. The amount of code generated depends on how many different types of classes are
created from the Template. C++ Templates do not have any run-time mechanisms. The compiler
creates normal code to substitute the template, similar to any ‘hand-written’ code.
In contrast, Java Generics are built into the language. The same Class object handles all the
Generic type variations. No additional code is generated, no matter how many Generic objects are
created with different type parameters. For example.
There is only one Class object created. The Class class itself is generic since Java 1.5.
The T type here represents the type that is handed to the Class object. The T type will be
substituted with the class being loaded.
Class<T>
Since Java 1.5, the class java.lang.Class is generic. It is an interesting example of using genericity
for something other than a container class.
For example, the type of String.class is Class<String>, and the type of Serializable.class is
Class<Serializable>. This can be used to improve the type safety of your reflection code.
In particular, since the newInstance() method in Class now returns a T, you can get more
precise types when creating objects reflectively.
Now we can use the newInstance() method to return a new object with exact type,
without casting.
// --- Using reflection, get a Java Bean property by its name ---
public static <T> T getProperty(Object bean, String propertyName)
{
if (bean == null ||
propertyName == null ||
propertyName.length() < 1)
{
return null;
}
// --- Based on the property name build the getter method name ---
String methodName = “get” +
propertyName.substring(0,1).toUpperCase() +
propertyName.substring(1);
T property = null;
try {
java.lang.Class c = bean.getClass();
java.lang.reflect.Method m = c.getMethod(methodName, null);
property = (T) m.invoke(bean, null);
} catch (Exception e) {
// --- Handle exception—
}
return property;
}
Wildcard Types
As we have seen above, generics give the impression that a new container type is created with
each different type parameter. We have also seen that in addition to the normal type checking, the
type parameter has to match as well when we assign generics variables.
In some cases this is too restrictive. What if we would like to relex this additional checking?
What if we would like to define a collection variable that can hold any generic collection,
regardless of the parameter type it holds?
Wildcard
The wildcard type is represented by the character <?>, and pronounced Unknown, or
Any-Type. This Unknown type matches anything, if it is used only by itself. Any-
Type can be express also by <? extends Object>. Any-Type includes Interfaces,
not only Classes.
So now we can define a collection whose element type matches anything. See below:
Collection<?> collUnknown;
Note that we can not add anything to this collection. We can only take out elements of type
Object from it. So what is the use of this variable if we can not add anything to the collection it
represents? The use of this new construct will be clear when you want to create a generic method
that takes any collection.
“<? extends ClassName>” specifies a restriction on the types of classes that may used.
For example, to create a collection that may only contain “Serializable” objects, specify:
The above code is valid because, the String class is serializable. Use of a class that is not
serializable would cause a compilation error.
The following collection can only contain objects that extend the class Animal.
fields - Fields hold data specific to each object. For example, an employee might
have an ID number. (It is also sometime called member variables)
member methods - Member methods perform operations on an object. For
example, an employee might have a method to issue his paycheck or to access his
name.
static fields - Static fields are common to any object of the same class. For
example, a static field within the Employee class could keep track of the last ID
number issued.
static methods - Static methods are methods that do not affect a specific object.
other classes - Sometimes it is useful to contain a class within another one if it is
useless outside of the class or should not be accessed outside the class.
Constructors - A special method that generates a new object.
Parameterized types - Since 1.5, ‘parameterized types’ can be assigned to a class
during definination. The ‘parameterized types’ will be substituted with the types
specified at the class’s instantiation. It is done by the compiler. It is simular the C
language macro ‘#define’ statement, where a pre-processor evaluate the ‘macros.
System.out.println(Employee.getNextID();
Employee a = new Employee(“John Doe”);
Employee b = new Employee(“Jane Smith”);
Employee c = new Employee(“Sally Brown”);
System.out.println(Employee.getNextID();
System.out.println(a.getID() + “: “ + a.getName());
System.out.println(b.getID() + “: “ + b.getName());
System.out.println(c.getID() + “: “ + c.getName());
0
3
0: John Doe
1: Jane Smith
2: Sally Brown
General Concepts
Abstraction
A class holds information about an entity in a complete system. Programmers produce code that
is inspired by the world around them. Extracting information from the world around them and
replicating the environment in a computer system is called Abstraction.
Concurrent
Collections Exceptions Reflection
Programming
The Java Virtual Machine (JVM), keeps track of the usage of object references. If there are no
more reference to the object, the object can not be used any more and becomes garbage. After a
while the heap memory will be full of unused objects. The JVM collects those garbage objects
and frees the memory they allocated, so the memory can be reused again when a new object is
created. See below a simple example:
{
// --- Create an object ---
MyObject obj = new MyObject();
The obj contains the object reference pointing to an object created from the MyObject class. The
obj object reference is in scope inside the { ). After the } the object becomes garbage. Object
references can be passed in to methods, object references can be returned from methods.
{
// --- Create an ‘MyObject’ for the first time the application started—
MyObject obj = new MyObject();
}
When an object from the MyObject class is created for the first time. The JVM searches the file
system for the definition of the class. The CLASSPATH environment variable contains locations
where Java classes are stored. The JVM is looking for the ‘MyObject.class’ file. Depending on
which package the class belongs to, the package name will be translated to a directory path.
When the ‘MyObject.class’ file is found, the JVM’s class loader loads the class in memory. The
JVM stores the code in memory, allocates memory for the static variables, and executes any
static initialize block. Memory is not allocated for the object member variables at this point,
memory will be allocated for them when an instance of the class, an object, is created.
There is no limit on how many objects from the same class can be created. Code and static
variables are stored only once, no matter how many objects are created. Memory is allocated for
the object member variables when the object is created. Thus, the size of an object is determined
not by its code’s size but by the memory it needs for its member variables to be stored.
You may ask why we need this clone method. Couldn’t I create a constructor and just passing in
the same object, and do the copying variable by variable? Lets see:
firstly, the private variables can not be assigned directly. To do that you need
setters and getters, which requires extra code.
secondly, and more importantly, performance. The clone() method copies the
whole object’s memory in one operation. This is much faster than using the new
keyword.
Object creation with the new keyword is expensive, so if you need to create lots of object with the
same type, performance will be better if you create one object and clone new ones from it. See
below a factory method that will return a new object using cloneing.
if ( template == null )
{
// --- Create template ---
template = new Customer();
_cacheTemplate.put( “Customer”, template );
}
return template.clone();
}
An other use of cloning could be to take a snapshot of an object that can change in time. Lets say
we want to store Customer objects in a collection, but we want to disassociate them from the
‘live’ objects . So before adding the object, we clone them, so if the original object changes from
that point forward, the added object won’t. Also lets say that the Customer object has a reference
to an Activity object that contains the customer activities. Now we are facing a promplem, it is
not enough to clone the Customer object, we also need to clone the referenced objects. The
solution:
}
return clonedCustomer;
}
}
Note that only mutable objects needs to be cloned. Object like String that can not change, the
same object reference can be used in the cloned object.
Object Serialization
The term Object Serialization refers to the act of converting the object to a byte
stream. The byte stream can be stored on the file system, or can be sent throught a
network.
At the later time the object can be re-created from that stream of bytes. The only
requirement is that the same class has to be available at both times, when the object is
serialized and also when the object is re-created. If that happens in deferent servers,
then the same class must be available on both servers. Same class means that exacly
the same version of the class must be available, otherwise the object won’t be able to
be re-created. This is a maintenance problem to those applications where java
seroalization is used to persist object or sent the object throught the network.
When a class is modified, there could be a problem re-creating those objects that were
serialized using an earlier version of the class.
Java has built in support for serialization.
Interfaces
Interfaces
Java does not allow you to create a subclass from two classes. There is no multiple inheritance.
The major benefit of that is that all java objects can have a common ancestor. That class called
Object. All java classes can be up-casted to Object. Example:
class MyObject
{
...
}
When you type the above code, it actually means the following:
class MyObject extends Object // -- The compiler adds ‘extends Object’. if not
specified
{
...
}
So it can be guaranteed that certain methods are available in all java classes. This makes the
language simpler.
To mimic multiple inheritance, java offers interfaces, which are similar to abstract classes. In
interfaces all methods are abstract by default, without the abstract key word. Interfaces have no
implementation and no variables, but constant values can be defined in interfaces.
}
Using Static Members
What does static mean?
When you declare a function, object, or variable static you are stating that it is independant of a
perticular object but rather to the entire class.
if you want a value to be shared or a method to be shared by all the defined objects of a paticular
class static is used . on a broader way can be considered as data sharing amongst objects of the
same class
Method, method parameter, and local variables have similar syntax: optional modifiers, a
required type, and the name of the value being declared.
Primitive Type
Object Reference Type
Java ia also known as a hybrid language. While supporting object oriented (OO) programming,
Java is not a pure OO language like Smalltalk or Ruby. Instead, Java offers both object types and
primitive types. Primitive types are used for boolean, character, and numeric values and
operations. This allows relative good performance when manipulating numeric data, at the
expense of flexibility. For example, you cannot subclass the primitive types and add new
operations to them.
Examples of Types
Below are two examples of Java types and a brief description of the allowed values and
operations for these types. Additional details on each are available in other modules.
Example: int
The primitive type int represents a signed 32 bit integer value. The allowed data values for int
are the integers between -2147483648 to 2147483647 inclusive.
The set of operations that may be performed on int values includes integer arithmetic such as +,
-, *, /, %, comparison operations (==, !=, <, >, <=, >=), assignments (=, ++, --,
+=, -=), bit-wise operations such as logical and, logical or, logical xor, negation (&, |, ^, ~),
bit shift operations (<<, >>, >>>), conversions to other numeric types and promotion to other
integer types.
For example, to declare a private integer instance field named length, one would use the
declaration
Example: String
You use class and interface definition in Java to define new types. Class and interface types
are associated with object references also sometime refered to as Reference types. An object
reference has two main attributes:
The String class is one such example. String values are a sequence of 0 or more Unicode
characters. The null reference is another valid value for a String expression.
The operations on a String reference variable are those available for all reference types, such as
comparison operations ==, != and assignment =.
The allowed operations on String object, however are the set of methods in the
java.lang.String class, which includes length(), toString(), toLowerCase(),
toUpperCase(), compareTo(String anotherString) and more... .
In addition, String objects also inherit the set of operations from the base class that String extends
from, which is java.lang.Object. These operations include methods such as equals(),
hashCode(), wait(), notifyAll(), and getClass().
Type is : String
The referenced object is also : String
Both the java.lang.String class methods and java.lang.Object class methods are
available for the object reference name.
Type is : Object
The referenced object is : String
Only the java.lang.Object class methods are available for the object reference name.
Array Types
Arrays in Java are represented as an in build Java Array object.
Concurrent
Collections Exceptions Reflection
Programming
finalize()
When an object is garbage-collected, the programmer may want to manually perform cleanup,
such as closing any open input/output streams. To accomplish this, the finalize() method is used.
Note that finalize() should never be manually called, except to call a super class’ finalize method
from a derivied class’ finalize method. Also, we can not rely on when the finalize() method will
be called. If the java application exits before the object is garbage-collected, the finalize() method
may never be called.
If, for example, a class declares two public methods with the same name, and a subclass overrides
one of them, the subclass still inherits the other method. In this respect, the Java programming
language differs from C++.
When a method is invoked , the number of actual arguments and the compile-time types of the
arguments are used, at compile time, to determine the signature of the method that will be
invoked . If the method that is to be invoked is an instance method, the actual method to be
invoked will be determined at run time, using dynamic method lookup.
Arrays
Intro to Arrays
An array is similar to a table of data, keyed by number. In Java an array is an object like all other
objects. Look at the following program:
import java.io.*;
public class ArrayExample {
static BufferedReader kbRead = new BufferedReader(new InputStreamReader(
System.in));
public static void main(String[] args) throws IOException {
int numNames = getInt(“Number of names? “);
String[] names = new String[numNames];
for (int i = 0; i < names.length; i++) {
names[i] = getString(“Enter name #” + i);
}
Copy the code and compile it. The program will ask you to enter some names then reprints the
names in order. It demonstrates three major aspects of arrays: how to define an array, how to set
data, and how to access it. The code String[] names = new String[numNames]; tells
Java to create an array of size numNames that will store Strings. To set data, use names[x] =
data where x is the index to access. Note that all Java arrays start at 0 and go to array size - 1.
Thus, if you dimension an array to size 10, the highest index is 9.
Array Fundamentals
To create an array, use the syntax DataType[] variable = new
DataType[ArraySize]. Alternatively, if you know the data beforehand, you can
write DataType[] variable = {item 1, item 2,...item n}
To access an item, use the syntax variable[i] where i is the index
To set an item, use the syntax variable[i] = data
To find the length of an array, use the syntax variable.length
Two-Dimensional Arrays
Two dimensional array is represented by array of an array. Beacuse an array is also an object like
any other object having the Object as the super class, it can be used to create an array where the
element of the array are also an array. In this way any number of dimensional array can be
created. See below how two create two dimentional arrays with the initializer blocks:
In the above example we defined an array which has three elements, each elements contains an
array having 5 elements. We could create the array having the 5 elements first and use that one in
the initialize block.
Multidimensional Array
Going futher any number of dimentional array can be defined.
<elementType>[][]...[] <arrayName>
or
<elementType><arrayName>[][]...[]
Introduction to Collections
The most basic collection interface is called Collection. This interface gives the user a generic
usage of a collection.
In the above there are two collections. The usage of the collections are the same, the
implementations are different. If the existing collection implementations do not meet your needs,
you can write your version of the implementation. Your version of the implementation just needs
to implement the same java.util.Collection interface, then you can switch using your
implementation and the code that is using the collection does not need to be changed.
import java.util.Collection;
import com.yourcomp.util.YourCollectionImpl;
...
Collection coll1 = new YourCollectionImpl();
Collection coll2 = new YourCollectionImpl();
...
< Use coll1 & coll2 >
The Java JDK collection implementations are quite good and powerful, so it is unlikely that you
will need to write your own.
All collections contain the object references. Because of that if the object is changed after it was
put in the collection, the object that is ‘in’ the collection also ‘changes’. The object is not really in
the collection, only the object reference is. It is not guaranteed that the objects ‘inside’ the
collections won’t change. This is an issue only if you put an actively used object in the collection.
In that case when you are adding an object that could change any time you need to make a copy
or clone of the object. A new object will be created and its reference will be put in the collection.
In that case there will be no object references outside of the collection, so the objects ‘inside’ the
collection can only be changed if we take out an object reference from the collection.
Addition to the java.util.Collection interface, the Java JDK has the java.util.Map
interface, as well. This defines key value mappings. Implementations of the Map interface do not
contain collections of objects, rather they contain collections of key->value mappings.
import java.util.Map;
import java.util.HashTable;
...
Map map = new HashTable();
...
map.put( key, value );
All collections need to have the same basic operations. Those are:
Can my collection contain the same elements, i.e. are duplicates allowed?
Can my collection contain the null element?
Should the collection maintain the order of the elements? Is the order important in
any way?
How do you want to access an element, by index, key or just with an iterator?
Does the collection need to be synchronized?
From a performance perspective, which one needs to be faster, updates or reads?
From a usage perspective, which operation will be more frequent, updates or
reads?
Once you know your needs, you can select an exsisting implementation. But first decide if you
need a ‘Collection’, or a ‘Map’.
Generics
Since JKD version 1.5 an enhancement to the type system of the Java language has been added. It
is called Generics. Most often Generics will be used with the collection classes.
All collection implementations since 1.5, now have one ‘parameterized type <E>’ added. The ‘E’
refers to an Element type. When a collection is created the actual ‘Element type’ will replace the
E.
Objects put into a collection is upcasted to Object class. It means that you need to cast the object
reference back when you get an element out from the collection. It also means that you need to
know the type of the object when you taking it out. For this reason usually we add object with the
same type to a collection. If a collection cantains different type of objects, we have the difficulty
finding out the type of the object nad run type.
With the use of the ‘parameterized type <E>’, the ‘Elements-type’ that can be put into the
collection, can be specified when the collection object is created.
ageList is a collection that can contain only Integer objects as elements. No casting is required
when we take out an element.
Collection or Map
The Java JDK contains two high level Interfaces:
java.util.Collection
java.util.Map
Implementations for those interfaces are not interchangeable. Collections are used for collecting
Java objects. Maps are used for mapping key/value pairs.
Collection
Use the Collection interface if you need to keep related (usually same type of) objects together in
a collection where you can:
boolean add( E o );
boolean addAll( Collection c );
boolean remove( Object o );
boolean removeAll( Collection c );
boolean retainAll( Collection c );
The methods above return true if the collection changed due to the operation. Note, that in
addAll() we can add any type of collection. This is the beauty of using the Collection interface.
You can have a LinkList and just call the addAll(list) method, passing in a list. You can pass
in a Vector, an ArrayList, a HashSet, a TreeSet, a YourImpOfCollection, ... All those
different type of collections will be magically converted to a LinkList.
Lets have a closer look at this magic. The conversion is easy because, the Collection interface
defines a standard way of looping through the elements. The following code is a possible
implementation of addAll() method of the LinkList.
import java.util.Collection
import java.util.Iterator
...
public String addAll( Collection coll )
{
int sizeBefor = _linkLink.size();
Iterator iter = coll.iterator();
while( iter.hasNext() )
{
_linkList.add( iter.next() );
}
if ( sizeBefore > _linkList.size();
{
return true;
}
else
{
return false;
}
}
The above code just iterate through the passed in collection and adds the elements to the link list.
You do not have to do that, since that is already defined. What you might need to code for is to
loop through a ‘Customer’ collection:
import java.util.Collection
import java.util.Iterator
import java.yourcompany.Customer
...
{
StringBuffer buf = new StringBuffer();
Iterator iter = customerColl.iterator();
while( iter.hasNext() )
{
Customer cust = (Customer) iter.next();
buf.append( cust.getName() );
buf.append( “\n” );
}
return buf.toString();
}
Map
Map, sometime also called as an Associated Array and sometimes as a Dictionary, can be thought
of as an array where the index need not be an integer.
Use the Map interface if you need to keep related objects together in a Map where you can:
Figure 2:
java.util.Set<E>
contains unique elements, so duplicates not allowed. It is similar to Mathematical
Set.
java.util.List<E>
elements are put in the list in a certain order, and can be accessed by an index.
Duplicates are allowed, the same element can be added to a list.
java.util.SortedSet<E>
same as the Set interface; plus the elements in the SortedSet are sorted
java.util.Queue<E>
queues provide additional insertion, extraction, and inspection operations. FIFO(first-
in-first-out), or LIFO(last-in-first-out) queues.
java.util.BlockingQueue<E>
wait for the queue to become non-empty when retrieving an element, and wait for
space to become available in the queue when storing an element, best used for
producer-consumer queues.
Set
Set can not have duplicates. You may wonder how duplicates are detected when we are adding
an object to the Set. We have to see if that object exsits in the Set or not. It is not enough to
check the object references, the objects values have to be checked as well.
To do that, fortunately, each java object has the boolean equal(Object obj);, method
available inherited from Object. You need to override it. That method will be called by the Set
implementation to compare the two objects to see if they are equal or not.
There is a problem, though. What if I put two different type of objects to the Set. I put an Apple
and an Orange. They can not be compared. Calling the equal() method would cause a
ClassCastException. There are two solutions to this:
Solution one : Override the int hashCode() method and return the same values
for the same type of objects and return different values for different type of
objects. The equal() method is used to compare objects only with the same value
of hasCode. So before an object is added, the Set implementation needs to.
find all the objects in the Set that has the same hashCode as the candidate
object hashCode
and for those, call the equal() methods passing in the candidate object
if any of them returns true, the object is not added to the Set.
Solution two : Create a super class for the Apple and Orange, lets call it Fruit
class. Put Fruits in the Set. You need to do the followings:
Do not override the equals() and hashCode() methods in the Apple and
Oragne classes
Create appleEquals() method in the Apple class, and create
orangeEquals() method in the Orange class
Override the hashCode() method in the Fruit class and return the same
value, so the equals() is called by the Set implementation
Override the equals() method in the Fruit class for something like this.
Note:
only those objects are compared that has the same hashCode.
you are responsible to override the equal() and hashCode() methods, the default
won’t work
only override the hashCode() method, if you want to elmiminate value
duplicates.
do not override the hashCode() method, if you know that the values of your
objects are different, and or if you only want to prevent adding the exactly same
object.
beware that the hashCode() may be used in other collection implementaions, like
in a HashTable to find an object fast. Overriding the default hasCode() method
may cause performance problems there.
the default hashCodes are unique for each object created, so if you decide not to
override the hashCode() method, there is no point overriding the equal()
method, it won’t be called.
SortedSet
The SortedSet interface extends the Set Interface. All elements in the SortedSet must implement
the Comparable Interface, futher more all elements must be mutually comparable.
Note that the ordering maintained by a sorted set must be consistent with equals if the sorted set is
to correctly implement the Set interface. This is so because the Set interface is defined in terms of
the equals operation, but a sorted set performs all element comparisons using its compareTo (or
compare) method, so two elements that are deemed equal by this method are, from the standpoint
of the sorted set, equal.
The SortedSet interface has additional methods due to the sorted nature of the ‘Set’. Those are:
List
The basic implemenation of the List interface is the ArrayList. The ArrayList is not
syncronized, not thread safe. Vector is syncronized, and thread safe. Vector is slower, because
of the extra overhead to make it thread safe. When only one thread is accessing the list, use the
ArrayList. Whenever you insert or remove an element from the list, there are extra overhead to
reindex the list. When you have a large list, and you have lots of insert and remove, consider
using the LinkList.
The name LinkList implies a special data structure where the elements/nodes are connected by
pointers. To remove an element from the link list the pointers need to be rearranged.
Queue
The Queue interface adds the following operations to the Collection interface:
Retrieves, but does not remove, the head of this queue. This method
E element() differs from the peek method only in that it throws an exception if this
queue is empty
boolean
Inserts the specified element into this queue, if possible.
offer(E o)
Retrieves, but does not remove, the head of this queue, returning null if
E peek()
this queue is empty
Retrieves and removes the head of this queue, or null if this queue is
E poll()
empty
Retrieves and removes the head of this queue. This method differs from
E remove()
the poll method in that it throws an exception if this queue is empty.
java.util.PriorityQueue<E>
orders elements according to an
order/priority specified at
construction time, null element is not
allowed.
java.util.concorrent.ArrayBlockingQueue<E>
orders elements FIFO; syncronized,
thread safe.
java.util.concorrent.SyncronousQueue<E>
each put must wait for a take, and
vice versa, does not have any internal
capacity, not even a capacity of one,
an element is only present when you
try to take it; you cannot add an
element (using any method) unless
another thread is trying to remove it
Map Classes
The Map interface has the following implementations:
java.util.TreeMap<E>
guarantees that the map will be in ascending key order, sorted according to the natural
order for the key’s class, not-syncronized.
java.util.HashMap<E>
is roughly equivalent to Hashtable, except that it is unsynchronized and permits
nulls
java.util.concurrent.ConcurrentHashMap
same HashTable, plus retrieval operations (including get) generally do not block, so
may overlap with update operations (including put and remove).
java.util.HashTable<E>
Syncronized, null can not be used as key
java.util.WeakHashMap<E>
entry in a WeakHashMap will automatically be removed when its key is no longer in
ordinary use. Nonsyncronized.
java.util.LinkHashMap<E>
This linked list defines the iteration ordering, which is normally the order in which
keys were inserted into the map (insertion-order). Note that insertion order is not
affected if a key is re-inserted into the map.
java.util.IdentityHashMap
This class implements the Map interface with a hash table, using reference-equality in
place of object-equality when comparing keys (and values). In other words, in an
IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2).
(In normal Map implementations (like HashMap) two keys k1 and k2 are considered
equal if and only if (k1==null ? k2==null : k1.equals(k2)).) Not-syncronized.
java.util.EnumMap
All of the keys in an enum map must come from a single enum type that is specified,
explicitly or implicitly, when the map is created. Enum maps are represented
internally as arrays. This representation is extremely compact and efficient. Not-
syncronized.
A new Java JDK package was introduced at Java 1.5, that is java.util.cuncurrent. This
package supplies a few Collection implementations designed for use in multithreaded
environments.
syncronized non-syncronized
java.util.Vector java.util.ArrayList
java.util.Stack
List
java.util.LinkList
java.util.cuncurrent.CopyOneWriteArrayList
Set java.util.TreeSet
java.util.HashSet
java.util.LinkHashSet
java.util.cuncurrent.CopyOneWriteArraySet
java.util.TreeMap
java.util.HashTable
Map java.util.HashMap
java.util.concurrent.ConcurrentHashMap
java.util.LinkHashMap
java.util.IdentityHashMap
java.util.EnumMap
Handling exceptions
Let’s examine the following code:
In the code sample, methodB is invalid. Because methodA and methodB pass (or throw)
exceptions, methodC must be prepared to handle them. This can be handled in two ways: a try -
catch block, which will handle the exception within the method and a throws clause which
would in turn throw the exception to the caller to handle. The above example will cause a
compilation error, as Java is very strict about exception handling. So the programmer forced to
handle any possible error condition at some point.
A method can do two thinks with an exception. Ask the calling method to handle it by the
throws declaration. Or handle the exception inside the method by the try-catch block.
To construct a throws declaration, add throws ExceptionName (additional exceptions can be
added with commas). To construct a try - catch block, use the following syntax
...
try {
//Possibly exception-causing code
}
catch (TheException e) {
//Handle the exception
}
finally {
//Optional. Executes regardless of exceptions thrown
}
The original code can be modified to work correctly in multiple ways. For example, the
following:
The AnotherException from methodB will be handled locally, while CustomException and
SomeException will be thrown to the caller to handle it.
Application Exceptions
Application Exception classes should extend the java.lang.Exception class. Some of the
JDK classes also throws exception objects inherited from java.lang.Exception. If any of
those Exception object is thrown, it must be caught by the application some point, by a catch-
block. The compiler will enforce that there is a catch-block associated with an exception thrown,
if the thrown exception object is inherited from java.lang.Exception and it is not the
java.lang.RuntimeException or its inherited objects. However,
java.lang.RuntimeException or its inherited objects, can be caught by the application, but
that is not enforced by the compiler.
Lets see what is the catching criteria for a catch block to catch the “thrown” exception.
the thrown exception object is the same as the exception object specified by the
catch-block
the thrown exception object is the subtype of the exception object specified by the
catch-block
try {
throw new Exception( “This will be catched below” );
}
catch( Exception e ) {
// --- The “thrown” object is the same what is specified at the catch-block—
}
try {
throw new NullPointerException( “This will be catched below” );
}
catch( Exception e ) {
// --- NullPointerException is subclass of the Exception class—
}
There can be more than one catch-block for a try-block. The catching blocks eveluated
sequentially one by one. If a catch-block catch the exception, the others will not be eveluated.
Example:
try {
throw new NullPointerException( “This will be catched below” );
}
catch( Exception e ) {
// --- The above NullPointerException will catched by here—
}
catch( NullPointerException e ) { // --- THIS CODE NEVER EXECUTED - Compiler error
// ---
}
try {
throw new NullPointerException( “This will be catched below” );
}
catch( NullPointerException e ) {
// --- The above NullPointerException will catched by here ---
}
catch( Exception e ) {
// --- Any other exception except the NullPointerException will be caught here—
}
Runtime Exceptions
The java.lang.RuntimeException exception class is inherited from
java.lang.Exception. It is a special exception class, because catching this exception class or
its subclasses are not enforced by the Java compiler.
runtime exception
Runtime exceptions are usually caused by data errors, like arithmetic overflow,
devide by zero, ... . Runtime exceptions are not business related exceptions. In a well
debbuged code, runtime exceptions should not occure.
NullPointerException
Applications should throw instances of this class to indicate other illegal uses of the null object.
The above code shows one of the pitfall of Java, and the most common source of bugs. No object
is created and the compiler does not detect it. NullPointerException is one of the most common
exception thrown in Java.
The reason we need it because many times we need to create a object reference, before the object
itself is created. Object references can not exsist without a value, so we assign the null value to
it.
...
}
return customer;
}
In the above code we want to create the Customer inside the try-block, but we also want to return
the object reference to the caller, so we need to create the object reference outside of the try-
block, because of the scopeing rule in Java. This is one of the pitfall of Java.
This page describes some techniques for preventing NullPointerException. It does not describe
general techniques for how you should program Java. It is of some use, to make you more aware
of null values, and to be more careful about generating them yourself. Note that this list is not
complete - there are no rules for preventing NullPointerException entirely in Java, because the
standard libraries have to be used, and they can cause NullPointerExceptions. Also, it is possible
to observe an uninitialised final field in Java, so you can’t even treat a final field as being
completely trusted during the object’s creation. A good approach is to learn how to deal with
NullPointerExceptions first, and become competent with that. These suggestions will help you to
cause less NullPointerExceptions, but they don’t replace the need to know about
NullPointerExceptions.
String s=null;
while (something)
if (something2)
s=”yep”;
if (s!=null)
something3(s);
boolean done=false;
while (!done && something)
if (something2)
{
done=true;
something3(“yep”);
}
You might also consider replacing null with “” in the first example, but default values bring about
bugs caused by default values being left in place. A NullPointerException is actually better, as it
allows the runtime to tell you about the bug, rather than just continue with a default value.
Minimize the use of the new Type[int] syntax for
creating arrays of objects
An array created using new Object[10] has 10 null pointers. That’s 10 more than we want, so use
collections instead, or explicitly fill the array at initialisation with:
or:
Object[] objects;
objects=new Object[]{”blah”,5,new File(“/usr/bin”)};
You can decide to trust some methods not to return null, if you like, but that’s an assumption
you’re making. Some methods that don’t specify that they might return null, actually do, instead
of throwing an exception.