Java Quiz #2

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

The do Statement

A do statement has the following syntax: do { statement-list; } while (condition); The statement is executed repeatedly until the condition becomes false The statement-list is executed once initially, and then the condition is evaluated

driver program

A driver program is often used to test your own written class The DogTestDrive class contains a main method that drives the use of the Dog class, exercising its services

Method With Parameters

A method can use/accept parameters, where the parameter list specifies the type and name of each parameter If a method takes a parameter, the caller must pass argument (the value passed to the method) of the compatible type: Dog d = new Dog(); d.bark(3);

Method Declaration

A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined

Instance Variables

A variable declared at the class level (such as size) is called an instance variable Each time a Dog object is created, a new memory space is reserved for variable size in this particular object The objects of a class share the same method definitions, but each object maintains its own (different) values for its instance variables, and thus its own state

The while Statement

A while statement has the following syntax: while ( condition ) statement; If the condition is true, the statement is executed then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false An example of a while statement: int count = 1; while (count <= 5) { System.out.println (count); count++; } If the condition of a while loop is false initially, the statement is never executed Therefore, the body of a while loop will execute zero or more times

Quick Check: Data Conversion

An int type can not store a float value Can fix it with casting to perform the narrowing conversion: int i = (int) 10.0/5 Output: 2

Another Example

Another example: If count equals 1, the "Dime" is printed If count is anything other than 1, then "Dimes" is printed Even when the conditional operator is a viable alternative, you should use it carefully because it may be less readable than an if-else statement.

Assignment Conversion

Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment int dollars = 20; double money = dollars;// OK long y = 32; int x = y; // won't compile

Autoboxing

Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object: Integer obj; int num = 42; obj = num; The assignment creates the appropriate Integer object The reverse conversion (called unboxing) also occurs automatically as needed Integer obj = new Integer(45); int num; num = obj; The assignment extracts the int value from obj

Casting

Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted double money = 84.69; int dollars =(int) money; // dollars = 84 Example of widening conversion: int total = 50; float result = (float) total / 6; (reads float, then division, then equals) Without the cast, the fractional part of the answer would be lost

Comparing Characters

Characters in Java are based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character 'a' is less than the character 'b' because 'a' comes before 'b' in the Unicode character set In Unicode, the digit characters ('0'-'9') are contiguous and in order Likewise, the uppercase letters ('A'-'Z') and lowercase letters ('a'-'b') are contiguous and in order

Java is Pass-by-value (cont)

Compatible type: you can pass an argument of smaller data type to a parameter of larger data type. So, you can pass a byte where an int is expected.

Quick Check: Are the following assignments valid?

Double value = 15.75; Yes, the double literal is autoboxed into a Double object. Character ch = new Character('T'); char myChar = ch; Yes, the char in the object is unboxed before the assignment. Integer i = new Integer(5); int j = i + 3; Yes, the int value in the object is unboxed before arithmetic computation.

Classes Revisited

Each class declares -Instance variables: descriptive characteristics or states of the object -Methods: behaviors of the object, i.e., what it can do

Quick Check: Nested Loops

How many times will the string "Here" be printed?

Lexicographic Ordering

If all characters are in the same case (upper or lower), the lexicographic ordering is the same as alphabetic ordering, therefore "book" comes before "bookcase" Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically)

Instance v.s. Local Variables

Instance variables always get a default value. If you don't explicitly assign a value to an instance variable, the instance variable still has a value. -integers: 0 -floating points: 0.0 -booleans: false -references: null

Enumerated Types

Java allows you to define an enumerated type, which can then be used as the type of a variable An enumerated type declaration lists all possible values for a variable of that type The values are identifiers of your own choosing The following declaration creates an enumerated type called Season enum Season {winter, spring, summer, fall}; Any number of values can be listed Once a type is defined, a variable of that type can be declared: Season time; And it can be assigned a value: time = Season.fall; The values are referenced through the name of the type Enumerated types are type-safe - you cannot assign any value other than those listed An enumerated type is a special type of class, and each variable of that type is an object The ordinal method returns the ordinal value of the object The first value in an enumerated type has an ordinal value of 0, the second 1, and so on time.ordinal(); // 3 The name method returns the name of the identifier corresponding to the object's value time.name(); // "fall"

Instance Variables are

Lifetime: instance variables exist as long as the object exists Scope: instance variables can be referenced by all methods in that class

Local Variables

Lifetime: when the method finishes, all local variables are destroyed (including the parameters of the method) Scope: local variables can only be used in that method

In Java, data conversions can occur in three ways: -assignment conversion -promotion -casting

Numeric data types: double > float > long > int > short > byte Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)

The break Statement

Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

Promotion

Promotion happens automatically when operators in expressions convert their operands Example: int count = 12; double sum = 490.27; double result = sum / count; The value of count is converted to a floating point value to perform the division calculation

Comparing Strings

Remember that in Java a character string is a String object The equals method can be called with strings to determine if two strings contain exactly the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name"); We cannot use the relational operators to compare strings The String class contains the compareTo method for determining if one string comes before another A call to name1.compareTo(name2) -returns zero if name1 and name2 are equal (contain the same characters) -returns a negative value if name1 is lexically before name2 -returns a positive value if name1 is lexically after name2

