1 of 34

Basic Data Types and Expressions

Module 6

2 of 34

Literal Types (1 of 2)

Integers:

  • By default an integer literal is type int: 5
  • If necessary force it to be type long by appending L: 5L

Decimals:

  • By default a decimal literal is type double: 5.0 or 5.
  • Force it to be type float by appending an F: 5.0F, 5.F or 5F

Characters:

  • Character literals are enclosed in single quotes: 'C'
  • Character literals are type char

2

3 of 34

Literal Types (2 of 2)

Booleans:

  • The literals true and false are type boolean

Strings:

  • String literals are enclosed in double quotes: "This is a string."
  • String literals are type String.

Note that every literal is a primitive type except for strings.

3

4 of 34

Unary Operation Result Types

The type of the result is the same as the type of the operand.

Given:� int ivar; long lvar; float fvar; boolean bvar;

4

Operation

Result Type

++ivar

int

++lvar

long

++fvar

float

!bvar

boolean

5 of 34

Binary Arithmetic Operation Result Types

  • Operands of the same type: the type of the operands.
  • Operands of different types: the type of the "longer" operand.

Given:� int ivar; long lvar; float fvar;

5

Operation

Result Type

ivar + lvar

long

ivar + fvar

float

ivar + dvar

double

6 of 34

Relational and Logical Operation Result Types

The result of a relational or logical operation is always type boolean.

6

Operation

Result Type

var1 < var2

boolean

var1 == var2

boolean

var1 && var2

boolean

var1 || var2

boolean

7 of 34

Conditional Expression Operation Result Type

The type of the "longer" of the second and third operands.

Given:� boolean bvar; int ivar; long lvar; double dvar;

7

Operation

Result Type

bvar ? ivar : lvar

long

bvar ? dvar : ivar

double

8 of 34

Special Case Result Type

The "addition" of a String object and any other type is type String.

Given:� boolean bvar; int ivar; double dvar; Object ovar;

8

Operation

Result Type

"Spot" + bvar

String

"Spot" + ivar

String

"Spot" + dvar

String

"Spot" + ovar

String

9 of 34

The Type of a Logical Expression

If an expression contains a logical (&&, ||) or relational operator (<, ==) the type of the result is boolean.

Given:� int ivar; long lvar; double dvar;

9

Operation

Result Type

ivar * lvar < 100

boolean

ivar * dvar >= 100

boolean

2 * ivar < 10 && vicky.seesSlot()

boolean

10 of 34

Casting

A expression can be converted to any "compatible" type by casting it. � double dvar = 3.14;� float fvar = (float)dvar;� int ivar = (int)fvar;� byte bvar = (byte)bvar;

Object ovar = "Spot";� String svar = (String)ovar;

10

11 of 34

Rounding

To round a decimal number to the nearest integer:

  1. Add .5.
  2. Cast the result to int.

11

// Generate a random integer between 0 (inclusive) and 100 (exclusive).

double dval = Math.rand() * 100;

int ival = (int)(dval + .5)

12 of 34

Review: Testing Decimal Numbers for Equality

Recall this exercise that demonstrates rounding errors:

12

public static void main( String[] args )

{

double x = .7 + .1;

double y = .9 - .1;

System.out.println( "x = " + x + ", y = " + y );

System.out.println( x == y );

}

Output:

x = 0.7999999999999999, y = 0.8

x = y: false

13 of 34

Review: The Epsilon Test for Equality

Test floating point numbers for equality using the epsilon test:

13

public static void main( String[] args )

{

double x = .7 + .1;

double y = .9 - .1;

double eps = .000001;

boolean equ = Math.abs( x - y ) < eps;

System.out.println( "x = " + x + ", y = " + y );

System.out.println( equ );

}

Output:

x = 0.7999999999999999, y = 0.8

x = y: true

14 of 34

Exercises

  1. Given: int inx = 5, double xco = 1.5:�Identify the type and value of each of the following expressions:��(double)inx / 2 inx / 3 inx / xco�inx / (int)xco xco / 3 inx / 2.�"alice " + inx "hatter " + xco�
  2. Write a method, int round( double val ), to round a decimal value to the nearest integer.
  3. Remove the cast from the assignment expression in the round method. Explain why the code no longer compiles.
  4. Write a method, boolean equals( double val, double val2, double epsilon ), which returns true if val1 is equal to val2 and false otherwise.

14

15 of 34

Sentinel Logic

The sentinel-controlled loop pattern runs a loop that ends when an incompatible value (the sentinel value) is reached.

15

public boolean equals( Object obj )

{

boolean result = false;

if ( obj instanceof String )

{

String str = (String)obj;

result = str.equals( "STOP" );

}

return result;

}

16 of 34

Preconditions

  • A precondition is something that you can assume is true when writing code.*
  • Preconditions make your life easier.

16

// Precondition: str contains at least 1 char

private char getSmallestChar( String str )

