cisc6795: internet computing and java programming xiaolan zhang spring 2011 1

75
CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Upload: augustus-white

Post on 20-Jan-2016

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMINGXiaolan ZhangSpring 2011

1

Page 2: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Course Objectives Basic programming concepts in Java language Object-oriented approach to software design and

development Java APIs including

Java Collection API Graphical User Interface packages Database connectivity (JDBC) Web application (applet)

Design and implement medium-size standalone and web applications

Assume some knowledge of C++ or C programming

2

Page 3: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Reference textbook

Thnking in Java, Bruce Eckel, Free Electronic Version Great for someone with C/C++ programming

experience Java How to Program, H.M. Deitel and P.J.

Deitel, 8th Edition, Prentice Hall, late object version For beginner programmers

We take late object approach i.e., we first focus on basic programming

constructs

3

Page 4: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Focus and philosophy

Software reuse: building-block approach to create programs. Avoid reinventing the wheel—use existing

pieces wherever possible. Building blocks: classes from class libraries,

classes you wrote before, and classes that others create and make available to you (many are available over Internet for free)

4

Page 5: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Focus and philosophy (2)

Benefits of software reuse: save program development time often improve program performance (as

libraries carefully written to perform efficiently) To use building blocks

Read documentation for the version of Java Refer to it frequently to be sure you are aware of

the rich collection of Java features and are using them correctly.

When in doubt, experiment and see what happens.

5

Page 6: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Online resource

• http://www.oracle.com/technetwork/java/index.html : official info. about Java including documentation, software, announcements, tutorials, and much more.

• In particular, class library documentation at http://download.oracle.com/javase/1.4.2/docs/api/ • Download a zip or tar file and install it on your

own PC.

6

Page 7: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

History of Java Originally for intelligent consumer-electronic devices in

Sun Microsystems (1990) Reason: C++ not a good fit:

Demanded too large a footprint Its complexity led to developer errors No garbage collection, programmers managing

system memory => challenging and error-prone Lack of portable support for security, distributed

programming, and threading Could not be easily ported to all types of devices

Now: large-scale enterprise applications, Web program, consumer devices (cell phones, etc.)

7

Page 8: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Memory footprint

Memory footprint: the amount of main memory that a program uses or references while running. Includes code, static data sections (both

initialized and uninitialized), heap, stacks structures introduced by run-time environment

(compiler, interpreter, Java Virtual Machine): such as symbol tables, constant tables, debugging structures, open files

Those that program ever needs while executing and will be loaded at least once during entire run.

8

Page 9: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Java as a platform

• Java is a platform for application development• Typically, a platform means some combination

of hardware and system software that will mostly run all same software. – e.g., PowerMacs running Mac OS 9.2 – e.g., DEC Alphas running Windows NT

• Problem: – Programs very closely tied to specific hardware

and operating system they run.– Program needs to be ported to different platforms

– Distributing executable programs from web pages is hard

9

Page 10: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Platform Independence of Java

• Java: write one, run everywhere• Java compiler (javac) produces byte code

• Byte code written in hexadecimal, byte by byte, looks like this:• CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00

20 08 …

• Byte code is exactly the same on every platform

• Interpreter/Just-in-time compiler (java) translates byte code to machine’s native language to execute• Compiler is not platform independent

10

Page 11: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Platform Independence

• Only interpreter/JIT compiler and a few native libraries need to be ported to get Java to run on a new computer or operating system• The rest of the runtime environment,

compiler and most of class libraries are written in Java.

• javac compiler, java interpreter, Java programming language, and more are collectively referred to as Java.

11

Page 12: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

The Scope of Java

J2SE J2EE J2ME

One Java Platform, Multiple Profiles

12

Page 13: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Java Profiles

Java Card: allows small Java-based applications to run securely on smart cards and similar small-memory-footprint devices Smart card, chip card, or integrated circuit

card, is any pocket-sized card with embedded integrated circuits, for providing identification, authentication, data storage and application processing

Java ME (Micro Edition): for devices which are sufficiently limited Supplying full set of Java libraries would take up

