Java class notes

weaverchurchΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 4 χρόνια και 8 μήνες)

302 εμφανίσεις


85

Lecture 12: Java

notes


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


Java compiler translates Java programs into byte code (program portability)

Byte code is neutral to any computer system.


It is interpr
eted by a Java interpreter and runs on a Java virtual machine

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


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


A standalone program must cont
ain 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++


Running Java

You type a Java program with an
y 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 a
rgv[])



{



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 langu
age

Several keywords (special meaning words) in this program: public, class, static, void. Other keywords:

-

abstract, Boolean, break, byte, case, catch, char, const, continue, default, do, double, else, extends, false,
final, finally, float, for, goto, if,

implements, import, instanceof, int, interface, long, native, new, null,
package, private, protected, return, short, strictfp, super, switch, synchronized, this, throw, throws,
transient, true, try, volatile, while


An identifier (e.g., ProgOne) must star
t with a letter, $, or _ followed by zero or more letters, $, _, or digits


-

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

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


-

Constant na
mes are written in uppercase, with _ separating parts of a composite name


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

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

You execute the method
ma
in

inside the compiled program by typing the command:
java ProgOne


Input data needed by the program is typed in the last command after the class name


Java types

Java has 8 built
-
in types: boolean (logical), byte (int), char (int), short (int), int, lon
g (int), float (fp), and
double (fp)

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


86


V
ariables are place in the stack

A variable can be initialized in the sa
me 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 assigned at most once at run
-
time (named
constant)


A variable decla
red 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 from an
y 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 final static 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 elem
ents 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 mul
ti
-
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 enclosin
g block statement

{


int x = 12;


{


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


}

}


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

The scope of a
for

loop variable is the entire
for
statement, inc
luding the header and the body



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


Strings

A string is an object of the predefined class String


-

A string literal consists of a sequence of characters within double quotes:
“CSC 461’, “January”


-

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


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


String s1 = “CSC 461”;


String s2;

// only a reference is created, not an string object


87


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


-

s1.leng
t
h
()

is the number of char
acters in s1


-

s1.equals(s2) is true if s1 and s2 contain the same sequence of characters, 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 fol
lowed by the characters of s2


-

s1.toString() is s1 itself


-

s1 + v is the same 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


C
lasses

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 c
lass declaration has the form:

[public] class class
-
name

{ /* class body goes here */ }


The class body may contain declaration of fields (data members), constructors, and methods (member
functions)


-

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


-

A method is what we know as a subroutine or function. It represents a message that an object can
receive


-

A constructor 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 (
stored in 2 separate files: BankAccount.java and BankAccountT
est.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;



balance = newBalance;


}


//Withdraw some
amount

from the bank account


public void withdraw(double amount)


{



double newBalance = balance
-

amount;



balance = newBalance;


}


88


// Get the current balance of the bank account


public double getBalance()


{



return balanc
e;


}


}



// Class to test the B
ankAccount class


public class BankAccountTest


{


// Test the methods of the BankAccount


public static void main(String[] args)


{



BankAccount ManuelsChecking = new BankAccount(); // create new acco
unt



ManuelsChecking.deposit(120000);



ManuelsChecking.withdraw(20000);



System.out.println(“Current Balance: “ + ManuelsChecking.getBalance());



ManuelsChecking = new BankAccount(50000); // overwrite current account



ManuelsChecking.withdra
w(30000);



System.out.println(“New Balance: “ + ManuelsChecking.getBalance());


}


}


==> Output: Current Balance: 100000.0




New Balance: 20000.0





One constructor can call another:


public BankAccount(double initBalance)


{



balance = initBal
ance;


}


public BankAccount()


{



this(0);

// Call the other constructor of this class with
value 0


}


The keyword
this

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


-

It can be used only inside a method


-

In the
balance

met
hod for
BankAccount

class you can say also
this.balance =
newBalance;


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


-

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


-

Static methods are tho
se methods than only uses the 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 ge
neric computations (e.g,
sqrt(x))


