Java class notes

moodusroundoSoftware and s/w Development

Aug 15, 2012 (5 years and 29 days ago)

451 views


80

Lecture 10
: Java

notes


Java is a programming language similar to C#

It was designed in 1991 by a group of people at Sun Microsystems

Main goal
s
:
write safe and
platform independent

code


-

Java programs can run on multiple platforms including on
embedded systems (e.g., appliances)

Java compiler translate
s Java programs into byte code, which is platform independent code



-


It is interpreted by a Java interpreter and runs on a Java virtual machine


-

Java compiler detects compile
-
time errors.
Interpreter detects run
-
time errors

Java VM runs on machines with many different OS: Microsoft Windows, Solaris OS, Linux, Mac OS

A Java platform includes the Java VM and the Java Application Programming Interface (API)

Java API is a collection of software

components organized into libraries and known as packages


Java is an objected oriented language. A program consists of class declarations



-

A standalone program must contain at least one class declaration with a method named
main

Java programs can run

on multiple tasks simultaneously (multithreaded)

Java provides automatic garbage collection

Java is syntactically similar to C++

JAVA API has multiple classes that you can use in your programs


-

Database access, XML generation, networkink, etc.


-

Yo
u should access the documentation of the Java Development Kit being used (i.e., JDK 6)


at
http://java.sun.com/javase/6/docs/api/


Several Java tutorials and material are available, some of these are:


-

Java Programming FACS and Tutorials:
http://www.apl.jhu.edu/~hall/java/FAQs
-
and
-
Tutorials.html


-

Online Java: Introduction to Programming Using Java:
http://math.hws.edu/javanotes/


-

Java Programming Notes:
http://www.leepoint.net/notes
-
java/index.html


Running Java

You type a Java program with any
text
editor or
using an IDE such as NetBeans or Eclipse

Simple Java Program:


/* This is a delimited comments


similar to c */


public class ProgOne

{


// a single comment; it extends to the end of the line



public static void main(String argv[])

{




int varOne = 2, varTwo = 3;


System.out.print(“Adding 2 plus 3: “);//another single line comment



System.out.println(varOne + varTwo);



}


}


The source file is named
ProgOne.java

Java is case sensitive and free
-
form language

Several reserve
words
are
(special meaning words) in this progr
am: public, class, static, void


Running the above program, the following output will be displayed:



Adding 2 plus 3: 5


An identifier (e.g., ProgOne) must star
t with a letter

or _ foll
owed b
y zero or more letters,


_

, or digits



-

They cannot be reserved words, such as
public
,
void
, etc.


-

Identifiers are case sensitive. Hi and hi are different identifiers


81

Java naming conventions for class names and variables (also class methods) are as shown in ProgOne.


Java is compiled with the command line:
javac ProgOne.java


-

Or,
by compiling and running a program from an IDE

Java compiler translates an error
-
free program and saved its byte code in the file
ProgOne.class

You execute the method
main

inside the compiled program by typing the command:
java ProgOne


Input data needed by a

prog
ram is typed

after the class name


Ja
va types

Java has 8 built
-
in types

(they start with lowercase):


-

boolean (logical), byte (int), char (int), short (int), int, long (int), float (fp), and double (fp)


-

Size in bytes: int(4), byte(1), short(2), long(8), double(8), float(4), char(2),
boolean(1 bit)

Every variable declared with these types has a default value of zero


-

Programmers do not need to use
new

to create
variables with these types


-

Local v
ariables are place in the stack

A variable can be initialized in the same statement

it is declared (see ProgOne code)


The declaration form is:
[ final ] type varname1 [= initvalue] [, varname2 …];


A variable declared with
final

must be initialized or ass
igned at most once at run
-
time


-

They are
named constant


A variable d
eclared with
static

is a static variable

(or class variable)


These variables are associated with a class and not with a specific object


Any instance of the class with a static variable shares this static variable


It can be accesse
d fro
m any instance of the class or
referenced by a class having no instance.


Example:


class MyMath

{



public static double pi = 3.1415;

//
pi is a static variable;



public

static
final
double PI = 3.1415; // PI is a constant



...


}



