Java Program Basics and Variables Adapted from Java Software Solutions (Lewis/Loftus), and Java Programming (King) by Nicole Tobias 1

LAST TIME…

2

A Simple Java Program • The following program displays the message Java rules! on the screen.

JavaRules.java // Displays the message "Java rules!" public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } }

3

Java Programs in General • Building blocks of a Java program: • Classes. A class is a collection of related variables and/or methods (usually both). A Java program consists of one or more classes. • Methods. A method is a series of statements. Each class may contain any number of methods. • Statements. A statement is a single command. Each method may contain any number of statements.

5

Integrated Development Environments • An integrated development environment (IDE) is an integrated collection of software tools for developing and testing programs. • A typical IDE includes at least an editor, a compiler, and a debugger. • A programmer can write a program, compile it, and execute it, all without leaving the IDE.

6

7

Program Layout • Comments • Tokens • Indentation | White Space • Identifiers | Brace Placement

8

Comments  Comments are an important part of every program.  They provide information that’s useful for anyone who will need to read the program in the future.  Typical uses of comments:  To document who wrote the program, when it was written, what changes have been made to it, and so on.  To describe the behavior or purpose of a particular part of the program, such as a variable or method.  To describe how a particular task was accomplished, which algorithms were used, or what tricks were employed to get the program to work.

9

Two Types of Comments • Single-line comments: // Comment style 1 • Multiline comments: /* Comment style 2 */

10

Single-line Comments • Many programmers prefer // comments to /* … */ comments, for several reasons: • • • •

Ease of use Safety Program readability Ability to “comment out” portions of a program

11

Tokens • A Java compiler groups the characters in a program into tokens. • The compiler then puts the tokens into larger groups (such as statements, methods, and classes). • Tokens in the JavaRules program:

public class JavaRules { public String [ ] args ) { System . "Java rules!" ) ; } }

static out .

void main println (

(

12

AVOIDING POTENTIAL PROBLEMS

13

Problems with Multiline Comments • Forgetting to terminate a multiline comment may cause the compiler to ignore part of a program: System.out.print("My "); /* forgot to close this comment... System.out.print("cat "); System.out.print("has "); /* so it ends here */ System.out.println("fleas");

14

Avoiding Problems with Tokens • Always leave at least one space between tokens that would otherwise merge together:

publicclassJavaRules { • Don’t put part of a token on one line and the other part on the next line:

pub lic class JavaRules {

15

Indentation • Programmers use indentation to indicate nesting. • An increase in the amount of indentation indicates an additional level of nesting. • The JavaRules program consists of a statement nested inside a method nested inside a class:

16

How Much Indentation? • Common amounts of indentation: • • • •

2 spaces: the bare minimum 3 spaces: the optimal amount 4 or 5 spaces: what many programmers use 8 spaces: probably too much

• The JavaRules program with an indentation of four spaces: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } }

17

Brace Placement • Brace placement is another important issue. • One technique is to put each left curly brace at the end of a line. The matching right curly brace is lined up with the first character on that line: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } 18

Brace Placement** • Some programmers prefer to put left curly braces on separate lines: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } • This makes it easier to verify that left and right braces match up properly. • Plus: Ms. Tobias prefers this way  19

Brace Placement • To avoid extra lines, the line containing the left curly brace can be combined with the following line: public class JavaRules { public static void main(String[] args) { System.out.println("Java rules!"); } } • (Not as commonly used as the prior two ways) • In a commercial environment, issues such as indentation and brace placement are often resolved by a “coding standard,” which provides a uniform set of style rules for all programmers to follow. • Some IDEs make it easy to apply these standards too!

20

STRINGS AND OUTPUT STATEMENTS

21

Character Strings

• A string literal is represented by putting double quotes around the text • Examples: "This is a string literal." "123 Main Street" "X"

• Every character string is an object in Java, defined by the String class • Every string literal represents a String object

22

Displaying Output on the Screen • Properties of System.out.print and System.out.println: • Can display any single value, regardless of type. • The argument can be any expression, including a variable, literal, or value returned by a method. • println always advances to the next line after displaying its argument; print does not.

23

The println Method

• In the Lincoln program from Chapter 1, we invoked the println method to print a character string

• The System.out object represents a destination (the monitor screen) to which we can send output

System.out.println("Whatever you are, be a good one.");

object

method name

information provided to the method (parameters)

24

The print Method

• The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line • See Countdown.java

