programming 2

55
Week 1 Col Clark [email protected] Objects are used to break big chunks of code into smaller, more manageable pieces Week 1 Friday, 5 August 2011 10:12 AM Programming 2 Page 1

Upload: nathan

Post on 16-Oct-2014

621 views

Category:

Documents


14 download

TRANSCRIPT

Page 1: Programming 2

Week 1Col [email protected]

Objects are used to break big chunks of code into smaller, more manageable pieces

Week 1Friday, 5 August 201110:12 AM

Programming 2 Page 1

Page 2: Programming 2

Week 2Import tells the computer what tools will be neededClasses are organised into packagesPackages group related classes togetherClasses group related methods togetherMethods group related statements together

Java.lang.Math.sqrt()

Java is the packageLang is the package as wellMath is the classSqrt() is the method

Why use packagesEasy to find and manage classesJava has security modifiers that work on package levelsCompiler compiles quicker with less stuff to search for.

Most common packagesJava.lang (imported by default)MathStringSystemJava.utilScannerRandomJava.ioFile* is import everything

All executed code needs to be in a method of some kindAll java programs require a main methodMain method is the entrypoint(runs through first)

Why use methods?Allows us to break codes into smaller portions, makes life easierEasy reuseServes as an entry point for an event driven codeMakes 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 togetherLarger problems can be divided into smaller simpler problemsSmaller problems can then be passed on to othersCode becomes self-documenting through readable method names

Week 2Friday, 5 August 201110:12 AM

Programming 2 Page 2

Page 3: Programming 2

Three things to do while writing a methodDetermine the method headerWrite the body of the methodCall the method

Three things needed to write a methodReturn typeMethod nameParameter typesCollectively 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 othersStatic: will be static until otherwiseVoid: return typeMain: method nameString[] 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 supportedOnly one value is returned (is supported) (an array can bring back moar)

Return statement is used to return a value from a methodReturn value must have a data type compatible with the return type of the methodWhen the return statement is uncounted, method exits immediately

If a method doesn’t return a value, it returns voidVoid methods can have return statements, but can’t return values

Non void methods must have a return statementCalling 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 typesWhen a method is called using primitive values, the values copied into the parametersWhen 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 variablesWhen an array is assigned to another variable, the reference is copied ,not the actual values of the array

Java doesn’t support multiple return valuesCan be necessary sometimesOne way to return multiple values is via arrays, aint pretty, but it works

Putting written code into a separate method, is called refactoringMethod names can’t have any punctuation except for $ and _Also can’t start with digitsCan’t contain another methodMust be placed directly within a class

Programming 2 Page 3

Page 4: Programming 2

Class Names must begin with a capital letterMethods should begin with a lowercaseMixed case…no idea wtf

General method size should fit on the screen, if larger, should be dividedThere are some exceptions

Formal ArgumentsParameters in the method headerInt countStrings(String s, String search)Actual parametersExpressions passed to the methodInt count = countStrings(name, “cat”);

Can methods have the same name? YESMulti methods with the same name is known as method overloadingCan 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? NoCan methods only differ by the return type? NoJava doesn’t 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 callMethod signatures doen’t include the parameter namesMethod signature does include the return type, however the return type doesn’t determine which method is called therefore methods that differ only by the return type will produce a compile error

Programming 2 Page 4

Page 5: Programming 2

Java's API for graphical user interfaces is called SwingAll of the swing classes are in the Javax.swing packageYou 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 windowsMessage Dialog - displays messagesConfirm Dialog - gives user choice of buttons to clickInput Dialog - allows user to type in a string

Using JOptionPaneJOptionPane can be instantiated and various option set before displaying the dialog.However Java provides a simpler one line approach using static methodsJOptionPane.showMessageDialog(…)JOptionPane.showConfirmDialgo(…)JOptionPane.showInputDialog(…)

Displaying a MessageThe header for showMessageDialog() is:

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.

The first parameter would be the window that the dialog is being displayed in front of.

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_MESSAGEJOptionPane.INFORMATION_MESSAGEJOptionPane.WARNING_MESSAGEJOptionPane.QUESTION_MESSAGEJOptionPane.PLAIN_MESSAGE

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

