Chapter 10 - JAVA PROGRAMMING Object-Oriented Thinking

¡Supera tus tareas y exámenes ahora con Quizwiz!

10.6 What happens when invoking the pop() method on a stack while size is 0?

An ArrayIndexOutOfRangeException would occur on elements[--size], which is elements[-1].

Aggregation

Special form of association that represents an ownership relationship between two objects. "has-a" relationship. UML indicates this with an open diamond to the owning class.

10.20 Suppose string s is created using new String(); what is s.length()?

0

Multiplicity

A number or interval that specifies how many of the class's objects are involved in a relationship. * is infinite and x..y indicates x is the lowest amount and y is the highest.

10.30 What is the internal storage for characters in a string and a string builder?

Both string and string buffer use arrays to hold characters. The array in a string is fixed once a string is created. The array in a string buffer may change if the buffer capacity is changed. To accommodate the change, a new array is created.

10.19 Does any method in the String class change the contents of the string?

No. The String class is immutable.

Aggregated Class/ Aggregated Object

The subject object/class in an aggregation association.

Wrapper Classes

These are used to wrap a primitive data type in an object class. These provide constructors, constants, and conversion methods for manipulating various data types.

10.2 Is the BMI class defined in Listing 10.4 immutable?

Yes.

10.28 Write three statements to reverse a string s using the reverse method in the StringBuilder Class.

1. StringBuilder A = new StringBuilder(s); 2. A.reverse(); 3.String s = A.toString();

10.29 Write three statements to delete a substring from a string s of 20 characters, starting at index 4 and ending with index 10. Use the delete method in the StringBuilder class.

1. StringBuilder a = new StringBuilder(s); 2.a.substring(4,10); 3.String s = a.toString();

10.11 What is the output of the following code? public class Test { public static void main(String[] args) { System.out.println(Integer.parseInt("10")); System.out.println(Integer.parseInt("10", 10)); System.out.println(Integer.parseInt("10", 16)); System.out.println(Integer.parseInt("11")); System.out.println(Integer.parseInt("11", 10)); System.out.println(Integer.parseInt("11", 16)); } }

10 10 10 base of 10 = 10 16 10 base of 16 = conversion to 16 11 11 11 base of 10 = 11 no change 17 11 base of 16 = 16+ 1 = 17

What is the output of the following code? public class Test { public static void main(String[] args) { java.math.BigInteger x = new java.math.BigInteger("3"); java.math.BigInteger y = new java.math.BigInteger("7"); java.math.BigInteger z = x.add(y); System.out.println("x is " + x); System.out.println("y is " + y); System.out.println("z is " + z); } }

3 7 10

Immutable Class

A class in which all data fields are private, and contains no public setter methods for any data fields. These classes create objects that cannot be changed. Note, if a field is set by a method such as DATE/TIME that pulls from the JAVA API, then it is not considered immutable.

10.3 What are common relationships among classes?

Association, Aggregation, Composition, Inheritance

StringBuilder / StringBuffer classes

Similar to the String class, but these are MUTABLE!

BigInteger and BigDecimal classes can be used to represent integers or decimal numbers of any size.

These classes are immutable.

Class encapsulation

When the details of implementation of a class are hidden from the user.

10.12 What are autoboxing and autounboxing? Are the following statements correct? a. Integer x = 3 + new Integer(5); b. Integer x = 3; c. Double x = 3; d. Double x = 3.0; e. int x = new Integer(3); f. int x = new Integer(3) + new Integer(4);

a. Correct, this is same as x = new Integer(3 + 5); b. Correct c. Wrong, this is same as Double x = new Integer(3); d. Correct e. Correct f. Correct

10.31 Suppose that s1 and s2 are given as follows: StringBuilder s1 = new StringBuilder("Java"); StringBuilder s2 = new StringBuilder("HTML"); Show the value of s1 after each of the following statements. Assume that the statements are independent. a. s1.append(" is fun"); b. s1.append(s2); c. s1.insert(2, "is fun"); d. s1.insert(1, s2); e. s1.charAt(2); f. s1.length(); g. s1.deleteCharAt(3); h. s1.delete(1, 3); i. s1.reverse(); j. s1.replace(1, 3, "Computer"); k. s1.substring(1, 3); l. s1.substring(2);

a. Java is fun b. JavaHTML c. Jais funva d. JHTMLava e. v f. 4 g. Jav h. Ja I. avaJ j. JComputera k. av l. va

10.18 Let s1 be " Welcome " and s2 be " welcome ". Write the code for the following statements: a. Replace all occurrences of the character e with E in s1 and assign the new string to s3. b. Split Welcome to Java and HTML into an array tokens delimited by a space and assign the first two tokens into s1 and s2.