25

//******************************************************************** // Countdown.java Author: Lewis/Loftus // // Demonstrates the difference between print and println. //******************************************************************** public class Countdown { //----------------------------------------------------------------// Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------public static void main (String[] args) { System.out.print("Three... "); System.out.print("Two... "); System.out.print("One... "); System.out.print("Zero... "); System.out.println("Liftoff!"); // appears on first output line System.out.println("Houston, we have a problem."); } }

26

Output

//******************************************************************** // Countdown.java Author: Lewis/Loftus Three... Two... One... Zero... Liftoff! // // Demonstrates the we difference print and println. Houston, have between a problem. //******************************************************************** public class Countdown { //----------------------------------------------------------------// Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------public static void main (String[] args) { System.out.print("Three... "); System.out.print("Two... "); System.out.print("One... "); System.out.print("Zero... "); System.out.println("Liftoff!"); // appears on first output line System.out.println("Houston, we have a problem."); } }

27

String Concatenation • The string concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly“ • It can also be used to append a number to a string

• A string literal cannot be broken across two lines in a program • See Facts.java

28

//******************************************************************** // Facts.java Author: Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //******************************************************************** public class Facts { //----------------------------------------------------------------// Prints various facts. //----------------------------------------------------------------public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); continue

29

continue // A numeric value can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } }

30

Output continue We present the following facts for your extracurricular edification: // A numeric value can be concatenated to a string Letters in the Hawaiian alphabet: System.out.println ("Dialing 12 code for Antarctica: " + 672); Dialing code for Antarctica: 672 Year in which Leonardo da Vinci in invented the parachute: 1515 System.out.println ("Year which Leonardo da Vinci invented " Speed of ketchup: 40 km per year + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } }

31

String Concatenation

• The + operator is also used for arithmetic addition

• The function that it performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, it performs string concatenation • If both operands are numeric, it adds them

• The + operator is evaluated left to right, but parentheses can be used to force the order • See Addition.java 32

//******************************************************************** // Addition.java Author: Lewis/Loftus // // Demonstrates the difference between the addition and string // concatenation operators. //********************************************************************