Confirm DialogConfirm Dialog is used to display a message that has a group of options to respond too.ExampleDelete a file?Yes No

Week 3Wednesday, 10 August 201112:59 PM

Programming 2 Page 5

Page 6: Programming 2

Yes No

showConfirmDialog

showConfirmDialog returns an int indicating what button was pressedJOptionPane defines the following constants to determine which button the int refers to:

JOptionPane.YES_OPTIONJOptionPane.NO_OPTIONJOptionPane.CANCEL_OPTIONJOptionPane.OK_OPTIONJOptionPane.CLOSED_OPTION

ExampleInt 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 statementJava provides the different switch statement when one variable needs to be compared with different values

switch (variable){case value1:statementsbreak;(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:statementsbreak;case value3:statementsbreak;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 switchStatements}

JOptionPane and switchswitch (buttonPressed){case JOptionPane.YES_BUTTON:…break;case JOptionPane.NO_BUTTON:…

Programming 2 Page 6

Page 7: Programming 2

…break;case JOptionPane.CANCEL_BUTTON:…break;}

Default statement is optional

SwitchThe 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 optionsAn optionType can be passed to showConfirmDialog

The optionType can be one of:JOptionPane.DEFAULT_OPTIONJOptionPane.YES_NO_OPTIONJOptionPane.YES_NO_CANCEL_OPTIONJOptionPane.OK_CANCEL_OPTION

Input DialogThe input dialog allows users to enter a string

JOptionPane.showInputDialog(null, “Enter your favorite saying”);

showInputDialog() returns the string the user enteredIf 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 ValuesSayings[] options = {"Legendary!", "Whatever", "Awesome!"};

Sayings choice = JOptionPane.showInputDialog(null, "Select a

favorite saying", "Sayings", JOptionPane.PLAIN_MESSAGE, null,

Sayings, "Whatever");

Entering NumbersshowInputDialog() always returns a stringIf the user enters a number, it needs to be converted into a destination type

Programming 2 Page 7

Page 8: Programming 2

If the user enters a number, it needs to be converted into a destination typeJava provides the following static methods to convert strings to primitive typesInteger.parseInt(String s)Double.parseDouble(String s)there are also versions for float, long, short, etc.

Number exampleString numberString = JOptionPane.showInputDialog(null, “Enter your age”);int number = Integer.parseInt(numberString);If anything but an int Is entered, it will exit with NumberFormatException

SummaryJoptionPane is a simple way to interact with a user using a GUI but without preforming a lot of tasks usually associated with GUIsMost 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 ProgrammingProgramming using ObjectsObjects encapsulates data and methodsClass VariablesVariables are allowed to be declared outside methods in the class.Class variables must be declared staticClass variables exist for the lifetime of the programLocal variables exist for the lifetime of the methodGlobal variables exist for the lifetime of the programThere is only ever one instance or copy of each class variableFor example, there is only one x variable in the life time of the program

Data StructuresCan group together related variables togetherIn Pascal, called RecordsIn C they're called struts

The data and methods are encapsulated into one structure called classWhen we define a new data structure, which in java is a class, it is now also a type.Therefore Student is now a typeThe 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 StudentAdditional 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-StaticWhen 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

Page 9: Programming 2

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

Creating a Class InstanceTo 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 objectClass variables are static variablesNon-static variables can be called by the following names:instance variablesobject variablesfieldsthis is the official Java term, but not used by other languages.propertiesattributesMethods and fields are both members of an object.

Classes vs ObjectsUsing 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();

ExampleStudent s = new Student();

Anything within an object can be accessed with a dotvariableName.fieldName

ExampleStudent s = new Student();

s.sNumber = "s2799700";

s.firstName = "Nathan";

s.lastName = "Clark";

s.email = "[email protected]";

System.out.println(s.firstName+" "s.lastName);

Visibility modifier determines whether the member can be accessed outside of the class3 levelsPrivate, protected, public

Private: Access modifier restricts access to the member to within the current class.Only methods of the current class can access private membersProtected: can be accessed by methods in current class, and also other classes within the same package (protected is default)PublicMembers 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

Page 10: Programming 2

classes.

Why private?So classes can't directly modify them

Instance methodsStatic methods can't access instance fieldsInstance methods can access instance fields

Methods + Data = objects

Programming 2 Page 10

Page 11: Programming 2

Java is an Object Oriented LanguageIn Java, an identifier that is made up by the programmer can consist of numbers, letters, undersores, and the dollor signA syntax error is a compile-time errorWhich of the following is not one of the four basic software development activities? Preliminary practice codingIn order for a program to run on a computer, it must be expressed in a machine languageSoftware requirements specify what a program should accomplishThe methods of an object define it define its potential behaviorsWhich 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 bytecodeWhich 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 aboveA parameter is a piece of data that we send to a methodWhich 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? 14Which of the following is not an arithmetic operation in JavaThese are all arithmetic operations in JavaIn order to make a variable a constant which modifier must be included in its declaration? FinalWhich 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 expressionResult = 15 % 4;What value stored in result after this line is executed?3Which 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 3025Information is most likely to be lost in what kind of data conversion? A narrowing conversionWhich of the following is an invalid way to instantiate a string object? All of the above were valid.

Question 1

1 out of 1 points

The ________________ operator is used to instantiate an object.

Selected Answer: new

Feedback:

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

HomeworkThursday, 11 August 20114:21 PM

Programming 2 Page 11

Page 12: Programming 2

Question 2

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

1 out of 1 points

Consider the following snippet of code:

Random generator = new Random();int randNum = generator.nextInt(20) + 1;

Which of the following will be true after these lines are executed?

Selected Answer:

randNum will hold a number between 1 and 20 inclusive.

Feedback:

When called with a parameter of 20, the nextInt() method will return an integer 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.

Question 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.

Feedback:

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

Question 6

1 out of 1 points

Which of the following best describes this code snippet?

System.out.println(“Hello World!”);if (count != 400)

Selected Answer:

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

Page 13: Programming 2

Feedback:

The != operator means is not equal to. Therefore if the variable count is not equal 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)