Repetition Statements

Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: while, do, and for loops

Nested Loops

Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop while ( condition1 ) { while ( condition2 ) statement; } For each iteration of the outer loop, the inner loop iterates completely

Data Conversion

Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it - they only generate a value as part of a computation

Infinite Loops

The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program (Control+C) This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally

The Conditional Operator

The conditional operator evaluates to one of two expressions based on a boolean condition Its syntax is: condition ? expression1 : expression2; If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated The value of the entire conditional operator is the value of the selected expression The conditional operator is similar to an if-else statement, except that it is an expression that returns a value For example: larger = ((num1 > num2) ? num1 : num2); If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger May serve as a shortcut for if-else statement

Formatting Parameters

The constructor of the DecimalFormat class takes a string that represents a pattern for the formatted number DecimalFormat fmt = new DecimalFormat("0.###"); -0 means at least one digit should be printed to the left of the decimal point (.), and should be a zero if the integer portion of the value is zero -### means the fractional part of the value should be rounded to three digits (trailing zeros are not printed) format method in the DecimalFormat class can then be used to format a particular value fmt.format(2.0/3); // "0.667" fmt.format(3.3/6); // "0.55"

The switch Statement

The general syntax of a switch statement is: The type of a switch expression must be char, byte, short and int (Question 4) You cannot use a switch with a boolean or a floating point value The value of each case must be a constant; it cannot be a variable or other expression You cannot perform relational checks (<, >) with a switch statement A switch statement can have an optional default case at the end The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

The for Statement

The increment section can perform any calculation: for (int num = 100; num > 0; num -= 5) System.out.println (num); A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

Wrapper Classes

The java.lang package contains wrapper classes that correspond to each primitive type: The following declaration creates an Integer object which represents the integer 40 as an object int age = 40; Integer ageWrap = new Integer(age); An object of a wrapper class can be used in any situation where a primitive value will not suffice Unwrap a wrapper value int age = ageWrap.intValue(); Other wrapper classes have similar methods Wrapper classes also contain static methods that help manage the associated type The Integer class contains a method to convert an integer stored in a String to an int value: String str = "234"; int num = Integer.parseInt(str); The Double class contains a method to convert a double value stored in a String to an double value: double d = Double.parseDouble("30.24");

A loop can also be used for input validation, making a program more robust

The number of games won must be greater than or equal to zero and less than or equal to the total number of games played

Writing Classes

The programs we've written in previous examples have used classes defined in the Java standard class library Now we will begin to design programs that rely on classes that we write ourselves The class that contains the main method is just the starting point of a program True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality

The Return Statement

The return type of a method indicates the type of value that the method sends back to the caller; void type means it does not return a value A return statement specifies the value that will be returned return result; The expression must be compatible with the return type in the method header You must use an explicit cast when the return type is smaller than what you are trying to return Even if the method has a non-void return type, the return value can be ignored

Comparing Object References

To see if two object references are the same (which means they refer to the same object on the heap), use the equality operator (==)

How about turning a primitive number into a String?

Use string concatenation double d = 30.24; String dString = "" + d; Use toString method in the Double class double d = 30.24; String dString = Double.toString(d); Check Java API for more such methods

Let's write a program to read a series of integer values from the user, sums them up, and computes their average

What variables do we need to maintain? -Current value from the user input -The sum of values entered so far -The number of values entered so far A sentinel value is a special input value that represents the end of input

Comparing Data

When comparing data using boolean expressions, it's important to understand the nuances of certain data types Let's examine some key situations: -Comparing floating point values for equality -Comparing characters -Comparing strings (lexicographic order) -Comparing object references

Formatting Output

When printing float point values System.out.println(2.0/3); It prints 0.6666666666666666 to the monitor screen The DecimalFormat class can be used to format a floating point value in various ways For example, you can specify that the number should be truncated to three decimal places It is part of the java.text package

More than One Parameter

You can send more than one thing to a method: first argument is passed to the first parameter, second argument to the second parameter, and so on.

Comparing Floating Point Values

You should rarely use the equality operator (==) when comparing two floating point values (float or double) because two floating point values are equal only if their underlying binary representations match exactly (0.1 + 0.2) == 0.3 // false To determine the equality of two floats, use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between the two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as 0.000001

An example of a for loop:

for (int count=1; count <= 5; count++) System.out.println (count); The initialization section can be used to declare a variable Like a while loop, the condition of a for loop is tested prior to executing the loop body Therefore, the body of a for loop will execute zero or more times

A for loop is functionally equivalent to the following while loop structure:

initialization; while ( condition ) { statement; increment; }

Switch Example 2

int i=2; switch (option) { case 1: Statement; case 2: Statement; case 3: Statement; }

An example of a switch statement:

switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; default: misc++; }


Set pelajaran terkait

unit 23 Mortgage Lending Tax Impacts

View Set

Multi-Step Percent Practice Problems

View Set

Prep U Chapter 40: Management of Patients with Gastric and Duodenal Disorders

View Set

Chapter 43: Medical Records Management

View Set

Network+ 8th edition Chapter 2 Quiz

View Set

Intro to Business Warm Up Chapter 5

View Set