Download Lecture slides

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CSC 243 - Java Programming,
Spring, 2013
Week 2: Java Data Types, Control
Constructs, and their C++
counterparts
Summary of Java built-in types
• Primitive type variables are not class objects
•
•
•
•
•
byte is 8-bit signed, -128 through 127 (page 32 in text)
short is 16-bit signed, -32768 through 32767
int is 32-bit signed, long is 64-bit signed
float is 32-bit type and double is 64-bit type
boolean is 1-bit true or false, char is UNICODE
• Some class types are built into the language
• java.lang.String a class built into the language
• Wrapper classes in java.lang wrap native types as
classes. Examples are Integer, Float, Long, Double.
Summary of Java control
constructs
•
•
•
•
•
•
•
•
boolean (true or false) is the basis for control flow
JavaLang/week1/bool
for, while and do-while loops, just like C++
if .. else if .. else selection, just like C++
switch statement also like C++
break exits the innermost loop or switch
continue goes to the top of innermost loop
There are no stand-alone functions! A method always exists
inside a class.
• A non-static method uses a class object.
• A static method uses only class-static data.
Java Methods
• A method is equivalent to a C++ member
function. In Java all methods resides in classes.
• A static method does not require an object.
• int intvar = java.lang.Integer.parseInt(“2”);
• System.out.println(“integer: “ + intvar);
• Statics method use static class variables.
• A regular method needs an object reference.
• Integer intObject = new Integer(“3”);
• System.out.println(“integer: “ + intObject.intValue());
Java storage of class and object
data
• Only one copy of a static data element exists
for its class. Both static methods and nonstatic methods (object methods) can use it.
• static java.lang.String oneStringPerClass = new String();
• There is one copy of each non-static data
element in each object. Only non-static
methods can use it.
• String oneStringPerObject = new String(“my value”);
Java access to class and object
methods and data
• Public methods and data can be used by any code
that imports the class.
• Protected methods and data can be used only by the
defining class and derived classes.
• Private methods and data can be used only by the
defining class.
• If there is no explicit access restriction, then package
methods and data can be used by any class in the
package.
First example Java program
• CountArgString counts distinct, nonoverlapping occurrences of a string in a file
•
•
•
•
Perform these steps to build and test CountArgString:
mkdir ~/JavaLang ; setenv CLASSPATH $HOME/JavaLang
cp -pr ~parson/JavaLang/countargs ~/JavaLang/countargs
cd ~/JavaLang/countargs ; gmake clean test
• Make sure CLASSPATH include your $HOME/JavaLang
• makefile drives execution of compile and test steps
•
•
•
•
gmake build to compile Java files
gmake test to run test cases
gmake clean to clean up test output and compiled files
setenv CLASSPATH $HOME/JavaLang goes into the bottom of your .cshrc file.
Boolean example code
• /export/home/faculty/parson/JavaLang/bool
• Make sure you have a copy of this.
• cp –pr ~parson/JavaLang/bool ~/JavaLang/bool
• Program verifies valid command line args.
• 1. Program reads command line into an array of
floats, raising an Exception if any of the command
line arguments is not a float.
• 2. Verify that array is in ascending order using &&.
• 3. Verify that array is in ascending order using ||.
Booleans
• Boolean variables and constants
• boolean isSortedAnd = true, isOutOfOrderOr = false ;
• Boolean expressions
• isOutOfOrderOr || ! isLessThanOrEqual(numbers[i],
numbers[i+1])
• Condition control constructs use booleans
• if (isSortedAnd != ! isOutOfOrderOr) {
• Conditional expressions use booleans
• System.exit(isSortedAnd ? 0 : 1);
Class java.lang.System
• System.in is equivalent to C++ cin.
• import java.util.Scanner ;
• Scanner inputScanner = new Scanner(System.in);
• System.out and System.err are equivalent to
C++ cout and cerr.
• System.out.println("sort result = " + isSortedAnd);
• System.exit(0) causes the process to exit with
status of 0, meaning there is no error. A non-0
exits status signifies an error.
Creating Java Arrays
• Arrays are constructed using new (like C++).
•
•
•
•
•
•
•
•
“float [] numbers ;” creates a null array reference.
float [] numbers = new float [ INTEGER_SIZE ] ;
Java implicitly initializes an array of numbers with 0.
Booleans gets false, chars get ‘\0000’.
float [] numbers = {1.9F, 2.9F, 3.4F, 3.5F} ;
Myclass [] myobject = new Myclass[ INTEGER_SIZE ] ;
Java initializes an array of object references with null.
Java objects and arrays created using “new” need not
be “deleted.” JAVA HAS GARBAGE COLLECTION!
Using Java Arrays
• “String [] args” is the parameter for Java main.
• public static void main(String args[]) {
• main is needed for running a class from the UNIX command line.
• Expression “numbers.length” gives the
number of elements in the array.
• if (args.length == 0) {
• float [] numbers = new float [ args.length ]
• A subscript access and element of an array
• numbers[i] = Float.parseFloat(args[i]);
Helper class java.util.Arrays
• Utility methods for manipulating arrays.
• public static int[] copyOf(int[] original, int newLength);
» First available in Java 1.6, not 1.5 on Mac OSX.
•
•
•
•
•
public static void fill(int[] a, int val);
public static void sort(int[] a);
public static int binarySearch(int[] a, int key);
public static <T> T[] copyOf(T[] original, int newLength);
public static <T> void sort(T[] a, Comparator<? super
T> c) ;
• Comparator int compare(T o1, T o2) returns -1 or 0 or 1
for o1 < o2, o1 == o2 or o1 > o2 respectively.
Multidimensional Arrays
• int [][] matrix ; // an array of arrays, null
• int [][] matrix = new int[4][3]; // 4 rows of 3
• int [][] matrix = { // See Figure 6.11, p. 204
• {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}
• };
• matrix[0][0] is the initial element of the initial row
• matrix[3][2] is the last element of the last sub-array
(last column of the last row)
“Ragged Arrays”
• int [][] triangle = {
// p. 205
• {1, 2, 3, 4, 5}, {2, 3, 4, 5}, {3, 4, 5}, {4, 5}, {5} };
• int [][] triangle = new int [5][];
• for (int i = 0 ; i < triangle.length ; i++) {
• triangle[i] = new int [triangle.length – i]; }
• triangle[1].length gives the length of the
second sub-array triangle[1], which == 4.
Handling an exception from a
library method
• Read on-line doc on java.lang.Float.parseFloat
try {
numbers[i] = Float.parseFloat(args[i]);
} catch (NumberFormatException nfexp) {
System.err.println("format error on " + args[i]
+ ": " + nfexp.getMessage());
isSortedAnd = false ;
isOutOfOrderOr = true ;
// Initialize array element to a default value.
numbers[i] = 0.0F ;
}
Notes on the makefile
• If you run a test that you intend to fail –
System.exit(NON-0) – then put a “-” in front of
that command invocation in the makefile.
• -java $(PACKAGE).$(BASENAME) -1.0 0 fred 1.0 32.0
• Also, since your error messages are sent to
System.err, you need to redirect System.err to
a file to capture its output to use with diff.
• >> $(BASENAME).out 2>&1
• >> $(BASENAME).out 2>$(BASENAME).err
Programming practices
• Always handle exceptions!
• We may handle some by explicitly ignoring them.
•
•
•
•
Always use { curly braces } for control blocks.
Use coding standards that we discuss in class.
Write Javadoc documentation.
Use both healthy and degenerate tests.
» Ignoring these rules will cost you points.