Question 10

1 out of 1 points

Which of the following logical operators has the highest precedence?

Selected Answer: !

Feedback:

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

Question 1

1 out of 1 points

A _______________ loop always executes its loop body at least once.

Selected Answer: do

Feedback:

The do loop always executes its loop body at least once. Both a for loop and 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

Page 14: Programming 2

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

Selected Answer: stop

Question 3

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

Question 4

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++)

Feedback:

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

Question 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: if(stringOne.equals(stringTwo))

Feedback:

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

1 out of 1 points

An infinite loop is a compile-time error.

Selected Answer:False

Feedback:

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

Question 7

1 out of 1 points

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

Selected Answer:False

Feedback:

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

Programming 2 Page 14

Page 15: Programming 2

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.

Question 9

1 out of 1 points

It is possible to implement a switch statement using if statements.

Selected Answer:True

Feedback:

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

Programming 2 Page 15

Page 16: Programming 2

Unified modelling LanguageUML 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 sectionsClass name, attributes, methods

Class name: Course

Students:String[]

Labs:Lab[]

Attributes: corseCode:String

Methods:If a class refers to another in some way, it has a relationship with the classUML defines several types of relationships

UML instance relationships are called associationsAn 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 notationLower limit .. Upper limitEg zero or many:0..Zero or 1: 0..1

Week 4Thursday, 18 August 201112:59 PM

Programming 2 Page 16

Page 17: Programming 2

InheritanceSeveral classes share a common functionalitySuper classes can be extracted like a method

Java has 2 APIs for generating random numbersMath.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.8484What if we want a random number between 1 and 10?1-10Math.random() x 10 + 1

You can extend the range by multiplicationDouble number = Math.random() * 10;

The result is that the random numbers will now extend from 0 to 10Now we need our numbers to be wholeWe can convert the numbers to whole numbers by casting to an intCasting involves putting the destination type within parentheses in front of the value to be

