introduction to computer science using java, iilibe50b/no2.e50b.2013.pdf · dynamically download...

30
CSCI E-50b Spring, 2013 Introduction to Computer Science Using Java, II Dr. Henry H. Leitner 2 Where Does Java Come From? In 1991, a group led by James Gosling and Patrick Naughton at Sun Microsystems designed a language (code- named “Green”) for use in consumer devices such as intelligent television “set-top” boxes and home security systems. No customer was ever found for this technology. The language was renamed “Oak ” (after a tree outside Gosling’s office) and was used to develop the HotJava browser, which had one unique property: it could dynamically download and run programs (“applets”) from the Web.

Upload: others

Post on 19-Mar-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

CSCI E-50bSpring, 2013

Introduction toComputer Science

Using Java, II

Dr. Henry H. Leitner

2

Where Does Java Come From?

In 1991, a group led by James Gosling and Patrick Naughton at Sun Microsystems designed a language (code-named “Green”) for use in consumer devices such as intelligent television “set-top” boxes and home security systems.

No customer was ever found for this technology.

The language was renamed “Oak” (after a tree outside Gosling’s office) and was used to develop the HotJava browser, which had one unique property: it could dynamically download and run programs (“applets”) from the Web.

3

Java island (1990 pop. 107,573,749), Indonesia, c.51,000 sq mi (132,090 sq km), one of the world's most densely populated regions. It constitutes only one seventh of Indonesia's area but contains nearly two thirds of the population and is the political and economic center of Indonesia. The climate is warm and humid, and the volcanic soil is exceptionally productive, yielding two or three crops a year when irrigated. Most of Indonesia's industry is on Java, and lumbering and mining also are important. From the 10th to 15th cent. the island was the center of Hindu-Javanese culture, from which it derives today's highly developed art forms. It was under Dutch rule from 1619 to 1946.

The “Other” Truth About Java

Other In!uential Languages

Simple

Multi-threaded

Recycles memory automatically

Distributed and secure

Robust

Portable; programs are compiled into byte code.Byte code is platform-neutral; it is executed by a program that pretends it is a computer based on the byte-code instruction set, namely a Java virtual machine.

Important Features of Java

6

What is OOP?

Object-oriented programming technology can be summarized by three key concepts:

Objects that provide encapsulation of procedures and data; it allows hiding of the implementation details of an object from the clients of the object.

Classes that implement inheritance within class hierarchies.

Messages that support polymorphism across objects; it allows the same code to be used with several different types of objects and behave differently depending on the actual type being used.

8

A Trivial Java Application

class Hello { public static void main ( String [ ] args) { System.out.println ( "I still miss Scratch! ");

}}

source code compile

byte code run compile run I still miss Scratch!

9

Trivial Application with a GUI

import javax.swing.JOptionPane;

class GUIapp{

public static void main (String [] args)

{ JOptionPane.showMessageDialog (null, "I still miss Scratch!”, “Hello”,

JOptionPane.WARNING_MESSAGE); }}

10

A Trivial Java Appletimport javax.swing.*; // File TrivialApplet.java import java.awt.*;public class TrivialApplet extends JApplet { public void paint( Graphics g )

