Analysis of Algorithms

concepcionsockSoftware and s/w Development

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

470 views

Java Review #1


Topics


Helpful web sites


Java Virtual Machine


Basic concepts


Instance variable modifiers


Methods


Java program structure


Constructors


Enums


Nested classes


Packages


Class modifiers


Arrays

Helpful Web Sites (1)


Java™ Platform, Standard Edition 7 API
Specification


http://docs.oracle.com/javase/7/docs/api/


Eclipse


http://www.eclipse.org/


NetBeans


http://www.netbeans.org/downloads/


The JDK and
BlueJ

for Mac or Windows


http://www.bluej.org/download/download.html


3

Helpful Web Sites (2)


JAVA download


http://www.java.com/en/download/


Complete Java™ language specification


http://www.oracle.com/technetwork/java/index.html


Textbook site


http://www.cs.armstrong.edu/liang/intro8e

4

Why Java?


Java is a general purpose programming language


Java enables users to develop and deploy applications on
the Internet for servers, desktop computers, and small
hand
-
held devices


Java is the Internet programming language


Java is portable


5

Compiling Java Source Code



One can port a source program to any machine with appropriate
compilers



The source program must be recompiled, however, because the
object program can only run on a specific machine (C++, etc.)



Java was designed to run object programs on any platform



With Java, you write the program once, and compile the source
program into a special type of object code, known as
bytecode



The
bytecode

can then run on any computer with a Java Virtual
Machine



Programs written in Java don't have to be rewritten to run on
different computers

6

The Java Virtual Machine (JVM)


Java Virtual Machine is a software that interprets Java
bytecode


The logical machine (non
-
physical machine) that
performs machine functions, typically implemented in
software on top of a "real" hardware platform and
operating system


The software implementation of a "CPU" designed to
run compiled Java code


Includes stand
-
alone Java applications, as well as
"applets" that run in Web browsers such as Internet
Explorer and Firefox

7

JVM

8


Java Bytecode

Java Virtual
Machine

Any
Computer

Java Application Program Interface Library



The application program interface (API) library contains
predefined classes and interfaces for developing Java
programs


The Java language is stable however the API library is
always expanding


One popular edition of Java is Java SE (standard
edition)


Can be used to develop standalone application and
applets


Other editions include Java Enterprise Edition (Java
EE)
-

(
http://en.wikipedia.org/wiki/Java_EE

)
and Java Micro
Edition (Java ME)


Java is Object
-
Oriented (1)



Java is inherently object
-
oriented


Although many object
-
oriented languages began
strictly as procedural languages, Java was designed
from the start to be object
-
oriented


Object
-
oriented programming
(OOP)
is a popular
programming approach that is replacing
traditional procedural programming techniques



10

Java is Object
-
Oriented (2)



One of the central issues in software development
is how to reuse code


Object
-
oriented programming provides great
flexibility, modularity, clarity, and reusability
through encapsulation, inheritance, and
polymorphism

11

Anatomy of a Java Program


Comments


Package


Reserved words


Modifiers


Statements


Blocks


Classes


Methods


The main ( ) method

12

Java Program Structure

/*

*
All Java code is encapsulated in a "class". The file holding this
class MUST be named using the class name followed by the ".java"
suffix

*/

public class AJavaApplication

{

//... methods (functions) and variables ...

/*

*
Method "main" is the entry point for all Java Applications. This
is the first method called when the application is executed.

*/

public static void main (String[] args)

{

//...
lines of code which can include calls to the methods of this

// and other classes.

}
// end main


}
// end of class JavaApplicationName

13

main( ) Method



The main method provides the control of program
flow



The Java interpreter executes the application by
invoking the main method




The main method looks like this:

public static void main(String[ ]
args
) {


// statements;

}

14

Hello World

public class Hello

{


public static void main( String
args
[ ] )

{


System.out.println
( "hello world" );


}

}



15

Reserved Words



Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be used
for other purposes in the program



For example, when the compiler sees the word class,
it understands that the word after class is the name for
the class