Programming 2 Page 17

Page 18: Programming 2

Int number = (int)(Math.random()*10);

Casting involves putting the destination type within parentheses in front of the value to be converted:

Int number = (int)(Math.random()*10)+1;

For numbers from 1 - 10, simply add + 1

The random class in in the java.util packageAn instance of random is required before it can be usedRandom random = new Random();

Return a random whole number between 0 and maxInt nextInt(int max)

Double nextDouble()

Returns a number between 0 and 1Identical to Math.random

To generate a random number between 1 and 10Random random = new Random();

Int number = random.nextInt(10)+1;

Random charactersJava can't generate random characters or strings, however we can map random numbers to character strings

Randomly select a color: red, green or blueRandom 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 RandomTesting 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 testedString[] colours = {“red”, “green”, “blue”};

Random random = new Random(0);

Programming 2 Page 18

Page 19: Programming 2

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

Page 20: Programming 2

A File class is used to represent files and directories.Creating a File Object doesn't create a fileThe 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

Tests to see if the file existsBoolean exists()

Gets the name of the file represented by the pathString getName()

Gets the name of the directory containing the fileString getParent

File length in bytesLong length()

A file objective can also represent a directory

Returns true if this is a file, not a directoryBoolean isFile()

Returns true if this is a directory, not a fileBoolean isDirectory()

Returns an array of file names in this directoryString[]list()

Creates the directory if it doesn't exist.Boolean mkdir()

Reading from a FileThe 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 fileScanner file = new scanner(new File("Test.txt"));Counting all the lines in a file

Week 5Wednesday, 24 August 20111:02 PM

Programming 2 Page 20

Page 21: Programming 2

Counting all the lines in a fileScanner file = new Scanner(new File(“Test.txt”));

int numLines = 0;

while (file.hasNextLine())

{

String line = file.nextLine();

numLines++;

}

System.out.println(numLines); file.close();

ScannerUses the same files as it is with the keyboardAll the existing Scanner methods work the sameNext()nextInt()nextDouble()nextLine()

ExceptionsAn 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 thrownAt this stage of the course, we are not going to catch(process) exceptions

ThrowsIf 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 itpublic 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 lockedEgFile.close();

Determining the end of the fileScanner has a number of has methods that indicate whether there is more data of the specified type to be read:

There is another word that can be readBoolean hasNext()

There is an entire line that can be readBoolean hasNextLine()

There is a whole number to be readBoolean hasNextInt()

There is a double that can be readBoolean hasNextDouble()

Reading from file examplepublic static void main(String[] args) throws FileNotFoundException

{ Scanner file = new Scanner(new File(“Marks.txt”));

Programming 2 Page 21

Page 22: Programming 2

{ 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() CautionNext() nextInt() nextDouble() don't consume the newline characters

Reading into an arrayWhen reading from a file we may not know in advance how many values there are.

There are several approaches to dealing with thisCreating an array that is much larger then is neededRead the file twice,, the first read determines how many entries, but doesn't store anyCreate 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

Having a fixed large array is the simplest solution, however it may break if a file is larger, also it wastes memory

Fixed-size large array

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.

Read the file twice

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.

Resizing the array

Java does provide an arrayList class which provides resizable array functionalityTo create oneArrayList a = new ArrayList();

Parameterised typesAn ArrayList stores generic objects by defaultWe can specify exactly what type of object using paramerised types which are specifically <>

ArrayList<String> a = new ArrayList<String>();An ArrayList of strings:

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 arrayE get(int index)

Programming 2 Page 22

Page 23: Programming 2

E get(int index)Returns the object to indexBoolean remove(object o)E set(int index, E e)Replaces element at index with eInt size()Returns the number of elements in the list

Adding in an element

arrayList<String> a = new ArrayList<String>();a.add("A String");

Creating an ArrayList of Strings and adding an element:

Initial size of the array doesn't need to be specifiedIndex 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 PrimitivesArrayList can only store objects

Autoboxing - converting primitives into objectsJava has a class for each primitive type in the java.lang packageBooleanCharacterIntegerLongFloatDouble

Primitive classes

They contain utility methods that are relevant to that type (eg. Integer.parseInt(string s))They can be instantiated as a container object

Primitive classes serve two purposes

When used as a container object, the sole purpose of the class is to contain a single field storing the primitiveThis 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

Integer x = new integer(9);Creating an integer object manually:

Creating an integer object automatically:Integer x - 9Behind the scenes java inserts the code newInteger(9)

Programming 2 Page 23

Page 24: Programming 2

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:

arrayList<int>list = new ArrayList<int>();Wrong

ArrayList<Integer>list = new Array<Integer>();Right

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

Allows primitives to be used in collections like ArrayListAdvantages for autoboxing

Objects use more memory than primitivesPrimitives are faster then objects because they fit in a CPU register.

Disadvantages:

The size of the data is known in advancePerformance is an issueMemory is an issue

You should use an array when:

When the array size is unknownWhen the array size can change (up or down)For convenience

ArrayList:

Java has a for-each loop for looping arrays and arraylistsWorks like thisFor(variable: array){}

Print all values in an arrayStandard loopString[] 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);

}