public class Addition { //----------------------------------------------------------------// Concatenates and adds two numbers and prints the results. //----------------------------------------------------------------public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); } }

33

Output

//******************************************************************** // Addition.java Author: Lewis/Loftus 24 and 45 concatenated: 2445 // // Demonstrates difference between69 the addition and string 24the and 45 added: // concatenation operators. //********************************************************************

public class Addition { //----------------------------------------------------------------// Concatenates and adds two numbers and prints the results. //----------------------------------------------------------------public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); } }

34

Quick Check What output is produced by the following? System.out.println("X: " + 25); System.out.println("Y: " + (15 + 50)); System.out.println("Z: " + 300 + 50);

35

Quick Check What output is produced by the following? System.out.println ("X: " + 25); System.out.println ("Y: " + (15 + 50)); System.out.println ("Z: " + 300 + 50); X: 25 Y: 65 Z: 30050

36

Displaying a Blank Line • One way to display a blank line is to leave the parentheses empty when calling println: System.out.println("Hey Joe"); System.out.println(); // Write a blank line

• The other is to insert \n into a string that’s being displayed by print or println: System.out.println("A hop,\na skip,\n\nand a jump");

Each occurrence of \n causes the output to begin on a new line.

37

AKA OUTPUT FLAIR 

ESCAPE SEQUENCES

38

Escape Sequences • The backslash character combines with the character after it to form an escape sequence: a combination of characters that represents a single character. • The backslash character followed by n forms \n, the new-

line character.

39

Escape Sequences • What if we wanted to print the quote character?

• The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you.");

• An escape sequence is a series of characters that represents a special character

• An escape sequence begins with a backslash character (\) System.out.println ("I said \"Hello\" to you.");

40

Escape Sequences • Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\

Meaning backspace tab newline carriage return double quote single quote backslash

• See Roses.java 41

//******************************************************************** // Roses.java Author: Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------// Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------public static void main (String[] args) { System.out.println ("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); } }

42

Output //******************************************************************** // Roses.java Roses are Author: red, Lewis/Loftus // Violets are blue, // Demonstrates the use of escape sequences. Sugar is sweet, //********************************************************************

But I have "commitment issues",

public class Roses So I'd rather just be friends { //----------------------------------------------------------------At this point in our relationship. // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------public static void main (String[] args) { System.out.println ("Roses are red,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); } }

43

Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously.

44

Quick Check Write a single println statement that produces the following output: "Thank you all for coming to my home tonight," he said mysteriously. System.out.println ("\"Thank you all for " + "coming to my home\ntonight,\" he said " + "mysteriously.");

45

VARIABLES AND ASSIGNMENTS

46

Using Variables • What is a variable? A storage location and an associated symbolic name (identifier) which contains some known or unknown quantity or information, a value. • In Java, every variable must be declared before it can be used. • Declaring a variable means informing the compiler of the variable’s name and its properties, including its type. • int is one of Java’s types. Variables of type int can store integers (whole numbers).

47

Declaring Variables • Form of a variable declaration: • The type of the variable • The name of the variable • A semicolon

• Example: int i; // Declares i to be an int variable • Several variables can be declared at a time: int i, j, k; • It’s often better to declare variables individually. 48

Initializing Variables • A variable is given a value by using =, the assignment

operator:

i = 0; • Initializing a variable means to assign a value to the variable for the first time. • Variables always need to be initialized before the first time their value is used.

49

Variable Initialization • The Java compiler checks that variables declared in methods are initialized prior to their first use. • A variable can be given an initial value in the declaration int sum = 0;

int base = 32, max = 149;

• See PianoKeys.java 50

//******************************************************************** // PianoKeys.java Author: Lewis/Loftus // // Demonstrates the declaration, initialization, and use of an // integer variable. //********************************************************************

public class PianoKeys { //----------------------------------------------------------------// Prints the number of keys on a piano. //----------------------------------------------------------------public static void main (String[] args) { int keys = 88; System.out.println ("A piano has " + keys + " keys."); } }

51

Output

//******************************************************************** // PianoKeys.java Author: Lewis/Loftus A piano has 88 keys. // // Demonstrates the declaration, initialization, and use of an // integer variable. //********************************************************************

public class PianoKeys { //----------------------------------------------------------------// Prints the number of keys on a piano. //----------------------------------------------------------------public static void main (String[] args) { int keys = 88; System.out.println ("A piano has " + keys + " keys."); } }

52

Assignment

• An assignment statement changes the value of a variable

• The assignment operator is the = sign

total = 55;

• The value that was in total is overwritten • You can only assign a value to a variable that is consistent with the variable's declared type 53

Changing the Value of a Variable • The assignment operator can be used both to initialize a variable and to change the value of the variable later in the program: i = 1; … i = 2;

// Value of i is now 1 // Value of i is now 2

• **When a variable is referenced in a program, its current value is used • See Geometry.java

54

//******************************************************************** // Geometry.java Author: Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. //********************************************************************

public class Geometry { //----------------------------------------------------------------// Prints the number of sides of several geometric shapes. //----------------------------------------------------------------public static void main (String[] args) { int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } }

55

Output //******************************************************************** // Geometry.javaA heptagon Author: Lewis/Loftus has 7 sides. // A decagon has 10 sides. // Demonstrates the use of an assignment statement to change the has 12 sides. // value stored a in dodecagon a variable. //********************************************************************

public class Geometry { //----------------------------------------------------------------// Prints the number of sides of several geometric shapes. //----------------------------------------------------------------public static void main (String[] args) { int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } }

56

Constants

• A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence • As the name implies, it is constant, not variable

• The compiler will issue an error if you try to change the value of a constant • In Java, we use the final modifier to declare a constant

final int MIN_HEIGHT = 69;

57

Constants • Constants are useful for three important reasons 1. First, they give meaning to otherwise unclear literal values • Example: MAX_LOAD means more than the literal 250

2. Second, they facilitate program maintenance • If a constant is used in multiple places, its value need only be set in one place 3. Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers 58

Advantages of Naming Constants • Advantages of naming constants: • Programs are easier to read. The alternative is a program full of “magic numbers.” • Programs are easier to modify. • Inconsistencies and typographical errors are less likely.

• Always create meaningful names for constants. There’s no point in defining a constant whose name signifies its value:

final int TWELVE = 12;

PRIMITIVE DATA TYPES

60

Primitive Data • There are eight primitive data types in Java • Four of them represent integers: • byte, short, int, long • Two of them represent floating point numbers: • float, double

• One of them represents characters: • char • And one of them represents boolean values: • boolean

61

Numeric Primitive Data • The difference between the numeric primitive types is their size and the values they can store: Type

Storage

Min Value

Max Value

byte short int long

8 bits 16 bits 32 bits 64 bits

-128 -32,768 -2,147,483,648 < -9 x 1018

127 32,767 2,147,483,647 > 9 x 1018

float double

32 bits 64 bits

+/- 3.4 x 1038 with 7 significant digits +/- 1.7 x 10308 with 15 significant digits 62

Literal(s) Examples • A literal is a token that represents a particular number or other value. • Examples of int literals: 0 297 30303 • Examples of double literals: 48.0 48. 4.8e1 4.8e+1 .48e2 480e-1 • The only boolean literals are true and false. • char literals are enclosed within single quotes: 'a'

'z'

'A'

'Z'

'0'

'9'

'%'

'.'

' ' 63

Using Literals as Initializers • Literals are often used as initializers:

double x = 0.0, y = 1.0; boolean b = true; char ch = 'f';

64

Characters

• A char variable stores a single character

• Character literals are delimited by single quotes:

'a'

'X'

'7'

'$'

','

'\n'

• Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' ';

• Note the difference between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters 65

Character Sets • A character set is an ordered list of characters, with each character corresponding to a unique number • A char variable in Java can store any character from the Unicode character set • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages

66

Characters

• The ASCII character set is older and smaller than Unicode, but is still quite popular • The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters

A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... 67

Boolean • A boolean value represents a true or false condition

• The reserved words true and false are the only valid values for a boolean type

boolean done = false; • A boolean variable can also be used to represent any two states, such as a light bulb being on or off

68

EXPRESSIONS

69

Expressions

• An expression is a combination of one or more operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder

+ * / %

70

INTEGER Arithmetic Expressions in Programming Languages • RULE: if both operands are integers (are the “int” data type) then the result of the operation must also be integer. • This is particularly important with the division operator (/) because remainders are simply disregarded!!!

71

INTEGER Arithmetic Expressions in Programming Languages • Examples: int x; // x can be an integer int a=5; // a can be an integer and is preset to 5 int b=2; // b can be an integer and is preset to 2 x = 5+6*2*a; x = a/b; x = a*6+1/b;

// what is “x”? // what is “x”? // what is “x”? 72

INTEGER Arithmetic Expressions in Programming Languages • Examples: int x; // x can be an integer int a=5; // a can be an integer and is preset to 5 int b=2; // b can be an integer and is preset to 2 x = 5+6*2*a; x = a/b; x = a*6+1/b;

// what is “x”? x = 65 // what is “x”? x = 2 // what is “x”? x = 30 73

Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)

14 / 3 8 / 12

equals equals

4 0

• The remainder operator (%) returns the remainder after dividing the first operand by the second 14 % 3 8 % 12

equals equals

2 8

DECIMAL NUMBER Arithmetic Expressions in Programming Languages • RULE: if both operands are decimal numbers (are the “float” data type), then the result of the operation must also be a decimal number. • Floating point division remembers everything after the decimal point!!!

75

DECIMAL NUMBER Arithmetic Expressions in Programming Languages • Java examples: float x; // x can be a float float a=5.0; // a can be a float and it is set to 5.0 float b=2.0; // b can be a float and it is set to 2.0 x = 5.0+6.5*2.0*a; x = a/b; x = a*6.5+1.0/b;

// what is “x”? // what is “x”? // what is “x”? 76

DECIMAL NUMBER Arithmetic Expressions in Programming Languages • Java examples: float x; // x can be a float float a=5.0; // a can be a float and it is set to 5.0 float b=2.0; // b can be a float and it is set to 2.0 x = 5.0+6.5*2.0*a; x = a/b; x = a*6.5+1.0/b;

// what is “x”? x = 70.0 // what is “x”? x = 2.5 // what is “x”? x = 33.0 77

MIXED Expressions... • You have to be very careful when mixing data types in an arithmetic expression in a programming language • RULE: If one operand is a “float” and the other is an “int”, then convert the “int” operand to a “float” and perform the operation. The result is also a “float”. • Obey all other precedence and order of operation rules…

78

MIXED Arithmetic Expressions in Programming Languages • Java examples: float x; int a=1; float b=2.0f; int c = 3; float d = 5.0f; x = a/b; x = a+b/c; x = d + a/b*d;

// // // // //

x can be an float a can be an integer and it b can be an float and it is c can be an integer and it d can be an float and it is

is preset to 1 preset to 2.0 is preset to 3 preset to 5.0

// what is “x”? // what is “x”? // what is “x”? 79

MIXED Arithmetic Expressions in Programming Languages • Java examples: float x; int a=1; float b=2.0f; int c = 3; float d = 5.0f; x = a/b; x = a+b/c; x = d + a/b*d;

// // // // //

x can be an float a can be an integer and it b can be an float and it is c can be an integer and it d can be an float and it is

is preset to 1 preset to 2.0 is preset to 3 preset to 5.0

// what is “x”? x = 0.5 // what is “x”? x = 1.6667 // what is “x”? x = 7.5

• If either or both operands are floating point values, then the result is a floating point value

80

The Modulus Operator • The remainder operator • In Java it is the % symbol • Both arguments must be integers. The result must be an integer as well. •5%3=2 • 17 % 4 = 1 • 16.5 % 4 = NO! NO!! • The arguments must be integers! 81

Quick Check What are the results of the following expressions? 12 / 2 12.0 / 2.0 10 / 4 10 / 4.0 4 / 10 4.0 / 10 12 % 3 10 % 3 3 % 10

82

Quick Check What are the results of the following expressions? 12 / 2 12.0 / 2.0 10 / 4 10 / 4.0 4 / 10 4.0 / 10 12 % 3 10 % 3 3 % 10

= = = = = = = = =

6 6.0 2 2.5 0 0.4 0 1 3

83

Operator Precedence • Operators can be combined into larger expressions

result

=

total + count / max - offset;

• Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated before addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order 84

Quick Check In what order are the operators evaluated in the following expressions? a + b + c + d + e

a + b * c - d / e

a / (b + c) - d % e

a / (b * (c + (d - e))) 85

Quick Check In what order are the operators evaluated in the following expressions? a + b + c + d + e 1 2 3 4

a + b * c - d / e 3 1 4 2

a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 86

Expression Trees • The evaluation of a particular expression can be shown using an expression tree • The operators lower in the tree have higher precedence for that expression + a + (b – c) / d

/

a b

d c

87

Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer

= 4

sum / 4 + MAX * lowest; 1

3

Then the result is stored in the variable on the left hand side

2

88

Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count

count

=

count + 1;

Then the result is stored back into count (overwriting the original value) 89

Using Assignment to Modify a Variable • Assignments often use the old value of a variable as part of the expression that computes the new value. • The following statement adds 1 to the variable i:

i = i + 1;

90

Assignment Operators • Often we perform an operation on a variable, and then store the result back into that variable • Java provides assignment operators to simplify that process • For example, the statement num += count; is equivalent to

num = num + count;

91

Compound Assignment Operators • The compound assignment operators make it easier to modify the value of a variable. • A partial list of compound assignment operators:

+= -= *= /= %=

Combines addition and assignment Combines subtraction and assignment Combines multiplication and assignment Combines division and assignment Combines remainder and assignment

92

Compound Assignment Operators • The right hand side of an assignment operator can be a complex expression • The entire right-hand expression is evaluated first, then the result is combined with the original variable • Therefore

result /= (total-MIN) % num; is equivalent to

result = result / ((total-MIN) % num); 93

Compound Assignment Operators • Examples:

i i i i i

+= -= *= /= %=

2; 2; 2; 2; 2;

// // // // //

Same Same Same Same Same

as as as as as

i i i i i

= = = = =

i i i i i

+ * / %

2; 2; 2; 2; 2;

94

Increment and Decrement • The increment (++) and decrement (--) operators use only one operand • The statement count++; is functionally equivalent to count = count + 1;

and count += 1; 95

Increment and Decrement • The increment and decrement operators can be applied in postfix form:

count++ • or prefix form: ++count • When used as part of a larger expression, the two forms can have different effects

• Because of their subtleties, the increment and decrement operators should be used with care

96

Assignment Operators • The behavior of some assignment operators depends on the types of the operands • If the operands to the += operator are strings, the assignment operator performs string concatenation

• The behavior of an assignment operator (+=) is always consistent with the behavior of the corresponding operator (+)

97

DATA CONVERSION

98

Data Conversion • Sometimes it is convenient to convert data from one type to another • For example, in a particular situation we may want to treat an integer as a floating point value • These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation • This is also something that we encounter when we have mixed data types in our expressions.

99

Data Conversion • Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) • Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) Widening Conversions

Narrowing Conversions

100

Data Conversion in Java • There are three ways that data get converted in Java: • Promotion • implicit promotion – Java does it automatically

• Assignment • implicit promotion – Java does it automatically

• Casting • explicit promotion – the programmer does it 101

Data Conversion in Java • Promotion • If the operands have different types, they must be converted to some common type before the operation can be performed. • This is what we have already covered

• Promotion is automatically performed by Java • 5 / 2.0 = 5.0 / 2.0 = 2.5 • The 5 gets ‘promoted’ to 5.0 so it can be divided by 5.0.

• Java’s strategy is to convert operands to a type that will safely accommodate both values. 102

Data Conversion in Java • Conversion during Assignment • In an assignment, Java converts expression on the right side to the type of variable on the left side, provided that variable’s type is at least as “wide” as expression’s type.

the the the the

• (Java converts the left type to the type on the right.)

• The numeric types are converted in order of increasing width: int then float 103

Assignment Conversion • Assignment conversion occurs when a value of one type is assigned to a variable of another • Example:

int dollars = 20; double money = dollars; • Only widening conversions can happen via assignment • Note that the value or type of dollars did not change

104

Data Conversion in Java • Examples of legal assignments:

int i; float f; … f = i; // the value of i is converted to float

105

Data Conversion in Java • An assignment in which the expression on the right side has a wider type than the variable on the left side is an error:

int i; //narrow float f; //wider … i = f; // WRONG • The reason for this rule is that storing a value into a narrower variable can cause bugs in the program. 106

Data Conversion in Java  Casting  A conversion that’s done at the programmer’s request is called a cast.  Casting is done by enclosing the desired type in parentheses and inserting it before the expression:

int i; float f; … i = (int) f;

// Cast f to int type

