Presentation is loading. Please wait.

Presentation is loading. Please wait.

Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions.

Similar presentations


Presentation on theme: "Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions."— Presentation transcript:

1 Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions Note: exam time has been changed to 16 August (Thursday) at 9 to noon, in WLH.

2 Summer 2007CISC121 - Prof. McLeod2 You Should Have: Finished reading the lecture notes on File I/O and Exceptions. Finished Exercise 1. Tried and then looked over the solutions to the old assignment 1. Started assignment 1. Contacted a TA if you don’t know how to get started or are stuck.

3 Summer 2007CISC121 - Prof. McLeod3 You Will Need To: Finish assignment 1 by Thursday. (I wanted to leave time for you to meet with a TA to get help.) From today’s notes, read about Wrapper classes and Strings. The API is your best reference for these classes.

4 Summer 2007CISC121 - Prof. McLeod4 What I Need To Do… Put together a new assignment! Put together some new exercises.

5 Summer 2007CISC121 - Prof. McLeod5 Today Write a small sample program – finding prime numbers. A quick look at exceptions to make sure you understand what is going on. Aside - Used with File I/O: JFileChooser. Style and Documentation Aside – Java keywords Class members – Attributes and Methods. Arrays – 1-D and Multi-D Passing parameters by value and by reference

6 Summer 2007CISC121 - Prof. McLeod6 Exceptions – From Last Lecture Text file input example: FileReader fileIn = null; try{ fileIn = new FileReader(filename); } catch (FileNotFoundException e) { System.out.println("Cannot open file!"); System.exit(0); } Scanner fileInput = new Scanner(fileIn);

7 Summer 2007CISC121 - Prof. McLeod7 Exceptions – From Last lecture A method can throw more than one kind of exception. Why would you want to do this? You can also include more than one line of code that can throw an exception inside a try block. Why would you not want to do this?

8 Summer 2007CISC121 - Prof. McLeod8 Built - In GUI Windows Easy to use, pre-designed GUI dialog boxes: –JOptionPane –JColorChooser –JFileChooser Imported from the javax.swing package. See “BuiltInDemo.java”.

9 Summer 2007CISC121 - Prof. McLeod9 JFileChooser A built in file browser/selector dialog box. The demo only used the chooser in the most simple way. For example, you can specify a starting folder and add as many file extension filters as you like. The chooser returns a File object, from which you can obtain much information about the file.

10 Summer 2007CISC121 - Prof. McLeod10 Simple Alternative Prompt the user for a filename as a String, using the console window. But if the user has to supply a path too?...

11 Summer 2007CISC121 - Prof. McLeod11 Aside - File Paths in Strings Sometimes you might have to include a path in the filename, such as “C:\Alan\CISC121\Demo.txt” Don’t forget that if you have to include a “ \ ” in a String, use “ \\ ”, as in: “C:\\Alan\\CISC121\\Demo.txt”

12 Summer 2007CISC121 - Prof. McLeod12 Programming Style & Documentation Purpose is to make your code readable (and “debuggable”) by you or another programmer who is familiar with the Java language. Internal style elements are documentation (comments), spacing, and descriptive variable names. Select the conventions you want to use and be consistent. (We will discuss creating external documentation through the use of the Javadoc utility later.)

13 Summer 2007CISC121 - Prof. McLeod13 Programming Style & Documentation – Cont. Comments: –Add a block comment to the top of the class and at the beginning of each method. Describe overall purpose of class/method, main algorithm used, author, date created, and any assumptions made and/or bugs found. Method comments should state what parameters are expected by the method and what the method returns. –Comments for variable declarations, when the name of variable is not self-explanatory. –Comments at the beginnings of logical blocks of code. –In-line comments to indicate the closing brackets of blocks and what they close.

14 Summer 2007CISC121 - Prof. McLeod14 Programming Style & Documentation – Cont. Spacing (alignment) –Class definition header starts at column 1, and closing bracket on column 1. –Indent of about 3 or 4 spaces is adequate. –Method headers and instance variable declarations indented once. –Code inside any block, including method code indented once from alignment of method header, or outer block.