Less codeNo need for index variablesReadable

For-each advantages

Print out all elements in a list, putting a blank line after every 10 elementsWe won't know when the 10th element has been encountered.

No access to the index variable, so no idea which position in the array the value is.Disadvantages

Da Summary

Use Random class and 0 seed for testingRandom

FilesScanner

Programming 2 Page 24

Page 25: Programming 2

Be aware of hasNextLine() and nextLine() behaviourScanner

Array resizing arrayListAutoboxingFor-each loop

Programming 2 Page 25

Page 26: Programming 2

Characters are stored as numbersJava char type is 16 bitsAllows the range of 0-65535Each number represents a type of characterCharacter encoding is mapping from numbers to characters

AscIIAmerican Standard Code for Information InterchangeIs 7 bits 0 -127

Additional characters required to support international languagesTherefore unicode was created16 bitAllows as much as the java char type

It gets bigger in newer versions

UTF-8Dominant character encoding of unicode charactersUniversal character set Transformaiton Format - 8 bit

Java can hold most unicode characters in a 16 bit char typeOnes that can't fit make up multiple chars

Character codes can be converted to numbers and vice verse through casting

Printing out the ASCII tablefor (int i = 0; i <= 127; i++){System.out.println(i + “: “ + (char)i);}

Java allows characters to be used with the relational operatorsEg uppercase characterschar c = ‘A’; if (c >= 65 && c <= 90) { System.out.println(c + “ is uppercase.”);}

Week 6Wednesday, 31 August 20111:01 PM

Programming 2 Page 26

Page 27: Programming 2

Characters can also be compared with character literalschar c = ‘A’; if (c >= ‘A’ && c <= ‘Z’){ System.out.println(c + “ is uppercase.”); }

Lowercasechar 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);

OutputJohn Smith, London.

Instance variables don't need to be initialised before useJava automatically initialises instance variablesPrimitives always have number 0 (booleans will be false)Reference type null

Java outputs null if trying to print a null stringnullPointerException 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

Page 28: Programming 2

ConstructorsAre special methods that run when an instance of the class is createdUsed to initialise instance variablesCan take parameters which can be used to initialise the variablesAre publicMust have the same name as the class and no return type

This is a java keyword that refers to the current instanceIn 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 existsTo 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 fieldA getter method returns the value of the fieldA getter method name starts with get followed by the field name

Mutator methodsUsed to change private fieldsSetter method takes a new value as a parameter and assigns it to the fieldBegins with set

Multiple constructorsUsed to have different parametersOther constructors can be invoked to do preliminary initialisation as long as it is invoked at the start of the constructor

Static VariablesUnlike instance variables, static variables are shared between all instances.Can be used to share information between all instancesCan be used to generate an id

Static variables can be accessed without an instance of the classNeed to be preceded with a class nameCan 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 idCreating a new person instance also results in nextID being incremented