Unlike C/C++, arrays in Java are always initialized and cannot be accessed outside of its range


-

An array of objects is actually an array of references, each reference automatically initialized to
null


-

You can also create an array of primitives. The elements are initialized to zero (0 or 0.0, or false)


-

Arrays are created with the

new
operator. Examples:


int[] a = new int[10];

//10 elements initialized to 0, first index is 0


final int SIZE =

3;


double[][] b = new double[SIZE][];


double[][] c = {{0.0}, {0.0, 0.0}, {0.0, 0.0, 0.0}};


String[] days = new String[7];

// all initialized to null



-

a.length

is the length of the one
-
dimensional array
a


-

ArrayStoreException is thrown if index

is less than 0 or greater or equal to
a.length


-

A multi
-
dimensional array
t[][]

is a one
-
dimensional array of arrays with components of type
t[]


-

All dimensions do not have to be created at once


Scope of variables

The scope of a variable extends
from its declaration to the end of the inner
-
most enclosing block statement

{


int x = 12;


{


int x = 96; // illegal in Java, legal in C/C++


}


82

}


The scope of a method or constructor parameter is the entire method or constructor body

The sco
pe of a
for

loop variable is the entire
for
statement, including the header and the body



for (int i = 1; … ; …) body


Strings

and the char type

A string is an object of the predefined class String


-

A string literal consists of a sequence of
Unicode
characters within double quotes:


-

Character escape sequence can be used (e.g.,
\
t,
\
n,
\
\
,
\

)


-

Examples”
“CSC 461”
, “January”
, “
\
”Hello
\
”!”


String s = new String(“CSC 461”
);


String s1 = “CSC 461”;


String s2;

// only a reference is created, not

an string object

Character constants are delimited by single quotes:


-

‘a’

is a character,
“a”

is a string


-

Unicode characters are expressed as:

\
u00177’

for character
‘Ñ’

Each Unicode character

was initially represented by a two
-
byte value


-

S
ome characters

require

now to be encoded as pair of character values




If s1 and s2 are strings then a subset of String methods are:


-

s1.leng
t
h
()

is the number of characters in s1


-

s1.equals(s2) is true if s1 and s2 contain the same sequence of ch
aracters, false otherwise


-

s1.charAt(i) is the character at position i in s1, counting from 0


-

s1.concat(s2) (or s1 + s2) is a new string with characters of s1 followed by the characters of s2


-

s1.toString() is s1 itself


-

s1 + v is the sam
e as s1.concat(Integer.toString(v)) if v has type int


-

s1.compareTo(s2) returns a negative integer, zero, or a positive integer if s1 precedes, equals, or follows s2


-

n = Integer.parseInt(inputStr);

// Get the integer value in the string inputStr


-

price = Double.parseDouble(inputStr);

// Gett a double value in the string inputStr


-

x = str.substring(start, end);

// Get a substring in the string s from characters at position start up to end


-

end is optional


Classes

In Java, a program

consists of class declarations

A class could abstract the concept of a vector, car, train, stock, food, student, movie, etc.

Objects are instances of some class (class instance) and a class defines the type of an object

A simple class declaration has the form:

[public] class class
-
name

{ /* class body goes here */ }


A variable whose type is a class does not hold an object


-

It is an object reference that holds the location of an object


-

For example:
Rectangle b
ox = new Rectangle(20, 30, 50, 60);


-

The variable box refers to the new rectangle object created after the statement is interpreted


The class body may contain declaration of fields (data membe
rs), constructors, and methods


-

Methods are known
as member functions


-

A field is an object of some type that we can communicate with via its reference or a primitive type


-

A method is what we kn
ow as a subroutine or function


-

It represents a message that an object can receive


83


-

A const
ructor is a method having the same name as the class of the objects it constructs


-

They are declared as public to enable the system to construct new objects of the class


-

Unlike methods, constructors do not have return values


-

E
xample
:

2

bank account classes (
sto
red in

separate files: BankAccount.java and BankAccountTest.java)



public class BankAccount

