SSD1 Unit 2

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

18 Νοε 2013 (πριν από 3 χρόνια και 8 μήνες)

80 εμφανίσεις

1




SSD1 Unit 2

Intro to Java

Presentation 2.3

Website
: http://www.icarnegie.com

2

Why Use Java?


Simple

-

Java has thrown out many of the complex features of C++ and C
resulting in a simpler language (no pointers, no unions, no enumerations)


Object
-
oriented

-

Java is a single
-
root, single
-
inheritance object oriented
language


Multithreaded

-

Java has a built
-
in support for multithreading


Distributed

-

Using Java RMI (remote method invocation) you can access
objects on other machines almost as if they were local


Portable
-

programs written in the Java language are platform independent

3

The Java execution environment



Like C and C++ programs, Java programs are compiled.



Unlike C and C++ programs, Java programs are not compiled down to
a platform
-
specific machine language. Instead, Java programs are
compiled down to a platform
-
independent language called
bytecode
.


Bytecode is similar to machine language, but bytecode is not designed
to run on any real, physical computer. Instead, bytecode is designed to
be run by a program, called a
Java Virtual Machine

(JVM), which
simulates a real machine.


4

JVM


Java Virtual Machine


JVM is an interpreter that translates Java bytecode into real
machine language instructions that are executed on the
underlying, physical machine


A Java program needs to be compiled down to bytecode
only once; it can then run on any machine that has a JVM
installed

5

JVM


Cont.

6

Running Java Programs

// file HelloWorld.java

public class

HelloWorld {


public static

void

main(
String
[] args) {



System.out.println(

Hello World !

);

}

}

> javac HelloWorld.java

The compilation phase: This command will produce the java bytecode file
HelloWord.class

> java HelloWorld

The execution phase (on the JVM):

This command will produce the output

Hello World!



7

Case Sensitivity


Case sensitivity:


String

is
not

the same as
string


MAIN

is
not

the same as
main


Java keywords are all lower case


e.g.
public class static void



8

Naming Conventions


Methods and variables start with a leading
lowercase letter


next, push(), index, etc.


Classes starts with a leading upper
-
case letter



String, StringBuffer, Vector, Calculator, etc.



9

Naming Conventions


Cont.


Constants (final) are all upper
-
case :



DEBUG, MAX_SCROLL_X, CAPACITY


final double PI = 3.1415926;


Word separation in identifiers is done by
capitalization (e.g maxValue), except for constants
where underscore is used (e.g
MAX_SCROLL_X
)


10

Comments


C++ Like:

// comment ..

/* this is a comment */



And Javadoc Comments:

/** this is javadoc comment */


11

Flow control

It is like C/C++:

if/else

do/while

for

switch

if(x==
4
) {


// act
1

} else {


// act
2

}

int i=5;

do {


// act1


i
--
;

} while(i!=0);

int j;

for(int i=0;i<=9;i++)

{


j+=i;

}

char
c=IN.getChar();

switch(c) {


case ‘a’:


case ‘b’:


// act
1


break;


default:


// act
2

}

12

Variables


There are two types of variables in Java,
primitive

types
(int, long, float etc.)

and
reference

types (objects)


In an assignment statement, the
value

of a primitive typed
variable is copied


In an assignment statement, the
pointer

of a reference
typed variable is copied

13

Primitive Types

Type

Values

boolean

true,false

char

16
-
bit unicode charecter

byte

8
-
bit signed integers

short

16
-
bit signed integers

int

32
-
bit signed integers

long

64
-
bit signed integers

float

32
-
bit signed integers

double

64
-
bit signed integers

void

-

* The default value for primitive typed variables is zero bit pattern


The Java programming language guarantees the size, range,
and behavior of its primitive types


14

Wrappers



Java provides Objects which wrap primitive
types.


Example:


Integer n = new Integer(“
4
”);

int m = n.intValue();


15

Reference Types


Reference types in Java are
objects



An object has a set of
data members (attributes)

and a set of
methods



All reference typed variables are
dynamically allocated

from
heap

at runtime (and can’t be explicitly deallocated by the
programmer)


Referenced typed variables can’t be dereferenced (no reference
* or derefernce & operators)


The default value of reference typed variables is
null




16

Reference Types

C++

5

9

a

b

MyObject *x
( not initialized !!!)

Java

MyObject x

a=b

MyObject x(5)

Since we’re handling pointers, the following is obvious :

5

9

a

b

N/A

17

How can I store groups of objects?


It is possible to store a group of objects in Java by using
Vectors and Arrays to collect the objects


thus are known
as “collections”.