-

There is no
this

for a static method



-

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 object



89

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 p
rintln)


-

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 a an object


-

Its implict action is to call the superclass 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 on
ly within a

class C and its nested classes


-

protected
: member is accessible 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 it
s package


-

final
: class cannot have subclasses


-

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


-

An abstract method has no implementation. Method is implemented in the subclass of the s
uperclass


Example of a new class BankAccount that has subclasses SavingAccount and CheckingAccount


-

Every account type have some monthly fees represented by method deductFees


public abstract class BankAccount


{



public abstract void deductFees();



...


}


A subclass C of class B is declared by an extends
-
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


90


-

Integer division
x/y

truncates, rounding toward 0 (10/3 is 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 logical 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 doubl
e


-

byte is a subtype of short, int, long, float, and 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;


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


-

brea
k

quits the loop without executing the remaining statements 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: statemen
t; 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



91

The labe
lled 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


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 method (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

"


OutOfMemo
ryError

"


StackOverflowError

"


Exception

checked


InterruptedException

"


IOException

"


ClassNotFoundException

"


RuntimeException

unchecked


ArithmeticException

"


ArrayStoreException

"


ClassCastException

"


IllegalArgumentException

"


IllegalMonitorS
tateException

"


IndexOutOfBoundsException

"


ArrayIndexOutOfBoundsException

"


StringIndexOutOfBoundsException

"


NullPointerException

"


Programmer can design his/her own exception types

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



-

Program terminates 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 immedi
ately. Execution continues with exception handler


92


Catching exceptions

Every exception should be handled somewhere in your program


-

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


You install an exceptio
n 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 }


finally


{ 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 termin
ates 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.




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(br
eader.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


93

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 d
irectly or indirectly

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


-

SavingsAccount and CheckingAccount inherit balance, deposit(), withdraw
()
,
trans
fer(),
and
getBalance()

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 rate


public class SavingsAccount extends BankAccount


{



private double interestRate;



public SavingsAccount(double rate)




{



interestRate = rate;



}





public
void
addInterest()



{



double interest = getBalance() * interestRate / 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



transactio
nCount = 0; // init transaction count


94



}



public

void deposit(double amount)



{



transactionCount++;



super.deposit(amount);



}



public void withdraw(double amount)



...


}




Interfaces

A Java interface declares a set of meth
ods 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 t
hem


-

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

Abstract 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 th
e class


import java.util.ArrayList;


ArrayList anArray = new 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.


95

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 a
s the first statement in the classes' code:


package packagename;

Example:


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 com/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

ja
vadoc is a tool that extracts the comments 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
-
nam
e
description
is used to describe each method 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


publ
ic void withdraw


{


...


}


/**



Gets the current balance of the bank account.



@return the current balance


*/


public double getBalance()


{


...


}


96


You invoke the javadoc utility with the command:


javadoc AClass.java

or

javadoc *.java


Lists

Ja
va provides several classes for implementing 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);

//ov
erwrite 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()


Obj
ect 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


Object
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.Iterator


public class ListTest


{



public static void main(String[] args)



{



LinkedList students = new LinkedList();



students.addLast("Tom");



students.addLast("Peter");



st
udents.addLast("John");


97




ListIterator iterator = students.listIterator
();



iterator.next();

// references "Peter"



iterator.add("M
anny");

// add student before "Peter
"

and iterator







// references after the new element



iterator.next();

// referen
ces "John"



iterator.remove();

// remove
"Manny"




iterator = students.listIterator();



while (iterator.hasNext())




System.out.println(iterator.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 class methods

-

Java does not support multiple inheritance

-

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

-

Java does not provide a
goto

statement.

-

The
break

and
continue

statements may be labeled

-

Operator overloading is 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 e
ncoded 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, 3rd 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 Morrison
, Differences between Java and C++
,
http://www.ui.ac.ir/books/trd_lng/java/java%20unleashed%20second%20edition/ap
pd.htm#