{


private double balance;

// can be accessed only by methods of the class


// Construct a bank account with zero balance


public
BankAccount()

{



balance = 0.0;


}


// Construct an account with some initial balance (overload constructor)


public BankAccount(double initBalance)

{



balance = initBalance;


}


// Deposit some
amount

in the bank account


public void deposit (double

amount)

{



double newBalance = balance + amount;

// declare a local variable



balance = newBalance;


}


//Withdraw some
amount

from the bank account


public void withdraw(double amount)

{



double newBalance = balance
-

amount;

// declare a loc
al variable



balance = newBalance;


}


// Get the current balance of the bank account


public double getBalance()

{



return balance;


}


}



// Class to test the B
ankAccount class


public class BankAccountTest

{


// Test the methods of the
BankAccount


public static void main(String[] args){



BankAccount My
Checking = new BankAccount(); // create new account



My
Checking.deposit(120000);



My
Checking.withdraw(20000);



System.out.print
ln(“Current Balance: “ + My
Checking.getBala
nce());



My
Checking = new BankAccount(50000); // overwrite current account



My
Checking.withdraw(30000);



System.out.p
rintln(“New Balance: “ + My
Checking.getBalance());


}


}


==> Output: Current Balance: 100000.0




New Balance: 20000.0




One
constructor can call another:


public BankAccount(double initBalance){



balance = initBalance;


}


public BankAccount(){



this(0);
// Call the other constructor of this class with value 0


}



84

The keyword
this

produces a reference to the object the method has been called for


-

It is the implicit parameter of the method


-

In the
balance

method for
BankAccount

class you can say also

this.balance = newBalance;


Java has two types of methods: instance method
s and static methods


-

Instance methods are those defined within a class and they use instance data

members


-

Static methods are those methods than only uses th
e variables passed as arguments


-

They are declared with

the
static

keyword



-

They cannot used instance
variables (
data members
)
, but they can access static variables


-

These methods are used to perform generic computations (e.g,
sqrt(x))


-

S
tatic method
s do not have the implicit parameter
this



-

You call a

static method for a class without any object



-

It is
equivalent to a global function. It can be called from outside the class defining the method


root = Math.sqrt(b*b
-
c);

//Math is a class and not an object,

//
sqrt does not operate on any ob
ject


All classes in the Java library start with an uppe
r
case letter (such as System)


-

Methods and objects start with a lowercase letter (such as out and println)


-

System.out.print is a call to the print method on the out object inside the System

class



-

Math.sqrt() is a call to the sqrt method inside the Math class


Java compiler creates a default constructor for a class with no constructors


-

It will
create
at least a method to build

an object


-

Its implict action is to call the super
class constructor


(predefined class Object is a superclass of all other classes)


class Bird


{ int i; }



public class DefaultConstructor


{



public static void main (String[] args)



{ Bird x = new Bird(); }


}


Java uses three explicit keywords for accessing class members:
public
,
private
, and
protected


-

public
: a member is accessible to all classes


-

private
: member is accessible only within a

class C and its nested classes


-

protected
: member is acces
sible in all classes in the same package (a collection of related classes)


A class has its own set of class modifiers:
public
,
final
, and
abstract


-

public
: accessible outside its package


-

final
: class cannot have subclasses


-

abstract
: class
cannot be instant
iated (a superclass). It can have abstract and non
-
abstract methods.


-

An abstrac
t method has no implementation


-

Method is implemented in the subclass of the superclass



Example of a new class BankAccount that has subcl
asses SavingAccount and CheckingAccount


-

Every account type have some monthly fees represented by method deductFees


public abstract class BankAccount


{


85



public abstract void deductFees();



...


}


A subclass C of class B is declared by an exten
ds
-
clause of the form:


class C extends B { ... }


Example:


public cl
ass CheckingAccount extends Ban
kAccount


{


...


}


public class Saving
s
Account extends BankAccount


{


...


}


Program flow

A variety

of e
xpressions in Java

compute

values
and change

variables, fields, array elements, etc.

Aritmetic operators:
+,
-
, *, /, %, ++x,
--
x, x++, x
--
,
-
x


-

x/0 or floating point overflow do not throw exceptions, but results are infinity or NaN