Collections allow programs to add objects to them and
making them available for later use or processing. This
can be done as many times as needed.


What is a Vector?


It is a class of the java.util package that allows collections of
objects that will easily add new objects, remove objects, and go
through collection processing of the objects (traversing the vector).
A vector has synchronized threading and also can dynamically
grow or shrink without having a specified size initially declared.


What is an Array?


It is not a Class! A primitive programming language feature that is
built into Java that uses indexing to support collections of data. It
uses only the field “length” to provide information on the number
of elements in the array. An array can also store primitive values.


Please refer to pp. 351
-

354 in the book

18

Casting

The changing of an object or primitive variable
from one declared state to another.

Ex: objvar1 variable1 = (difvar1) variable2;

Ex: Animal myDog= new Dog ();

Dog spot = (Dog) myDog;


long x, y, z; //64 bits, from 9 to
-
9 quintillion


int j, k; // 32 bits, from 2 to
-
2 billion


y = 55; // is this ok?


k = 22; // is this ok?


j = y; // is this ok?


k = 32L // is this ok?


j = (int) y; // is this ok?

19

Iteration through a Vector


Calling a vector:


Vector vec = new Vector ()


Adding an object to a vector:


vec.add(object)


Traversing vectors with for loops:



for (i=0; i < size of collection; i++) {

process element number(i)




}








Looking for an AlgaeColony?


Vector neighbors = simulation.getNeighbors(row, col, 0);


int index;

for (index = 0; index < neighbors.size(); index++) {

if (neighbors.get(index) instanceof AlgaeColony) {

return true;

} else {

return false;

}

}

20

Arrays


Java arrays are objects, so they are declared using
the new operator



The size of the array is fixed


Animal[] arr; // nothing yet …


arr = new Animal[4]; // only array of pointers


for(int i=0 ; i < arr.length ; i++) {


arr[i] = new Animal();


// now we have a complete array

21

Garbage Collection


In C++ we use the ‘delete’ operator to release allocated
memory. ( Not using it means : memory leaks )


In Java there is no ‘delete’ and there are no memory leaks.
O
bjects are freed automatically by the
garbage collector

when it is clear that the program cannot access them any
longer.


Thus, there is no "dangling reference" problem in
Java.

22

Classes in Java


In a
Java program
, everything must be in a class.


There are no global functions or global data


Classes have fields (data members) and methods (functions)


Fields and methods are defined to be one
-
per
-
object, or one
-
per
-
class
(static)


Access modifiers (private, protected, public) are placed on each
definition for each member (not blocks of declarations like C++)

23

Class Example

package example;

public class Rectangle {




public int width =
0
;


public int height =
0
;


public Point origin;



public Rectangle() {


origin = new Point(
0
,
0
);


}


public Rectangle(int w, int h) {


this(new Point(
0
,
0
), w, h);


}


public Rectangle(Point p, int w, int h) {


origin = p;


width = w;


height = h;


}


public void setWidth(int width)


{


this.width = width;



}

}

data members

constructors

a method

24

Examples of Finding Specific Objects


Dynamic typing means the declared type (called the
apparent type
) and
the actual type (called the
dynamic type
) can vary over the lifetime of a
variable


Java comes with some mechanisms for testing the type of an object


Instanceof operator


Variable

instanceof
ClassName

if ( tape instanceof Movie ){…}


Returns true if the variable holds reference to an instance of the
class (or any descendent class)


getClass() method


Class getClass()

if(tape.getClass().equals(Movie.class))

{…}


Returns dynamic type of the object

25

Packages


A package physically and logically bundles a group of
classes


Classes are easier to find and use (bundled together)


Avoid naming conflicts


Control access to classes


Unrestricted access between classes of the same package


Restricted access for classes outside the package


26

Creating a Package


place a
package

statement at the top of the source file in
which the class or the interface is defined.


If you do not use a package statement, your class or interface ends
up in the
default package
, which is a package that has no name


The scope of the package statement is the entire source file.


package p1;


public class C1 {...}

class C2 {...}

C1.java

27

Using Package Members


Only public package members are accessible outside the
package in which they are defined.


Refer to a member by its long (
qualified
) name


A qualified name of a class includes the package that contains the
class


Good for one
-
shot uses


Import the package member


When only a few members of a package are used


Import the entire package


May lead to name ambiguity


28

Using Package Members
-

Examples


Refer to a package member by its qualified name:

p1.C1 myObj = new p1.C1();


Importing a package member


Place an import statement at the beginning of the file,
after the package statement:

import p1.C1;

...

C1 myObj = new C1();


29

Questions?