unacceptably large amounts of storage.

13

Page 14: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Java Profiles (cont’d)

Java SE (Standard Edition): For general-purpose use on desktop PCs, servers and similar devices.

Java EE (Enterprise Edition): Java SE plus various APIs useful for multi-tier client–server enterprise applications

14

Page 15: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

15

Page 16: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Life-cycle of Java Program

javac welcome1.java

java welcome1

16

Page 17: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

17

Page 18: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Introduction to Java Programming We demonstrate how to:

Display messages Obtain information from the user Arithmetic calculations Decision-making fundamentals A quick start, and Illustrates several

important Java language features

18

Page 19: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

1 // Fig. 2.1: Welcome1.java

2 // Text-printing program.

3

4 public class Welcome1

5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.println( "Welcome to Java Programming!" );

10

11 } // end method main

12

13 } // end clazss Welcome1

Welcome to Java Programming!

Line numbers not part of program, added for reference

19

Page 20: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

First Program in Java: Printing a Line of Text (Cont.)

Comments start with: // Comments ignored during program execution Document and describe code Provides code readability

Traditional comments: begin with /*,end with *//* This is a traditional comment. It can be split over many lines */

No space between / and *

1 // Fig. 2.1: Welcome1.java

2 // Text-printing program.

20

Page 21: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice Every program should begin with a

comment that explains the purpose of the program, the author and the date and time the program was last modified.

21

Page 22: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Class declaration

Blank line Makes program more readable Blank lines, spaces, and tabs are white-space characters

Ignored by compiler

Begins class declaration for class Welcome1 Every Java program has at least one user-defined class Keyword: words reserved for use by the language (here, Java)

class keyword must be followed by class name Naming classes: capitalize every word, i.e., camel case

SampleClassName Java programmers know that such identifiers normally

represent Java classes, so naming your classes in this manner makes your programs more readable.

3

4 public class Welcome1

22

Page 23: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Syntax Error The syntax of a programming language

specifies rules for creating a proper program in that language.

A syntax error occurs when the compiler encounters code that violates Java’s language rules (i.e., its syntax). E.g., keyword class not followed by an identifier a

syntax error When it happens, compiler does not

generate .class file. Instead, it issues an error message to help programmer identify and fix incorrect code.

also called compiler errors, compile-time errors or compilation errors, because compiler detects them during compilation phase.

23

Page 24: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Rules for identifier

Welcome1 is an example of identifier, name for variable, class or method Series of characters consisting of letters,

digits, underscores ( _ ) and dollar signs ( $ )

Does not begin with a digit, has no spaces Examples: Welcome1, $value, _value, button7 7button is invalid

Java is case sensitive (capitalization matters) a1 and A1 are different

4 public class Welcome1 24

Page 25: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Class declaration (2)

Important rules: The above code must be saved as file

Welcome1.java, i.e., class name with .java extension

Different from C++

