Chapter 2 Java Fundamentals Goals Introduce the Java syntax necessary to write programs Be able to write a program with user input and console output Evaluate and write arithmetic expressions Use a few of Java's types such as int and double 2.1 Elements of Java Programming The essential building block of Java programs is the class. In essence, a Java class is a sequence of characters (text) stored as a file, whose name always ends with .java. Each class is comprised of several elements, such as a class heading (public class class-name) and methods—a collection of statements grouped together to provide a service. Below is the general form for a Java class that has one method: main. Any class with a main method, including those with only a main method, can be run as a program. General Form: A simple Java program (only one class) // Comments: any text that follows // on the same line import package-name.class-name; public class class-name { public static void main(String[] args) { variable declarations and initializations messages and operations such as assignments } } General forms describe the syntax necessary to write code that compiles. The general forms in this textbook use the following conventions: Boldface elements must be written exactly as shown. This includes words such as public static void main and symbols such as [, ], (, and). Italicized items are defined somewhere else or must be supplied by the programmer.
Integer Floating Point String Character Boolean Null -2147483648 -1.0 "A" 'a' true null -1 0.0 "Hello World" '0' false 0 39.95 "\n new line" '?' 1 1.23e09 "1.23" ' ' 2147483647 -1e6 "The answer is: " '7' Note: Other literals are possible such as 12345678901L for integers > 2,147,483,647. Comments Comments are portions of text that annotate a program, and fulfill any or all of the following expectations: Provide internal documentation to help one programmer read and understand another’s program. Explain the purpose of a method. Describe what a method expects of the input arguments (n must be > 0, for example). Describe a wide variety of program elements. Comments may be added anywhere within a program. They may begin with the two-character special symbol /* when closed with the corresponding symbol */. /* A comment may extend over many lines when using slash start at the beginning and ending the comment with a star slash. */ An alternate form for comments is to use // before a line of text. Such a comment may appear at the beginning of a line, in which case the entire line is “ignored” by the program, or at the end of a line, in which case all code prior to the special symbol will be executed. // This Java program displays "hello, world to the console. Comments can help clarify and document the purpose of code. Using intention-revealing identifiers and writing code that is easy to understand, however, can also do this. Self-Check 2-1 List each of the following as a valid identifier or explain why it is not valid. -a abc -i H.P. -b 123 -j double -c ABC -k 55_mph -d _.$ -l sales Tax -e my Age -m $$$$ -f identifier -n ______ -g (identifier) -o Mile/Hour -h mispellted -p Scanner 2-2 Which of the following are valid Java comments?
Chapter 7 Arrays Goals This chapter introduces the Java array for storing collections of many objects. Individual elements are referenced with the Java subscript operator []. After studying this chapter you will be able to declare and use arrays that can store reference or primitive values implement methods that perform array processing 7.1 The Java Array Object Java array objects store collections of elements. They allow a large number of elements to be conveniently maintained together under the same name. The first element is at index 0 and the second is at index 1. Array elements may be any one of the primitive types, such as int or double. Array elements can also be references to any object. The following code declares three different arrays named balance, id, and tinyBank. It also initializes all five elements of those three arrays. The subscript operator [] provides access to individual array elements. // Declare two arrays that can store up to five elements each double[] balance = new double[5]; String[] id = new String[5]; // Initialize the array of double values balance[0] = 0.00; balance[1] = 111.11; balance[2] = 222.22; balance[3] = 333.33; balance[4] = 444.44; // Initialize all elements in an array of references to String objects id[0] = "Bailey"; id[1] = "Dylan"; id[2] = "Hayden"; id[3] = "Madison"; id[4] = "Shannon"; The values referenced by the arrays can be drawn like this, indicating that the arrays balance, and id, store collections. balance is a collection of primitive values; id is a collection of references to String objects.
} public void add(E element) { elements[n] = elementToAdd; n++; } // . . . public E get(int index) { return (E)elements[index]; } } import static org.junit.Assert.*; import org.junit.Test; public class ArrayBagTest { // Test highlighting passing type arguments String and Integer @Test public void testGenericity() { ArrayBag<String> names = new ArrayBag<String>(); names.add("Taylor"); names.add("Kim"); ArrayBag<Integer> testScores = new ArrayBag<Integer>(); testScores.add(99); testScores.add(77); testScores.add(88); } } In the add method, Object is replaced with E so only elements of the type argumentString, or Integer abovecan be added to that collection. The compiler catches accidental add messages using the wrong type of argument. For example, the following three attempts to add the wrong type generate compiletime errors (not runtime errors later. This is a good thing. It is better than waiting until runtime when the program would otherwise terminate. names.add(999); The method add(String) in the type ArrayBag<String> is not applicable for the arguments (int) testScores.add("a String"); The method add(Integer) in the type ArrayBag <Integer> is not applicable for the arguments (String) You also don’t have to manually box primitives during add messages. testScores.add(new Integer(89)); Nor do you have to cast the return values names.add("First"); names.add("Second"); String noCastToStringNeeded = strings.get(0); noCastToStringNeeded = strings.get(1); because the cast is now done in the get method.
first.next.next The Node reference variable named first is not an internal part of the linked structure. The purpose of first is to find the beginning of the list so algorithms can find an insertion point for a new element, for example. In a singly linked structure, the instance variable data of each Node refers to an object in memory, which could be of any type. The instance variable next of each Node object references another node containing the next element in the collection. One of these Node objects stores null to mark the end of the linked structure. The null value should only exist in the last node. Self-Check Use this linked structure to answer the questions that follow. 15-1 What is the value of first.data? 15-2 What is the value of first.next.data? 15-3 What is the value of first.next.next.next.data? 15-4 What is the value of first.next.next.next? Each node stores a reference to the element A linked structure would be pictured more accurately with the data field shown to reference an object somewhere else in memory. However, it is more convenient to show linked structures with the value of the element written in the node, especially if the elements are strings. This means that even though both parts store a reference value (exactly four bytes of memory to indicate a reference to an object), these structures are often pictured with a box dedicated to the data value, as will be done in the remainder of this chapter. The reference values, pictured as arrows, are important. If one of these links becomes misdirected, the program will not be able to find elements in the list. Traversing a Linked Structure Elements in a linked structure can be accessed in a sequential manner. Analogous to a changing int subscript to reference all elements in an array, a changing Node variable can reference all elements in a singly linked structure. In the following for loop, the Node reference begins at the first node and is updated with next until it becomes null. for (Node ref = first; ref != null; ref = ref.next) { System.out.println(ref.data.toString());