Person doesn't have a main method therefore it is not a complete programCan be used by another class that contains a main method

Main class contains a main methodMain method is static and makes the other methods and variables in the main class also staticimport java.util.*;

public class People

{

public static void main(String[] args)

{

// Create a new person

Person p = new Person();

// Get person’s details

Scanner keyboard = new Scanner(System.in);

p.setSurname(keyboard.next());

Programming 2 Page 28

Page 29: Programming 2

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.DelimiterChanging the delimiter from whitespace to a comma causes problems cus Scanner no longer treats a new line as a separator between fieldsA 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 constructorThe 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

Page 30: Programming 2

Programming 2 Page 30

Page 31: Programming 2

Need to knowScannerExpressionsLoopsWriting and calling methodsCharacter upper/lowercase testing and conversion

Similar to labs

Midsemester examWednesday, 7 September 201112:58 PM

Programming 2 Page 31

Page 32: Programming 2

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 tooInt value1=1Int value2=2If(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 oriterationWhile(expression)

Statement(s)}

{

For(initialization, termination, increment)

Statement(s){

}

Comparing charactersChar c = 'A'If (c >= 65 && c <= 90)

System.out.println(c+"is uppercase");{

}

Lowercase and digitsLowercase:

Week7Wednesday, 7 September 201112:59 PM

Programming 2 Page 32

Page 33: Programming 2

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

Page 34: Programming 2

Lists and tables are used to display informationJlist can display a list of stringsJtable can display a grid of strings with column names

The data for Jlist can be specified as an array of stringsJFrame 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

The outer array represents an array of rowsThe inner array represents the data for each column

Data can be specified in a 2d array

ExampleString*+*+ 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);

When placed in a JScrollPaneColumn names are displayed

Column widths are the same for each column

To customise visual aspectssetShowGrid(boolean)setShowHorizontalLines(boolean)setShowVerticalLines(boolean)

Images can be loaded and displayed using ImageIcon classJlabels and Jbuttons can display the image that ImageIcon specifiesGIF,JPEG, and PNG formats

To create and displayImageIcon image = new ImageIcon(“Jobs.jpg”); JLabel imageLabel = new JLabel(image); frame.add(imageLabel); frame.pack() // sets window size to image size

Week 8Wednesday, 14 September 20111:21 PM

Programming 2 Page 34

Page 35: Programming 2

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

This is the object that the event will occur on (eg. JButton)Event Source Object

A method provided by the event source object to register a listening object (eg. addActionListener())

Event Source Registering Method

Any object that conforms to the requirements of an event listenerEvent Listener Object

The particular method in the event listener that will be called.Event Listener Method

Interfacepublic interface Description{String getName();String getDescription();}

Implementing the person classclass 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 typesPerson 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 arraysDescription*+ 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 objectsfor (int i = 0; i < d.length; i++) , if (d*i+ != null) , System.out.println(“Name: ” + d*i+.getName());

Programming 2 Page 35

Page 36: Programming 2

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 listenersjava.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

Page 37: Programming 2

A program can do one of four things when dealing with an errorIgnore the errorQuietly handle the errorDisplay the error to the user or in a logDisplay the error to the user and allow the user to choose the best action to take

Errors used to be communicated through return valuespublic 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 -1return -1;}}

Special values can indicate errors, like negative numbers or null.Problems show up when functions also uses the return value to return valid information.

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 codesint 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 codeJava has 2 types of exceptionsChecked and unchecked

Check exceptions must be handled with either a try..catch statement or a throws statement in the method header

Week 9Wednesday, 21 September 201111:08 AM

Programming 2 Page 37

Page 38: Programming 2

method headerUnchecked exceptions are common and don't require handling

Throwable is the superclass of both error and exception subclasses

Like out of memory errorThe error class is used for serious errors that should not be handled

Errors should not be caught

Subclasses of runtimeException are unchecked exceptionsRuntime exceptions are exceptions that could occur in common codeExamples areArrayIndexOutOfBoundsExceptionStringIndexOutOfBoundsExceptionArithmeticExceptionNullPointerException