16

Identifiers


An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and $


Java is case sensitive


Should not use the $


An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit


$ sign is bad form in java


An identifier cannot be a reserved word


(See Appendix A, “Java Keywords,” for a list of reserved words)


An identifier can be of any length

17

Constants

final datatype CONSTANTNAME = VALUE;


final double PI = 3.14159;

final int SIZE = 3;

18

Packages


Packages


Collection of classes defined in the same subdirectory


Each file in the package contains a package statement


package
packageName
;


The subdirectory must have the same name as the
packageName


A package can be defined in a single file containing
several classes but when compiled, the classes will be
complied in separate files


19

import


The
import
keyword is used to include external classes or
entire packages


import packageName.className


import packageName.*;


(entire package)



20

Statements


Assignments


Decisions


if
-
then


if
-
then
-
else


switch
-
case


Iterations


while


do
-
while


for


Restricted
gotos


break


continue


return

21

Classes and Objects


A class is a template or blueprint for objects


What is a class?


A class is corresponding to a concept


Student, Faculty, Staff, Rectangle, Circle


A class is a set of objects with the same behavior


What is an object?


An object is a corresponding entity


Susan, Mark, Alan


An object is an entity that you can manipulated by invoking
methods (functions)


Each object belongs to a class

22

Data Types


Primitive (built
-
in)


int
, long, short, double, float, boolean, byte (char)


Classes


Strings, Objects

23

Numerical Data Types


24


Name




Range


Storage Size


byte


2
7
(
-
128) to 2
7

1 (127)

8
-
bit signed


short


2
15
(
-
32768) to 2
15

1 (32767)

16
-
bit signed


int


2
31
(
-
2147483648) to 2
31

1 (2147483647)

32
-
bit signed


long


2
63
to 2
63

1

64
-
bit signed


(i.e.,
-
922337203685
4775808


to 9223372036854775807)


float

Negative range:

32
-
bit IEEE 754



-
3.4028235E+38 to
-
1.4E
-
45


Positive range:


1.4E
-
45 to 3.4028235E+38


double

Negative range:

64
-
bit IEEE 754



-
1.7976931348623157E+308 to


-
4.9E
-
324


Pos
itive range:

4.9E
-
324 to 1.7976931348623157E+308


Number Literals



A
literal
is a constant value that appears directly in the
program




For example, 34, 1000000, and 5.0 are literals in the
following statements:


int

i

=

34
;

long

x

=

1000000
;

double

d

=

5
.
0
;


25

Integer Literals



An

integer

literal

can

be

assigned

to

an

integer

variable

as

long

as

it

can

fit

into

the

variable



A

compilation

error

would

occur

if

the

literal

were

too

large

for

the

variable

to

hold



For

example,

the

statement

byte

b

=

1000

would

cause

a

compilation

error,

because

1000

cannot

be

stored

in

a

variable

of

the

byte

type



26

27

Floating
-
Point Literals



Floating
-
point

literals

are

written

with

a

decimal

point



By

default,

a

floating
-
point

literal

is

treated

as

a

double

type

value



For

example,

5
.
0

is

considered

a

double

value,

not

a

float

value



One

can

make

a

number

a

float

by

appending

the

letter

f

or

F,

and

make

a

number

a

double

by

appending

the

letter

d

or

D



One

uses

100
.
2
f

or

100
.
2
F

for

a

float

number



One

uses

100
.
2
d

or

100
.
2
D

for

a

double

number



Scope (1)


Scope of variable: region of program where the
variable can be referred by its name


Local variable scope: from definition to end of
block


Class scope: all methods of the class


Overlapping scope: local scope wins over class
scope

28

Scope (2)


Static scope


Static fields


A field that belongs to a class instead of any object


Non
-
static fields are instance fields while static
fields are class fields


Minimize the use of static fields


Static methods


No implicit parameters


Too many static methods are a sign of a lack of
Object
-
oriented design techniques

29

Numeric Type Conversion