a. String s3 = s1.replaceAll("e", "E"); b. String[] tokens = "Welcome to Java and HTML".split(' '); s1 = tokens[0]; s2 = tokens[1];

Wrapper class conversion methods

doubleValue(), floatValue(), intValue(), longValue(), shortValue()

10.25 Show the output of the following code. public class Test { public static void main(String[] args) { String s = "Hi, Good Morning"; System.out.println(m(s)); } public static int m(String s) { int count = 0; for (int i = 0; i < s.length(); i++) if (Character.isUpperCase(s.charAt(i))) count++; return count; } }

m(s) returns an int value. with the loop, you see there are 3 upper case characters in string s. therefore 3 is what is printed out.

StringBuffer

methods for modifying the buffer in this method are synchronized, meaning only one task is allowed to execute the method at a time.

Wrapper class parse methods to parse a numeric string into an appropriate number value based on 10 or any specified radix

parseByte(), parseShort(), parseInt(), parseLong(), parseFloat(), parseDouble()

10.10 Show the output of the following code. public class Test { public static void main(String[] args) { Integer x = new Integer(3); System.out.println(x.intValue()); System.out.println(x.compareTo(new Integer(4))); } }

3 -1

10.13 Show the output of the following code? public class Test { public static void main(String[] args) { Double x = 3.5; System.out.println(x.intValue()); System.out.println(x.compareTo(4.5)); } }

3 -1

stack

A data structure that holds data in a last-in, first-out fashion.

Association

A general binary relationship that describes an activity between two classes.

Composition

A special aggregation association in which an owner object exclusively "owns" the subject object. UML indicates this with a filled diamond pointing to the owner class.

Abstract Data Type

Abstract or encapsulated class

10.5 What is UML notation of aggregation and composition?

Aggregation: empty diamond on the aggregating class. Composition: Solid diamond on the aggregating class.

10.4 What is association? What is aggregation? What is composition?

Association is a general binary relationship that describes an activity between two classes. Aggregation is a special form of association that represents an ownership relationship between two objects. Aggregation models has-a relationships. An object can be owned by several other aggregating objects. If an object is exclusively owned by an aggregating object, the relationship between the object and its aggregating object is referred to as a composition.

Boxing

Converting a primitive value to a wrapper object

Show the output of the following program: public class Test { public static void main(String[] args) { String s = "Java"; StringBuilder builder = new StringBuilder(s); change(s, builder); System.out.println(s); System.out.println(builder); } private static void change(String s, StringBuilder builder) { s = s + " and HTML"; builder.append(" and HTML"); } }

Java Java and HTML NOTE: Inside the method, the statement s = s + " and HTML" creates a new String object s, which is different from the original String object passed to the change(s, buffer) method. The original String object has not been changed. Therefore, the output from the original string is Java. Inside the method, the content of the StringBuilder object is changed to Java and HTML. Therefore, the output from buffer is Java and HTML.

10.1 If you redefine the Loan class in Listing 10.2 with out setter methods is the class immutable?

No. The Loan class has the getLoanDate() method that returns loanDate. loanDate is an object of the Date class. Since Date is mutable, the contents of loanDate can be changed. So, the Loan class is not immutable.

10.7 Describe primitive type wrapper classes.

Primitive wrapper classes allow the conversion of a primitive type to an object and allows for conversion between objects for these types as well.

10.6 Why both aggregation and composition are together referred to as composition?

Since aggregation and composition relationships are represented using classes in the same way, we will not differentiate them and call both compositions for simplicity.

10.16 To create the string Welcome to Java, you may use a statement like this: String s = "Welcome to Java"; or: String s = new String("Welcome to Java"); Which one is better? Why?

String s = "Welcome to Java"; is better, because this type of string is stored as an interned string(in the heap). The interned strings of the same value share the same object.

10.5 Replace the statement in line 17 in Listing 10.5 TestCourse.java so that the loop displays each student name followed by a comma except the last student name.

System.out.print(students[i] + (i < course1.getNumberOfStudents() - 1 ? ", " : " "));

Autoboxing / Autounboxing

The JAVA compiler will automatically box a primitive value that appears in a context requiring an object, and will unbox a primitive object that appears in a context requiring a primitive value.

10.26 What is the difference between StringBuilder and StringBuffer?

The StringBuilder class, introduced in JDK 1.5, is similar to StringBuffer except that the update methods in StringBuffer are synchronized.

Class's contract

The collection of methods and fields that are accessible from outside the class, together with the description of how these members are expected to behave.

