Sei sulla pagina 1di 33

-1-

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.

The most special about Java in relation to other programming


languages is that it lets you write special programs called applets that
can be downloaded from the Internet and played safely within a web
browser.
Even more dangerous software would be promulgated if any web page
you visited could run programs on your system. You have no way of
checking these programs for bugs or for out-and-out malicious
behavior before downloading and running them.
Java solves this problem by severely restricting what an applet can do.
A Java applet cannot write to your hard disk without your permission. It
cannot write to arbitrary addresses in memory and thereby introduce a
virus into your computer. It should not crash your system.

The properties that make Java so attractive are present in other


programming languages. Many languages are ideally suited for certain
types of applications, even more so than Java. But Java brings all these
properties together, in one language.

Let's look at some of the properties in more detail: -


 simple and ease-of-use
-2-

 purely object-oriented
 multi-threaded
 automatic garbage collection
 secure
 network and "Internet" aware
 platform independent

Simple and ease-of-use


Java draws its roots from the C++ language. C++ is widely used,
and very popular. Yet it is regarded as a complex language, with
features like multiple-inheritance, templates and pointers that are
counter-productive. Java, on the other hand, is closer to a "pure"
object-oriented language. Access to memory pointers is removed, and
object-references are used instead. Support for multiple-inheritance
has been removed, which lends itself to clearer and simpler class
designs. The I/O and network library is very easy to use, and the Java
API provides developers with lots of time-saving code (such as
networking and data-structures). After using Java for awhile, most
developers are reluctant to return to other languages, because of the
simplicity and elegance of Java.

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-

it is translated as it is run. For this reason, interpreted code is quite


slow, but often portable across different operating systems and
processor architectures.
Java takes the best of both techniques. Java code is compiled into a
platform-neutral machine code, which is called Java bytecode. A
special type of interpreter, known as a Java Virtual Machine (JVM),
reads the bytecode, and processes it. Figure One shows a disassembly
of a small Java application. The bytecode, indicated by the arrow, is
represented in text form here, but when compiled it is represented as
bytes to conserve space.

Figure One - Bytecode disassembly for "HelloWorld"

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.

Automatic garbage collection


The term garbage collection refers to the reclamation of unused
memory space. When applications create objects, the JVM allocates
memory space for their storage. When the object is no longer needed
(no reference to the object exists), the memory space can be
reclaimed for later use.
Languages like C++ force programmers to allocate and deallocate
memory for data and objects manually. This adds extra complexity, but
also causes another problem - memory leaks. When programmers
forget to deallocate memory, the amount of free memory available is
-6-

decreased. Programs that frequently create and destroy objects may


eventually find that there is no memory left. In Java, the programmer is
free from such worries, as the JVM will perform automatic garbage
collection of objects.

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.

Network and "Internet" aware


Java was designed to be "Internet" aware, and to support
network programming. The Java API provides extensive network
support, from sockets and IP addresses, to URLs and HTTP. It's
extremely easy to write network applications in Java, and the code is
completely portable between platforms. In languages like C/C++, the
networking code must be re-written for different operating systems,
and is usually more complex. The networking support of Java saves a
lot of time, and effort.
-7-

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.

Platform independence works because Java is an interpreted rather


than a compiled language. Unlike C or C++ code, when Java is
compiled, it is not compiled into platform specific machine code, but
into platform independent byte code. This byte code is distributed over
the web and interpreted by a virtual machine (typically built right into
a web browser these days) on whichever platform it is being run.
Thus, as a programmer, you need only concern yourself with the
generic Java programming language and compile your applications into
byte code on whatever system you are using. You can then be assured
that your byte code will be executed correctly whether your clients are
using Macs, Pcs, UNIX boxes or anything else.

In Java programming language, all source code is first written in


plain text files ending with the .java extension. Those source files are
then compiled into .class files by the javac compiler. A .class file
-8-

does not contain code that is native to your processor; it instead


contains byte codes — the machine language of the Java Virtual
Machine (Java VM). The java tool then runs your application with an
instance of the Java Virtual Machine.

An overview of the software development process.


Since the Java VM is available on many different operating systems,
the same .class files are capable of running on Microsoft Windows, the
Solaris operating System, Linux, or Mac OS.

Through the Java VM, the same application is capable of running on


multiple platforms.

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.

API (Application Programming Interface)