 Casting a floating-point number to an integer type causes the floating point number to be truncated.  General form of a cast:

( type-name ) expression

107

Data Conversion in Java  Casting  Is the most dangerous  because you can lose information, e.g. in lost decimal places.

 Some examples: int a = 5, b = 2, c = 9; float x; x = a/b; x = (float)a/b; x = a/(float)b; x = (float)(a/b); x = a + b / c + (float) a;

108

Casting • Casting is the most powerful, and dangerous, technique for conversion

• Both widening and narrowing conversions can be accomplished by explicitly casting a value • To cast, the type is put in parentheses in front of the value being converted int total = 50; float result = (float) total / 6; • Without the cast, the fractional part of the answer would be lost

109

Making use of them and understanding what they have to offer!

METHODS

Methods • What is a method? • A method is a series of statements that can be executed as a unit. • A method does nothing until it is activated, or called. • To call a method, we write the name of the method, followed by a pair of parentheses. • The method’s arguments (if any) go inside the parentheses. • A call of the println method:

System.out.println("Java rules!");

INPUT / OUTPUT

Input and Output • Most programs require both input and output. • Input is any information fed into the program from an outside source. • Output is any data produced by the program and made available outside the program.

Packages, Classes, Methods, and the import Statement • Package: collection of related classes • Java allows classes to be grouped into larger units known as

packages. • Java comes with a large number of standard packages.

• Class: consists of methods • Method: designed to accomplish a specific task

114

import Statement • Used to import the components of a package into a program • Reserved word • import java.io.*; • Imports the (components of the) package java.io into the program

• Primitive data types and the class String • Part of the Java language • Doesn’t need to be imported

115

Interactive Programs • Programs generally need input on which to operate • The Scanner class provides convenient methods for reading input values of various types

• A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard • Keyboard input is represented by the System.in object

The Scanner Class • We will go into this more in a future Chapter… • I will mention just the basics here.

Reading Input • The following line creates a Scanner object that reads from the keyboard:

Scanner scan = new Scanner (System.in); • The new operator creates the Scanner object • Once created, the Scanner object can be used to invoke various input methods, such as:

answer = scan.nextLine();

Reading Input • The Scanner class is part of the java.util class library, and must be imported into a program to be used • The nextLine method reads all of the input until the end of the line is found • See Echo.java • The details of object creation and class libraries are discussed further in Chapter 3

import java.util.Scanner; public class Echo { //----------------------------------------------------------------// Reads a character string from the user and prints it. //----------------------------------------------------------------public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\""); } }

Copyright © 2012 Pearson Education, Inc.

//******************************************************************** // Echo.java Author: Lewis/Loftus // // Demonstrates the use of the nextLine method of the Scanner class // to read a string from the user. //********************************************************************

Sample Run

//******************************************************************** // Echo.java Author: Lewis/Loftus Enter a line of text: // // Demonstrates thefries use of the nextLine method of the Scanner class You want with that? // to read a string from the user. You entered: "You want fries with that?" //******************************************************************** import java.util.Scanner; public class Echo { //----------------------------------------------------------------// Reads a character string from the user and prints it. //----------------------------------------------------------------public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text:"); message = scan.nextLine();

System.out.println ("You entered: \"" + message + "\""); } }

Input Tokens • Unless specified otherwise, white space is used to separate the elements (called tokens) of the input • White space includes space characters, tabs, new line characters • The next method of the Scanner class reads the next input token and returns it as a string • Methods such as nextInt and nextDouble read data of particular types • See GasMileage.java

//******************************************************************** // GasMileage.java Author: Lewis/Loftus // // Demonstrates the use of the Scanner class to read numeric data. //********************************************************************

import java.util.Scanner; public class GasMileage { //----------------------------------------------------------------// Calculates fuel efficiency based on values entered by the // user. //----------------------------------------------------------------public static void main (String[] args) { int miles; double gallons, mpg; Scanner scan = new Scanner (System.in); continue

continue System.out.print("Enter the number of miles: "); miles = scan.nextInt(); System.out.print("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } }

continue

Sample Run Enter the number of miles: 328

System.out.print ("Enter the number of miles: "); Enter the gallons of fuel used: 11.2 miles = scan.nextInt();

Miles Per Gallon: 29.28571428571429

System.out.print ("Enter the gallons of fuel used: "); gallons = scan.nextDouble(); mpg = miles / gallons; System.out.println ("Miles Per Gallon: " + mpg); } }

DEBUGGING

Debugging • Debugging is the process of finding bugs in a program and fixing them. • Types of errors: • Compile-time errors • Run-time errors (called exceptions in Java) • Logical (Incorrect behavior/results)

Fixing Compile-Time Errors • Strategies for fixing compile-time errors: • Read error messages carefully. Example: Buggy.java:8: Undefined variable: i System.out.println(i); ^ Buggy.java:10: Variable j may not have been initialized System.out.println(j); ^

• Pay attention to line numbers. • Fix the first error.

Fixing Compile-Time Errors • Don’t trust the compiler (completely). The error isn’t always on the line reported by the compiler. Also, the error reported by the compiler may not accurately indicate the nature of the error. • Example: System.out.print("Value of i: ") System.out.println(i);

A semicolon is missing at the end of the first statement, but the compiler reports a different error: Buggy.java:8: Invalid type expression. System.out.print("Value of i: ") ^ Buggy.java:9: Invalid declaration. System.out.println(i); ^

Fixing Run-Time Errors • When a run-time error occurs, a message will be displayed on the screen. Example: Exception in thread "main"

java.lang.NumberFormatException: foo at java.lang.Integer.parseInt(Compiled Code) at java.lang.Integer.parseInt(Integer.java:458) at Buggy.main(Buggy.java:11)

• Once we know what the nature of the error is and where the error occurred, we can work backwards to determine what caused the error.

Fixing Behavioral Errors • Errors of behavior are the hardest problems to fix, because the problem probably lies either in the original algorithm or in the translation of the algorithm into a Java program. • Other than simply checking and rechecking the algorithm and the program, there are two approaches to locating the source of a behavioral problem, depending on whether a debugger is available.

Using a Debugger • A debugger doesn’t actually locate and fix bugs. Instead, it allows the programmer to see inside a program as it executes. • Things to look for while debugging: • Order of statement execution • Values of variables

• Key features of a debugger: • Step • Breakpoint • Watch

Debugging Without a Debugger • The JDK includes a debugger, named jdb. • A debugger isn’t always necessary, however. • If a run-time error occurs in a Java program, the message displayed by the Java interpreter may be enough to identify the bug. • Also, System.out.println can be used to print the values of variables for the purpose of debugging: System.out.println("Value of a: " + a + " Value of b: " + b);

Choosing Test Data • Testing a program usually requires running it more than once, using different input each time. • One strategy, known as boundary-value testing, involves entering input at the extremes of what the program considers to be legal. • Boundary-value testing is both easy to do and surprisingly good at revealing bugs. And just fyi** • Be sure to test you code and programs for all cases. Sample data given to you for an assignment will not be the only data that I test your code with…

End Here 