-

Integer division
x/y

truncates, rounding toward 0 (10/3 i
s 3,
-
10/3 is
-
3)

Logical and relational operators:
&&, ||, !, ==, !=, <, <=, >=, >

Bitwise operators:

~ (complement), & (and), | (or), ^ (exclusive or)


-

Used on integer types


-

For boolean type, the bitwise
&
and
|

have the same effect as the log
ical operators (but no short
-
circuit)

Shift operators:
<< (left), >> (signed right), >>> (unsigned right)


-

Used on integer types

Conditional expression:
e1 ? e2 : e3

(
e1

must be
Boolean
)


Casting operators: Java will change one type t1 of data into
another type t2 when t1 is a subtype of t2


-

The compiler will automatically promote t1 into t2. Casting is necessary when you go from t2 into t1


-

char is a subtype of int, long, float, and double


-

byte is a subtype of short, int, long, float, a
nd double


-

short is a subtype of int, long, float, and double


-

int is a subtype of long, float, and double


-

long is s
ubtype of float, and double


-

float is a subtype of double


long l = (long) i; // it is not necessary the cast (assuming i
is int)


int j = (int) x;

// needed if x is long, float, or double


Literals:

char c = 0xffff;

// max char hex value


byte b = 0x7f;

// max byte hex value



short s = 0x7fff;


int i1 = 0x2f, i2 = 0X2F, i3 = 0177; // last one is octal


long n1 = 200L, n2 =

200l, n3 = 200; // middle one is confusing


float f1 = 1, f2 = 1F, f3 = 1F, f4 = 1e
-
45f, f5 = 1e+9f, f6 = 1.2;


double d1 = 1d, d2 = 1D, d3 = 47e47d, d4 = 405.12;



The if
-
else statement



if (boolean
-
expr) statement;

or

if (boolean
-
expr) statement else
statement;


86


Iterations


while(boolean
-
expr) loop
-
body


do loop
-
body while (boolean
-
expr);


for(initialization; boolean
-
expr; step) loop
-
body


break

and
continue

can control the flow of the loop


-

break

quits the loop without executing the remaining stat
ements in the loop


-

continue
stops the execution of the current iteration


The switch statement


switch (int
-
expr) {

//

int
-
expr must have type int, short, char, or byte



case int
-
value1: statement; break;



case int
-
value2: statement; break;



...



default: statement;


}


The return statement


return;



// for a method of type void


return expression;
// inside the body of a method with return

type being a supertype of expression


The labelled statement


label : statement;

// label is an identifier

Used with:

break label;
// to break an inner
-
most switch or loop and starts a new iteration of an outer loop


or:

continue label;
// terminates an inner loop and starts the next iteration of an outer loop


Graphical applic
ations

The design of GUI applications require the use of classes in the java
x
.swing package

These applications have several graphical objects inside a window: a frame window, menu, etc.


-

We are not discussing these classes in this tutorial


Exceptions

An exception signals an abnormal situation during the execution of a program.

An exception is an object of an exception type:

a subclass of class
Throwable

The evaluation of an expression or the execution of an statement
(e.g., problem reading) may throw
an
exception


-

You can also throw an exception with a
throw

statement (use for exceptional cases)

There are two types of exceptions: checked and unchecked


-

You

m
ust

indicate that
a method might

cause checked
exceptions

in the throw
-
clause of a metho
d (or
constructor)


public static void main(String[] args) throws IOException



Most of the most important predefined exception types and their status are:


Throwable


Error

unchecked


ExceptionInInitializerError

"


OutOfMemoryError

"


StackOverflowError

"


Exception

checked


InterruptedException

"


IOException

"


ClassNotFoundException

"


87


RuntimeException

unchecked


ArithmeticException

"


ArrayStoreException

"


ClassCastException

"


IllegalArgumentException

"


IllegalMonitorStateException

"


IndexOutOfBoundsException

"


ArrayIndexOutOfBoundsException

"


StringIndexOutOfBoundsException

"


NullPointerException

"


Programmer can design his/her own exception types

A thrown exception may be caught by an enclosing try
-
catch statement



-