10.23 What is wrong in the following program? 1 public class Test { 2 String text; 3 4 public void Test(String s) { 5 text = s; 6 } 7 8 public static void main(String[] args) { 9 Test test = new Test("ABC"); 10 System.out.println(test); 11 } 12 }

The constructor is defined incorrectly. It should not have void.

Aggregating Class / Aggregating Object

The owner object/class in a aggregation association.

Class abstraction

The separation of class implementation from the use of the class

10.22 Why does the following code cause a NullPointerException? 1 public class Test { 2 private String text; 3 4 public Test(String s) { 5 String text = s; 6 } 7 8 public static void main(String[] args) { 9 Test test = new Test("ABC"); 10 System.out.println(test.text.toLowerCase()); 11 } 12 }

The text is declared in Line 2 as a data field, but redeclared in Line 5 as a local variable. The local variable is assigned with the string passed to the constructor, but the data field is still null. In Line 10, test.text is null, which causes NullPointerException when invoking the toLowerCase() method.

10.27 How do you create a string builder from a string? How do you return a string from a string builder?

Use the StringBuilder's constructor to create a string buffer for a string, and use the toString method in StringBuilder class to return a string from a StringBuilder. StringBuilder A = new StringBuilder("your string"); String B = A.toString();

10.21 How do you convert a char, an array of characters, or a number to a string?

Use the overloaded static valueOf method in the String class.

10.17 What is the output of the following code? String s1 = "Welcome to Java"; String s2 = s1.replace("o", "abc"); System.out.println(s1); System.out.println(s2);

Welcome to Java Welcabce tabc Java Hint: No method in the String class can change the content of the string. String is an immutable class.

stringLiteral

a sequence of characters enclosed inside double quotes.

Regular Expression (regex)

a string that describers a pattern for matching a set of strings. Allows one to match, replace, or split a string by specifying a pattern. Example: "440-02-4534".matches("\\d{3}-\\d{2}-\\d{4})";

10.15 Suppose that s1, s2, s3, and s4 are four strings, given as follows: String s1 = "Welcome to Java"; String s2 = s1; String s3 = new String("Welcome to Java"); String s4 = "Welcome to Java"; What are the results of the following expressions? a. s1 == s2 b. s1 == s3 c. s1 == s4 d. s1.equals(s3) e. s1.equals(s4) f. "Welcome to Java".replace("Java", "HTML") g. s1.replace('o', 'T') h. s1.replaceAll("o", "T") i. s1.replaceFirst("o", "T") j. s1.toCharArray()

a. True. b. False. c. False. Why is this true? d. True. e. True. f. Welcome to HTML g. WelcTme tT Java h. WelcTme tT Java I. WelcTme to Java j. W + e + l + c + o +m +e + + t + o + + J + a + v + a

10.8 Can each of the following statements be compiled? a. Integer I = new Integer("23"); b. Integer I = new Integer(23); c. Integer I = Integer.valueOf("23"); d. Integer I = Integer.parseInt("23",8); e. Double d = new Double(); f. Double d = Double.valueOf("23.45"); g. int I = (Integer.valueOf("23")).doubleValue(); h. double d = (Double.valueOf("23.4")).doubleValue(); I. int I = (Double.valueOf("23.4")).intValue(); j. String s = (Double.valueOf("23.4")).toString();

a. yes. b. yes. c. yes d. yes. e. no. f. yes. g. yes. h. yes I. yes j. yes.

10.24 10 Show the output of the following code. public class Test { public static void main(String[] args) { System.out.println("Hi, ABC, good".matches("ABC ")); System.out.println("Hi, ABC, good".matches(".*ABC.*")); System.out.println("A,B;C".replaceAll(",;", "#")); System.out.println("A,B;C".replaceAll("[,;]", "#")); String[] tokens = "A,B;C".split("[,;]"); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); } }

false true A,B;C A#B#C A B C

10.9 How do you convert an integer into a string? How do you convert a numeric string into an integer? How do you convert a double number into a string? How do you convert a numeric string into a double string?

int -> string : Integer("int").toString(); or int + " "; num string to int -> Integer.parseInt("int"); double num to string -> Double("dub").toString(); num string to double -> Double.parseDouble("int");


Conjuntos de estudio relacionados

Exam #3 - Cognitive Psychology - Dr. Klein - University of North Alabama

View Set

PEDIATRIC SUCCESS ORTHOPEDIC DISORDERS CHAPTER 12

View Set

Cambridge English Profile Level C1

View Set

Southern Rock: Allman Brothers / Lynyrd Skynyrd / Charlie Daniels

View Set

notecards for lebron james research project

View Set

What pronoun would I use when.....

View Set