Left brace { Begins body of every class Right brace ends declarations (line 13)

4 public class Welcome1

5 {

It is an error not to end a file name with .java extension for a file containing a class declaration.

25

Page 26: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice Whenever you type an opening left brace, {, in your

program immediately type the closing right brace, }, then reposition the cursor between the braces indent the entire body of class declaration

i.e., begin lines with the body by a fixed number of spaces, or a tab

Prevent missing or unmatching braces, a syntax error Indentation emphasizes class declaration's structure

and makes it easier to read.

26

Page 27: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice: indentation

Set a convention for indent size you prefer

Uniformly apply that convention. use Tab key may be used to create indents,

but tab stops vary among text editors. use three spaces to form a level of indent.

27

Page 28: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

main method

Part of every Java application Applications begin executing at main

Parentheses indicate main is a method (Ch. 3 and 6) Java applications contain one or more methods

Exactly one method must be called main Methods can perform tasks and return

information void means main returns no information For now, mimic this line in your program

Left brace begins body of method declaration Ended by right brace } (line 11)

7 public static void main( String args[] )

8 {

28

Page 29: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice Similar to class declaration, for a

method: the body of the method declaration starts

with left brace, {, and ends with right brace, }

Indent entire body of each method declaration one “level” of indentation

Makes structure of codes stand out

29

Page 30: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Statement

Statement: instructs computer to perform an action Prints string of characters

String - series characters inside double quotes White-spaces in strings are not ignored by compiler

System.out Standard output object, usually pointing to command

window (i.e., MS-DOS prompt, or PuTTy window) Method System.out.println

Displays a line of text Statements must end with semicolon ;

Omitting semicolon at end of a statement is a syntax error.

9 System.out.println( "Welcome to Java Programming!" );30

Page 31: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Error-Prevention Tip

When learning how to program, try “break” a working program to familiarize yourself with compiler's syntax-error messages. E.g. remove a semicolon or brace, see error

messages incurred Syntax error messages not always give

exact position or problem in the code. Cascading effects … Check reported line first, and then check

preceding lines for syntax errors

31

Page 32: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

First Program in Java: Printing a Line of Text (Cont.)

Ends method declaration

Ends class declaration Comments are added to keep track of

ending braces

11 } // end method main

13 } // end class Welcome1

To improve readability, follow closing right brace (}) of a method body or class declaration with an end-of-line comment indicating the method or class declaration to which the brace belongs.

32

Page 33: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Compile Java program

From a command prompt window, go to directory where program is stored

Type javac Welcome1.java If no syntax errors, Welcome1.class

created Has bytecodes that represent application

33

Page 34: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Possible error messages

“bad command or filename,” or “javac: command not found” or “'javac' is not recognized as an internal or external command, operable program or batch

file,” your Java software installation was not completed

properly E.g. system’s PATH environment variable was not set

properly Review J2SE Development Kit installation instructions at

java.sun.com/j2se/5.0/install.html

34

Page 35: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Interpret syntax-error messages

Each syntax-error messages contains file name and line number where an error is detected. E.g., Welcome1.java:6 refers to Welcome1.java

at line 6. Remainder of error message provides

information about the syntax error.

35

Page 36: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Common compiler error message “Public class ClassName must be defined

in a file called ClassName.java” The file name does not match the

name of the public class in the file

36

Page 37: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Execute Your First Java Program

From terminal window (e.g., Putty) or command prompt (of Windows), type java Welcome1 Launches Java Virtual Machine JVM loads .class file for class Welcome1

.class extension omitted from command JVM execute the program by calling method main of the class

37

Page 38: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Common error message

“Exception in thread "main" java.lang.NoClassDefFoundError: Welcome1,” Your CLASSPATH environment variable has

not been set properly. See related slide before

38

Page 39: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

1 // Fig. 2.3: Welcome2.java

2 // Printing a line of text with multiple statements.

3

4 public class Welcome2

5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.print( "Welcome to " );

10 System.out.println( "Java Programming!" );

11

12 } // end method main

13

14 } // end class Welcome2

Welcome to Java Programming!

System.out.print keeps the cursor on the same line, so System.out.println continues on the same line.

print vs println

39

Page 40: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Display special characters

How to display special characters, such as double-quote, newline, … ?

Use escape character which starts with backslash ( \ ) to indicate special character

E.g., newline characters (\n) Indicates cursor should be at the beginning

of the next line

Line breaks at \n

9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

40

Page 41: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

1 // Fig. 2.4: Welcome3.java

2 // Printing multiple lines of text with a single statement.

3

4 public class Welcome3

5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.println( "Welcome\nto\nJava\nProgramming!" );

10

11 } // end method main

12

13 } // end class Welcome3

Welcome to Java Programming!

Notice how a new line is output for each \n escape sequence.

Page 42: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Some common escape sequences

Escape sequence

Description

\n Newline. Position the screen cursor at the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of the

current line—do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For example,

System.out.println( "\"in quotes\"" );

displays

"in quotes"

42

Page 43: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Displaying Text with printf

System.out.printf Displays formatted data

