Sie sind auf Seite 1von 55

Week 1

Friday, 5 August 2011 10:12 AM

Week 1
Col Clark c.clark@griffith.edu.au Objects are used to break big chunks of code into smaller, more manageable pieces

Programming 2 Page 1

Week 2
Friday, 5 August 2011 10:12 AM

Week 2
Import tells the computer what tools will be needed Classes are organised into packages Packages group related classes together Classes group related methods together Methods group related statements together Java.lang.Math.sqrt() Java is the package Lang is the package as well Math is the class Sqrt() is the method Why use packages Easy to find and manage classes Java has security modifiers that work on package levels Compiler compiles quicker with less stuff to search for. Most common packages Java.lang (imported by default) Math String System Java.util Scanner Random Java.io File * is import everything All executed code needs to be in a method of some kind All java programs require a main method Main method is the entrypoint(runs through first) Why use methods? Allows us to break codes into smaller portions, makes life easier Easy reuse Serves as an entry point for an event driven code Makes code easier to read An approach to deal with larger problems is Structured design, which works with the idea of divide and conquer A program should be subdivided into logical groups of methods, usually have the following phases: Input, Processing, Output. Advantages of Structured design: The logical groups of code are contained together Larger problems can be divided into smaller simpler problems Smaller problems can then be passed on to others Code becomes self-documenting through readable method names

Programming 2 Page 2

Three things to do while writing a method Determine the method header Write the body of the method Call the method Three things needed to write a method Return type Method name Parameter types Collectively this is known as the method signature Public static void main(String[] args); Public: visibility modifier, must be public for main, can be private or blank for others Static: will be static until otherwise Void: return type Main: method name String[] args: parameters/arguments Public static int coutStrings(String s, String t); Methods have data going in (through parameters) and data going out (through return value) Multiple parameters are supported Only one value is returned (is supported) (an array can bring back moar)

Return statement is used to return a value from a method Return value must have a data type compatible with the return type of the method When the return statement is uncounted, method exits immediately
If a method doesnt return a value, it returns void Void methods can have return statements, but cant return values Non void methods must have a return statement Calling methods: run, execute, call, invoke, all means the same thing When calling a method, we need to know 3 things: The method name, types of parameters, return types When a method is called using primitive values, the values copied into the parameters When a method calls on a reference value, the reference is copied but not the data being refurred. When primitive values are passed into a method, they are copied in, the original variable are not changed Arrays are stored as references to variables When an array is assigned to another variable, the reference is copied ,not the actual values of the array

Java doesnt support multiple return values Can be necessary sometimes One way to return multiple values is via arrays, aint pretty, but it works
Putting written code into a separate method, is called refactoring Method names cant have any punctuation except for $ and _ Also cant start with digits Cant contain another method Must be placed directly within a class

Programming 2 Page 3

Class Names must begin with a capital letter Methods should begin with a lowercase Mixed caseno idea wtf General method size should fit on the screen, if larger, should be divided There are some exceptions Formal Arguments Parameters in the method header Int countStrings(String s, String search) Actual parameters Expressions passed to the method Int count = countStrings(name, cat); Can methods have the same name? YES Multi methods with the same name is known as method overloading Can methods have the same parameter names? YES Can methods have the same names and parameter types? Neg Can methods have the same names, and same types, but different parameter names? No Can methods only differ by the return type? No Java doesnt look at the return type to determine which method to call What can we conclude? Parameter names are completely ignored when determining which method to call Method signatures doent include the parameter names Method signature does include the return type, however the return type doesnt determine which method is called therefore methods that differ only by the return type will produce a compile error

Programming 2 Page 4

Week 3
Wednesday, 10 August 2011 12:59 PM

Java's API for graphical user interfaces is called Swing All of the swing classes are in the Javax.swing package You will need to import javax.swing when using a swing class Swing provides the JOptionPane class to provide a basic GUI interaction with the user. JOptionPane supports 3 types of windows Message Dialog - displays messages Confirm Dialog - gives user choice of buttons to click Input Dialog - allows user to type in a string Using JOptionPane JOptionPane can be instantiated and various option set before displaying the dialog. However Java provides a simpler one line approach using static methods JOptionPane.showMessageDialog() JOptionPane.showConfirmDialgo() JOptionPane.showInputDialog() Displaying a Message The header for showMessageDialog() is:

The first parameter would be the window that the dialog is being displayed in front of. Normally in GUI program a dialog is modal, which means that no other interaction with the underlying window is possible until the dialog is closed. Currently using null since there is no windows. Second parameter can be a string to be displayed.
Since showMessageDialog() is static, we don't need to make an instance of JOptionPane, but we have to specify the Class name since we are calling it from outside the class. JOptionPane.showMessageDialog(null,"Greetings Morons".); Setting the Title The messageType parameter can be one of the following

JOptionPane.ERROR_MESSAGE JOptionPane.INFORMATION_MESSAGE JOptionPane.WARNING_MESSAGE JOptionPane.QUESTION_MESSAGE JOptionPane.PLAIN_MESSAGE JOptionPane.showMessageDialog(null,"All your bases are belong to us","My victory, your defeat",JoptionPane.ERROR_MESSAGE);

Confirm Dialog Confirm Dialog is used to display a message that has a group of options to respond too. Example Delete a file? Yes No
Programming 2 Page 5