! { g.setFont (new Font(”Times", Font.BOLD, 50)); g.setColor (Color.RED);

g.drawLine ( 15, 10, 240, 10 ); g.drawLine ( 15, 70, 240, 70 ); g.setColor(Color.BLUE);

g.drawString( "I *really* miss Scratch!", 50, 50 ); } }

<html> <!-- File TrivialApplet.html --> <applet code= "TrivialApplet.class" width=450 height=500> </applet> </html>

11

Identi"ers in JavaIdentifiers must begin with a letter and may contain additional letters and digits.

In place of a letter you may use $, _, or letters from other alphabets (such as Greek, Japanese, Arabic, etc. — all part of the Unicode character set).

Keywords and literals cannot be used:

abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, false, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, true, try, void, volatile, while

12

Strings… are objects containing a sequence of characters.

To construct a String: start and end with a double-quote "

Examples:"hello""This is a rather looong string!"

Restrictions:May not span multiple lines."This is nota legal String."

May not contain a " character."This is not a "legal" String either."

Escape SequencesA special sequence of characters used to represent certain characters in a string:

\t tab character

\n new line character

\" quotation mark character

\\ backslash character

Example: What does this print?System.out.println("\\hello\nhow\tare \"you\"?\\\\");

14

Unicode Example

15

Operator Precedence, part 1

[].

( … )++, --

array indexingobject member reference

method invocation & expr evaluationpostfix increment, decrement

L to R

++, --+, -~, !

prefix increment, decrementunary plus, minus

bitwise NOT, logical NOTR to L

new( type )

object instantiationtype-cast R to L

*, /, % multiplication, division, remainder L to R

16

+-

addition and string concatenationsubtraction L to R

<<, >>>>>

left shift, right shiftright shift with zero fill L to R

<, >, >=, >=instanceof

less-than, greater-than, etc.type comparison L to R

==, != equal, not-equal L to R

& bitwise AND, boolean AND L to R

^ bitwise XOR, boolean XOR L to R

| bitwise OR, boolean OR L to R

&& logical AND L to R

|| logical OR L to R

Operator Precedence, part 2

17

Operator Precedence, part 3

? : conditional operator R to L

=+=-=*=/=%=<<=>>=

>>>=&=^=|=

assignmentaddition / string concatenationsubtraction, then assignment

multiplication, then assignmentdivision, then assignment

remainder, then assignmentleft shift, then assignment

right shift (sign), then assignmentright shift (zero), then assignmentbitwise / boolean AND, assignmentbitwise / boolean XOR, assignmentbitwise / boolean OR, assignment

R to L

18

Control Flow in Java, part 1

if (condition) {Java statements1 }else { Java statements2 }

switch (integer-valued expression)

{ case i1: Java statements1 ;

case i2: Java statements2 ; …

default: Java statementsn ;

}

Decision-Making

Looping

19

Control Flow in Java, part 2

for (initialize; test; increment) { Java statements }while (condition) { Java statements }do {Java statements } while (condition);

continue optional-label ;break optional-label ;return optional-expression ;

Branching

Primitive Data Types in JavaType Contains Default Size Minimum Maximum

boolean true or false false 1 bit

char Unicode character \u0000 16 bits \u0000 \uFFFF

byte signed int 0 8 bits -128 127

short signed int 0 16 bits -32768 32767

int signed int 0 32 bits -2,147,483,648 2,147, 483,647

long signed int 0 64 bits -2 63 263 - 1

float IEEE 754 floating pt. 0.0 32 bits -3.4 E38 3.4 E38

double IEEE 754 floating pt. 0.0 64 bits -1.7 E308 1.7 E308

An array is a sequence of values of the same type

Construct array: new double[10]

Store in variable of type double[]:double [] data = new double[10];

When array is created, all values are initialized depending on array type:

Numbers: 0, 0.0

boolean: false

Object References: null

A Quick Review of Arrays

0

0

0

0

0

0

0

0

0

0

data[0][1][2][3][4][5][6][7][8][9]

22

Single-Dimensioned Arrays, continued

If array arr has n elements, the first one is arr[0] and the last is arr[n-1] . Array elements contain primitive data, or they contains references (pointers) to objects.

What does the following code do?

String [] strArr = new String [5];for (int k = 0; k < strArr.length; k++) { strArr[k] = “Hello” + k + 1; }

You can’t directlychange the size of an array at execution timecompare arrays for equality using ==print an array simply using print or println

23

The java.util.Arrays classMethod Name Description

binarySearch (array, value) returns the index of the given value in a SORTED array

copyOf (array, newLength) returns a new copy of an array (possibly truncated or padded)

equals (array1, array2) returns true if the 2 arrays contain the same elements

fill (array, value) sets every element of an array to a particular value

toString (array) returns a string representation of the contents of the specified array

24

Arrays Get Passed by ReferenceChanges made in the method are also seen by the caller. E.g.,

public static void main (String [] args) { int[] iq = {3, 5, 7};

increase (iq, 3); System.out.println ( Arrays.toString(iq)); }

public static void increase (int [] a, int f) { for (int i = 0; i < a.length; i++) { a[i] *= f; } }

Output?

25

2-Dimensional Array GameNim is an ancient game. There are a number of variations; you can play with bones, skulls, or anything else you have lying around. In this simple version, 2 opponents play with n match sticks.

At each turn, a player takes 1, 2 or 3 matches.

The player left with one match is the loser.

Our program will be written so that a computer or a human can be either player A or player B; the computer knows nothing about Nim strategy but will instead learn from “experience.” See files Lnim.java and Table.java

26

3 Table Objects

[1]

[2]

[3]

[1]

[2]

[3]

[1]

[2]

[3]

[2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

history

aMoves

bMoves

0 0 0 0 0 0 0 0 0 000

00

00

00

00

00

00

00

00

00

000

000

000

000

000

000

000

000

000

000

000

000

000

000

000

000

000

000

000

0001

1

1

1

1

11

1 -1-1

[0] [1]

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10][11]

[0]

[1]

[2]

[3]

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0 0

What a Table Object Really Looks Like

void initialize (int aValue) void setValue (int row, int col, int aValue)void displayValues () int chooseOneToThree (int left)

array

Fields(state)

Methods(behavior)

Review of Objects (brie!y)object: An entity that contains data (variables inside the object) and behavior (methods inside the object).

You interact with the methods.

The data is hidden in the object.

A class is the data type of objects.

Constructing (creating) an object:

Type objectName = new Type (formal parameters);

Calling an object's method: objectName.methodName (actual arguments);

bark(int n)

eat()

sleep()

rollOver()

size

name

chaseCat()

isHungrysit()breed

weight

29

Class java.lang.Stringint length()String trim()boolean equalsIgnoreCase(String other)int compareTo(String other)String substring(int begin)String substring(int begin, int pastEnd)

String toLowerCase()String toUpperCase()boolean endsWith(String suffix)boolean startsWith(String prefix)boolean startsWith(String prefix,int offset)

boolean equals(String other)

See StringTest.java

30

Class java.lang.StringBuilder3 constructorsint length()int capacity()char charAt (int index)char setCharAt (int index, char ch)StringBuilder append (String str)StringBuilder append (char ch)

StringBuilder insert (int offset, String str)StringBuilder insert (int offset, char ch)

StringBuilder reverse ()String substring (int start)String substring (int start, int end)

See StringBuilderTest.java

31

Where are the Other Classes?Java programs contain one or more classes that contain definitions of methods (each is a sequence of instructions that describes how to carry out a computation). Every Java app contains at least one class with a method named main.

Java classes are grouped into packages. If you use a class from a package other than java.lang

“import” the class; or

use the FULL name (both package and class names) whenever you use a class. For example,

java.util.Scanner s = new java.util.Scanner (System.in);

Java API PackagesJava contains many predefined classes grouped into packages. Together, these packages are referred to as the Java applications programming interface (Java API). Some examples:

java.applet

javax.swing (contains classes for creating GUIs)

java.awt, java.awt.event and java.awt.image

java.io (contains classes for dealing with files)

java.util (contains Scanner class)

java.net

java.lang (automatically imported by the compiler)

Class Scanner

Enumerated Types

Autoboxing

Variable Length Parameter Lists

New for Loop

Formatted output using printf

Generic Types

Some of the New Features in Java ≥1.5

35

Keyboard Input (the old way)import java.io.*;

class Hello{

public static void main (String [] args) throws IOException{ BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print("How old are you? "); int age = Integer.parseInt(br.readLine()); System.out.println("Wow, next year you’ll " + "be " + (age+1) + "!");

}}

36

Keyboard Input a la Java 1.5import java.util.Scanner;

class Hello

{

public static void main (String [] args) { Scanner keyboard = new Scanner(System.in); System.out.print("How old are you? "); int age = keyboard.nextInt(); System.out.println("Wow, next year you’ll " + "be " + (age+1) + "!");

}

}

Scanner helps “iterate” over collection of items

String nextLine()

Returns the remaining keyboard input line as a String. Note: ‘\n’ is read and discarded.

boolean nextBoolean()

double nextDouble()

int nextInt()

others …

Preview: these methods throw an unchecked InputMismatchException if the next token isn’t of the correct type.

Scanner Class

38

boolean methods hasNextInt(), etc. Returns true if the next “token” in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method. The scanner does not advance past any input.

useDelimiter (String aString)

Makes aString the only delimiter used to separate input. aString is often a “regular expression.”

next()

Returns input up to, but not including, the first delimiter (any whitespace character is the default)

More on the Scanner Class

39

import java.util.Scanner;

class Delimit

{ public static void main(String [] args)

{

Scanner in = new Scanner(System.in);

String word1, word2; in.useDelimiter ("#"); System.out.print ("Enter two words: "); word1 = in.next(); word2 = in.next();

System.out.println (word1 + " was entered first"); System.out.println ("Then you entered " + word2); }}

Example Involving useDelimiter()OUTPUTEnter two words: one#two#one was entered firstThen you entered two

OUTPUTEnter two words: onetwo#three#onetwo was entered firstThen you entered three

40

An enumerated type creates a new type of variable and establishes all possible values by listing them. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

enum Grade { A, B, C, D, F } ;

Grade myGrade = Grade.A;

if (myGrade == Grade.F)

System.out.println(“You fail”);

System.out.println(myGrade);

Enumerated Types

41

No invalid value can be assigned

Internally, each value has a corresponding ordinal value, starting at 0

You cannot use the ordinal values directly. Instead you can use the

ordinal() method

Java also provides a name() method

enum types cannot be declared locally

You can pass enum variables and values as arguments

Enumerated Types, continued

42

public class Enumerated{ enum Grade { A, B, C, D, F}

public static void main(String [] args) { Grade myGrade = Grade.A;

if (myGrade == Grade.F) System.out.println("You fail"); else System.out.println("You pass");

System.out.println("myGrade: " + myGrade); System.out.println("myGrade.ordinal(): " + myGrade.ordinal()); System.out.println("myGrade.name(): " + myGrade.name()); }}

Enumerated Type Example

43

… the automatic conversion from a primitive value to the corresponding “wrapper” object

Integer myInt;

int number = 5; myInt = number;

Unboxing converts from an object to the primitive type, e.g.,

Integer myInt2 = new Integer(15);

int number = myInt2;

Autoboxing

44

Java methods can now accept a variable number of arguments

These arguments will be stored in an array. For example,public static void main (String [] args){ myMethod ("A", "B", "C", "D");}

public static void myMethod (String ... data){ for (int i = 0; i < data.length; i++)

{ System.out.println (data[i]); }

}

OUTPUTABCD

Variable Length Arguments

45

Methods can accept other parameters, in addition to the variable length parameter

The variable length parameter must come last in the argument list

Methods can accept only one variable length parameter, e.g.,

void myMethod (int a, double b, int ... numbers) {

Variable Length Arguments, cont'd.

46

To iterate through a sequence of elements, such as those in an array or an ArrayList:

int [] list = {1, 2, 3, 4, 5};

for (int num : list){

System.out.println(num);}

OUTPUT12345

The New “For Each” Loop

47

Formaed Output Using printfSystem.out.printf (“format string”, expr1, expr2, … exprn);

The format string contains ordinary characters that get printed, and

placeholders that tell how each value should be printed.

Each placeholder begins with a % character and ends with a letter that indicates the format type. For example, %d or %x

Flags, width, and .precision specifiers are options BEFORE the type that indicate exceptions to the default output. For example,

%,d format as decimal integer with commas

%-9.2f format as floating-point, left-justified with 2 digits of precision

48

printf Exampleclass PrintfDemo{ public static void main (String [] args) {

System.out.printf ("I have %.2f bugs to fix!\n", 47568.09876);

System.out.printf ("I have %,.2f bugs to fix!\n", 47568.09876);

System.out.printf ("I have %,15.3f bugs to fix!\n", 47568.09876); }}

49

Simple Recursive MethodsA recursive definition is a statement in which something is defined in terms of smaller (simpler) versions of itself.  

A recursive alternative to the built-in method Math.pow to compute xn :

Base case:

Recursive case[s]:

static double power (double x, int n) { // finish this off

Printing Strings in Reverse

public static void reverse (Scanner input) { if (input.hasNextLine()) { String line = input.nextLine(); reverse (input); System.out.println (line); } } // see file Reverse.java

Recursion in Koch Snow!ake

TheRule:

If you still don't get it, See: "Recursion"

52

When to Use Recursion

Often, the decision to use recursion is suggested by the "appropriate" nature of the problem itself:

It must be possible to decompose the original into simpler instances of the same problem.

Once each of these simpler subproblems has been solved, it must be possible to combine these solutions to produce a solution to the original problem.

As the large problem is broken down into successively less complex ones, those subproblems must eventually become so simple that they can be solved without further subdivision.

53

General Scheme for Recursiondata-type recursiveSolve (instanceOfaProblem i)

{ if (instance i is trivial) { return (solve i directly); }

else

{ Break instance i into smaller instances il, i2, ... in data-type s1 = recursiveSolve (i1); data-type s2 = recursiveSolve (i2); … return combine/assemble the sn solutions;

}}

54

Towers of HanoiThe book Mathematical Recreations and Essays (11th ed.) gives a history of the puzzle, introduced in 1883:

"In the great temple of Benares … rests a brass plate in which are fixed 3 diamond needles, each a cubit high and as thick as the body of a bee. On one of these needles, at the creation, God placed 64 disks of pure gold, the largest disk resting on the brass plate, and the others getting smaller and smaller up to the top one. This is the Tower of Brahmah. Day and night unceasingly the priests transfer the disks from one diamond needle to another according to the fixed and immutable laws of Brahmah, which require that the priest on duty must not move more than 1 disk at a time, and that he must place this disk on a needle so that there is no smaller disk below it. When the 64 disks shall have been thus transferred from the needle on which at the creation God placed them, to one of the other needles, tower, temple, and Brahmins alike will crumble into dust, and with a thunderclap the world will vanish!”

55

Towers of Hanoi Model http://www.mazeworks.com/hanoi

56

Towers of Hanoi, continuedRecursive algorithm:

static void towers(char origin, char dest, char intermed, int numDisks){ if ( numDisks == 1 ) // base case System.out.println ("Move disk #1 from ” + origin + " to " + dest ); else { towers ( ); System.out.println ("Move disk #" + numDisks + " from " + origin + " to " + dest); towers ( ); }}

4

6 74

5

11

2

3

Origin

Origin

Origin

Origin

Origin

Origin Origin

Dest

Dest

Dest

Dest

Dest

Dest Dest

Intermed

Intermed

Intermed

Intermed Intermed Intermed

Intermed

numDisks

numDisksnumDisks

numDisks

numDisks numDisks numDisks

towers ( 's', 'd', 'i', 3); ‘s’‘d’‘i’3

‘s’‘i’‘d’2

‘s’‘d’‘i’1

‘d’‘i’‘s’1

‘d’‘i’

‘s’2

Flow of Control in Hanoi.java

18,446,744,073,709,551,615

58

Numbers as Character StringsTo recursively print the int n in decimal as a character sequence, view n as consisting of the units digit (n % 10), and everything else (n / 10):

“if needed,” print (n/10) recursively

print the units digit, (n % 10)

Now substitute any "base" from binary to decimal for 10, and write the whole thing in Java:

static void writeBase (int n, int base){ if (n >= base) writeBase ( char [] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; System.out.print ( digits [n % base] ); }

59

Classes and Objects Revisited

class: A program entity that represents

A program, or

A template for a new type of objects. E.g., the Movie class is a template for creating new Movie objects.

object: An entity that combines state and behavior.

object-oriented programming (OOP): Programs that perform their behavior as interactions between objects.

60

iPod Blueprint Analogystate:

current song volume

battery lifebehavior:

power on/off change station/song

change volume choose random song

iPod #1state:

song = "True Romance"

volume = 17 battery life =

12.5 hrsbehavior:

power on/off change station/

song change volume

iPod #2state:

song = "Letting You"

volume = 9 battery life =

3.41 hrsbehavior:

power on/off change station/

song change volume

iPod #3state:

song = "Discipline"

volume = 24 battery life = 1.8

hrsbehavior:

power on/off change station/

song change volume