Java Notes
Java Notes
What is Java?
Java - an island of Indonesia, a type of coffee, and a
programming
language. Three very different meanings, each in varying degrees of
importance. Java is a high-level programming language, like C, C++,
Smalltalk, Perl, and many others. You can use Java to write computer
applications that crunch numbers, process words, play games, store
data or do any of the thousands of other things computer software can
do.
purely object-oriented
multi-threaded
automatic garbage collection
secure
network and "Internet" aware
platform independent
Object-oriented
Many older languages, like C and Pascal, were procedural
languages. Procedures (also called functions) were blocks of code that
were part of a module or application. Procedures passed parameters
(primitive data types like integers, characters, strings, and floating
point numbers). Code was treated separately to data. You had to pass
around data structures, and procedures could easily modify their
contents. This was a source of problems, as parts of a program could
have unforeseen effects in other parts. Tracking down which procedure
-3-
was at fault wasted a great deal of time and effort, particularly with
large programs.
In some procedural language, you could even obtain the memory
location of a data structure. Armed with this location, you could read
and write to the data at a later time, or accidentally overwrite the
contents.
Java is an object-oriented language. An object-oriented language deals
with objects. Objects contain both data (member variables) and code
(methods). Each object belongs to a particular class, which is a
blueprint describing the member variables and methods an object
offers. In Java, almost every variable is an object of some type or
another - even strings. Object-oriented programming requires a
different way of thinking, but is a better way to design software than
procedural programming.
There are many popular object-oriented languages available today.
Some like Smalltalk and Java are designed from the beginning to be
object-oriented. Others, like C++, are partially object-oriented, and
partially procedural. In C++, you can still overwrite the contents of
data structures and objects, causing the application to crash.
Thankfully, Java prohibits direct access to memory contents, leading to
a more robust system.
Portable
Most programming languages are designed for a specific
operating system and processor architecture. When source code (the
instructions that make up a program) are compiled, it is converted to
machine code which can be executed only on one type of machine.
This process produces native code, which is extremely fast.
Another type of language is one that is interpreted. Interpreted code is
read by a software application (the interpreter), which performs the
specified actions. Interpreted code often doesn't need to be compiled -
-4-
The approach Java takes offers some big advantages over other
interpreted languages. Firstly, the source code is protected from view
and modification - only the bytecode needs to be made available to
users. Secondly, security mechanisms can scan bytecode for signs of
modification or harmful code, complimenting the other security
mechanisms of Java. Most of all though, it means that Java code can be
compiled once, and run on any machine and operating system
combination that supports a Java Virtual Machine (JVM). Java can run
on Unix, Windows, Macintosh, and even the Palm Pilot. Java can even
run inside a web browser, or a web server. Being portable means that
the application only has to be written once - and can then execute on a
wider range of machines. This saves a lot of time, and money.
-5-
Multi-threaded
If you've ever written complex applications in C, or PERL, you'll
probably have come across the concept of multiple processes before.
An application can split itself into separate copies, which run
concurrently. Each copy replicates code and data, resulting in
increased memory consumption. Getting the copies to talk together
can be complex, and frustrating. Creating each process involves a call
to the operating system, which consumes extra CPU time as well.
A better model is to use multiple threads of execution, referred to as
threads for short. Threads can share data and code, making it easier to
share data between thread instances. They also use less memory and
CPU overhead. Some languages, like C++, have support for threads,
but they are complex to use. Java has support for multiple threads of
execution built right into the language. Threads require a different way
of thinking, but can be understood very quickly. Thread support in Java
is very simple to use, and the use of threads in applications and
applets is quite commonplace.
Secure
Security is a big issue with Java. Since Java applets are
downloaded remotely, and executed in a browser, security is of great
concern. We wouldn't want applets reading our personal documents,
deleting files, or causing mischief. At the API level, there are strong
security restrictions on file and network access for applets, as well as
support for digital signatures to verify the integrity of downloaded
code. At the byte code level, checks are made for obvious hacks, such
as stack manipulation or invalid byte code. The strong security
mechanisms in Java help to protect against inadvertent or intentional
security violations, but it is important to remember that no system is
perfect. The weakest link in the chain is the Java Virtual Machine on
which it is run - a JVM with known security weaknesses can be prone to
attack. It is also worth noting that while there have been a few
identified weaknesses in JVMs, they are rare, and usually fixed quickly.
Java also includes support for more exotic network programming, such
as remote-method invocation (RMI), CORBA and Jini. These distributed
systems technologies make Java an attractive choice for large
distributed systems.
Platform Independent
Java is platform independent. It means that programs written in
the Java language will run similarly on any supported
hardware/operating-system platform. One should be able to write a
program once, compile it once, and run it anywhere. Programs can be
written anywhere and be run anywhere. That is, any computer with a
Java virtual machine can run a Java program. This is crucial because if
a language can not run on any machine, it cannot be used on the web
that must service every machine, language, and environment
imaginable.
Byte Code
-9-
Java byte code is the form of instructions that the Java virtual
machine executes. Each byte code instruction is one byte in length
(hence the name)
The API provides a set of standard class libraries. The virtual machine
and API have to be consistent with each other and are therefore
bundled together as the JRE. This can be considered a virtual computer
in which the virtual machine is the processor and the API is the user
interface.
Java
Java is a programming language originally developed by Sun
Microsystems and the first public implementation of Java is Java 1.0 in
1995.
Java's Editions (In mid-1999, Sun defined three editions for Java)
The Standard Edition: The Java 2 Standard Edition (J2SE) is
the basic version for creating regular applications and applets.
The Enterprise Edition: The Java 2 Enterprise Edition (J2EE) is
the Java version that comes bundled with support for EJB, JMS, JNDI,
servlets, JSP, and other enterprise services.
The Micro Edition: The Java 2 Micro Edition (J2ME) is the Java
version for developing programs on small platforms such as cell
phones, PDAs, and printers.
JDK (SDK):
A Java Developer's Kit (JDK) or Software Developer's Kit
(SDK) includes a compiler for Java source code (.java files) as well as a
runtime engine for Java classes (.class files).
- 10 -
JRE:
This JRE (Java Runtime Environment) is a software bundle
from sun Microsystems consists of the JVM and the programming
interface (API).
A Java Runtime Environment (JRE) includes only the runtime
engine. If you plan on writing code, then you must have developers kit
called “JDK" or "SDK", (depending on the Java version). If you only need
to run java classes that someone else created, the runtime
environment (which is much smaller) is enough.
The API and Java Virtual Machine insulate the program from the underlying hardware.
Note: every version from 1.2 and beyond is known as "Java 2",
and contains Java's advanced graphics libraries (Swing and
Java 2D).
- 11 -
Java Versions
Java has had several releases in its early years and the language has
quickly grown in size:
Data Types
There are 9 data types in Java, 8 primitive types and a reference type.
- 14 -
boolean
The boolean data type has only two possible values: true and
false. Use this data type for simple flags that track true/false
- 15 -
conditions. This data type represents one bit of information, but its
"size" isn't something that's precisely defined.
char
To support Unicode characters, Java provides the char data type. Based on this, to
declare a variable that would be used to store characters, use the char keyword.
To initialize the variable, assign it a single-quoted character.
byte
A byte is series of 8 bits. It is used to represent (very) small
numbers. To declare a variable that would hold a natural number
between -128 and 127, you can use the byte data type.
The Java class associated with the byte data type is called Byte
short
An integer is referred to as short if its value is between -32768
and 32767. This number can fit in 16 bits.
The Java class associated with the short data type is called
Short
int
The word integer is also used for a natural number. An integer is
simply a natural number. Many, if not most, languages provide
different data types for various categories of integers. In Java, an
integer is variable whose values are between -2,147,483,648 and
2,147,484,647. The value is also said to fit in a 32-bit range.
The Java class associated with the int data type is called
Integer
long
A number that is higher than a regular integer can hold is called
a long integer. To support this type of number, the Java language
provides the long data type. A long integer is a variable that can hold
very large number that may require 64 bits to be stored accurately.
- 16 -
init:
deps-jar:
Compiling 1 source file to
C:\Programs\JavaLessons\Exercise1\build\classes
C:\Programs\JavaLessons\Exercise1\src\exercise1\Main.java:24: integer
number too large: 245885475475
long days = 245885475475;
1 error
BUILD FAILED (total time: 0 seconds)
The program would not work because the compiler would have reserved space for
an integer but the assigned value needs more room. If you insist on using enough
memory for a long integer, when initializing it, on the right side of the value, type
L. Here is an example:
package exercise1;
This time, the program works fine because the compiler was explicitly asked to
reserve enough memory.
The Java class associated with the long data type is called Long.
Double-Precision Values
- 17 -
Double
The Java class associated with the double data type is called Double
Single-Precision Values
float
The float data type is a single-precision 32-bit IEEE 754 floating
point.
Although a double variable uses memory more than the average variable, because
memory is not expensive anymore, most programmers usually use the double
data type instead of the float when declaring their variables. Use float only if you
must.
The Java class associated with the float data type is called Float.
Final Variables
A variable is referred to as final when its value doesn't change throughout the
program. This is the C/C++/C# equivalent to a constant. To create a final value,
type final, followed by the type of the variable, its name, the assignment operator
"=", and the desired value.
Default Values
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
The following chart summarizes the default values for the above data
types.
- 18 -
Keywords are reserved words that are predefined in the language. All
the keywords are in lowercase.
Escape Characters
Access specifiers
Class
A class is a blueprint for creating different objects which defines
its properties and behaviors. An object exhibits the properties and
behaviors defined by its class.
Objects
An object is an instance of a class created using a new operator.
The new operator returns a reference to a new instance of a class. This
reference can be assigned to a reference variable of the class. The
process of creating objects from a class is called instantiation.
Instantiating a Class
The new keyword is a Java operator that creates the object. The
new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator
also invokes the object constructor.
Constructor
All classes have at least one constructor. If a class does not
explicitly declare any, the Java compiler automatically provides a no-
argument constructor, called the default constructor. This default
constructor calls the class parent's no-argument constructor or the
Object constructor if the class has no other parent. If the parent has no
constructor (Object does have one), the compiler will reject the
program.
Constructors
A class contains constructors that are invoked to create objects
from the class blueprint. Constructor declarations look like method
declarations—except that they use the name of the class and have no
return type.
- 23 -
You don't have to provide any constructors for your class, but you must
be careful when doing this. The compiler automatically provides a no-
argument, default constructor for any class without constructors. This
default constructor will call the no-argument constructor of the super
class. In this situation, the compiler will complain if the super class
doesn't have a no-argument constructor so you must verify that it
does. If your class has no explicit super class, then it has an implicit
super class of Object, which does have a no-argument constructor
All classes have at least one constructor. If a class does not explicitly
declare any, the Java compiler automatically provides a no-argument
constructor, called the default constructor. This default constructor
calls the class parent's no-argument constructor or the Object
constructor if the class has no other parent. If the parent has no
constructor (Object does have one), the compiler will reject the
program.
When you define a class derived from another class, the first line of a
constructor must be a call to the constructor of the base class, unless
the base class has an accessible constructor that takes no parameters.
Note
Parameters refer to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method
is invoked. When you invoke a method, the arguments used must
match the declaration's parameters in type and order.
Modifiers
You can use the same modifiers for inner classes that you use for other
members of the outer class. For example, you can use the access
- 24 -
Interface
An interface is a contract between a class and the outside world.
When a class implements an interface, it promises to provide the
behavior published by that interface. This section defines a simple
interface and explains the necessary changes for any class that
implements it.
In Java an interface is similar to an abstract class in that its members
are not implemented. In interfaces, _none_ of the methods are
implemented. There is no code at all associated with an interface.
Package
A package is a namespace for organizing classes and interfaces
in a logical manner. Placing your code into packages makes large
software projects easier to manage. This section explains why this is
useful, and introduces you to the Application Programming Interface
(API) provided by the Java platform.
so using the this reference. Note that the this reference cannot be
used in a static
context, as static code is not executed in the context of any object.
Abstract Classes
Interfaces
Java does not allow multiple inheritance for classes (ie. a subclass
being the extension of more than one superclass). To tie elements of
different classes together Java uses an interface. Interfaces are
similar to abstract classes but all methods are abstract and all
properties are static final. As an example, we will build a Working
interface for the subclasses of Animal. Since this interface has the
method called work(), that method must be defined in any class using
Working.
- 26 -
When you create a class that uses an interface, you reference the
interface with the reserved word implements Interface_list.
Interface_list is one or more interfaces as multiple interfaces are
allowed. Any class that implements an interface must include code for
all methods in the interface. This ensures commonality between
interfaced objects.
Polymorphism
Polymorphism is the capability of an action or method to do
different things based on the object that it is acting upon. This is the
third basic principle of object oriented programming. We have already
used two types of polymorphism (overloading and overriding). Now we
will look at the third: dynamic method binding.
- 27 -
Assume that three subclasses (Cow, Dog and Snake) have been
created based on the Animal abstract class, each having their own
speak() method.
String Manipulation
String manipulation forms the basis of many algorithms and utilities.
Input validation, text analysis and file conversions are several direct
applications of string manipulation. This tutorial explores some of the
basics needed. Unless otherwise noted, the following classes are
contained in the java.lang library.
String class objects are immutable (ie. read only). When a change is
made to a string, a new object is created and the old one is disused.
This causes extraneous garbage collection if string modifier methods
are used too often. The StringBuffer class should be used instead of
String objects in these cases.
Warning: Since strings are stored differently than other data (as a
memory address), you can't use the == operator for comparison.
However the string methods equals() and equalsIgnoreCase() do
the required comparison. A simple example is:
String testString="agjSDRoir";
String validChars = "atgc";
testString=testString.toLowerCase(); // make sure case is correct
for (int i=0;i<testString.length();i++)
{
char c = testString.charAt(i);
if (validChars.indexOf(c)== -1)
{System.out.printf("Invalid character[)"+c+"] at position "+i}
}
import java.util.*;
public class Test
{
public static void main(String args[])
{
int idx = 0; int tokenCount;
String words[] = new String [500];
String message="The text of the message to be broken up for
analysis";
StringTokenizer st = new StringTokenizer(message);
tokenCount = st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // make sure there is stuff to get
{ words[idx] = st.nextToken(); idx++; }
for (idx=0;idx<tokenCount; idx++)
{ System.out.println(words[idx]); }
}
}
Applets
Java applications that run from within a browser are referred to as
Applets. They are similar to java programs but have a template of
sequence for execution, without having a main in the application.
Java provides its own browser to view applets. It is referred to as
appletviewer, can be found in the bin directory.
The java program is compiled to get the .class file which is then
embedded inside the html code, to get executed from within the
browser.
1. init()
Executes only once in the life time of the
applet, used to initialize variables, or create
components.
2. start()
Executes every time the control return to
the page after it has lost the focus. It is used to
resume thread operations.
3. paint()
Executes every time you leave and return to
the page. It is used to display data, set page
properties such as colors, fonts or to change
dimension of the page.
Terminating
1. stop()
Terminate the applet by performing any
garbage collection.
2. destroy()
Dispose the applet. (Totally removes the
applet from the memory)
Syntax:
<APPLET CODE = appletFile WIDTH = pixels HEIGHT = pixels>
</APPLET>
CODE:
CODE is a required attribute that gives the name of the file
containing your applet’s compiled .class file. This file should be in the
directory mention by the CODEBASE attribute.
WIDTH & HEIGHT are the required attributes that gives the size
(in pixels) of the applet display area.