15 Summer 2007CISC121 - Prof. McLeod15 Programming Style & Documentation – Cont. –Opening “{“ can be at the end of a statement line or on the line and position immediately below the declaration line: public static void main (String[] args) { or public static void main (String[] args) {

16 Summer 2007CISC121 - Prof. McLeod16 Programming Style & Documentation – Cont. –Closing “}” on same column as the column where the method header is declared, or the statement containing the opening “{“. “}” is usually by itself on a line. –Add a comment after “}” to indicate what is being closed. –If you have an overlong line, it is OK to continue the line on the line below, but indent the continued part of the line. (Note – do not try to continue a line in the middle of a String literal!)

17 Summer 2007CISC121 - Prof. McLeod17 Programming Style & Documentation – Cont. Spacing (“white space”) –Add blank lines before and after methods and larger logical blocks. –One statement per line. (Longer statements can be broken onto multiple lines.) –Use a space before “{“, “(“ and “[“. Use a space after “)” and “]” (unless the next character is “;”). –No code after “{“ or “}” on same line. –No space after “(“ or before “)”. (Not too critical!) –Use space after “,” or “;” in parameter lists or for loop arguments, but not before. –Put a space on both sides of an operator. –No space before “ ; ”.

18 Summer 2007CISC121 - Prof. McLeod18 Do public class StyleDemo { public static int someSum (int num1, int num2) { int sum = num1 + num2; return sum; } // end someSum method } // end StyleDemo class Of course, this still needs comments for the class and for the method.

19 Summer 2007CISC121 - Prof. McLeod19 Don’t! public class StyleDemo{ public static int s(int l,int l1){ int S=l+l1; return S;}} Look at “ S=l+l1 ” in Times New Roman Font: S=l+l1

20 Summer 2007CISC121 - Prof. McLeod20 Roedy Green’s “Unmaintainable Code” See: http://mindprod.com/jgloss/unmain.html “In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!”

21 Summer 2007CISC121 - Prof. McLeod21 Programming Style & Documentation – Cont. Variable Names –Also applies to method and class names. –Follow java restrictions on names: Use only letters, numeric digits (0 to 9) and the “_” character. Cannot start name with a number. Java is case sensitive! –Variables and method names usually start with a lower case character. Class names start with an upper case character. Constants are all in upper case. –Variables are usually nouns. –Methods are verbs or verbs and nouns.

22 Summer 2007CISC121 - Prof. McLeod22 Programming Style & Documentation – Cont. –Be descriptive, but not excessive! –Examples: numStudents setPassingGrade ( parameter list ) –Somewhat too long…: flagThatIsSetToTrueIfAProblemArisesWhen ThereIsAFullMoonOverMyHouseInTheWinterW hileMyProgramIsRunning –It is OK to use single letter variable names such as i, j, k for counters in loops.

23 Summer 2007CISC121 - Prof. McLeod23 Programming Style & Documentation – Cont. The java compiler ignores all white space including space characters, tabs and carriage return/line feed characters. Note that java keywords are in lower case. You will get an error message if you attempt to use a keyword as a variable name. Speaking of keywords …

24 Summer 2007CISC121 - Prof. McLeod24 Java Keywords abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

25 Summer 2007CISC121 - Prof. McLeod25 Java Keywords – Primitive Types abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

26 Summer 2007CISC121 - Prof. McLeod26 Java Keywords - Loops abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

27 Summer 2007CISC121 - Prof. McLeod27 Java Keywords - Conditionals abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

28 Summer 2007CISC121 - Prof. McLeod28 Java Keywords - Exceptions abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

29 Summer 2007CISC121 - Prof. McLeod29 Java Keywords – Class & Method Headers abstractdoubleintsuper assertelseinterfaceswitch booleanenumlongsynchronized breakextendsnativethis bytefornewthrow casefinalpackagethrows catchfinallyprivatetransient charfloatprotectedtry classgotopublicvoid constifreturnvolatile continueimplementsshortwhile defaultimportstatic doinstanceofstrictfg                                   

30 Summer 2007CISC121 - Prof. McLeod30 Instance Variables Also called “class variables” or “attributes” or “fields”. These variables are declared at the same level as the methods in a class. They are known to all methods within a class. Their scope is the entire class in which they were declared. They are the only variables accessible from outside the class, as well, provided they have not been declared to be private. Class attributes are not “global” variables!

31 Summer 2007CISC121 - Prof. McLeod31 Instance Variables, Cont. The syntax for the declaration of attributes: [private|public] [static] [final] type variable_name [= literal_value]; The “ | ” in this syntax means “one or the other”. The “ [ ] ” means that this part is optional.

32 Summer 2007CISC121 - Prof. McLeod32 Instance Variables, Cont. private or public determines if the attribute can be accessed from outside the class. If private or public is not stated, then the access is protected, by default. A static attribute shares only a single memory location, regardless of how many times its class is instantiated. So, every instantiation shares this attribute, and any of them can change it. Otherwise, the declaration of an attribute is just the same as any other variable declaration.

33 Summer 2007CISC121 - Prof. McLeod33 Aside - “Instantiation”??? Simply put, it is the creation of a new Object, an instance, using the new keyword. Another Object is required to provide the “pattern” for the new Object: String aString = new String(“Hello class!”); int[] anArray = new int[1000]; Scanner input = new Scanner(System.in); Instances

34 Summer 2007CISC121 - Prof. McLeod34 Aside - More About static Attributes that are used by a class’ main method must be declared static. Methods invoked by main that are in the same class as main must be declared static. That is because main is static. If you forget, don’t worry, the compiler will remind you!

35 Summer 2007CISC121 - Prof. McLeod35 Methods The syntax for simple method declaration: [private|public] [static] return_type method_name ([parameter_list]) {…}

36 Summer 2007CISC121 - Prof. McLeod36 Methods - Cont. Often, “utility” methods that are only used by other methods within a class are kept private. When the “ static ” keyword is used with methods, it means that the method can be used without instantiation. (All the methods in the Math class are static, for example.) When a static method is invoked for the first time, it is loaded into memory and then will stay in memory until the program completes.

37 Summer 2007CISC121 - Prof. McLeod37 Methods - Cont. A method must also have a return_type. A return type is what the method will return. It can be any single Object or a primitive type. (For example: an int, double, String, an array, or any other pre-defined Object.) If the method does not return anything, then the keyword “ void ” is used instead. The main method does not return any value, so that’s why it is declared as in: public static void main (String[] args) {…}

38 Summer 2007CISC121 - Prof. McLeod38 Methods - Cont. parameter_list provides a means of passing items, or parameters, into a method. It is optional. It can consist of one or many parameters, separated by commas. Each parameter type must be declared in the parameter list.

39 Summer 2007CISC121 - Prof. McLeod39 Methods - Cont. Also important: Unless the return type is void, the method must contain at least one return statement. A “ void ” method can also use a return statement without anything after it, as a means of termination of the method. A method always stops (terminates) when a return statement is encountered. Syntax: return [literal|expression];

40 Summer 2007CISC121 - Prof. McLeod40 Methods - Cont. The type of “ literal|expression ” must match the return type specified in the method declaration statement.

41 Summer 2007CISC121 - Prof. McLeod41 Method Examples public void printHello() { System.out.println(“Hello”); } // end printHello public void printHelloName(String yourName) { System.out.println(“Hello “ + yourName); } // end printHelloName public void printAvg(int a, int b) { System.out.println((a + b) / 2.0); } // end printAvg

42 Summer 2007CISC121 - Prof. McLeod42 Method Examples - Cont. public double average(double a, double b) { return (a + b) / 2; } // end average public int lowest(int a, int b) { if (a <= b) return a; else return b; } // end lowest

43 Summer 2007CISC121 - Prof. McLeod43 Methods - Cont. Why use methods? Avoids repetitious code. Independent testing of sub-tasks. Reusable code. –Design and test a method once, and re-use it whenever you need to solve a similar problem. Isolation from unintended side effects. –The only variables from the caller that can be seen from a method are those in the argument list. Fits in well with modular design practices.

44 Summer 2007CISC121 - Prof. McLeod44 Methods - Cont. Start thinking of your program as a collection of methods, where the main method only acts to call the other methods. Using good modular class design techniques with methods and private attributes is called “encapsulation” or “information hiding”. (More on this starting Thursday?)

45 Summer 2007CISC121 - Prof. McLeod45 Methods - Cont. When designing method operations, make sure a method only does one “thing”, do not combine operations (except in main ). Concentrate on coding the individual methods, one at a time, when you write a program. If you have thought out the “code-level interface” between the methods, then the methods will be completely independent of each other. Try to minimize the size of the main method, if possible. However, if the main method is going to be responsible for screen I/O then more code may be necessary.

46 Summer 2007CISC121 - Prof. McLeod46 One-Dimensional Arrays An array is just a collection of items, stored in computer memory (RAM). In Java: –The items must all be of the same base type. –Can be of any primitive type or object. –The size of the array must be declared before any items can be stored. –The size of the array cannot be changed after declaration. –An array occupies a contiguous memory space. –Array elements are numbered from zero.

47 Summer 2007CISC121 - Prof. McLeod47 One-Dimensional Arrays - Cont. The use of arrays in memory offers great speed advantages over processing data in and out of files. –File operations are always much slower than operations dealing only in RAM. –Typically, you will write array programs to: Read values from a file. Carry out all the calculations and manipulations required, in memory. Save the data back to another file. Arrays make it much easier to carry out the same calculation on many values.

48 Summer 2007CISC121 - Prof. McLeod48 One-Dimensional Arrays - Declaration For example, to create an array to hold 10 integers: int[] testArray = new int[10] ; testArray now points to an area of memory that holds locations for 10 integers. It also points to one location that holds testArray.length which is an attribute of the array, that is equal to the number of elements. Arrays are Objects in Java.

49 Summer 2007CISC121 - Prof. McLeod49 00000000000000000000 One-Dimensional Arrays - Declaration, Cont. 0180ff … int[] testArray 0480ff 10.length As a “pointer”, testArray points to an area of memory that contains a series of int values as well as the attribute length.

50 Summer 2007CISC121 - Prof. McLeod50 One-Dimensional Arrays - Declaration, Cont. The java statement above can be split into two: int[] testArray; testArray = new int[10]; The first statement creates a variable of type int[] - that is to say that it will be an array of int ’s. The variable, testArray is now an object of type int[] that contains an “object reference” or a pointer. The object reference is null after the first statement.

51 Summer 2007CISC121 - Prof. McLeod51 One-Dimensional Arrays - Declaration, Cont. int[] testArray; testArray = new int[10]; The second statement looks for a chunk of memory big enough to contiguously hold 10 integers (about 40 bytes), and then changes the object reference of testArray from null to the memory location of the chunk. This assignment of the object reference of the testArray object is carried out by the “ = “ assignment operator. The new keyword is responsible for blocking out the memory space and initializing each memory location to the default value for a new memory location of type int (zero).

52 Summer 2007CISC121 - Prof. McLeod52 Back to the 10 array elements in memory: testArray[0] testArray[1] testArray[2] testArray[3] testArray[4] testArray[5] testArray[6] testArray[7] testArray[8] testArray[9] One-Dimensional Arrays - Cont. 00000000000000000000 10 testArray.length

53 Summer 2007CISC121 - Prof. McLeod53 One-Dimensional Arrays - Indices The numbers 0 to 9 are called the index values of the array. The notation used above allows you to refer to individual elements. Note that the elements of the array are numbered from zero. arrayname.length returns the number of elements in the array.

54 Summer 2007CISC121 - Prof. McLeod54 One-Dimensional Arrays - Cont. for loops are often used with arrays. For example, to initialize each of the elements of testArray to the value 1000 * i : int i; for (i = 0; i < 10; i++) testArray[i] = 1000 * i; Arrays can also be initialized at declaration, using an “array initializer”. To get the same array as above: int[] testArray = {0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000};

55 Summer 2007CISC121 - Prof. McLeod55 One-Dimensional Arrays - Cont. Arrays can also be created using a variable (or constant) to specify the array size: final int MAX_SIZE = 1000; int[] testArray = new int[MAX_SIZE]; int size = testArray.length; // size is 1000

56 Summer 2007CISC121 - Prof. McLeod56 One-Dimensional Arrays - Cont. All the examples so far, have been arrays of int ’s. Could be arrays of double ’s, boolean ’s or even String ’s: (anything in fact, as long as all the array elements are the same “thing”) For example:

57 Summer 2007CISC121 - Prof. McLeod57 More Declaration Examples double[] dArray = new double[50]; String[] sArray = new String[100]; String[] sArray2 = {“Hi”, “Ho”, “Silver!”}; Note that there is some flexibility in where the first set of “ [] ” goes. These two declarations are equivalent: double[] disNDat = new double[1000]; double disNDat[] = new double[1000];

58 Summer 2007CISC121 - Prof. McLeod58 One-Dimensional Arrays - “Out-of- bounds” Error If n is the size of the array, then: Array indices (or “subscripts”) < 0 or  n are illegal, since they do not correspond to real memory locations in the array. These indices are said to be out-of-bounds. Reference to an out-of-bounds index produces an out-of-bounds exception, and the program will crash if the exception is not caught.

59 Summer 2007CISC121 - Prof. McLeod59 Multi-Dimensional Arrays Multi-dimensional arrays are just arrays of arrays. For example, to create a two-dimensional array: int[][] twoDArray = new int[10][20]; Holds 200 elements. Initialize each element to the sum of its indices, for example: int i, j; for (i = 0; i < 10; i++) for (j = 0; j < 20; j++) twoDArray[i][j] = i + j ;

60 Summer 2007CISC121 - Prof. McLeod60 Multi-Dimensional Arrays - Cont. Everything is the same as for one-dimensional arrays, except that you have a set of “ [] ” for each dimension. Two-dimensional arrays are suitable for storage of a single type of data that would normally be viewed in a table with rows and columns. Java does not place any limitation on the number of dimensions used in an array.

61 Summer 2007CISC121 - Prof. McLeod61 Multi-Dimensional Arrays - Cont. Consider: int[][] exArray = new int[3][5]; int[][] exArray 0480ff int[] exArray[0] 1002fc int[] exArray[1] 1010fc int[] exArray[2] 1201ab 0000000000 0000000000 0000000000 1002fc 1201ab 1010fc

62 Summer 2007CISC121 - Prof. McLeod62 Multi-Dimensional Arrays - Cont. So exArray points to three one dimensional arrays: exArray[0] exArray[1] exArray[2] Each of these arrays has the same length: exArray[2].length // returns 5

63 Summer 2007CISC121 - Prof. McLeod63 Multi-Dimensional Arrays - Cont. int[][] twoDArray = new int[10][20]; The above is equivalent to: int[][] twoDArray; twoDArray = new int[10][]; for (int i = 0; i < 10; i++) twoDArray[i] = new int[20]; As shown above: twoDArray.length// gives 10 twoDArray[0].length // gives 20

64 Summer 2007CISC121 - Prof. McLeod64 Multi-Dimensional Arrays - Cont. “Ragged Arrays” are not “square” and are legal in Java: int[][] raggedArray = new int[5][]; raggedArray[0] = new int[2]; raggedArray[1] = new int[4]; raggedArray[2] = new int[6]; raggedArray[3] = new int[8]; raggedArray[4] = new int[10];

65 Summer 2007CISC121 - Prof. McLeod65 Multi-Dimensional Arrays - Cont. Array initializer for two-D array, for example: int[][] twoDArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; System.out.println(twoDArray.length); // 4 System.out.println(twoDArray[0].length); // 3

66 Summer 2007CISC121 - Prof. McLeod66 Aside - Aliasing Objects Arrays are objects, so we can use them to demonstrate aliasing. What is the output of the following code segment? int[] arrayA = {1, 2, 3, 4, 5}; int[] arrayB = {100, 200, 300}; arrayA = arrayB; arrayA[1] = 1000; System.out.println(arrayB[1]); System.out.println(arrayA[0]);

67 Summer 2007CISC121 - Prof. McLeod67 Aliasing Objects, Cont. So both arrayA and arrayB point to the same array: {100, 200, 300} Which becomes {100, 1000, 300} arrayA and arrayB are aliased. What happens to {1, 2, 3, 4, 5} ?

68 Summer 2007CISC121 - Prof. McLeod68 Passing Parameters by Reference The rule for parameter passing into methods is: –Objects are passed by reference, primitive types are passed by value. –An object passed into a method through the parameter list is aliased to the object outside the method. See PassingDemo.java –Has a method with two parameters - an array and an int - which one(s) will stay changed? –Instead of going element by element, if you re-assign the array to another array within the method, what happens?

69 Summer 2007CISC121 - Prof. McLeod69 Passing Arrays by Reference Summary of PassingDemo.java: –Primitive types are passed by value. –Only element by element changes in arrays will “stick”. –Re-assigning the array to a pointer that has local scope in a method will not “stick”.

70 Summer 2007CISC121 - Prof. McLeod70 Wrapper Classes Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. –Some data structures only store Objects. –Some Java methods only work on Objects. Wrapper classes also contain some useful constants and a few handy methods.

71 Summer 2007CISC121 - Prof. McLeod71 Wrapper Classes - Cont. Each primitive type has an associated wrapper class: Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. charCharacter intInteger longLong floatFloat doubleDouble

72 Summer 2007CISC121 - Prof. McLeod72 Wrapper Classes - Cont. Integer number = new Integer(46);//”Wrapping” Integer num = new Integer(“908”); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt(“453”) // returns 453 Integer.toString(653) // returns “653” number.equals(num) // returns false int aNumber = number.intValue(); // aNumber is 46

73 Summer 2007CISC121 - Prof. McLeod73 Wrapper Classes – Cont. The Double wrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble(“0.45E-3”) // returns 0.45E-3 parseDouble is only available in Java 2 and newer versions. See the Java documentation for more on Wrapper classes.

74 Summer 2007CISC121 - Prof. McLeod74 String Class Since String’ s are Objects they can have methods. String methods include: length() equals(OtherString) equalsIgnoreCase(OtherString) toLowerCase() toUpperCase() trim() charAt(Position) substring(Start) substring(Start, End)

75 Summer 2007CISC121 - Prof. McLeod75 String Class - Cont. indexOf(SearchString) replace(oldChar, newChar) startsWith(PrefixString) endsWith(SuffixString) valueOf(integer) String ’s do not have any attributes. See the API Docs for details on all the String class methods.

76 Summer 2007CISC121 - Prof. McLeod76 Examples: int i; boolean aBool; String testStuff = “A testing string.”; i = testStuff.length(); // i is 17 aBool = testStuff.equals(“a testing string.”); // aBool is false aBool = testStuff.equalsIgnoreCase(“A TESTING STRING.”); // aBool is true String Class - Cont.

77 Summer 2007CISC121 - Prof. McLeod77 String Class - Cont. char aChar; aChar = testStuff.charAt(2); // aChar is ‘t’ i = testStuff.indexOf(“test”); // i is 2

78 Summer 2007CISC121 - Prof. McLeod78 Aside - More about String ’s Is “Hello class” (a String literal) an Object? Yup, “Hello class!”.length() would return 12. String ’s are actually stored as arrays of char ’s. So, a String variable is actually just a pointer to an array in memory.


Download ppt "Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions."

Similar presentations


Ads by Google