- Q I’m confused about the differences between objects and the primitive data types, such as int and boolean.
- A The primitive types (byte, short, int, long, float, double, boolean, and char) are not objects, although in many ways they can be handled like objects. They can be assigned to variables and passed in and out of methods.
Objects are instances of classes and as such usually are much more complex data types than simple numbers and characters. They often contain numbers and characters as instance or class variables.
- Q The length() and charAt() methods in the StringChecker application (Listing 3.3) don’t appear to make sense. If length() says that a string is 38 characters long, shouldn’t the characters be numbered from 1 to 38 when charAt() is used to display characters in the string?
- A The two methods look at strings differently. The length() method counts the characters in the string, with the first character counting as 1, the second as 2, and so on. The charAt() method considers the first character in the string to be located at position number 0. This is the same numbering system used with array elements in Java. Consider the string "Charlie Brown". It has 13 characters ranging from position 0 (the letter C) to position 12 (the letter n).
- Q If Java lacks pointers, how can I do something like linked lists, where there’s a pointer from one node to another so that they can be traversed?
- A It’s incorrect to say that Java has no pointers; it just has no explicit pointers. Object references are effectively pointers. To create something like a linked list, you could create a class called Node, which would have an instance variable also of type Node. To link node objects, assign a node object to the instance variable of the object immediately before it in the list. Because object references are pointers, linked lists set up this way behave as you would expect them to. (You work with the Java class library’s version of linked lists on Day 8, “Data Structures.”)