Program t
erminates with an error message

if exception is not

caught


The throw statement


throw
expression;

// expression must be a subtype of Throwable


You
r program

throw
s

an exception

when an error is detected and control is passed to a handler for the
exception

Example
:

public void withdraw(double amount)

{


if(amount > balance)


{
throw new IllegalArgumentException("Amount exceeds balance");

}


balance = balance
-

amount;

}


When the program

throws the exception, the method exits immediately. Execution continues with exception handler


Catching exceptions

Every exception should be handled somewhere in your program


-

If no handler exists for the exception, Java prints an error message and t
he program terminates


You install an exception handler with the try
-
catch statement. It has the form:


try


{ body

}


catch (
E1 x1)

// E1, E2 are names of exception types


{ catch
-
body1 }


catch (E2 x2)

// x1, x2 are exception objects


{ catch
-
body2 }


fi
nally


{ finallybody }


The stat
ement executes

body.
If the execution of

body
terminates normally, the

catch
-
bodies
are ignored

If

body
terminates abnormally, by throwing an exception
e

of class

Ei,
then the

catch
-
bodyi
is
executed

If there is no matching

Ei,
then the entire

try
-
catch
statement terminates abnormally with
exception
e

If a finally clause is present, then the
finallybody

is always executed last


Example:

The following method attempts to read three lines from a file, each containing a single f
loating
-
point

number
. Things that may go wrong during reading: premature end
-
of
-
file, ill
-
formed number.




88


static double[] readRecord(String filename) throws IOException


{



Reader freader = new FileReader(filename);



BufferReader breader = new BufferReader(freader);

// To read from the console, replace the above lines by the line below

// BufferReader
breader

= new BufferReader(new InputStreamReader (System.in));



double[] x = new double[3];




try



{




x
[0] =
new
Double(b
reader.readLine())
.doubleValue()
;



x
[1] = new Double(breader.readLine()).doubleValue();



x
[2] = new Double(breader.readLine()).doubleValue();



}



finally



{



breader.close();



freader.close();



}



return x;


}


To write into a text file use:

FileWriter writer = new FileWriter("output.txt");


PrintWriter out = new PrintWriter(writer)


out.println("Hello World");

Inheritance

It is a method for extending existing classes by adding methods and fields;
and
/or changing

methods'
behavior


-

Inheritance has the advantage of code reuse


-

Java allows only single inheritance

A class (subclass) is an specialization of another more general class (superclass)


-

A subclass inherits behavior (methods) and state (fields) from the superclass


Every class extends the
Object

class either directly or indirectly

Example of page 4 is shown in a class diagram where inheritance is represented by a solid arrow with a
h
ollow traingle that points to the superclass


-

SavingsAccount and CheckingAccount inherit balance, deposit(), withdraw
()
,
transfer(),
and
getBalance()


89

Object
+
deposit
(
in amount
:
double
)
+
withdraw
(
in amount
:
double
)
+
getBalance
() :
double
+
transfer
(
in other
:
BankAccount
,
in amount
:
double
)
-
balance
:
double
BankAccount
+
addInterest
()
-
interestRate
:
double
SavingsAccount
+
deposit
(
in amount
:
double
)
+
withdraw
(
in amount
:
double
)
+
deductFees
()
-
transactionCount
:
int
-
static final FREE
_
TRANSACTIONS
:
int
=
3
-
static final TRANSACTION
_
FEE
:
double
=
2
.
0
CheckingAccount

File SavingsAccount.java


// An account that earns interest at a fixed ra
te


public class SavingsAccount extends BankAccount


{



private double interestRate;



public SavingsAccount(double rate)



{



interestRate = rate;



}





public
void
addInterest()



{



double interest = getBalance() * interestRat
e / 100.0;



deposit(interest);



}


}


File CheckingAccount.java


public class CheckingAccount extends BankAccount


{



private int transactionCount;



private static final int FREE_TRANSACTIONS = 3;



private static final double TRANSACTION_FEE = 2.0;



public CheckingAccount(int initBalance)



{



super(initBalance); // construct superclass



transactionCount = 0; // init transaction count



}



public

void deposit(double amount)



{



transactionCount++;



super.deposit(amount);



}



public void withdraw(double amount)



...


90


}


