The Building Blocks - Utah Valley University

Download Report

Transcript The Building Blocks - Utah Valley University

Data Types
and Control Structures
CS3250
Java Data Types
• Everything is an Object
• Except Primitive Data Types
– For efficiency
– Platform independent
• Portable
• “slow”
• Objects are often required
– In collections, for example
• Every primitive has a corresponding object
wrapper
Primitive Types
Primitive
Size Min Max
Wrapper
boolean
char
byte
short
int
long
float
double
void
—
16
8
16
32
64
32
64
—
Boolean
Character
Byte
Short
Integer
Long
Float
Double
Void
—
—
Unicode
-128 127
-215 215-1
-231 231-1
-263 263-1
IEEE
IEEE
—
—
All are signed except boolean and char
Java Character Type
• Internationalization
– 16-bit Unicode character.
– ASCII is a subset of Unicode - ISO-8859 (Latin-1)
– Escape sequence:
• \uhhhh: hex-decimal code, e.g. \u000A
• \ddd: octal code, e.g. \040
• \n, \t, \b, \r, \f, \\, \', \".
• Java programs are also in Unicode.
• Unicode standard: http://www.unicode.org
Operators
• Much the same as C++
– Booleans are short circuit
• New operators:
– instanceof
– >>>
• logical right shift: fills in with zeros rather than sign bit
• Important difference
– Binary operands are evaluated left-to-right:
x = f() + g();
– Equality operator (==) only checks object references (use
equals() instead)
Enumerated Types
• New in JDK 5.0
• Has finite number of named values
enum Day {FRIDAY, SATURDAY, SUNDAY};
Day today = Day.FRIDAY;
• Cannot be local to a method
• Will print name, not number
(toString does the right thing)
• More info in Chapter 5 of textbook
The String Class
•
•
•
•
•
Strings are first-class objects.
Strings are not arrays of char's.
String index starts from 0.
String constant: "AStringConstant"
String concatenation
s1+s2 and s1+=s2
• s.length()
the length of a string s
• s.charAt(i)
character at position i
• Strings are immutable.
Comparing Strings
• You should not use == to compare
characters in two strings.
String s1 = "foo", s2 = "foo";
if (s1 == s2) ...
– Will compile
– Will give the expected results in some situations (with
shared strings).
– Will not give the expected results in other situations (e.g.,
result of substring method).
• Use the equals method instead:
String s1 = "foo", s2 = "goo";
if (s1.equals(s2)) ...
Input
• Prior to JDK 5.0:
– learn the magic formula or
– get an input class from a textbook
• JDK 5.0 and beyond:
– Use the Scanner class
• in the java.util package
• InputTest.java example from book (p. 64 8th ed.)
– Still some issues:
• nextLine() after nextInt()
• "subtle bugs" with more than one scanner on the
same stream
File Input
Scanner in = new Scanner(new
File("myfile.txt"));
String line = in.nextLine();
Output
System.out.print
System.out.println
System.out.printf
– Similar to the C function with the same name
– New with JDK 5.0
– Not the only way to format output, but the
easiest.
int age = 42;
System.out.printf("I am %d years old", age);
Formatting without Printing
String hiStr
= String.format("Hi %s", name);
File Output
public PrintWriter openOutFile(String
fileName) {
PrintWriter out = null;
try {
out = new PrintWriter(fileName);
} catch (IOException x) {
x.printStackTrace();
}
return out;
out.println("Hello, File");
}
Control Flow
The same as C and C++ except:
• No goto
• labeled break and continue
• "for each" loop
– new with JDK 5.0
– discussed with arrays
Constrained Branching
• Labeled break
– To exit deeply nested loops
– Example: Loop (from Prof. Allison's examples)
• Labeled continue
– To cycle on outer loops
– Example: Nested3 (from Prof. Allison's examples)
Non-standard Flow
• Errors alter the execution path of a program
• Error handling techniques should be simple
• Exceptions:
– Provides an alternate return mechanism from
functions
– Should only be used in exceptional cases (that is,
for errors)
• Continued in Exceptions.ppt
Arbitrary Precision Arithmetic
• Classes BigInteger and BigDecimal
• Arbitrarily long sequences of digits
• Use methods instead of operators for
addition, subtraction, etc.
• Use static valueOf method to convert
normal values to Big values:
BigInteger a = BigInteger.valueOf(100);
• Example: BigIntegerTest.java, p. 89 (8th ed)
Java Arrays
• Arrays are first-class objects.
– sized at runtime!
• Indexes are always bounds-checked.
• Array index starts from 0.
int[] ia = new int[3];
int ia[] = new int[3];
int[] ia = {1, 2, 3};
float[][] mat = new float[4][4];
for (int y = 0; y < mat.length; y++) {
for (int x = 0; x < mat[y].length; x++)
mat[y][x] = 0.0;
}
The "for each" Loop
• New in JDK 5.0
• loop through elements in an array or in a
collection (Vector, List, etc.)
– elements must be in class that implements
Iterable
tring[] names = {"Groucho", "Harpo", "Chico"};
S
for (String name : names)
System.out.println(name);
More about Arrays…
• Copying:
System.arraycopy(from, fromIndex,
to, toIndex, count);
• Sorting:
import java.util.*;
int[] a = new int[10000];
…
Arrays.sort(a);