Exceptions can be caught using the try...catch statementtry{// 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.

ThrowsIf a method is not able to deal with the exception, it can declare in the method header that the exception is thrown

FinallyA 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 objectsUsing exceptions is that the objects can contain extra information about the exception that has occurred

Java has two ways to create your own exceptionsUsing the existing exception classCreating a subclass of exception

Exception class can be instantiated directlyException e = new Exception(“A custom exception.”);

Programming 2 Page 38

Page 39: Programming 2

Exception e = new Exception(“A custom exception.”);throw e;

Writing to filesThe PrintWriter class can be used to write to a file in javaIt provides the same print()/println() methods as system.out

The constructor makes a string which is the path to the fileThe PrintWriter should be closed after writing to the file.

Programming 2 Page 39

Page 40: Programming 2

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 classAkaPublic class Horse extends Mammal

Inheritance relationships are is-a relationshipsExampleHorse is-a mammal

Very top of java inheritance hierarchy is the Object classIs default if no superclass is specified

Following are equivalent

Public class MyClass{}

Public class MyClass extends Object{}Contains two types of methodsThread synchronisation methods (don't worry about right now)Methods designed to be overridden by subclasses

Mammal m1 = new Horse();An instance of a subclass can be assigned to a variable with a type of superclass

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

Horse h1 = new Animal();The following would compile an error

An animal is not a Horse

Lets define a methodAnimal - move()Bird - fly()All subclasses of animals can also move()All subclasses of bird can also fly()

Animal a1 = new Bird();

Compile error: the compiler only knows that a1 is an animal, since that is the variable typeA1.fly();

Animal a1 = new Bird();

Compiles cus move () is a method of AnimalA1.move();

Week 10Wednesday, 5 October 20111:00 PM

Programming 2 Page 40

Page 41: Programming 2

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 modifierTherefore a public method can't be overriden by a private method, it'll make a compile error.

Overriding exampleObject 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

Page 42: Programming 2

this.interestRate = interestRate; }// Applies interest rate to balance and returns new

// balance public double calculateInterest(int months) {return 0;

} }

Abstract classesJava allows a method to be declared with no body as an abstract methodClasses 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 bordersAny 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

EmptyBorderMatteBorderSoftBevelBorder

Some of these include

Empty border's make borders that are the same colour as the background

EmptyBorder emptyBorder = new EmptyBorder(10,10,10,10);

Panel.setBorder(emptyBorder);

ColoursColours 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

Page 43: Programming 2

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

REDGREENBLUEBLACKWHITEGRAY

Color.

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 fontsTo create a font object you will need the name, style, and size of the font

System font constants

DIALOGDIALOG_INPUTMONOSPACEDSANS_SERIFSERIF

Font.

Java supports the following styles

BOLDITALICPLAIN

Font.

These can be combinedFont.BOLD | Font.ITALIC

Programming 2 Page 43

Page 44: Programming 2

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 assignmentBorders and custom font will be needed, and custom colors

Programming 2 Page 44

Page 45: Programming 2

encapsulation

Feedback:

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.

Question 2

1 out of 1 points

When applied to instance variables, the ________________ visibility modifier enforces encapsulation.

Selected Answer: private

Feedback:

The private visibility modifier guards against inappropriate data access, and 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.

Question 3

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

Feedback:

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

Question 4

1 out of 1 points

Which of the following method headers is most likely a header for a mutator method?

Selected Answer: public void setAge(int newAge)

Feedback:

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.

Question 5

1 out of 1 points

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

Selected Answer: static

Feedback:

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

Quiz stuffThursday, 13 October 201111:14 AM

Programming 2 Page 45

Page 46: Programming 2

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.

Question 7

1 out of 1 points

The ________________ reference always refers to the currently executing object.

Selected Answer: this

Feedback:

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

Question 8

1 out of 1 points

A method that has multiple definitions is an __________________ method.

Selected Answer: overloaded

Feedback:

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.

Question 9

1 out of 1 points

A(n) ________________ is a step-by-step process for solving a problem.