Interfaces

A Java interface declares a set of methods and their signatures (i.e., name, parameters, return type).


-

Unlike a class,

it provides no implementation, no fields, all methods are abstract and public


-

It helps programmers to design what you want your programs to do before implementing them


-

An interface is realized by a class


-

One or more classes can realize more

than one interface

Example
:


public interface Measurable


{



double getMeasure();


}


public class BankAccount implements Measurable


{



private double balance;



public double getMeasure()



{



return balance;



}



...


}



Packages

A package is a set of related classes

The Java library consists of several packages. Examples:



Package

Description

Sample Class



java.lang

for language support

Math


java.util

Utility classes

Random


java.io

Input and Output

PrintStream


java.awt

Abst
ract Windowing Toolkit

Color


java.net

Networking

Socket


java.applet

Applets

Applet


javax.swing

Swing user interface

JButton


java.sql

Database access via SQL

ResultSet


If you want to use a class from a package you can either:


-

Refer to the class by its full name (inconvenient). Example:


java.util.ArrayList anArray = new java.util.ArrayList();


-

Import a class name with an import statement before you refer to the class


import java.util.ArrayList;


ArrayList anArray = n
ew ArrayList();


-

Import all classes of a package with an import statement that ends in .*


import java.awt.*


You don't need to import classes in
java.lang

explicitly. These classes are always avai
l
able to you.

Packages avoid name clashes


-

You can tell Java which class you need by referring to them with the complete name. Examples:


java.lang.Object

and
java.omg.CORBA.Object

To put classes in a package, you must insert the following line as the first statement in the classes' code:


p
ackage packagename;

Example:


91


package com.mp.pk1


public class AClass


{


...


}


A package is located in a subdirectory that matches the package name.


-

Successive parts of the name are subdirectories


-

package com.mp.pk1 is placed in subdirectory c
om/mp/pk1

The package can be placed in the directory of a program that uses the package, or


-

In a single directory if more than one program uses the package.


-

Example:
/home/mpenaloz/lib/com/mp/pk1


-

Then, you add the
/home/mpenaloz/lib

to the class path


in Unix:
export CLASSPATH=/home/mpenaloz/lib:.


In Windows:
set CLASSPATH=c:
\
home
\
mpenaloz
\
lib;.


Comment documentation

Java makes easier to maintain the documentation of your code with javadoc

javadoc is a tool that extracts the commen
ts and puts them into a set of HTML pages

A documentation comment starts with a /** (a special javadoc delimiters) and ends with */


-

Used to comment a class, method, or variable

Line with tag
@param
parameter
-
name
description
is used to describe each m
ethod parameter

Line with tag
@return description

is used to describe the return value of a method

Line with tag
@author description

is used to provide author's information (e.g., name, email)

Other tags are
@see, @version, @since, @throws


Example:


/**



A bank account has a
balance

that can be changed by



deposits and withdraws
.


*/


public class BankAccount