The API is a large collection of ready-made software components
that provide many useful capabilities. It is grouped into libraries of
related classes and interfaces; these libraries are known as packages.
The API provides the core functionality of the Java programming
language. It offers a wide array of useful classes ready for use in your
own applications.

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:

Versio classe package Release Comment


n s s d

1.0 212 8 1996

1.1 504 23 1997

Also called "Java 2, Release 1.2"


1.2 1520 59 1998

Also called "Java 2, Release 1.3


1.3 1840 76 2000 Standard Edition". Version 1.3
focused on speed
improvements, while adding
fewer enhancements than
previous releases.
Also called "Java 2, Release 1.4
1.4 2991 135 2002 Standard Edition". Version 1.3
focused on I/O and XML support
Sometimes still referred to as
5.0 3279 166 2004 "Java 2, Release 1.5 Standard
Edition". Version 5.0 focused on
speed/memory improvements
and several developer
improvements like generics and
enumerated types.
- 12 -

There were five primary goals in the creation of the Java


language:
⇒ It should use the object-oriented programming methodology.
⇒ It should allow the same program to be executed on multiple
operating systems.
⇒ It should contain built-in support for using computer networks.

⇒ It should be designed to execute code from remote sources


securely.
⇒ It should be easy to use by selecting what were considered the
good parts of other object-oriented languages.
- 13 -

Data Types
There are 9 data types in Java, 8 primitive types and a reference type.
- 14 -

Type Memory Default Comments


in Bytes Values
This type of variable can be either true or
boolean 1 false false.

The char type is used to represent single


char 2 '\u0000' characters between single quotes using
Unicode encoding.
Uses at bits to represent a number from
byte 1 0 -128 to 127
An integer between -32,768 to 32,767. If
short 2 0 your variable will be bounded, using a short
instead of an int is a good way to save
memory.
An integer between -2,147,483,648 and
int 4 0 2,147,483,647.This is the most commonly
used integer type because how often are
you counting values over 2 billion?
An integer between
–9,223,372,036,854,775,808L to
long 8 0L 9,223,372,036,854,775,807L. If you are
counting numbers that large, you must be
working for NASA or the accounting Dept. for
Congress.
Float is used to represent integers with
float 4 0.0f fractional parts such as 12.3456. Valid
values span 6-7 decimal digits.
A double works like an even more precise
double 8 0.0d float. Valid values span 15 decimal digits. In
most cases, you will use a double instead of
a float since the memory use is not usually
too burdensome and the precision is quite a
bit better.
String (Object) null

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 characters that are not traditionally used in (US) English,


another character format was created: Unicode. This includes Latin-
based and non-Latin-based languages.

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 -

Minimum -9,223,372,036,854,775,808 and a maximum value of


9,223,372,036,854,775,807 (inclusive).

When you declare a long variable, by default, the compiler "allocates"


only enough memory for an integer so there would not be a waste. In
some cases, you may want the compiler to use 64 bits for your long
variable.

public class Main {

public static void main(String[] args) {


// TODO code application logic here
long days = 245885475475;
System.out.print("Days: ");
System.out.print(days);
}
}

This would produce:

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;

public class Main {

public static void main(String[] args) {


// TODO code application logic here
long days = 245885475475L;
System.out.print("Days: ");
System.out.print(days);
}
}

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 double data type is a double-precision 64-bit IEEE 754


floating point. For decimal values, this data type is generally the
default choice. As mentioned above, this data type should never be
used for precise values, such as currency.

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 -

Local variables are slightly different; the compiler never assigns a


default value to an uninitialized local variable. If you cannot initialize
your local variable where it is declared, make sure to assign it a value
before you attempt to use it. Accessing an uninitialized local variable
will result in a compile-time error.

Keywords are reserved words that are predefined in the language. All
the keywords are in lowercase.

abstract continue for new switch


assert*** default goto* package synchronize
d
boolean Do if private this
break double implements protected throw
byte Else import public throws
case Enum**** instanceof return transient
catch extends int short try
char Final interface static void
class Finally long strictfp** volatile
const* Float native super while

* not used ** added in *** added in **** added in


1.2 1.4 5.0

Escape Characters

Seq Name Seq Name

\b Backspace \f Form feed

\t horizontal tab \" double quote

\n New line \' single quote

\r carriage return \\ backslash


- 19 -

\ Latin encoded character \uHHHH Unicode encoded character


###

Access specifiers

• private -- accessible only in the class