Consider

the

following

statements
:

byte

bv

=

100
;

long

lv

=

bv

*

3

+

4
;

double

dv

=

bv

*

3
.
1

+

lv

/

2
;


Rules

for

conversions

follow
……


30

Conversion Rules


When performing a binary operation involving two
operands of different types, Java automatically converts
the operand based on the following rules:


1.


If one of the operands is double, the other is
converted into double

2.


Otherwise, if one of the operands is float, the other is
converted into float

3.


Otherwise, if one of the operands is long, the other is
converted into long

4.


Otherwise, both operands are converted into
int


31

Type Casting

Implicit

casting


double

dv

=

3
;

(type

widening)


Explicit

casting


int

i

=

(
int
)
3
.
0
;

(type

narrowing)


int

i

= (
int
)3.9; (Fraction part is
truncated)

32


byte
,
short, int, long, float, double

range

increases

Converting to Objects


Built in data types can be easily converted to objects


IntegerObject

= new Integer (78)


This statement creates an integer object containing
the value 78


33

Operator Overloading


Java does not allow for operator overloading


34

Unicode Format


Java characters use Unicode, a 16
-
bit encoding scheme established
by the Unicode Consortium to support the interchange,
processing, and display of written texts in the world’s diverse
languages


Super set of ASCII (
http://charts.unicode.org

)



Unicode takes two bytes, preceded by
\
u, expressed in four
hexadecimal numbers that run from
'
\
u0000'

to
'
\
uFFFF
'
.

So,
Unicode can represent
65535 + 1 characters

Unicode
\
u03b1
\
u03b2
\
u03b3 for three Greek
letters

35

Escape Sequences for Special Characters

36

Description Escape Sequence


Unicode

Backspace
\
b



\
u0008

Tab
\
t



\
u0009

Linefeed
\
n



\
u000A

Carriage return
\
r



\
u000D

Backslash
\
\



\
u005C

Single Quote
\
'




\
u0027

Double Quote
\
"




\
u0022

The String Type



The char type only represents one character



To represent a string of characters one uses the data type called
String



String message = "Welcome to Java";





String is actually a predefined class in the Java library



The String type is not a primitive type


// Three strings can be concatenated

String message = "Welcome " + "to " + "Java";


37

More on Java Classes


Java classes compose of


Instance variables (fields)


Where data of Java objects is stored


Primitive data types or objects


Methods


Functions, constructors, or procedures


The dot ( . ) operator is use to access members of an objects


Examples:


myObject.objectData;


myObject.myMethod( );


38

Modifiers



Java uses certain reserved words called modifiers
that specify the properties of the data, methods, and
classes and how they can be used

39

Instance Variable (Fields) Modifiers


Controls the scope of instance variables


public



anyone can access


protected



only methods of the same package or its subclasses
can access


private



only methods of the same class can access


friendly


(default) can be accessed by any class in the same
package



static

-

(global) associated with the class and not individual
instances of the class


final

(
constant)


must be initialized


Initial value cannot be changed

40

Methods


Functions


Procedures (with return type void)


Composed of a body (code), return type, and a
signature (interface)


The main method get invokes when a stand
-
alone
application executes





41

Methods Modifiers


Public, protected, private, and friendly


Similar meaning as instance variable modifiers


Abstract


No code associated with the method


Final



Cannot be overridden by a subclass


Static method


Used to change the state of static variables


Non static methods can access static variables


Static methods cannot access instance variables



Static methods can be used without invoking an instance of the class


42

Classes Modifiers


Abstract


Class that has abstract methods


Abstract classes cannot be instantiated. They can have both abstract
methods, which must be implemented by a subclass, and normal
methods.


Final


Class that has no subclasses


Public


Class that can be instantiated or extended by anything in the same package
or by anything that imports the class


Resides in a separate file called classname.java


Friendly


Default


Class that can be used and instantiated by all classes in the same package

43

Constructors


Same name as the class


Multiple constructors can be written for a class (overloading)