Selected Answer: algorithm

Feedback:

An algorithm is a step-by-step solution for solving a problem. A UML diagram is a 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.

Question 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

Page 47: Programming 2

Selected Answer: void

Feedback:

Methods that do not need to return any data should have void specified as the 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

Feedback:

Methods that can be called directly through the class name must be declared 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: private

Feedback:

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

Question 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

Feedback:

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

Nayan

Question 1

1 out of 1 points

In Java, array indexes always begin at ________________.

Selected Answer: 0

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

Question 2

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

Page 48: Programming 2

holds 50 integers

Feedback:

The code represents the declaration and initialization of an array 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.

Feedback:

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

Question 4

1 out of 1 points

What will be the output of the following code snippet?

int[] array = new int[25];System.out.println(array.length);

Selected Answer: 25

Feedback:

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

Question 5

1 out of 1 points

Which of the following array declarations are invalid?

Selected Answer:

all of the above are valid

Feedback:

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

Question 6

1 out of 1 points

Which of the following is a true statement?

Selected Answer:

Arrays are passed as parameters to methods like object types.

Feedback:

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

Programming 2 Page 48

Page 49: Programming 2

Question 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

Question 8

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];

Feedback:

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

Question 9

1 out of 1 points

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

Selected Answer: public int average(int ... list)

Feedback:

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.

Question 10

1 out of 1 points

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

Selected Answer: int[][] matrix;

Feedback:

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

Question 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];

Feedback:

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

Programming 2 Page 49

Page 50: Programming 2

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: iterator

Feedback:

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

Programming 2 Page 50

Page 51: Programming 2

Collections FrameworkA number of classes for dealing with collections of objects

A collections object is commonly used to replace an array

The advantages of collectionsReduces the programmming effortIncreases performanceProvides interoperability between unrelated APIsReduces the effort required to learn APIsReduces the effort required to design and implement APIsFosters software reuse.

Collection typesThe collections framework supports a number of collection types, including:A generic collection interfaceListsSetsMapsQueues

Most of the collection classes implement the collection interface

Add(E element)Clear()Boolean contains(Object o)Remove(Object o)Int size()Object[] toArray()And other methods

The collection interface provides the following methods:

ListsList classes implement the list interfaceThe list interface extends the collection interfaceOrdered collection also known as a sequenceDuplicates are generally permittedAllows positional access

List interface

Add(int index, E element)E get(int index)Int indexOf(Object o)E remove(int index)List<E>sublist(int fromIndex, int toIndex)

The list interface provides the additional methods for positional access

List implementations

ArrayListLinkedList

The collections framework provides two classes that implement the list interface:

ArrayList and LinkedList use different mechanisms for storing data, resulting in different performance characteristics.

Week 11Monday, 17 October 20112:18 PM

Programming 2 Page 51

Page 52: Programming 2

performance characteristics.

ArrayListThe ArrayList class represents a List of objects using an arrayAn 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 locationAn 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 ExampleArrayList 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 TypesParameterised 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

Page 53: Programming 2

A Linked List represents a list as a series of objects linked together.There is no arrayIn 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

LinkedList must traverse the listArray is faster to acces an index

ArrayList must shift elements after the deletion index.Linked list is faster to delete an item

ArrayList must create a new array and copy existing elementsLinked List is faster to grow

ArrayList must shift all elements after the insertion indexLinkedList is faster to insert

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 liststhe 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

Page 54: Programming 2

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 notSets generally have an optimised lookup algorithm for the boolean contains(Object o) method

TreeSet - orderedHashSet - unordered

Java has 3 set implementations

A treeSet stores items in a tree structure according to their natural orderNavigating through a tree is generally very efficient compared to searching the list linearly

Time complexitythe time for an algorithm it complete

HashSetuses 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 valuethe hash value is used to efficiently store items in a lookup tableif 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 typestree map - orderedhasmap - unordered

Programming 2 Page 54

Page 55: Programming 2

Week 12Wednesday, 19 October 201112:54 PM

Programming 2 Page 55