{


/**



Withdraws money from the bank account.



@param
amount
the amount to withdraw


public void withdraw


{


...


}


/**



Gets the current balance of the bank account.



@return the current balance


*/


public double getBalance()


{


...


}


You invoke the javadoc utility with the command:


javadoc AClass.java

or

javadoc *.java


Lists


92

Java provides several classes for im
plementing lists:
ArrayList
,
LinkedList
, and
Vector
.

An array list is a sequence of objects
, each object can be accessed separately.

References to objects are stored in an ArrayList instance. Example: an array of coins:


ArrayList coins = new ArrayList();


Coin aNickel = new Coin(0.05, "nickel");

// define a nickel


coins.add(new Coin(0.1, "dime");

// add a dime coin


coins.add(1, aNickel);

// add a nickel


coins.get(0);

// get the first coin




coins.set(4, aNickel);

//overwrite coin at position 4



coins
.remove(2);

// remove coin at position 2


int k = coins.size();

// return the number of elements in the list


coins.clear();

// remove all elements from the list


A Vector is an old version of ArrayList

A linked list is

a collection of self
-
referential objects, called nodes, connected or linked by references
.

The
Java library provides a linked
-
list class
, LinkedList with the methods:


void add(int index, Object obj)

// insert obj at position index


b
oolean add(Object
obj)


// append obj to end of the list

void addFirst(Object obj)

// insert obj to the beginning of the list


void addLast(Object obj)


// insert obj to the end of the list


b
oolean contains(Object obj)

// returns true if list contains obj


Object getFirst(
)


Object getLast()


Object removeFirst()


Object removeLast()


Object remove(int index)


boolean remove(Object obj)


Object set(
int index,
Object obj)


int size()

//get the number of nodes in the list


void clear()

// removes all elements from the list


O
bject toArray()

//returns an array with all elements


The Java library supplies a ListIterator type. It contains a position in the linked list


-

Initially it references to the first element of the list


-

You can move the iterator position with the
next

method:
iterator.next();


-

ListIterator has other methods:
set, remove, add, hasNext, hasPrevious, previous


-

NoSuchElementException is thrown if iterator tries to go beyond the end of the list



-

method
hasNext

is called before
next

to solve this problem

Example:


import java.util.LinkedList;


import java.util.
List
Iterator
;


public class ListTest


{



public static void main(String[] args)



{



LinkedList
<String>

students = new LinkedList
<String>
();



students.addLast("Tom");



students.addLast("Peter");



students.addLast("John");




ListIterator
<String>

iterator = students.listIterator
();



iterator.next();

// references "Peter"



iterator.add("M
anny");

// add
student before "Peter
"

and iterator







// references after the new element


93



iterator.next();

// references "John"



iterator.remove();

// remove
"Peter
"




iterator = students.listIterator();



while (iterator.hasNext())




System.out.println(iterato
r.next());



}


}




Numbers cannot be inserted into these lists because they are not object

You must use wrapper classes (Integer, Double, Boolean) that wrap numbers and truth values inside objects

Example:


ArrayList data = new ArrayList();



data.add(
new Double(24.12)
);



Double w = (Double)data.get(0);



double x = w.doubleValue();



Differences from C++

Java seems to inherit some of the C++ characteristics. But there are several differences:

-

Java does not have a preprocessor. No
#define,, #include,
#ifdef

directives

-

Not explicit pointers. Java makes heavy use of references, passing arrays and objects by references

-

NO structs and unions. They can be implemented with classes

-

Java is a purer object
-
oriented language. Java forces programmers to define c
lass methods

-

Java does not support multiple inheritance

-

Strings objects are not arrays of characters. You cannot use the “
[]
” operator on them

-

Java does not provide a
goto

statement.

-

The
break

and
continue

statements may be labeled

-

Operator overloading i
s not supported in Java.

-

Java does not support automatic C++=style of coercion. In Java, you need to cast a data element if
coercion will result in loss of information

-

Java does not support variable arguments

-

Command
-
line arguments passed by the system is

different in two aspects. In C++, two arguments are
passed:
argc
and
argv
. Also, the name of the program is the first argument.


String[] args;

//in Java, where args[0] is the first argument

-

Class fields are automatically initialized to default values

-

The

try statement can have a
finally

clause

-

Automatic garbage collection in Java

-

Array know their sizes and are always initialized

-

Classes can be final (they cannot be extended)

-

Java does not provide the
long int

data type. It must be written as
long

-

Boolean
is not an integral type in Java. They cannot be casted as integers or integers as Booleans

-

Characters are encoded in unicode, not ASCII (
\
u00E9 is the international character é)


Material extracted and/or adapted from the following r
eferences:

Cay Horstmann,
Computing Concepts with Java Essentials
,

John Wiley and Sons, 4
th

edition.

Bruce Eckel,
Thinking in Java
, Prentice Hall, 3rd edition

Peter Sestoft,
Java Precisely
, an online book available at www.dina.kvl.dk/~sestoft/javaprecisely

Michael Mo
rrison
, Differences between Java and C++
,
http://www.ui.ac.ir/books/trd_lng/java/java%20unleashed%20second%20edition/appd.htm#