Each will have a different signature


Cannot return a value


Automatically executed when an object is created


The abstract, final, and static method modifiers are not valid


Objects are created by the use of the new operator followed by a
call to a constructor


The new operator returns a reference (pointer) to the newly
created object


For example: Clock myClock = new Clock (12,24,49);

Trace a Program Execution

public class ComputeArea {


/** Main method */


public static void main(String[] args) {


double radius;


double area;




// Assign a radius


radius = 20;




// Compute area


area = radius * radius * 3.14159;




// Display results


System.out.println("The area for the circle of radius " +


radius + " is " + area);


}

}

45

no value

radius

allocate memory
for radius

animation

Trace a Program Execution

public class ComputeArea {


/** Main method */


public static void main(String[] args) {


double radius;


double area;




// Assign a radius


radius = 20;




// Compute area


area = radius * radius * 3.14159;




// Display results


System.out.println("The area for the circle of radius " +


radius + " is " + area);


}

}

46

no value

radius

memory

no value

area

allocate memory
for area

animation

Trace a Program Execution

public class ComputeArea {


/** Main method */


public static void main(String[] args) {


double radius;


double area;




// Assign a radius


radius = 20;




// Compute area


area = radius * radius * 3.14159;




// Display results


System.out.println("The area for the circle of radius " +


radius + " is " + area);


}

}

47

20

radius

no value

area

assign 20 to radius

animation

Trace a Program Execution

public class ComputeArea {


/** Main method */


public static void main(String[] args) {


double radius;


double area;




// Assign a radius


radius = 20;




// Compute area


area = radius * radius * 3.14159;




// Display results


System.out.println("The area for the circle of radius " +


radius + " is " + area);


}

}

48

20

radius

memory

1256.636

area

compute area and assign it
to variable area

animation

Trace a Program Execution

public class
ComputeArea

{


/** Main method */


public static void main(String[]
args
) {


double radius;


double area;




// Assign a radius


radius = 20;




// Compute area


area = radius * radius * 3.14159;




// Display results


System.out.println
("The area for the circle of radius " +


radius + " is " + area);


}

}

49

20

radius

memory

1256.636

area

print a message to the
console

animation

Simple Input


Built
-
in special object: System.in


Related class: java.util.Scanner

1. Create a Scanner object

Scanner scanner = new Scanner(System.in);

2. Use the methods
next(), nextByte(), nextShort(), nextInt(),
nextLong(), nextFloat(), nextDouble(), or nextBoolean()
to obtain to a string, byte, short, int, long, float, double, or
boolean value




50

Simple Output


Simple output methods:


Built
-
in static object: System.out


An instance of the java.io.PrintStream class


print(Object)


print(String)


println(String)

51

Example Using Scanner

Scanner input = new Scanner(
System.in
);


// Prompt the user to enter an integer


System.out.print
("Enter an integer: ");


int

intValue

=
input.nextInt
();


System.out.println
("You entered the integer " +
intValue
);


// Prompt the user to enter a double value


System.out.print
("Enter a double value: ");


double
doubleValue

=
input.nextDouble
();


System.out.println
("You entered the double value "


+
doubleValue
);


// Prompt the user to enter a string


System.out.print
("Enter a string without space: ");


String
string

=
input.next
();


System.out.println
("You entered the string " + string);


}

}

52

SecondJavaProgram


import java.io.*;


//Line 1

public class
SecondJavaProgram

//Line 2

{


//Line 3


static final
int

NUMBER = 12; //Line 4



static
BufferedReader

keyboard = new


BufferedReader
(new
InputStreamReader
(
System.in
)); //Line 5



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

//Line 6


{

//Line 7


int

firstNum
;


//Line 8


int

secondNum
;


//Line 9



firstNum

= 18;


//Line 10


System.out.println
("Line 11:
firstNum

= “



+
firstNum
);


//Line 11


System.out.print
("Line 12: Enter an integer: "); //Line 12


secondNum

=
Integer.parseInt
(
keyboard.readLine
()); //Line 13


System.out.println
(); //Line 14


System.out.println
("Line 15:
secondNum

= "


+
secondNum
); //Line 15


firstNum

=
firstNum

+ NUMBER + 2 *
secondNum
; //Line 16


System.out.println
("Line 17: The new value of " +


"
firstNum

= " +
firstNum
); //Line 17


} //Line 18

} //Line 19



}

}