First parameter is format string, a string made up of Fixed text, e.g., \n in above example Format specifier – placeholder for a value,

specify the type and format for each subsequent paramters

Format specifier %s – placeholder for a string

9 System.out.printf( "%s\n%s\n", 10 "Welcome to", "Java Programming!" );

43

Page 44: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

1 // Fig. 2.6: Welcome4.java

2 // Printing multiple lines in a dialog box.

3

4 public class Welcome4

5 {

6 // main method begins execution of Java application

7 public static void main( String args[] )

8 {

9 System.out.printf( "%s\n%s\n",

10 "Welcome to", "Java Programming!" );

11

12 } // end method main

13

14 } // end class Welcome4

Welcome to Java Programming!

System.out.printf displays formatted data.

Page 45: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice

Place a space after each comma (,) in an argument list to make programs more readable.

Long statement can be split into multiple lines Indent all subsequent lines of the statement Splitting in the middle of an identifier or a

string is a syntax error.

45

Page 46: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Second Java Application: Adding Integers

Upcoming program Use Scanner to read two integers from user Use printf to display sum of the two

values Use packages

46

Page 47: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

OutlineAddition.java

(1 of 2) import

declaration Scanner nextInt

1 // Fig. 2.7: Addition.java

2 // Addition program that displays the sum of two numbers.

3 import java.util.Scanner; // program uses class Scanner

4

5 public class Addition

6 {

7 // main method begins execution of Java application

8 public static void main( String args[] )

9 {

10 // create Scanner to obtain input from command window

11 Scanner input = new Scanner( System.in );

12

13 int number1; // first number to add

14 int number2; // second number to add

15 int sum; // sum of number1 and number2

16

17 System.out.print( "Enter first integer: " ); // prompt

18 number1 = input.nextInt(); // read first number from user

19

import declaration imports class Scanner from package java.util.

Declare and initialize variable input, which is a Scanner.

Declare variables number1, number2 and sum.

Read an integer from the user and assign it to number1.

47

Page 48: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Outline Additio

n.java (2 of 2) 4. Addition 5. printf

20 System.out.print( "Enter second integer: " ); // prompt

21 number2 = input.nextInt(); // read second number from user

22

23 sum = number1 + number2; // add numbers

24

25 System.out.printf( "Sum is %d\n", sum ); // display sum

26

27 } // end method main

28

29 } // end class Addition

Enter first integer: 45 Enter second integer: 72 Sum is 117

Read an integer from the user and assign it to number2.

Calculate the sum of the variables number1 and number2, assign result to sum.

Display the sum using formatted output.

Two integers entered by the user.

48

Page 49: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Second Java Application: Adding Integers (Cont.)

import declarations Used by compiler to identify and locate classes

used in Java programs Tells compiler to load class Scanner from java.util package

Begins public class Addition Recall that file name must be Addition.java

Lines 8-9: begins main

3 import java.util.Scanner; // program uses class Scanner