{

int len = str.length();

char result = str.charAt( 0 );

for ( int inx = 1 ; inx < len ; ++inx )

{

. . .

*Many people would disagree with me, but this is the sense used on the AP CS exam.

17 of 34

Postconditions

  • A postcondition is something that must be true when your code is done.
  • Postconditions make your job harder.

17

// Postcondition: on completion every field in bench will be set to

// an appropriate default value.

private void initState( Workbench bench )

{

. . .

18 of 34

The GrowthRates Class

  • Ask the user to enter an interest rate; report how long it would take for the user to double her money at that rate.
  • Illustrates the sentinel-controlled loop pattern.
  • The sentinel value is 0.

See GrowthRates.java

18

19 of 34

The GrowthRatesAlt Class

  • Performs the same job as the GrowthRates class.
  • Moves the logic from the constructor to the execute method.
  • Moves the operator input logic to a helper method.
  • Uses StringBuilder to assemble the response string.
  • Demonstrates the assign-and-test technique.
  • Eliminates duplicate logic.

double rate = 0;

while ( (rate = askRate()) > 0 )� . . .�

See GrowthRatesAlt.java

19

Parentheses are required to resolve precedence issues.

20 of 34

Assignment Operators

Java has special assignment operators that provide arithmetic shortcuts, including:

20

Operator

Example

Equivalent To

+=

inx += jnx

inx = inx + jnx

-=

inx -= jnx

inx = inx - jnx

*=

inx *= jnx

inx = inx * jnx

/=

inx /= jnx

inx = inx / jnx

%=

inx %= jnx

inx = inx % jnx

Note: there are others.

21 of 34

The Double.parseDouble Class Method

Use Double.parseDouble( String ) to convert a string to a double.

21

private static double askUser()

{

String prompt = "Please enter a decimal number";

String input = JOptionPane.showInputDialog( null, prompt );

double result = Double.parseDouble( input );

return result;

}

22 of 34

Exercises

In the following exercises please use the special assignment operators whenever possible.

Enter and test the GrowthRatesAlt class, substituting special assignment operators whenever possible.

Textbook, Chapter 6 page 6-4�Exercises 6.1 - 6.3, 6.6

22

23 of 34

Library Classes

  • Eliminate duplicate code.
  • Make adapting code much easier.
  • Generally, every method is a class method (declared static).
  • Generally, have a private constructor.
  • Often, methods are only a few lines of code.

23

24 of 34

The IOUtils Class

  • Simplifies use of JOptionPane features.
  • Can be adapted later to incorporate error checking.

24

25 of 34

The IOUtils Class: Constructor

Since this is a library class, the constructor is private to prevent instantiation.

25

private IOUtils

{

}

26 of 34

The IOUtils Class: say Method

Display a message in a dialog.

26

public static void say( Object message )

{

JOptionPane.showMessageDialog( null, message );

}

27 of 34

The IOUtils Class: askLine Method

  • Ask the user to enter a line of text.
  • Return null if the operation is canceled.

27

public static String askLine( String prompt )

{

String line =

JOptionPane.showInputDialog( null, prompt );

return line;

}

28 of 34

The IOUtils Class: askDouble Method

  • Ask the user to enter a decimal number.
  • Return Double.NaN if the operation is canceled.
  • Crash if the user's input is invalid.

28

public static double askDouble( String prompt )

{

String input =

JOptionPane.showInputDialog( null, prompt );

double result = Double.NaN;

if ( input != null )

result = Double.parseDouble( input );

return result;

}

29 of 34

The IOUtils Class: askInt Method

  • Ask the user to enter an integer.
  • Return Integer.MIN_VALUE if the operation is canceled.
  • Crash if the user's input is invalid.

29

public static int askInt( String prompt )

{

String input =

JOptionPane.showInputDialog( null, prompt );

int result = Integer.MIN_VALUE;

if ( input != null )

result = Integer.parseInt( input );

return result;

}

Not a particularly good sentinel value.

30 of 34

Exceptions

Under certain error circumstances a method might throw or raise an exception.�it the exception is not caught (or handled) your program will crash.

30

Error Example

Exception Thrown

String s = null;

s.length();

NullPointerException

Integer.parseInt( "3.14" );

NumberFormatException

Double.parseDouble( "3.1.4" );

NumberFormatException

int inx = 0;

int jnx = 5/inx;

ArithmeticException

31 of 34

Digression: Invalid Operations on Decimals

Errors with type decimal numbers don't typically throw exceptions; instead, a sentinel value is returned.

31

Error Example

Sentinal Value

Math.sqrt( -1 )

Double.NaN

1.0 / 0

Double.POSITIVE_INFINITY

-1.0 / 0

Double.NEGATIVE_INFINITY

0. / 0

Double.NaN

32 of 34

Handling Exceptions

Exceptions can be handled (or caught) in a try/catch block.

32

public static boolean isValidNumber( String str )

{

boolean rval;

try

{

Double.parseDouble( str );

rval = true;

}

catch ( NumberFormatException exc )

{

rval = false;

}

return rval;

}

33 of 34

Exercises

  1. Add public static int askNonNegInt( String prompt ) to IOUtils. Use a loop to ask the user to enter a non-negative integer; if she enters a negative number display an error message and loop until she gets it right. If she cancels the operation, terminate the loop and return Integer.MIN_VALUE.�
  2. Add public static int askNearestInt( String prompt ) to IOUtils. Allow the user to enter a decimal number then round it to the nearest integer before returning it.�
  3. Revise IOUtils.askDouble so that if the user enters invalid data it displays an error dialog and returns Double.NaN.�
  4. Revise IOUtils.askInt so that if the user enters invalid data it displays an error dialog and returns Integer.MIN_VALUE.

33

34 of 34

More About Strings

Add a " to a string: "He said, \"Whatever\""�Add a special character to a string: "And then I want you\nto go"�Add a Unicode character to a string: "The value of \u03c0 is 3.14"�length()�trim() substring() charAt() �contains() startsWith() endsWith()�split()... exercise with care!*

character constants: 'a' '\u03c0' '\\' '\b'

34

*The argument to split() is a regular expression. If you don't know what a regular expression is, maybe you shouldn't use this utility.