Yes No showConfirmDialog showConfirmDialog returns an int indicating what button was pressed JOptionPane defines the following constants to determine which button the int refers to: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION JOptionPane.OK_OPTION JOptionPane.CLOSED_OPTION Example Int buttonPressed = JOptionPane.showConfirmDialog(null,"Is this a true statement?"); if (buttonPressed == JOptionPane.YES_BUTTON) { } else if (buttonPressed == JOptionPane.NO_BUTTON) { } else if (buttonPressed == JOptionPane.CANCEL_BUTTON) { } Switch statement Java provides the different switch statement when one variable needs to be compared with different values switch (variable) { case value1: statements break; (Break is required at the end of each case, if there's no break, then the next case block will be executed, even if the values don't match) case value2: statements break; case value3: statements break; default: (The default block runs if no cases match. No break is required in the default block since it's the last block on the switch Statements } JOptionPane and switch switch (buttonPressed) { case JOptionPane.YES_BUTTON: break; case JOptionPane.NO_BUTTON:
Programming 2 Page 6

break; case JOptionPane.CANCEL_BUTTON: break; } Default statement is optional Switch The variable passed to the switch statement must be a primitive type, switch can't be used with Strings, arrays, or any type of object. Switch can be used to check multiple values { case a: case b: case c: break; case d: break; } The case block will execute if c matches 'a','b', or 'c' showConfirmDialog options An optionType can be passed to showConfirmDialog

The optionType can be one of: JOptionPane.DEFAULT_OPTION JOptionPane.YES_NO_OPTION JOptionPane.YES_NO_CANCEL_OPTION JOptionPane.OK_CANCEL_OPTION Input Dialog The input dialog allows users to enter a string JOptionPane.showInputDialog(null, Enter your favorite saying); showInputDialog() returns the string the user entered If the user presses the cancel button, it will return null. showInputDialog() allows the initial input value to be specified: JOptionPane.showInputDialog(null, "Enter your favorite saying", "Legendary@"); Multiple Values Sayings[] options = {"Legendary!", "Whatever", "Awesome!"}; Sayings choice = JOptionPane.showInputDialog(null, "Select a favorite saying", "Sayings", JOptionPane.PLAIN_MESSAGE, null, Sayings, "Whatever"); Entering Numbers showInputDialog() always returns a string If the user enters a number, it needs to be converted into a destination type
Programming 2 Page 7

If the user enters a number, it needs to be converted into a destination type Java provides the following static methods to convert strings to primitive types Integer.parseInt(String s) Double.parseDouble(String s) there are also versions for float, long, short, etc. Number example String numberString = JOptionPane.showInputDialog(null, Enter your age); int number = Integer.parseInt(numberString); If anything but an int Is entered, it will exit with NumberFormatException Summary JoptionPane is a simple way to interact with a user using a GUI but without preforming a lot of tasks usually associated with GUIs Most scanner and System.out.print() functionality can be replicated with one line JOptionPane calls. System.out.print() statements can be replaced with JOptionPane.showMessageDialog() Scanner nextLine() statements can be replaced with JOptionPane.showInputDialog() Object oriented Programming Programming using Objects Objects encapsulates data and methods Class Variables Variables are allowed to be declared outside methods in the class. Class variables must be declared static Class variables exist for the lifetime of the program Local variables exist for the lifetime of the method Global variables exist for the lifetime of the program There is only ever one instance or copy of each class variable For example, there is only one x variable in the life time of the program Data Structures Can group together related variables together In Pascal, called Records In C they're called struts The data and methods are encapsulated into one structure called class When we define a new data structure, which in java is a class, it is now also a type. Therefore Student is now a type The student type can be used anywhere a data type is expected. Data types of variables, eg. Student s; Data types of arrays, eg. Student[] students; Parameter types, eg. void print(Student s) Return types, eg. Student readStudent() Advantages of using data structure like class Student are: Variables, method calls, and method parameters only need one variable which is an instance of Student Additional variables can be added to Student without changing any existing code that uses Student. The variables within the Student class are not declared static, which means they are only accessible within instances of the class. Static vs Non-Static When a class is first loaded, the class variables are initalised. There is only ever one instance(copy) of class (static) variables. Non static variables however are not created when the program is launched. Therefore static code cannot access non-static variables. A class can have both, but a compile error will be generated if a static method tries to access a non static variable.
Programming 2 Page 8

will be generated if a static method tries to access a non static variable.


Creating a Class Instance To get access to the non-static members of a class, we must first create a new instance. A class instance is also known as an object. Even though each Object has variables specified by the class, the variables are stored in each individual object and can therefore have different independent values. A class instance (or sometimes just instance) is also called an object Class variables are static variables Non-static variables can be called by the following names: instance variables object variables fields this is the official Java term, but not used by other languages. properties attributes Methods and fields are both members of an object. Classes vs Objects Using database as an analogy, a class is like schema for a database table. An object would be an individual record in the table. Syntax for creatign an instance is: New ClassName() We also tend to assign the new instance variable of the same type: ClassName variableName = new ClassName(); Example Student s = new Student(); Anything within an object can be accessed with a dot variableName.fieldName Example Student s = new Student(); s.sNumber = "s2799700"; s.firstName = "Nathan"; s.lastName = "Clark"; s.email = "Grimmuald@gmail.com"; System.out.println(s.firstName+" "s.lastName); Visibility modifier determines whether the member can be accessed outside of the class 3 levels Private, protected, public Private: Access modifier restricts access to the member to within the current class. Only methods of the current class can access private members Protected: can be accessed by methods in current class, and also other classes within the same package (protected is default) Public Members declared with the public access modifier can be accessed by any class Which access modifiers to use? In general fields should be declared private. Methods required by other classes should be declared public. The only fields that should be declared public are class constants that need to be used by other classes.
Programming 2 Page 9

classes.
Why private? So classes can't directly modify them Instance methods Static methods can't access instance fields Instance methods can access instance fields Methods + Data = objects

Programming 2 Page 10

Homework
Thursday, 11 August 2011 4:21 PM

Java is an Object Oriented Language In Java, an identifier that is made up by the programmer can consist of numbers, letters, undersores, and the dollor sign A syntax error is a compile-time error Which of the following is not one of the four basic software development activities? Preliminary practice coding In order for a program to run on a computer, it must be expressed in a machine language Software requirements specify what a program should accomplish The methods of an object define it define its potential behaviors Which of the following will is considered a logical error, Multiplying two numbers when you meant to add them. The Java compiler translates Java source code into Java bytecode Which of the following might be included in an IDE, all of them Which of the following are examples of invalid string literals: none of the above A parameter is a piece of data that we send to a method Which of the following is an example of an invalid assignment or declaration statement? int years = 1; months = 12; days = 365; Java has two basic kinds of numeric values: integers, which have no fractional parts, and floating points which do. Consider the expression: result = 12 + 5 / 2; What value stored in result after this line is executed? 14 Which of the following is not an arithmetic operation in Java These are all arithmetic operations in Java In order to make a variable a constant which modifier must be included in its declaration? Final Which of the following data types only allows one of two possible values to be assigned? Boolean. Which of the following is an example of an invalid expression in Java? Result = ((19 + 4) - 5; Consider the expression Result = 15 % 4; What value stored in result after this line is executed? 3 Which of the following lines allows a programmer to use the scanner class in a Java program? import Java.util.Scanner; Consider the following snippet of code: System.out.println("30 plus 25 is "+30+25); What is printed by this line? 30 plus 25 is 3025 Information is most likely to be lost in what kind of data conversion? A narrowing conversion Which of the following is an invalid way to instantiate a string object? All of the above were valid.

Question 1 The ________________ operator is used to instantiate an object. Selected Answer:

1 out of 1 points

new

Feedbac The new operator instantiates an object. There is no static operator, and k: the + and operators are for arithmetic expressions (although the + operator can also be used for String concatenation).

Programming 2 Page 11

Questio n2

0 out of 1 points Assume that we have a Random object referenced by a variable called generator. Which of the following lines will generate a random number in the range 5-20 and store it in theint variable randNum? Selected Answer: randNum = generator.nextInt(15) + 5;

Question 3 Consider the following snippet of code: Random generator = new Random(); int randNum = generator.nextInt(20) + 1;

1 out of 1 points

Which of the following will be true after these lines are executed?
Selected Answer: randNum will hold a number between 1 and 20 inclusive. Feedbac When called with a parameter of 20, the nextInt() method will return an integer k: between 0 and 19 inclusive. Adding one to this will result in a number between 1 and 20 inclusive.

Question 4

0 out of 1 points When two references point to the same object, ________________________________ . Selected Answer: a compiler error will occur.

Questi on 5

1 out of 1 points Which of the following statements best describes the flow of control in the main method of a Java program that has no conditionals or loops? Selected Answer:

Program statements are executed linearly, with earlier statements being executed first.

Feedbac Program statements in a Java program are executed linearly when there are no k: conditionals or loops. This means that statements that appear earlier in the code are executed before statements that appear later in the code.

Questi on 6 Which of the following best describes this code snippet? if (count != 400) System.out.println(Hello World!); Selected Answer:

1 out of 1 points

If the variable count is not equal to 400, Hello World will be printed. Feedbac The != operator means is not equal to. Therefore if the variable count is not equal Programming 2 Page 12

Feedbac The != operator means is not equal to. Therefore if the variable count is not equal k: to 400, the following line will be executed. The boolean operator to test is equal to is ==. There are no boolean operators that test the cases specified in choices c and d.

Question 7

1 out of 1 points Which of the following is not a valid relational operator in Java Selected Answer:

<>

Question 8

0 out of 1 points Let a and b be valid boolean expressions. Which of the following best describes the result of the expression a || b? Selected Answer:

None of the above statements correctly describes the evaluation of the expression.

Question 9

0 out of 1 points Which of the following expressions best represents the condition if the grade is between 70 and 100? Selected Answer: if (75 > grade || grade < 100)

Questio n 10 Which of the following logical operators has the highest precedence? Selected Answer:

1 out of 1 points

Feedbac The not operator has the highest precedence of the three logical operators k: (!, &&, ||) , and therefore choice a is correct. Choices d and e are relational operators, not logical operators.

Questio n1 A _______________ loop always executes its loop body at least once. Selected Answer:

1 out of 1 points

do

Feedbac The do loop always executes its loop body at least once. Both a for loop and k: a while loop may never execute their loop body if their termination condition immediately evaluates to false. There is no repeat loop in Java.

Question 2

0 out of 1 points

The ___________________ statement causes execution of a loop to stop, and the statement

Programming 2 Page 13

The ___________________ statement causes execution of a loop to stop, and the statement following the loop to be subsequently executed. Selected Answer: stop

Questio n3

0 out of 1 points The ___________________ statement causes current iteration of a loop to stop and the condition to be evaluated again, either stopping the loop or causing the next iteration. Selected Answer: break

Questio n4

1 out of 1 points Which of the following for loop headers will cause the body of the loop to be executed 10 times? Selected Answer:

for(int i = 0; i < 10; i++)

Feedbac The loop executes when i is equal to 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Therefore it k: executes exactly 10 times. Choice a and c execute 11 times, while choice a executes 9 times.

Questi on 5

1 out of 1 points
Suppose we want to condition an if statement on whether two String objects, referenced by stringOne and stringTwo, are the same. Which of the following is the correct way to achieve this? Selected Answer: Feedba ck: if(stringOne.equals(stringTwo))

In Java, a programmer should not use conditional operators to compare objects for equality. Instead, the equals() method should be used. Therefore choice c is correct, and choices a and d are incorrect. The compareTo() method does not evaluate to a boolean, so choice b will not compile. There is no operator in Java that is represented by ===, so choice e is incorrect.

Question 6 An infinite loop is a compile-time error. Selected Answer:

1 out of 1 points

False

Feedback An infinite loop is usually caused by a logical error, and will not be caught by : the compiler.

Questio n7 A while statement always executes its loop body at least once. Selected Answer: Feedbac k:

1 out of 1 points

False

A do statement always executes its loop body at least once. A while statement

Programming 2 Page 14

k:

A do statement always executes its loop body at least once. A while statement will not if its condition evaluates to false on the first pass.

Question 8

1 out of 1 points The relational operators should not be used to test the equality of objects.

Selected Answer:

True

Feedback: To test the equality of objects, the equals() method should be used.

Questio n9 It is possible to implement a switch statement using if statements. Selected Answer:

1 out of 1 points

True

Feedbac By using nested if statements, a programmer can implement any switch statement k: using a series of nested if statements. The code for a switch statement may be clearer and more readable, however.

Programming 2 Page 15

Week 4
Thursday, 18 August 2011 12:59 PM

Unified modelling Language UML is a set of standards for visually modelling different aspects of programming. UML also specified a notation for class design. A class in UML has 3 sections Class name, attributes, methods Class name: Course Attributes: corseCode:String Students:String[] Labs:Lab[] Methods: If a class refers to another in some way, it has a relationship with the class UML defines several types of relationships UML instance relationships are called associations An instance is associated with another instance if it is used within the class in any way.

An association can also indicate the cardinality of the relationship UML represents cardinality using the following notation Lower limit .. Upper limit Eg zero or many:0.. Zero or 1: 0..1

Programming 2 Page 16

Inheritance Several classes share a common functionality Super classes can be extracted like a method

Java has 2 APIs for generating random numbers Math.random() Java.util.Random class Math.random() returns a double random number between 0 (inclusive) and 1 (exclusive) Examples include: 0.001, 0.5, 0.774, 0.8484 What if we want a random number between 1 and 10? 1-10 Math.random() x 10 + 1 You can extend the range by multiplication Double number = Math.random() * 10; The result is that the random numbers will now extend from 0 to 10 Now we need our numbers to be whole We can convert the numbers to whole numbers by casting to an int Casting involves putting the destination type within parentheses in front of the value to be
Programming 2 Page 17

Casting involves putting the destination type within parentheses in front of the value to be converted: Int number = (int)(Math.random()*10); For numbers from 1 - 10, simply add + 1 Int number = (int)(Math.random()*10)+1; The random class in in the java.util package An instance of random is required before it can be used Random random = new Random(); Int nextInt(int max) Return a random whole number between 0 and max Double nextDouble() Returns a number between 0 and 1 Identical to Math.random To generate a random number between 1 and 10 Random random = new Random(); Int number = random.nextInt(10)+1;

Random characters Java can't generate random characters or strings, however we can map random numbers to character strings
Randomly select a color: red, green or blue Random random = new Random(); int number = random.nextInt(3); String colour = ; switch (number) { case 0: colour = red; break; case 1: colour = green; break; case 2: colour = blue; break; } The randomly generated number can be used as an index into an array of values: String[] colours = {"red","green, blue}; Random random = new Random(); I nt number = random.nextInt(3); String colour = colours[number]; Testing Random Testing programs that have random numbers can be difficult as there is no way to know what the program will output. Random number generators are actually deterministic, in other words they will always generate the same sequence of numbers as long as the seed is the same. The seed is usually based on the current time allowing each run of the random number generator to produce different outputs.

The random class allows a seed to be specified in the constructor. For testing purposes in JPL we will always use the seed 0 so that the program output can be tested String[] colours = {red, green, blue}; Random random = new Random(0);
Programming 2 Page 18

Random random = new Random(0); int number = random.nextInt(3); String colour = colours[number]; System.out.println(colour); Will always print red

The File class is used to represent files and directories

Programming 2 Page 19

Week 5
Wednesday, 24 August 2011 1:02 PM

A File class is used to represent files and directories. Creating a File Object doesn't create a file The File object merely represents an existing or potentially existing file. A file class is used by other classes to locate files for reading and writing To use the File class, you need to use the Java.io.* import

When creatinga new file object path specified will be relative to the directory the program is running from Saying File f = new File("Test.txt"); presumes that the text file is in the same directory as the java program itself Absolute Paths - File f = new File("C:\\Users\\myaccount\\Test.txt"); Be careful of the backslashes File methods Boolean exists() Tests to see if the file exists String getName() Gets the name of the file represented by the path String getParent Gets the name of the directory containing the file Long length() File length in bytes A file objective can also represent a directory Boolean isFile() Returns true if this is a file, not a directory Boolean isDirectory() Returns true if this is a directory, not a file String[]list() Returns an array of file names in this directory Boolean mkdir() Creates the directory if it doesn't exist. Reading from a File The scanner class can be used to read from a file by passing a file objective into the constructor. Reading from keyboard; Scanner keyboard = new Scanner(system.in); Reading from file Scanner file = new scanner(new File("Test.txt")); Counting all the lines in a file
Programming 2 Page 20

Counting all the lines in a file Scanner file = new Scanner(new File(Test.txt)); int numLines = 0; while (file.hasNextLine()) { String line = file.nextLine(); numLines++; } System.out.println(numLines); file.close(); Scanner Uses the same files as it is with the keyboard All the existing Scanner methods work the same Next() nextInt() nextDouble() nextLine() Exceptions An exception in java is an error that can be handled by the program A FileNotFoundException can occur indicating a possible error such as the file not existing. Some exceptions must be either caught or thrown At this stage of the course, we are not going to catch(process) exceptions Throws If a method can throw an exception it will be stated in the method header If a method can throw an exception, the calling code must either catch or thrown it public static void main(String[] args) throws FileNotFoundException { Scanner file = new Scanner(new File(Test.txt)); int numLines = 0; while (file.hasNextLine()) { String line = file.nextLine(); } It is important when working with files to close the Scanner objects when finished with the file. If the file isn't closed, it may become locked Eg File.close(); Determining the end of the file Scanner has a number of has methods that indicate whether there is more data of the specified type to be read: Boolean hasNext() There is another word that can be read Boolean hasNextLine() There is an entire line that can be read Boolean hasNextInt() There is a whole number to be read Boolean hasNextDouble() There is a double that can be read Reading from file example public static void main(String[] args) throws FileNotFoundException { Scanner file = new Scanner(new File(Marks.txt));
Programming 2 Page 21

{ Scanner file = new Scanner(new File(Marks.txt)); double total = 0; int count = 0; while (file.hasNext()) { String sNumber = file.next(); int mark = file.nextInt(); total += mark; count++; } file.close(); System.out.println(Average: + total / count); } nextLine() Caution Next() nextInt() nextDouble() don't consume the newline characters Reading into an array When reading from a file we may not know in advance how many values there are. There are several approaches to dealing with this Creating an array that is much larger then is needed Read the file twice,, the first read determines how many entries, but doesn't store any Create a new larger array when the existing array becomes full final int MAX = 1000; String[] sNumbers = new String[MAX]; int[] marks = new int[MAX]; Scanner file = new Scanner(new File(Marks.txt)); int i = 0; while (file.hasNext()) { String sNumber = file.next(); int mark = file.nextInt(); sNumbers[i] = sNumber; marks[i] = mark; i++; } file.close();

Best array approach Fixed-size large array Having a fixed large array is the simplest solution, however it may break if a file is larger, also it wastes memory Read the file twice Counting the entries in the file first has the most efficient memory usage, however it requires the file be read twice, which can be slow. Resizing the array Resizing the array requires periodic memory allocations and copying which can also be slow but possibly not as slow as reading through the file twice.

Java does provide an arrayList class which provides resizable array functionality To create one ArrayList a = new ArrayList();
Parameterised types An ArrayList stores generic objects by default We can specify exactly what type of object using paramerised types which are specifically <> An ArrayList of strings: ArrayList<String> a = new ArrayList<String>();

Full type is: ArrayList<String>


The E used below refers to whatever <type> The ArrayList is, for example, it can be a String. Boolean add(E e) Adds e to the end of the array E get(int index)
Programming 2 Page 22

E get(int index) Returns the object to index Boolean remove(object o) E set(int index, E e) Replaces element at index with e Int size() Returns the number of elements in the list Adding in an element Creating an ArrayList of Strings and adding an element: arrayList<String> a = new ArrayList<String>(); a.add("A String"); Initial size of the array doesn't need to be specified Index to add string doesn't need to be specified. // No need to specify an initial size ArrayList<String> sNumbers = new ArrayList<String>(); ArrayList<Integer> marks = new ArrayList<Integer>(); Scanner file = new Scanner(new File(Marks.txt)); int i = 0; while (file.hasNext()) { String sNumber = file.next(); int mark = file.nextInt(); // No need to specify the index, it will be added to the end sNumbers.add(sNumber); marks.add(mark); i++; } file.close(); ArrayList and Primitives ArrayList can only store objects Autoboxing - converting primitives into objects Java has a class for each primitive type in the java.lang package Boolean Character Integer Long Float Double Primitive classes Primitive classes serve two purposes They contain utility methods that are relevant to that type (eg. Integer.parseInt(string s)) They can be instantiated as a container object When used as a container object, the sole purpose of the class is to contain a single field storing the primitive This allows the primitive to be used as an object Autoboxing is a language level feature where Java will automatically create the object if it is needed

Creating an integer object manually: Integer x = new integer(9); Creating an integer object automatically: Integer x - 9 Behind the scenes java inserts the code newInteger(9)
Programming 2 Page 23

Behind the scenes java inserts the code newInteger(9) Because arrayList can only store objects we must specify a class name for its type, not a primitive type: Wrong arrayList<int>list = new ArrayList<int>(); Right ArrayList<Integer>list = new Array<Integer>(); Once the ArrayList is created Java will automatically do the autoboxing conversion whenever primitive values are inserted into the array or retreving from the array Advantages for autoboxing Allows primitives to be used in collections like ArrayList Disadvantages: Objects use more memory than primitives Primitives are faster then objects because they fit in a CPU register. You should use an array when: The size of the data is known in advance Performance is an issue Memory is an issue ArrayList: When the array size is unknown When the array size can change (up or down) For convenience Java has a for-each loop for looping arrays and arraylists Works like this For(variable: array) { }

Print all values in an array Standard loop String[] colours = {red, green, blue}; for (int i = 0; i < colours.length; i++) { System.out.println(colours[i]); }
For-each loop: String[] colours = {red, green, blue}; for (String colour : colours) { System.out.println(colour); } For-each advantages Less code No need for index variables Readable Disadvantages No access to the index variable, so no idea which position in the array the value is. Print out all elements in a list, putting a blank line after every 10 elements We won't know when the 10th element has been encountered. Da Summary Random Use Random class and 0 seed for testing Files Scanner
Programming 2 Page 24

Scanner Be aware of hasNextLine() and nextLine() behaviour Array resizing arrayList Autoboxing For-each loop

Programming 2 Page 25

Week 6
Wednesday, 31 August 2011 1:01 PM

Characters are stored as numbers Java char type is 16 bits Allows the range of 0-65535 Each number represents a type of character Character encoding is mapping from numbers to characters AscII American Standard Code for Information Interchange Is 7 bits 0 -127

Additional characters required to support international languages Therefore unicode was created 16 bit Allows as much as the java char type It gets bigger in newer versions UTF-8 Dominant character encoding of unicode characters Universal character set Transformaiton Format - 8 bit Java can hold most unicode characters in a 16 bit char type Ones that can't fit make up multiple chars Character codes can be converted to numbers and vice verse through casting Printing out the ASCII table for (int i = 0; i <= 127; i++) { System.out.println(i + : + (char)i); } Java allows characters to be used with the relational operators Eg uppercase characters char c = A; if (c >= 65 && c <= 90) { System.out.println(c + is uppercase.); }

Programming 2 Page 26

Characters can also be compared with character literals char c = A; if (c >= A && c <= Z) { System.out.println(c + is uppercase.); } Lowercase char c = q; if (c >= a && c <= z) { System.out.println(c + is lowercase.); } char c = 5; if (c >= 0 && c <= 9) { System.out.println(c + is a digit.); }

A simple class to represent a person: Class Person { String surname; String firstname; String town; String info; }
Create an instance: Person p = new Person(); Assign values: p.surname="Smith"; p.firstname="John"; p.town="London"; p.info=""; System.out.println(p.firstname + " " + p.surname + ", " + p.town + ". " + p.info); Output John Smith, London. Instance variables don't need to be initialised before use Java automatically initialises instance variables Primitives always have number 0 (booleans will be false) Reference type null Java outputs null if trying to print a null string nullPointerException will be generated if you try to access an instance variable or method of a null reference Instance variables (fields) should be made private to prevent other classes from directly modifying them. Accessing a private variable outside the class produces a compile error

Constructors
Programming 2 Page 27

Constructors Are special methods that run when an instance of the class is created Used to initialise instance variables Can take parameters which can be used to initialise the variables Are public Must have the same name as the class and no return type This is a java keyword that refers to the current instance In the constructor, the parameters and instance variables have the same names If only the variable name is specified, then java will first presume it is referring to a local variable if one exists To refer to the instance variable, the variable name needs to be preceded with this. To access the private variable, move functionality into the person class. The print() method needs to be public A method called getter or accessor can be used to access an individual field A getter method returns the value of the field A getter method name starts with get followed by the field name Mutator methods Used to change private fields Setter method takes a new value as a parameter and assigns it to the field Begins with set Multiple constructors Used to have different parameters Other constructors can be invoked to do preliminary initialisation as long as it is invoked at the start of the constructor

Static Variables Unlike instance variables, static variables are shared between all instances. Can be used to share information between all instances Can be used to generate an id Static variables can be accessed without an instance of the class Need to be preceded with a class name Can also be accessed through instances
The nextID static field is going to be incremented each time a new person is created. Each new person will be given the next largest id Creating a new person instance also results in nextID being incremented Person doesn't have a main method therefore it is not a complete program Can be used by another class that contains a main method Main class contains a main method Main method is static and makes the other methods and variables in the main class also static import java.util.*; public class People { public static void main(String[] args) { // Create a new person Person p = new Person(); // Get persons details Scanner keyboard = new Scanner(System.in); p.setSurname(keyboard.next());
Programming 2 Page 28

p.setSurname(keyboard.next()); p.setFirstname(keyboard.next()); p.setTown(keyboard.next()); p.setInfo(keyboard.nextLine()); // Print person p.print(); } } Files often contain records which can be represented using instances of classes. import java.io.*; import java.util.*; public class BookShelf { private static Book[] books; private static int numBooks; public static void main(String[] args) throws FileNotFoundException { books = new Book[100]; numBooks = 0; readFromFile(books.txt); } } Scanner.useDelimiter() Is a different delimiter can be specified using the use delimiter() function import java.io.*; import java.util.*; public class BookShelf { public static void readFromFile(String path) { Scanner file = new Scanner(new File(path)); file.useDelimiter(,); } } Problems with use.Delimiter Changing the delimiter from whitespace to a comma causes problems cus Scanner no longer treats a new line as a separator between fields A way to fix it is to read each line in its entirety and then use a second scanner to process each individual line

The scanner class allows a string to be passed into its constructor The scanner will then scan the string, rather than the keyboard or a file
Use trim() to fix up the Delimiter() It removes whitespaces from the start and end of a string (not middle) Because useDelimiter() leaves in whitespace nextInt() will generate an error because whitespace is not a number. Instead we will need to read the number in as a word, trim it, and then use Integer.parseInt() to convert to an integer: int year = Integer.parseInt(file.next().trim());

Programming 2 Page 29

Programming 2 Page 30

Midsemester exam
Wednesday, 7 September 2011 12:58 PM

Need to know Scanner Expressions Loops Writing and calling methods Character upper/lowercase testing and conversion Similar to labs

Programming 2 Page 31

Week7
Wednesday, 7 September 2011 12:59 PM

Import java.util.*; Public class TakeInputUsingScanner { Public static void main(string[]args) { Scanner file = new Scanner(newFile("marks.txt")) } } Relation operators == equals too != not equals to > Greater then >= greater then or equal too < less then <=less then or equal too Int value1=1 Int value2=2 If(value1==value2) { System.out.println("value1 == value2"); } If(value1!=value2) { System.out.println("value1 != value2"); } If(value1<=value2) { System.out.println("value1 <= value2"); } && conditional and ||conditional or iteration While(expression) { Statement(s) } For(initialization, termination, increment) { Statement(s) } Comparing characters Char c = 'A' If (c >= 65 && c <= 90) { System.out.println(c+"is uppercase"); } Lowercase and digits Lowercase:
Programming 2 Page 32

Lowercase: Char c = 'q' If(c>= 'a' && c<='z') { System.out.println(c+"is lowercase"); } Char c = '5' If(c>= '0' && c <= '9') { System.out.println(c + "is a digit"); } Calling max(): variables

Programming 2 Page 33

Week 8
Wednesday, 14 September 2011 1:21 PM

Lists and tables are used to display information Jlist can display a list of strings Jtable can display a grid of strings with column names The data for Jlist can be specified as an array of strings JFrame frame = new JFrame("List example"); String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"}; JList list = new JList(data); frame.add(list);

To make them scrollable, put them into a JScrollPane JFrame frame = new JFrame("List example"); String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"}; JList list = new JList(data); JScrollPane listScrollPane = new JScrollPane(list); frame.add(listScrollPane); To change the Jlist data, call setListData(): String*+ data2 = ,Apple, Banana, Orange, Pear-; list.setListData(data2); JTable is used in swing Data can be specified in a 2d array The outer array represents an array of rows The inner array represents the data for each column Example String*+*+ data = , ,AAPL, Apple, $377.48-, ,MSFT, Microsoft, $25.74-, ,ORCL, Oracle, $26.00- }; String*+ columnNames = ,Stock, Company, Price-; JTable table = new JTable(data, columnNames); frame.add(table); Column names are displayed When placed in a JScrollPane Column widths are the same for each column To customise visual aspects setShowGrid(boolean) setShowHorizontalLines(boolean) setShowVerticalLines(boolean) Images can be loaded and displayed using ImageIcon class Jlabels and Jbuttons can display the image that ImageIcon specifies GIF,JPEG, and PNG formats To create and display ImageIcon image = new ImageIcon(Jobs.jpg); JLabel imageLabel = new JLabel(image); frame.add(imageLabel); frame.pack() // sets window size to image size
Programming 2 Page 34

frame.pack() // sets window size to image size Images can't be scaled or resized A JLabel ImageIcon can be changed after the label has been created using setIcon(): ImageIcon image2 = new ImageIcon(Gates.jpg); imageLabel.setIcon(image2); Event handling components Event Source Object This is the object that the event will occur on (eg. JButton) Event Source Registering Method A method provided by the event source object to register a listening object (eg. addActionListener()) Event Listener Object Any object that conforms to the requirements of an event listener Event Listener Method The particular method in the event listener that will be called. Interface public interface Description { String getName(); String getDescription(); }

Implementing the person class class Person implements Description { private String surname; private String firstname; private String town; private String info; ... public String getName() { return firstname + + surname; } public String getDescription() { return info; } }
Interfaces can also be used as types Person p1 = new Person(Smith, John, London, ); Description p2 = new Person(Lincoln, Abe, Washington, ); Book b1 = new Book(The Art of Computer Programming, Donald E. Knuth, 1962); Description b2 = new Book(The C Programming Language, Kernighan and Ritchie, 1978); Also as arrays Description*+ d = new Description*10+; d*0+ = new Person(Smith, John, London, ); d*1+ = new Person(Lincoln, Abe, Washington, ); d*2+ = new Book(The Art of Computer Programming, Donald E. Knuth, 1962); d*3+ = new Book(The C Programming Language, Kernighan and Ritchie, 1978); Accessing an array of interface objects for (int i = 0; i < d.length; i++) , if (d*i+ != null) , System.out.println(Name: + d*i+.getName());
Programming 2 Page 35

for (int i = 0; i < d.length; i++) , if (d*i+ != null) , System.out.println(Name: + d*i+.getName()); System.out.println(Description: + d*i+.getDescription()); - For event listeners java.awt.event For multiple buttons (using super and subclasses) public class FileListFrame extends JFrame implements ActionListener { private JButton viewButton = new JButton(View Image); private JButton deleteButton = new JButton(Delete); public FileListFrame() { ... viewButton.addActionListener(this); deleteButton.addActionListener(this); ... } public void actionPerformed(ActionEvent e) { if (e.getSource() == viewButton) { viewSelectedImage(); } else if (e.getSource() == deleteButton) {...} } }

Programming 2 Page 36

Week 9
Wednesday, 21 September 2011 11:08 AM

A program can do one of four things when dealing with an error Ignore the error Quietly handle the error Display the error to the user or in a log Display the error to the user and allow the user to choose the best action to take Errors used to be communicated through return values public int setVal(int pos, double val) { if (pos >= 0 && pos < this.data.length) { this.data[pos] = val; return 0; } else { // Index is out of range, return -1 return -1; } } Problems show up when functions also uses the return value to return valid information. Special values can indicate errors, like negative numbers or null. Additionally the function can not communicate detailed information to the calling method (aka the name of the file currently being accessed. It's possible that the error can occure deep in the call stack, which may then need to propagate to the top before it can be handled. This then requires all methods in the call stack to have the capability to handle and return the error For handling error codes int error = openFile(); if (error != -1) { error = readPerson(); if (error != -1) { error = addToDatabase(); if (error != -1) { displayMessage(); } } } The purpose of exceptions is to remove error handling from the main flow of the program. The result is usually more readable and manageable code Java has 2 types of exceptions Checked and unchecked Check exceptions must be handled with either a try..catch statement or a throws statement in the method header
Programming 2 Page 37

method header Unchecked exceptions are common and don't require handling
Throwable is the superclass of both error and exception subclasses The error class is used for serious errors that should not be handled Like out of memory error Errors should not be caught Subclasses of runtimeException are unchecked exceptions Runtime exceptions are exceptions that could occur in common code Examples are ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException ArithmeticException NullPointerException Exceptions can be caught using the try...catch statement try { // Code that can cause the exception } catch (ExceptionClass variableName) { // Code to handle the exception } // Additional exceptions can be caught The code within the try block must be able to generate the exceptions specified in the catch blocks When an exception occurs, the code stops executing at that point and either finds the first matching catch handler in the method or, propagates to the calling method Subclasses of exception which are not subclasses of runtime exception are checked exceptions, which must be explicitly thrown or caught, in not, a compile error will be generated. Throws If a method is not able to deal with the exception, it can declare in the method header that the exception is thrown Finally A try statement can have an optional clause following the catch clauses designated by the reserved word finally. The statements in the finally blocked are always executed. If no exceptions are generated, the statements in the finally clause are executed after the statements in the try block complete. If one is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete.

Exception objects Using exceptions is that the objects can contain extra information about the exception that has occurred
Java has two ways to create your own exceptions Using the existing exception class Creating a subclass of exception Exception class can be instantiated directly Exception e = new Exception(A custom exception.);
Programming 2 Page 38

Exception e = new Exception(A custom exception.); throw e; Writing to files The PrintWriter class can be used to write to a file in java It provides the same print()/println() methods as system.out The constructor makes a string which is the path to the file The PrintWriter should be closed after writing to the file.

Programming 2 Page 39

Week 10
Wednesday, 5 October 2011 1:00 PM

Inheritance allows code to be reused by allowing a subclass to extend the functionality of another class A class can have many subclasses, but only one superclass Extends keyword is used to specify that a class is a subclass of another class Aka Public class Horse extends Mammal Inheritance relationships are is-a relationships Example Horse is-a mammal Very top of java inheritance hierarchy is the Object class Is default if no superclass is specified Following are equivalent Public class MyClass { } Public class MyClass extends Object { } Contains two types of methods Thread synchronisation methods (don't worry about right now) Methods designed to be overridden by subclasses An instance of a subclass can be assigned to a variable with a type of superclass Mammal m1 = new Horse(); An instance of Horse can be assigned to a variable of type Mammal, cus a Horse is-a mammal. An instance of a superclass can't be assigned to a variable of the type of subclass The following would compile an error Horse h1 = new Animal(); An animal is not a Horse Lets define a method Animal - move() Bird - fly() All subclasses of animals can also move() All subclasses of bird can also fly() Animal a1 = new Bird(); A1.fly(); Compile error: the compiler only knows that a1 is an animal, since that is the variable type Animal a1 = new Bird(); A1.move(); Compiles cus move () is a method of Animal
Programming 2 Page 40

Compiles cus move () is a method of Animal Methods defined in a superclass can be overridden by a subclass Example of overriding toString(): Public class MyClass extends Object { Public String toString() { Return "A string!"; } } The method must have the same signature, that is, same name, parameters, and return type The overridden method must also have the same visibility modifier Therefore a public method can't be overriden by a private method, it'll make a compile error. Overriding example Object obj1 = new MyClass(); System.out.println(obj1.toString()); Often it's useful to also call the superclass's method since the subclass may be extending its behaviour.

public class MyClass extends Object { public String toString() { return A string! + super.toString(); } }
Instance methods can be declared final, which prevents subclasses from overriding them. public class MyClass extends Object { public final String toString() { return A string! + super.toString(); } } Instance variables can be overriden, however it's very confusing and should be avoided Object overriding is when a subclass declares the same method as the superclass Method overloading is when a method in the same class declares a method with the same name as an existing method but with different parameter types. public class BankAccount { protected double balance; protected double interestRate; public BankAccount(double balance, double interestRate) { this.balance = balance; this.interestRate = interestRate;
Programming 2 Page 41

this.interestRate = interestRate; } // Applies interest rate to balance and returns new // balance public double calculateInterest(int months) { return 0; } } Abstract classes Java allows a method to be declared with no body as an abstract method Classes that contain abstract methods are abstract classes, and cannot be instantiated. public abstract class BankAccount { protected double balance; protected double interestRate; public BankAccount(double balance, double interestRate) { this.balance = balance; this.interestRate = interestRate; } // Applies interest rate to balance and returns new // balance public abstract double calculateInterest(int months); } (assignment start with a uml diagram) Jpanel class is also a container, but it can be used in any layout. Layout can be specified by JPanel during creation A Jpanel with its own border layout: Jpanel panel = new Jpanel(new BorderLayour()); Panel.add(new Jlabel("Title"), BorderLayout.NORTH); Frame.add(panel); Using borders Any Jcomponent can have a border applied using the setBorder() method Border is an interface which has many implementations defined in the javax.swing.border package Some of these include EmptyBorder MatteBorder SoftBevelBorder Empty border's make borders that are the same colour as the background EmptyBorder emptyBorder = new EmptyBorder(10,10,10,10); Panel.setBorder(emptyBorder); Colours Colours are specified using the color class. Found in the java.awt package Colour values are represented using red, green, blue, and alpha components
Programming 2 Page 42

Colour values are represented using red, green, blue, and alpha components Component values can be specified as intergers (0-255) or floats(0-1.0)

Color red = new Color(255,0,0); Color green = new Color(0,255,0); Color blue = new Color(0,0,255); Color alsoRed = new Color(1.0, 0, 0); Color alsoGreen = new Color(0x00FF00);

Color semiTransparentGreen = new Color(0,1.0,0,0.5);


Color constants Color. RED GREEN BLUE BLACK WHITE GRAY Jcomponent supports two methods that take color objects as parameters, setBackground() and setForeground(): Panel.setBackground(Color.WHITE); Panel.setForeground(Color.DARK_GRAY); The font class in the java.awt package is used to represent fonts To create a font object you will need the name, style, and size of the font System font constants Font. DIALOG DIALOG_INPUT MONOSPACED SANS_SERIF SERIF Java supports the following styles Font. BOLD ITALIC PLAIN These can be combined Font.BOLD | Font.ITALIC
Programming 2 Page 43

Font.BOLD | Font.ITALIC Font can be set for any Jcomponent using the setFont() method Jlabel title = new Jlabel("a Title"); Title.setFont(new Font(Font.Dialog, Font.BOLD, 24)); For the assignment Borders and custom font will be needed, and custom colors

Programming 2 Page 44

Quiz stuff
Thursday, 13 October 2011 11:14 AM

encapsulation
Feedba ck: Encapsulation is the object-oriented principle that specifies that an objects data should be guarded from inappropriate access. Therefore choice a is correct. Inheritance and polymorphism are features of object-oriented programming that allow for class flexibility and re-use. Instance variables and methods play important roles in object-oriented programming, but are not fundamental principles. 1 out of 1 points When applied to instance variables, the ________________ visibility modifier enforces encapsulation. Selected Answer: private

Questi on 2

Feedbac The private visibility modifier guards against inappropriate data access, and k: therefore promotes encapsulation. Choices a and b are not visibility modifiers, and choice c is a visibility modifier that allows public access to an objects data, which violates the principle of encapsulation.

Questio n3

1 out of 1 points
Which of the following types of methods do not have any return type (not even a void return type)? Selected Answer: constructors

Feedbac Constructors are the only methods that do not have any return type. They do not k: even have a void return type. All of the other methods must specify a return type or be declared as void.

Questi on 4

1 out of 1 points Which of the following method headers is most likely a header for a mutator method? Selected Answer: Feedba ck:

public void setAge(int newAge)

Mutators are methods that change the value of an instance variable, and are often referred to as setters. Therefore, choice d is the correct answer. Choice a is an example of a header for a accessor method, often referred to as a getter. Choice c is a constructor, and choice b is a class method.

Questi on 5
A _______________ variable is shared among all instances of a class.

1 out of 1 points

Selected Answer:

static

Feedbac A static variable is shared among all instances of a class. A final variable is a k:

Programming 2 Page 45

k:

A static variable is shared among all instances of a class. A final variable is a constant, a public variable is one that is accessible from outside the object and a private variable is one that cannot be accessed outside of the object.

Question 6

1 out of 1 points __________________ parameters are the values that are used when calling a method. Selected Answer:

actual

Feedback Actual parameters are sent in when calling a method. Formal parameters are : used when defining a method.

Questio n7

1 out of 1 points The ________________ reference always refers to the currently executing object. Selected Answer:

this

Feedbac The this reference always refers to the currently executing object. A nullreference k: is a reference that is not pointing to any object. The other three choices are not special references in Java.

Questi on 8

1 out of 1 points

A method that has multiple definitions is an __________________ method.


Selected Answer: Feedba ck:

overloaded

A method that has multiple definitions is an overloaded method. The versions of an overloaded method are distinguished by the number, type and order of their parameters. Overridden methods are methods that have been redefined later in an inheritance hierarchy. They will be studied in more detail later. Choice c and d are not types of methods in Java.

Questi on 9 A(n) ________________ is a step-by-step process for solving a problem. Selected Answer:

1 out of 1 points

algorithm

Feedbac An algorithm is a step-by-step solution for solving a problem. A UML diagram is a k: way of visually representing how classes and objects interact. An aggregate object is an object that is composed, in part, of other objects. A class can be thought of as a blueprint for a set of objects.

Questi on 10

1 out of 1 points All methods (with the exception of constructors) must specify a return type. What is the return type for a method that does not return any values? Selected Answer: void

Programming 2 Page 46

Selected Answer:

void

Feedbac Methods that do not need to return any data should have void specified as the k: return type. A method cannot have public specified as its return type, so choice b is incorrect. Choice a and choice c specify a return type, and therefore they must return data of that type.

Question 11

1 out of 1 points

Methods that can be called directly through the class name and do not need to have an object instantiated are called _________________.
Selected Answer: static

Feedbac Methods that can be called directly through the class name must be declared k: as static. Choice b and choice d are visibility modifiers for a method. Methods declared as final cannot be overridden. Question 12 1 out of 1 points If a service is so complex that it cannot be reasonably be implemented using one method, it is often helpful to decompose it to make use of ________________ support methods. Selected Answer: Feedbac k: private

Private support methods are useful when a service is too complex to be defined in a single method. Therefore choice d is correct.

Questio n 13

1 out of 1 points The versions of an overloaded method are distinguished by ___________________________. Selected Answer:

the number, type and order of their parameters

Feedbac Overloaded methods are two methods in the same class that have the same k: identifier, but a different number, type or order of parameters. Therefore, choice a is correct and the rest are incorrect.

Nayan
Question 1 In Java, array indexes always begin at ________________. Selected Answer: 1 out of 1 points

Feedback: In Java, the array indexes are from 0 to one less than the length of the array.

Questio n2

1 out of 1 points (Extra credit) Which of the following statements best describes this line of code? int[] numbers = new int[50]; Selected Answer: this is the declaration and initialization of an array that Programming 2 Page 47

holds 50 integers
Feedbac The code represents the declaration and initialization of an array k: that will hold 50 integers. The indexes of this array will begin at 0 and end at 49.

Question 3

1 out of 1 points Which of the statements is true about the following code snippet? int[] array = new int[25]; array[25] = 2; Selected Answer: This code will result in a run-time error.

Feedbac This code will throw anArrayIndexOutOfBoundsException, since the k: last index in this array will be 24. This causes a run-time error.

Questio n4 What will be the output of the following code snippet? int[] array = new int[25]; System.out.println(array.length); Selected Answer: 25

1 out of 1 points

Feedbac Note that the length instance variable can be accessed k: directly. Therefore this will not result in any errors. The array has length 25, and therefore the code will output 25.

Questio n5 Which of the following array declarations are invalid? Selected Answer:

1 out of 1 points

all of the above are valid


Feedbac All three of these are valid array declarations. Choice b uses an k: alternate syntax. Choice c uses an initializer list to initialize the array.

Questio n6 Which of the following is a true statement? Selected Answer:

1 out of 1 points

Arrays are passed as parameters to methods like object types.

Feedbac Arrays are passed to methods by reference. This means that if the k: content of the array is changed in a method, the change will be reflected in the calling method

Programming 2 Page 48

Questi on 7

0 out of 1 points Suppose we have an array of String objects identified by the variable names. Which of the following for loops will not correctly process each element in the array. Selected Answer: for(String name : names) all of these will correctly process each element

Questio n8

1 out of 1 points Which of the following statements will assign the first command-line argument sent into a Java program to a variable called argument? Selected Answer: argument = args[0];

Feedbac Choice d is the correct answer. The Systemobject does not have any k: methods calledgetFirstArgument or getArgument, and the argsarray's index starts at 0. Therefore the other choices are incorrect.

Questi on 9

1 out of 1 points Which of the following method declarations correctly defines a method with a variable length parameter list?

Selected Answer:
Feedba ck:

public int average(int ... list)

The only choices with valid syntax are choice a and choice b. Choice a represents a method declaration with a single parameter, which is a reference to an array. Choice b correctly represents a valid declaration for a method with a variable length parameter list.

Questio n 10

1 out of 1 points

Which of the following is a valid declaration for a two-dimensional array?


Selected Answer:

int[][] matrix;

Feedbac Choice a is the only valid declaration for a two-dimensional k: array. Choices b and c contain invalid Java syntax, and choice d is a valid declaration for a single dimensional array.

Questio n 11

1 out of 1 points Which of the following lines of code accesses the second element of the first array in a two-dimensional array of integers,numbers, and stores the result in a variable called num? Selected Answer: num = numbers[0][1];

Feedbac Choice b accesses the second element of the first array. Choice a k: accesses the third element of the second array. Choices c and d do not represent valid Java syntax

Programming 2 Page 49

Question 12

0 out of 1 points Which of the following are true about two-dimensional arrays? Selected Answer:

Two-dimensional integer arrays cannot be initialized via an initializer list.

Question 13

1 out of 1 points What is the precedence of the index operator ( [ ] ) relative to other operators in Java? Selected Answer: It has the highest precedence of all Java operators.

Feedback The index operator has the highest precedence of all Java : operators.

Question 14

1 out of 1 points Every Java array is a(n) _________________, so it is possible to use a foreach loop to process each element in the array. Selected Answer: Feedbac k:

iterator

Every Java array is an iterator, therefore a foreach loop can be used to process each element in the array.

Programming 2 Page 50

Week 11
Monday, 17 October 2011 2:18 PM

Collections Framework A number of classes for dealing with collections of objects A collections object is commonly used to replace an array The advantages of collections Reduces the programmming effort Increases performance Provides interoperability between unrelated APIs Reduces the effort required to learn APIs Reduces the effort required to design and implement APIs Fosters software reuse. Collection types The collections framework supports a number of collection types, including: A generic collection interface Lists Sets Maps Queues Most of the collection classes implement the collection interface The collection interface provides the following methods: Add(E element) Clear() Boolean contains(Object o) Remove(Object o) Int size() Object[] toArray() And other methods Lists List classes implement the list interface The list interface extends the collection interface Ordered collection also known as a sequence Duplicates are generally permitted Allows positional access List interface The list interface provides the additional methods for positional access Add(int index, E element) E get(int index) Int indexOf(Object o) E remove(int index) List<E>sublist(int fromIndex, int toIndex) List implementations The collections framework provides two classes that implement the list interface: ArrayList LinkedList ArrayList and LinkedList use different mechanisms for storing data, resulting in different performance characteristics.
Programming 2 Page 51

performance characteristics.
ArrayList The ArrayList class represents a List of objects using an array An Arraylist is very fast to lookup an object at an index as it is a simple array lookup. Removing from an ArrayList is slow since the elements following the removed element must be moved up one location An ArrayList will dynamically resize as items are added, resizing the array may be slow as all of the existing elements must be copied to the new array. ArrayList Example ArrayList list = new ArrayList(); list.add("Hello"); list.add("Jackass!");

Items can be retrieved at a location using the get(int index) method. Since ArrayList is a generic class, it doesn't know what type of object the elements will be. As a result the compiler only knows that the value returned from get() is an instance of the object class. Getting and casting ArrayList list = new ArrayList(); list.add("Hello"); list.add("Jackass"); String firstWord = (String)list.get(0); Parameterised Types Parameterised types allow the code using the class to determine what subtype the class is using. public class MyClass<subtype> { private Subtype data; public MyClass(Subtype data) { this.data = data; } public Subtype getData() { return data; } } since <String> is specified as the subtype, anywhere in the class definition where subtype occurs is now effectively replaced with String, allowing the compiler to handle the following code without errors: MyClass<String> m = new MyClass<String>("Hello Jackass!"); String message = m.getData(); Subtypes have the advantage of reducing runtime errors since the types can be checked at compile time.

ArrayList<String> list = new ArrayList<String>(); list.add(Hello); list.add(Jackass!); String firstWord = list.get(0);

Programming 2 Page 52

A Linked List represents a list as a series of objects linked together. There is no array In Java, LinkedList is doubly linked. to access an object at an index, the entire list must be traversed. A LinkedList node can be seen as a class with a reference to data and also a reference to the previous and next nodes: public class linkedListNode<E> { private E data; private LinkedListNode<E>previous next; } Using LinkedList is identical to ArrayList as they both implement the List interface: LinkedList<String> list = new LinkedList<String>(); list.add(Hello); list.add(Jackass!); String firstWord = list.get(0); ArrayList vs LinkedList Array is faster to acces an index LinkedList must traverse the list Linked list is faster to delete an item ArrayList must shift elements after the deletion index. Linked List is faster to grow ArrayList must create a new array and copy existing elements LinkedList is faster to insert ArrayList must shift all elements after the insertion index It is generally good practise to define variables using the type of the List interface This reduces the dependence on a particular implementation of List, and allows it to be easily changed at a later date: This reduces the dependence on a particular implementation of List, and allows it to be easily changed at a later date:

List<String> list = new LinkedList<String>(); list.add(Hello); list.add(World!!); String firstWord = list.get(0);

Iterating through lists the number of elements in a list can be retrieved using the size() method: List<String> list = new LinkedList<String>(); list.add(Hello); list.add(Jackass!); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }

The Java For-each loop can also be used with lists:


List<String> list = new LinkedList<String>(); list.add(Hello); list.add(Jackass!);
Programming 2 Page 53

list.add(Jackass!); for (String s: list) { System.out.println(s); } A set is a collection of elements which contains no duplicates. the set may or may not be ordered. A set is generally used to determine if an item is in the set or not Sets generally used to determine if an item is in the set or not Sets generally have an optimised lookup algorithm for the boolean contains(Object o) method

Java has 3 set implementations TreeSet - ordered HashSet - unordered


A treeSet stores items in a tree structure according to their natural order Navigating through a tree is generally very efficient compared to searching the list linearly Time complexity the time for an algorithm it complete HashSet uses a different storage mechanism to a TreeSet and as a result doesn't retain the ordering of elements. Every java object has a unique hash value the hash value is used to efficiently store items in a lookup table if two objects hash to the same location then a list of objects will be stored at the location. count the number of unique words in a file: Set<String> words = new TreeSet<String>(); Scanner file = new Scanner(new File(input.txt)); while (file.hasNext()) { String word = file.next(); words.add(word); } file.close(); System.out.println(Unique words: + words.size()); A Map is similar to a set in that it contains unique keys. however it also contains a mapping between a key and a value. Every key has exactly one value. java has 2 types tree map - ordered hasmap - unordered

Programming 2 Page 54

Week 12
Wednesday, 19 October 2011 12:54 PM

Programming 2 Page 55

Das könnte Ihnen auch gefallen