• no modifier, so-called "package" or “default” access -- accessible
only in the same package
• protected -- accessible (inherited) by subclasses, and accessible
by code in same package
• public -- accessible anywhere the class is accessible, and
inherited by subclasses

Summary of access to fields in Java


privat "packag protecte
access by public
e e" d
the class itself yes yes yes yes
a subclass in same package no yes yes yes
non-subclass in same
no yes yes yes
package
a subclass in other package no no yes yes
non-subclass in other
no no no yes
package

import java.util.*; // imports java.util.Date


import java.sql.*; // also import java.util.Date
public class Collision {
HashMap m;
Date d;
}
Does not compile.
- 20 -

About Class & Objects

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.

Declaring a Variable to Refer to an Object


class Point
{
…………
…………
}
Point originOne;

If you declare originOne like this, its value will be undetermined


until an object is actually created and assigned to it. Simply declaring a
reference variable does not create an object. For that, you need to use
the new operator, as described in the next section. You must assign an
object to originOne before you use it in your code. Otherwise, you will
get a compiler error.
- 21 -

A variable in this state, which currently references no object, can be


illustrated as follows (the variable name, originOne, plus a reference
pointing to nothing):

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.

Note: The phrase "instantiating a class" means the same thing as


"creating an object." When you create an object, you are creating an
"instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a


constructor. The name of the constructor provides the name of the
class to instantiate.

The new operator returns a reference to the object it created. This


reference is usually assigned to a variable of the appropriate type, like:

Point originOne = new Point(23, 94);

The reference returned by the new operator does not have to be


assigned to a variable. It can also be used directly in an expression. For
example:
int height = new Rectangle().height;
int areaOfRectangle = new Rectangle(100, 50).getArea();
- 22 -

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.

Instance Variables (Non-Static Fields)


Non-static fields are also known as instance variables because
their values are unique to each instance of a class

Class Variables (Static Fields)


A class variable is any field declared with the static modifier; this
tells the compiler that there is exactly one copy of this variable in
existence; regardless of how many times the class has been
instantiated.

Java Output Stmt


The printing facility is part of the Java standard library: The
System class defines a public static field called out. The out object is
an instance of the PrintStream class and provides the method
println(String) for displaying data to the screen while creating a new
line (standard out).

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 -

specifiers — private, public, and protected — to restrict access to inner


classes, just as you do to other class members.

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.

this and super keywords


Java has two keywords, this and super to help you explicitly
name
the field or method that you want. Using this and super you have full
control on whether to call a method or field present in the same class
or
to call from the immediate superclass. This keyword is used as a
reference to the current object which is an instance of the current
class.
The keyword super also references the current object, but as an
instance of the current class's super class.

The this reference to the current object is useful in situations where a


local variable hides, or shadows, a field with the same name. If a
method needs to pass the current object to another method, it can do
- 25 -

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

As seen from the previous example, the superclass is more general


than its subclass(es). The superclass contains elements and properties
common to all of the subclasses. The previous example was of a
concrete superclass that objects can be made from. Often, the
superclass will be set up as an abstract class which does not allow
objects of its prototype to be created. In this case only objects of the
subclass are used. To do this the reserved word abstract is included in
the class definition.

Abstract methods are methods with no method statements. Subclasses


must provide the method statements for their particular meaning. If
the method was one provided by the superclass, it would require
overriding in each subclass. And if one forgot to override, the applied
method statements may be inappropriate.

public abstract class Animal // class is abstract


{
private String name;
public Animal(String nm)
{ name=nm; }
public String getName() // regular method
{ return (name); }
public abstract void speak(); // abstract method - note no {}
}

Abstract classes and methods force prototype standards to be followed


(ie. they provide templates).

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 -

public interface Working


{
public abstract void work();
}

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.

public class WorkingDog extends Dog implements Working


{
public WorkingDog(String nm)
{
super(nm); // builds ala parent
}
public void work() // this method specific to WorkingDog
{
speak();
System.out.println("I can herd sheep and cows");
}
}

Interfaces can be inherited (ie. you can have a sub-interface). As with


classes the extends keyword is used. Multiple inheritance can be used
with interfaces.

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.

public class AnimalReference


{
public static void main(String args[])
Animal ref // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Earnie");

// now reference each as an Animal


ref = aCow;
ref.speak();
ref = aDog;
ref.speak();
ref = aSnake;
ref.speak();
}

Notice that although each method reference was to an Animal (but no


animal objects exist), the program is able to resolve the correct
method related to the subclass object at runtime. This is known as
dynamic (or late) method binding.

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 • StringTokenizer • Project:


