In Java and other object-oriented languages, an object is a collection of data that provides a set of methods. Strings are objects, too. They contain characters and provide methods for manipulating character data.
We explore some of those methods in this chapter. Not everything in Java is an object: intdoubleand boolean are so-called primitive types. We will explain some of the differences between object types and primitive types as we go along. Strings provide a method named charAtwhich extracts a character. It returns a chara primitive type that stores an individual character as opposed to strings of them. The argument 0 means that we want the letter at position 0. Like array indexes, string indexes start at 0, so the character assigned to letter is b.
Characters work like the other primitive types we have seen. You can compare them using relational operators:. Character literals, like 'a'appear in single quotes. Unlike string literals, which appear in double quotes, character literals can only contain a single character.
The increment and decrement operators work with characters. So this loop displays the letters of the alphabet:. Java uses Unicode to represent characters, so strings can store text in other alphabets like Cyrillic and Greek, and non-alphabetic languages like Chinese.
The code units for uppercase Greek letters run from toso we can display the Greek alphabet like this:. This example uses a type cast to convert each integer in the range to the corresponding character. Strings provide methods, toUpperCase and toLowerCasethat convert from uppercase to lowercase and back. These methods are often a source of confusion, because it sounds like they modify strings.
But neither these methods nor any others can change a string, because strings are immutable. When you invoke toUpperCase on a string, you get a new string object as a return value. For example:. Another useful method is replacewhich finds and replaces instances of one string within another. This example demonstrates a common way to work with string methods.
It invokes text. Then it assigns the new string to textreplacing the old string. The following loop traverses the characters in fruit and displays them, one on each line:.
Strings provide a method called length that returns the number of characters in the string. Because it is a method, you have to invoke it with the empty argument list. Unfortunately, the enhanced for loop does not work with strings.
But you can convert any string to a character array and iterate that:. The problem is that there is no sixth letter in "banana". Since we started counting at 0, the 6 letters are indexed from 0 to 5. To get the last character, you have to subtract 1 from length.Due to the print book page limit, we cannot inlcude all good CheckPoint questions in the physical book.
The CheckPoint on this Website may contain extra questions not printed in the book. The questions in some sections may have been reordered as a result. Nevertheless, it is easy to find the CheckPoint questions in the book on this Website. Please send suggestions and errata to Dr.
Liang at y. Indicate the book, edition, and question number in your email. Chapter 9 Check Point Questions Section 9. Can an array contain elements of an object type? Describe the default value for the elements of an array.7.6. (Part 1) Driver's License Exam - Java
How do you display the current time? Suppose p1 and p2 are two instances of Point2D, how do you obtain the distance between the two points? How do you obtain the midpoint between the two points? Let f be an instance of F.
Which of the statements in b are correct? Can you invoke an instance method or reference an instance variable from a static method?
Chapter 9 Strings and things
Can you invoke a static method or reference a static variable from an instance method? What is wrong in the following code? What is a mutator method? What are the naming conventions for accessor methods and mutator methods?
Does the highlighted code cause any problems? If so, explain why. Date[ 10 ]; 4 System.Pages Home Books Affiliate Disclosure.
Daniel LiangY. A private double data field named balance for the account default 0. A private double data field named annualInterestRate that stores the cur- rent interest rate default 0. Assume all accounts have the same interest rate. A private Date data field named dateCreated that stores the date when the account was created.
A no-arg constructor that creates a default account. A constructor that creates an account with the specified id and initial balance. The accessor and mutator methods for idbalanceand annualInterestRate. The accessor method for dateCreated. A method named getMonthlyInterestRate that returns the monthly interest rate. A method named getMonthlyInterest that returns the monthly interest. A method named withdraw that withdraws a specified amount from the account. A method named deposit that deposits a specified amount to the account.
Draw the UML diagram for the class and then implement the class. Hint: The method getMonthlyInterest is to return monthly interest, not the interest rate. Note that annualInterestRate is a percentage, e. You need to divide it by ArrayList ; import java. Daniel Liang.
Unknown 25 February at Newer Post Older Post Home. Subscribe to: Post Comments Atom.Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. Question 1: What methods would a class that implements the java. CharSequence interface have to implement? Answer 1: charAtlengthsubSequenceand toString. Answer 2: It has a method implementation in it.
Only default and static methods have implementations. Answer 4: Yes. Methods are not required. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.
Exercise 1: Write a class that implements the CharSequence interface found in the java. Your implementation should return the string backwards. Select one of the sentences from this book to use as the data. Write a small main method to test your class; make sure to call all four methods. Answer 1: See CharSequenceDemo.
Exercise 2: Suppose that you have written a time server, which periodically notifies its clients of the current date and time. Write an interface that the server could use to enforce a particular protocol on its clients. Answer 2: See TimeClient. All rights reserved. Questions Question 1: What methods would a class that implements the java. Question 2: What is wrong with the following interface?Post a Comment.
Pages Home Books Affiliate Disclosure. Daniel LiangY. A private int data field named speed that specifies the speed of the fan the default is SLOW. A private boolean data field named on that specifies whether the fan is on the default is false. A private double data field named radius that specifies the radius of the fan the default is 5. A string data field named color that specifies the color of the fan the default is blue. The accessor and mutator methods for all four data fields. A no-arg constructor that creates a default fan.
A method named toString that returns a string description for the fan. If the fan is on, the method returns the fan speed, color, and radius in one com- bined string. Draw the UML diagram for the class and then implement the class. Write a test program that creates two Fan objects. Assign maximum speed, radius 10color yellowand turn it on to the first object. Assign medium speed, radius 5color blueand turn it off to the second object. Display the objects by invoking their toString method. The fan is OFF.
FAST ; fan1. Daniel Liang. No comments :. Newer Post Older Post Home. Subscribe to: Post Comments Atom.Computers are often used to automate repetitive tasks. Repeating tasks without making errors is something that computers do well and people do poorly. Running the same code multiple times is called iteration.
We have seen methods, like countdown and factorialthat use recursion to iterate. Although recursion is elegant and powerful, it takes some getting used to.
Java provides language features that make iteration much easier: the while and for statements. Using a while statement, we can rewrite countdown like this:.
When you get to zero, print Blastoff! The expression in parentheses is called the condition. The statements in braces are called the body. The flow of execution for a while statement is:. This type of flow is called a loopbecause the last step loops back around to the first. The body of the loop should change the value of one or more variables so that, eventually, the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
In the case of countdownwe can prove that the loop terminates when n is positive. But in general, it is not so easy to tell whether a loop terminates.
For example, this loop continues until n is 1 which makes the condition false :. Each time through the loop, the program displays the value of n and then checks whether it is even or odd. If it is even, the value of n is divided by two. For example, if the starting value the argument passed to sequence is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.
Chapter 7 Loops
Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever reach 1 and that the program will ever terminate. For some values of nwe can prove that it terminates. For example, if the starting value is a power of two, then the value of n will be even every time through the loop until we get to 1.
The previous example ends with such a sequence, starting when n is The hard question is whether this program terminates for all values of n. So far, no one has been able to prove it or disprove it! Loops are good for generating and displaying tabular data.
Before computers were readily available, people had to calculate logarithms, sines and cosines, and other common mathematical functions by hand. To make that easier, there were books of tables where you could look up values of various functions. Creating these tables by hand was slow and boring, and the results were often full of errors.Due to the print book page limit, we cannot inlcude all good CheckPoint questions in the physical book.
The CheckPoint on this Website may contain extra questions not printed in the book. The questions in some sections may have been reordered as a result. Nevertheless, it is easy to find the CheckPoint questions in the book on this Website. Please send suggestions and errata to Dr. Liang at y. Indicate the book, edition, and question number in your email. Chapter 6 Check Point Questions Section 6. How do you invoke a method?
A call to a method with a void return type is always a statement itself, but a call to a value-returning method cannot be a statement by itself. Can you have a return statement in a void method? Does the return statement in the following method cause syntax errors? Return a sales commission, given the sales amount and the commission rate.
Display the calendar for a month, given the month and year. Return a square root of a number. Test whether a number is even, and returning true if it is. Display a message a specified number of times. Return the monthly payment, given the loan amount, number of years, and annual interest rate.
Return the corresponding uppercase letter, given a lowercase letter.
Answers to Questions and Exercises: Interfaces
Use the end-of-line brace style. Can the argument have the same name as its parameter? Show the result of the following programs.
What is hexCharToDecimal '7'? What is hexToDecimal 'A9'?