Output

Line 11:
firstNum

= 18

Line 12: Enter an integer: 88


Line 15:
secondNum

= 88

Line 17: The new value of
firstNum

= 206

BUILD SUCCESSFUL (total time: 3 seconds)

53

Date Class

package date;


import
java.util.Date
;


public class date {


public static void main(String[]
args
) {




Date today = new Date();



System.out.println
("Today's date " + today );



Date holiday = new Date("2011 December 25");



System.out.println
("The date specified is " + holiday );


}

}

Output

Today's date Fri Dec 10 20:19:56 PST 2010

The date specified is Sun Dec 25 00:00:00 PST 2011

54

Enums


Used to improve readability and maintainability


Syntax


Modifier enum enumName {value_name
1
, value_name
2
,…,
value_name
n
}


where modifier is public, protected, or private


Example:


public enum day {MON, TUES, WED} ;


Enums type have a few built
-
in methods such as valueOf which
returns the enum value



55

Enum

Example

public class
DayTripper


{


public
enum

Day {MON, TUE,WED};


public static void main (String[ ]
args
){


Day
myDay

= Day.MON;


System.out.println
("Initially
myDay

is " +
myDay
);


myDay

= Day.WED;


System.out.println
(“Now my
myDay

is " +
myDay
);


Day
yourDay

=
Day.valueOf
("WED");


System.out.println
("Is
myDay

and
yourDay

equal? " + (
myDay
==
yourDay
));


}

}

Output

Initially
myDay

is MON

Now
myDay

is WED

Is
myDay

and
yourDay

equal? true


56

Arrays


A set of data cells with fixed size, each cell holding a data item and
all data items being the same type


Once an array is created, its size is fixed


Indices



0 through length
-
1


Common algorithms on arrays


Find max/min values


Find average value


Linear search


Copying and cloning arrays


57

Arrays


Arrays are objects


Members functions and fields are available


For example


length


clone( )


Array elements could be objects


Boundary checking is performed


java.lang.ArrayIndexOutOfBoundsException is executed

58

Strings and Character Arrays


String objects are usually stored internally as an array of characters


Java provides a way to create string objects from character arrays
and vice versa


To create an object of class String from a character
array


new String (A) returns a string where A is a character array


Example:



if A =[1,2,3] then a String (A) returns 123


To create a character array from a String object, S


S.toCharArray
( ) returns a character array


Example: if S contains 123 then a character array [1,2,3] is
returned

59

Array Example


import java.io.*;

import
java.util.Scanner
;

class
myArray

{

public static void main(String
arg
[ ]) {


int

month;


int

day;


int

totalDays
;


int

daysPerMonth
[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};



Scanner keyboard = new Scanner(
System.in
);


System.out.println

("
\
nEnter

month (1 to 12): "); // get date


month =
keyboard.nextInt
();


System.out.println

("Enter day (1 to 31): "); // get day


day =
keyboard.nextInt
();


totalDays

= day;


for(
int

index=0; index<month
-
1; index++){



totalDays

+=
daysPerMonth
[index];


}


System.out.println

("Total days from start of year is: " +
totalDays
);



int

[]
yourArray
;



yourArray

= new
int
[12];


yourArray

=
daysPerMonth.clone
();


System.out.println

("size of copied array: " +
yourArray.length
);


System.out.println

("first element: " +
yourArray
[0]);


}


}

Array Example Output

output

Enter month (1 to 12):

5

Enter day (1 to 31):

8

Total days from start of year is: 128

size of copied array: 12

first element: 31



More examples

See quadratic and statistic examples