• StringBuffer Class Cipher Text Prep
Class • Regular • Project:
• StringBuilder Expressions WordCounting
- 28 -

Class • String • Project:


Applications XHTML Analysis

NOTE: For the following method parameters the prefix g indicates


string, i indicates integer and c indicates character types.

The String Class


String class objects work with complete strings instead of treating
them as character arrays as some languages do.

Accessor methods: length(), charAt(i), getBytes(),


getChars(istart,iend,gtarget[],itargstart), toCharArray(),
valueOf(g,iradix), substring(iStart [,iEndIndex)]) [returns up to but not
including iEndIndex]

Modifier methods: toLowerCase(), toUpperCase(), trim(), concat(g),


replace(cWhich, cReplacement). The method format(gSyn,g) uses c-
like printf syntax for fixed fields if required in reports.

Boolean test methods: contentEquals(g), endsWith(g), equals(g),


equalsIgnoreCase(g), matches(g), regionMatches(i1,g2,i3,i4),
regionMatches(bIgnoreCase,i1,g2,i3,i4), startsWith(g)

Integer test methods: compareTo(g) [returns 0 if object equals


parameter, -1 if object is before parameter in sort order, +1 if
otherwise], indexOf(g) [returns position of first occurrence of substring
g in the string, -1 if not found], lastIndexOf(g) [returns position of last
occurrence of substring g in the string, -1 if not found], length().

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 aName = "Roger"; String bName = "Roger";


if (aName == bName) {System.out.println('== worked')};
- 29 -

if (aName.equals(bName)) {System.out.println('equals worked')};

Here is a program fragment to validate characters in a string, possibly


from data entry or from a file. Regular Expression techniques can
also be used for validation.

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}
}

The String Buffer Class


StringBuffer class objects allow manipulation of strings without
creating a new object each time a manipulation occurs. Examples of
setting up a string buffer variable are:

StringBuffer aString = new StringBuffer("the start value"); // sets


value
StringBuffer nulString = new StringBuffer(6); // explicitly sets size
StringBuffer defString = new StringBuffer(); // sets size to default
of 16

Accessor methods: capacity(), length(), charAt(i)

Modifier methods: ensureCapacity(), setLength(), append(g),


delete(i1, i2), deleteCharAt(i), insert(iPosn, g), setCharAt(iposn, c),
replace(i1,i2,gvalue), reverse(), toString(g)

The String Buider Class


- 30 -

StringBuilder class methods are similar to StringBuffer ones but they


are unsychronized (ie not for multithreaded apps). They are also
much faster. Examples of setting up a string buffer variable are:

StringBuilder aString = new StringBuilder("the start value"); // sets


value
StringBuilder nulString = new StringBuilder(6); // explicitly sets size
StringBuilder defString = new StringBuilder(); // sets size to default
of 16

Accessor methods: capacity(), length(), charAt(i), indexOf(g),


lastIndexOf(g)

Modifier methods: append(g), delete(i1, i2), insert(iPosn, g),


getChars(i), setCharAt(iposn, c), substring(), replace(i1,i2,gvalue),
reverse(), trimToSize(g ), toString(g)

The String Tokenizer Class [java.util


library]
Many text manipulation utilities require a tokenizer function which
breaks up lines of text into subunits called tokens based on specific
delimiters or break characters. The most common delimiter is
whitespace which yields words as the tokens. Java has a very useful
StringTokenizer class to perform this type of task.

StringTokenizer class objects may be created by one of three


constructor methods depending on the parameters used. If a string is
used as a single parameter, it is the source text to be broken at the
default set of whitespace delimiters (space, tab, newline, cr,
formfeed). If a second string is also passed, it is assumed to be the set
of delimiting characters. Use the escaper \ character when
representing the string quote character " or any non-typeable
delimiters such as tab (\t). If a true flag is added as a third parameter,
any delimiters found are also returned as string tokens.

Note: If the information to be tokenized is coming from a file, the


StreamTokenizer object may be a more efficient choice.

The StringTokenizer methods are int countTokens(), boolean


hasMoreTokens() and String nextToken().
- 31 -

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.

Life cycle of an applet


Loading
- 32 -

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)

The APPLET Tag

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:


- 33 -

WIDTH & HEIGHT are the required attributes that gives the size
(in pixels) of the applet display area.

Potrebbero piacerti anche