5 public class Addition 6 {

49

Page 50: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Common Programming Error All import declarations must appear before the

first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error.

Forgetting to “import” a class used in your program typically results in compilation error such as “cannot resolve symbol.” Make sure to provide proper import declarations

50

Page 51: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Variable declaration statement

Variables Location in memory that stores a value

Declare with name and type before use input is of type Scanner,a class that enables a

program to read data from keyboard Variable name: any valid identifier (recall the

rule?) Declarations end with semicolons ; Initialize variable in its declaration

Equal sign stands for assignment operator The parameter System.in refers to standard input object

(often links to keyboard) The input variable will be used to read inputs from keyboard

10 // create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in );

51

Page 52: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Primitive types

Declare variable number1, number2 and sum of type int int holds integer values (whole numbers): i.e., 0, -4, 97 Types float and double hold decimal numbers Type char holds a single character: i.e., x, $, \n, 7 int, float, double and char are primitive types

Comments to describe purpose of variables

Can declare multiple variables of the same type in one declaration

Use comma-separated list

13 int number1; // first number to add14 int number2; // second number to add15 int sum; // second number to add

int number1, // first number to add number2, // second number to add sum; // second number to add

52

Page 53: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice

Declare each variable on a separate line allows a descriptive comment to be easily inserted next to each declaration.

Choose meaningful variable names self-documenting program

Convention for variable-name identifiers begin with a lowercase letter, and every subsequent word in the name begins with a capital letter e.g., firstNumber, studentRecord, …

53

Page 54: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Second Java Application: Adding Integers (Cont.)

Message called a prompt - directs user to perform an action

Result of call to nextInt given to number1 using assignment operator = Assignment statement = binary operator - takes two operands

Expression on right evaluated and assigned to variable on left

Read as: number1 gets the value of input.nextInt()

17 System.out.print( "Enter first integer: " ); // prompt

18 number1 = input.nextInt(); // read first number from user

54

Page 55: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Software Engineering Observation 2.1

By default, package java.lang is imported in every Java program; thus, java.lang is the only package in the Java API that does not require an import declaration.

55

Page 56: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice Place spaces on either side of a binary

operator to make it stand out and make the program more readable.

56

Page 57: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Another Java Application: Adding Integers (Cont.)

Similar to previous statement Prompts the user to input the second integer

Similar to previous statement Assign variable number2 to second integer input

Assignment statement Calculates sum of number1 and number2 (right hand

side) Uses assignment operator = to assign result to

variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands

20 System.out.print( "Enter second integer: " ); // prompt

21 number2 = input.nextInt(); // read second number from user

23 sum = number1 + number2; // add numbers

57

Page 58: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Another Java Application: Adding Integers (Cont.)

Use System.out.printf to display results Format specifier %d

Placeholder for an int value

Calculations can also be performed inside printf

Parentheses around the expression number1 + number2 are not required

25 System.out.printf( "Sum is %d\n: " , sum ); // display sum

System.out.printf( "Sum is %d\n: " , ( number1 + number2 ) );

58

Page 59: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Variables stored in memory

Variable has a name, a type, a size and a value

Variables are stored in main memory Size of memory depends on the type Name corresponds to location in memory

Mapping performed by compiler Assignment statement: place new value into

variable, replaces (and destroys) previous value

Reading variables from memory does not change them

59

Page 60: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Illustration of variables in memory

60

Page 61: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Arithmetic Expression

Arithmetic calculations used in most programs Usage

* for multiplication / for division % for remainder +, -

Integer division truncates remainder7 / 5 evaluates to 1

Remainder operator % returns the remainder 7 % 5 evaluates to 2

61

Page 62: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Arithmetic operators

Java operation

Arithmetic operator

Algebraic expression

Java expression

Addition + f + 7 f + 7

Subtraction – p – c p - c

Multiplication * Bm b * m

Division / x / y or or x ÷ y

x / y

62

Exercise: write an expression to convert temperature fromFarenheith degree to Celsus degree:

Hint: Tf = (9/5)*Tc+32; Tc = temperature in degrees Celsius Tf = temperature in degrees Fahrenheit

Page 63: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Operator Precedence

Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed

Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3

63

Page 64: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Precedence of arithmetic operators

Operator(s) Operation(s) Order of evaluation (precedence)

*

/

%

Multiplication

Division

Remainder

Evaluated first. If there are several operators of this type, they are evaluated from left to right.

+

-

Addition

Subtraction

Evaluated next. If there are several operators of this type, they are evaluated from left to right.

64

Page 65: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Good Programming Practice

Refer to operator precedence chart when writing expressions containing many operators. Confirm that the operations in the

expression are performed in the order you expect.

When uncertain, use parentheses to force the order, exactly as you would do in algebraic expressions.

Some operators, such as assignment, =, associate from right to left rather than from left to right.

65

Page 66: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Evaluation order of a second-degree polynomial

66

Page 67: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Decision Making: Equality and Relational Operators

if statement (Simple version here, more detail later)if (condition) body If the condition is true, then the body of the if

statement executed Execute resumes at statement after the if statement Condition: expression that is either true or false can be formed using equality or relational operators Body of the if statement can be: A single statement A block of statement

67

Page 68: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Equality and relational operators

Standard algebraic equality or relational operator

Java equality or relational operator

Sample Java condition

Meaning of Java condition

Equality operators == x == y x is equal to y != x != y x is not equal to y Relational operators > x > y x is greater than y < x < y x is less than y >= x >= y x is greater than or equal to y ≤ <= x <= y x is less than or equal to y

68

Page 69: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

1 // Fig. 2.15: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 import java.util.Scanner; // program uses class Scanner 5 6 public class Comparison 7 { 8 // main method begins execution of Java application 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 int number1; // first number to compare 15 int number2; // second number to compare 16 17 System.out.print( "Enter first integer: " ); // prompt 18 number1 = input.nextInt(); // read first number from user 19 20 System.out.print( "Enter second integer: " ); // prompt 21 number2 = input.nextInt(); // read second number from user 22 23 if ( number1 == number2 ) 24 System.out.printf( "%d == %d\n", number1, number2 ); 25 26 if ( number1 != number2 ) 27 System.out.printf( "%d != %d\n", number1, number2 ); 28 29 if ( number1 < number2 ) 30 System.out.printf( "%d < %d\n", number1, number2 );

Test for equality, display result using printf.

Compares two numbers using relational operator <.

69

Page 70: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

31 32 if ( number1 > number2 ) 33 System.out.printf( "%d > %d\n", number1, number2 );

34

35 if ( number1 <= number2 )

36 System.out.printf( "%d <= %d\n", number1, number2 );

37

38 if ( number1 >= number2 )

39 System.out.printf( "%d >= %d\n", number1, number2 );

40

41 } // end method main

