Basic Data Types and Expressions
Module 6
Literal Types (1 of 2)
Integers:
Decimals:
Characters:
2
Literal Types (2 of 2)
Booleans:
Strings:
Note that every literal is a primitive type except for strings.
3
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 |
Binary Arithmetic Operation Result Types
Given:� int ivar; long lvar; float fvar;
5
Operation | Result Type |
ivar + lvar | long |
ivar + fvar | float |
ivar + dvar | double |
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 |
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 |
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 |
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 |
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
Rounding
To round a decimal number to the nearest integer:
11
// Generate a random integer between 0 (inclusive) and 100 (exclusive).
double dval = Math.rand() * 100;
int ival = (int)(dval + .5)
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
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
Exercises
14
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;
}
Preconditions
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.
Postconditions
17
// Postcondition: on completion every field in bench will be set to
// an appropriate default value.
private void initState( Workbench bench )
{
. . .
The GrowthRates Class
See GrowthRates.java
18
The GrowthRatesAlt Class
double rate = 0;
while ( (rate = askRate()) > 0 )� . . .�
19
Parentheses are required to resolve precedence issues.
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.
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;
}
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
Library Classes
23
The IOUtils Class
24
The IOUtils Class: Constructor
Since this is a library class, the constructor is private to prevent instantiation.
25
private IOUtils
{
}
The IOUtils Class: say Method
Display a message in a dialog.
26
public static void say( Object message )
{
JOptionPane.showMessageDialog( null, message );
}
The IOUtils Class: askLine Method
27
public static String askLine( String prompt )
{
String line =
JOptionPane.showInputDialog( null, prompt );
return line;
}
The IOUtils Class: askDouble Method
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;
}
The IOUtils Class: askInt Method
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.
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 |
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 |
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;
}
Exercises
33
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.