42

43 } // end class Comparison Enter first integer: 777 Enter second integer: 777 777 == 777 777 <= 777 777 >= 777 Enter first integer: 1000 Enter second integer: 2000 1000 != 2000 1000 < 2000 1000 <= 2000

Enter first integer: 2000 Enter second integer: 1000 2000 != 1000 2000 > 1000 2000 >= 1000

Compares two numbers using relational operator >, <= and >=.

70

Page 71: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Decision Making: Equality and Relational Operators (Cont.)

Line 6: begins class Comparison declaration Line 12: declares Scanner variable input

and assigns it a Scanner that inputs data from the standard input

Lines 14-15: declare int variables Lines 17-18: prompt the user to enter the

first integer and input the value Lines 20-21: prompt the user to enter the

second integer and input the value

71

Page 72: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Decision Making: Equality and Relational Operators (Cont.)

if statement to test for equality using (==) If variables equal (condition true)

Line 24 executes If variables not equal, statement skipped Empty statement

No task is performed

Lines 26-27, 29-30, 32-33, 35-36 and 38-39 Compare number1 and number2 with the

operators !=, <, >, <= and >=, respectively

23 if ( number1 == number2 ) 24 System.out.printf( "%d == %d\n", number1, number2 );

72

Page 73: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Common Programming Error

Confusing equality operator, ==, with assignment operator, =, leads to logic error or syntax error. == read as “is equal to” = read as “gets”, or “gets the value of.”

It is a syntax error to add spaces between symbols in operators ==, !=, >= and <=

Reversing operators !=, >= and <=, as in =!, => and =<, is a syntax error.

Placing a semicolon immediately after right parenthesis of condition in an if statement is normally a logic error.

73

Page 74: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Assignments

You can choose to set up Java environment on your own computer (Optional) Download and install Eclipse IDE

for Java at http://www.eclipse.org/downloads/ Download and install Java Runtime

Environment at Use info. at the following page to decide which

version to download: http://www.eclipse.org/downloads/moreinfo/jre.php

Lab1 assignment

74

Page 75: CISC6795: INTERNET COMPUTING AND JAVA PROGRAMMING Xiaolan Zhang Spring 2011 1

Acknowledgement Parts of the slides are adapted from

powerpoint s slides for Java How To Program, 1992-2010 by Pearson Education, Inc. All Rights Reserved.

75