Java program

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

Chapter 1

A computer is an electronic device that stores and processes data. 2. A computer includes both hardware and software. 3. Hardware is the physical aspect of the computer that can be touched. 4. Computer programs, known as software, are the invisible instructions that control the hardware and make it perform tasks. 5. Computerprogrammingisthewritingofinstructions(i.e.,code)forcomputerstoperform. 6. The central processing unit (CPU) is a computer's brain. It retrieves instructions from memory and executes them. 7. Computers use zeros and ones bec

Chapter 13

Abstract classes are like regular classes with data and methods, but you cannot create instances of abstract classes using the new operator. 2. An abstract method cannot be contained in a nonabstract class. If a subclass of an abstract superclass does not implement all the inherited abstract methods of the super- class, the subclass must be defined as abstract. 3. A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that doesn't contain any abstract methods. 4. A subclass can be abstract even if its superclass is concrete. 5. An interface is a class-like construct that contains only constants and abstract methods. In many ways, an interface is similar to an abstract class, but an abstract class can con- tain constants and abstract methods as well as variables and concrete methods. 6. An interface is treated like a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular class. 7. The java.lang.Comparable interface defines the compareTo method. Many classes in the Java library implement Comparable. Programming Exercises 529 8. The java.lang.Cloneable interface is a marker interface. An object of the class that implements the Cloneable interface is cloneable. 9. A class can extend only one superclass but can implement one or more interfaces. 10. An interface can extend one or more interfaces.

Chapter 7

AvariableisdeclaredasanarraytypeusingthesyntaxelementType[] arrayRefVar or elementType arrayRefVar[]. The style elementType[] arrayRefVar is preferred, although elementType arrayRefVar[] is legal. 2. Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. An array variable is not a primitive data type variable. An array variable contains a reference to an array. 3. You cannot assign elements to an array unless it has already been created. You can create an array by using the new operator with the following syntax: new elementType[arraySize]. 4. Each element in the array is represented using the syntax arrayRefVar[index]. An index must be an integer or an integer expression. 5. After an array is created, its size becomes permanent and can be obtained using arrayRefVar.length. Since the index of an array always begins with 0, the last index is always arrayRefVar.length - 1. An out-of-bounds error will occur if you attempt to reference elements beyond the bounds of an array. 6. Programmers often mistakenly reference the first element in an array with index 1, but it should be 0. This is called the index off-by-one error. 276 Chapter 7 Single-Dimensional Arrays 7. When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, \u0000 for char types, and false for boolean types. 8. Java has a shorthand notation, known as the array initializer, which combines declaring an array, creating an array, and initializing an array in one statement, using the syntax elementType[] arrayRefVar = {value0, value1, ..., valuek}. 9. When you pass an array argument to a method, you are actually passing the reference of the array; that is, the called method can modify the elements in the caller's original array. 10. If an array is sorted, binary search is more efficient than linear search for finding an element in the array. 11. Selection sort finds the smallest number in the list and swaps it with the first element. It then finds the smallest number remaining and swaps it with the first element in the remaining list, and so on, until only a single number remains.

Chapter 2

Chapter 2

Page 28

Every statement in Java ends with a semicolon (;), known as the statement terminator. 31. Reserved words, or keywords, have a specific meaning to the compiler and cannot be used for other purposes in the program. 32. In Java, comments are preceded by two slashes (//) on a line, called a line comment, or enclosed between /* and */ on one or several lines, called a block comment or para- graph comment. Comments are ignored by the compiler. 33. Java source programs are case sensitive. 34. Programming errors can be categorized into three types: syntax errors, runtime errors, and logic errors. Errors reported by a compiler are called syntax errors or compile errors. Runtime errors are errors that cause a program to terminate abnormally. Logic errors occur when a program does not perform the way it was intended

Chapter 9

. A class is a template for objects. It defines the properties of objects and provides constructors for creating objects and methods for manipulating them. 2. A class is also a data type. You can use it to declare object reference variables. An object reference variable that appears to hold an object actually contains a reference to that object. Strictly speaking, an object reference variable and an object are different, but most of the time the distinction can be ignored. 3. An object is an instance of a class. You use the new operator to create an object, and the dot operator (.) to access members of that object through its reference variable. 4. An instance variable or method belongs to an instance of a class. Its use is associated with individual instances. A static variable is a variable shared by all instances of the same class. A static method is a method that can be invoked without using instances. 5. Everyinstanceofaclasscanaccesstheclass'sstaticvariablesandmethods.Forclarity, however, it is better to invoke static variables and methods using ClassName.variable and ClassName.method. 6. Visibility modifiers specify how the class, method, and data are accessed. A public class, method, or data is accessible to all clients. A private method or data is acces- sible only inside the class. 7. You can provide a getter (accessor) method or a setter (mutator) method to enable clients to see or modify the data. 8. A getter method has the signature public returnType getPropertyName(). If the returnType is boolean, the get method should be defined as public boolean isPropertyName(). A setter method has the signature public void setPropertyName(dataType propertyValue). 9. All parameters are passed to methods using pass-by-value. For a parameter of a primi- tive type, the actual value is passed; for a parameter of a reference type, the reference for the object is passed. 10. A Java array is an object that can contain primitive type values or object type values. When an array of objects is created, its elements are assigned the default value of null. 11. Once it is created, an immutable object cannot be modified. To prevent users from modifying an object, you can define immutable classes. 12. The scope of instance and static variables is the entire class, regardless of where the variables are declared. Instance and static variables can be declared anywhere in the class. For consistency, they are declared at the beginning of the class in this book. 13. The keyword this can be used to refer to the calling object. It can also be used inside a constructor to invoke another constructor of the same class.

Chapter 4

1 Javaprovidesthemathematicalmethodssin,cos,tan,asin,acos, atan,toRadians, toDegree, exp, log, log10, pow, sqrt, cell, floor, rint, round, min, max, abs, and random in the Math class for performing mathematical functions. 2. The character type char represents a single character. 3. An escape sequence consists of a backslash (\) followed by a character or a combina- tion of digits. 4. The character \ is called the escape character. 5. The characters ' ', \t, \f, \r, and \n are known as the whitespace characters. 6. Characters can be compared based on their Unicode using the relational operators. 7. The Character class contains the methods isDigit, isLetter, isLetterOrDigit, isLowerCase, isUpperCase for testing whether a character is a digit, letter, lower- case, and uppercase. It also contains the toLowerCase and toUpperCase methods for returning a lowercase or uppercase letter. 8. A string is a sequence of characters. A string value is enclosed in matching double quotes ("). A character value is enclosed in matching single quotes ('). 9. Strings are objects in Java. A method that can only be invoked from a specific object is called an instance method. A non-instance method is called a static method, which can be invoked without using an object. 150 Chapter 4 Mathematical Functions, Characters, and Strings 10. Youcangetthelengthofastringbyinvokingitslength()method,retrieveachar- acter at the specified index in the string using the charAt(index) method, and use the indexOf and lastIndexOf methods to find a character or a substring in a string. 11. You can use the concat method to concatenate two strings, or the plus (+) operator to concatenate two or more strings. 12. You can use the substring method to obtain a substring from the string. 13. You can use the equals and compareTo methods to compare strings. The equals method returns true if two strings are equal, and false if they are not equal. The compareTo method returns 0, a positive integer, or a negative integer, depending on whether one string is equal to, greater than, or less than the other string. 14. The printf method can be used to display a formatted output using format specifiers.

Chapter 3

1. A boolean type variable can store a true or false value. 2. The relational operators (<, <=, ==, !=, >, >=) yield a Boolean value. 3. Selection statements are used for programming with alternative courses of actions. There are several types of selection statements: one-way if statements, two-way if-else statements, nested if statements, multi-way if-else statements, switch statements, and conditional expressions. 4. The various if statements all make control decisions based on a Boolean expression. Based on the true or false evaluation of the expression, these statements take one of two possible courses. 5. The Boolean operators &&, ||, !, and ^ operate with Boolean values and variables. 6. When evaluating p1 && p2, Java first evaluates p1 and then evaluates p2 if p1 is true; if p1 is false, it does not evaluate p2. When evaluating p1 || p2, Java first evaluates p1 and then evaluates p2 if p1 is false; if p1 is true, it does not evaluate p2. Therefore, && is referred to as the conditional or short-circuit AND operator, and || is referred to as the conditional or short-circuit OR operator. 7. The switch statement makes control decisions based on a switch expression of type char, byte, short, int, or String. 8. The keyword break is optional in a switch statement, but it is normally used at the end of each case in order to skip the remainder of the switch statement. If the break statement is not present, the next case statement will be executed. 9. The operators in expressions are evaluated in the order determined by the rules of parentheses, operator precedence, and operator associativity. 10. Parentheses can be used to force the order of evaluation to occur in any sequence. 11. Operators with higher precedence are evaluated earlier. For operators of the same precedence, their associativity determines the order of evaluation. 12. All binary operators except assignment operators are left-associative; assignment operators are right-associative.

Chapter 8 Summary

1. A two-dimensional array can be used to store a table. 2. A variable for two-dimensional arrays can be declared using the syntax: elementType[][] arrayVar. 3. A two-dimensional array can be created using the syntax: new elementType [ROW_SIZE][COLUMN_SIZE]. 4. Each element in a two-dimensional array is represented using the syntax: arrayVar[rowIndex][columnIndex]. 5. You can create and initialize a two-dimensional array using an array initializer with the syntax:elementType[][] arrayVar = {{row values}, . . . , {row values}}. 6. You can use arrays of arrays to form multidimensional arrays. For example, a variable for three-dimensional arrays can be declared as elementType[][][] arrayVar, and a three-dimensional array can be created using new elementType[size1][size2]

14

1. JavaFX is the new framework for developing rich Internet applications. JavaFX com- pletely replaces Swing and AWT. 2. A main JavaFX class must extend javafx.application.Application and imple- ment the start method. The primary stage is automatically created by the JVM and passed to the start method. 3. A stage is a window for displaying a scene. You can add nodes to a scene. Panes, con- trols, and shapes are nodes. Panes can be used as the containers for nodes. 4. A binding property can be bound to an observable source object. A change in the source object will be automatically reflected in the binding property. A binding property has a value getter method, value setter method, and property getter method. 5. The Node class defines many properties that are common to all nodes. You can apply these properties to panes, controls, and shapes. 6. You can create a Color object with the specified red, green, blue components, and opacity value. 7. You can create a Font object and set its name, size, weight, and posture. 8. The javafx.scene.image.Image class can be used to load an image and this image can be displayed in an ImageView object. 9. JavaFX provides many types of panes for automatically laying out nodes in a desired loca- tion and size. The Pane is the base class for all panes. It contains the getChildren() method to return an ObservableList. You can use ObservableList's add(node) and addAll(node1, node2, ...) methods for adding nodes into a pane. 578 Chapter 14 JavaFX Basics download image files 10. A FlowPane arranges the nodes in the pane horizontally from left to right or vertically from top to bottom in the order in which they were added. A GridPane arranges nodes in a grid (matrix) formation. The nodes are placed in the specified column and row indi- ces. A BorderPane can place nodes in five regions: top, bottom, left, right, and center. An HBox lays out its children in a single horizontal row. A VBox lays out its children in a single vertical column. 11. JavaFX provides many shape classes for drawing texts, lines, circles, rectangles, ellip- ses, arcs, polygons, and polylines.

Chapter 6

1. Making programs modular and reusable is one of the central goals in software engineer- ing. Java provides many powerful constructs that help to achieve this goal. Methods are one such construct. 2. The method header specifies the modifiers, return value type, method name, and param- eters of the method. The static modifier is used for all the methods in this chapter. 3. A method may return a value. The returnValueType is the data type of the value the method returns. If the method does not return a value, the returnValueType is the keyword void. 4. The parameter list refers to the type, order, and number of a method's parameters. The method name and the parameter list together constitute the method signature. Param- eters are optional; that is, a method doesn't need to contain any parameters. 5. A return statement can also be used in a void method for terminating the method and returning to the method's caller. This is useful occasionally for circumventing the nor- mal flow of control in a method. 6. The arguments that are passed to a method should have the same number, type, and order as the parameters in the method signature. 7. When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached. 8. A value-returning method can also be invoked as a statement in Java. In this case, the caller simply ignores the return value. 9. A method can be overloaded. This means that two methods can have the same name, as long as their method parameter lists differ. 10. A variable declared in a method is called a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the vari- able. A local variable must be declared and initialized before it is used. 11. Method abstraction is achieved by separating the use of a method from its implementa- tion. The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated in the method and hidden from the client who invokes the method. This is known as information hiding or encapsulation. 12. Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as collections of concise methods are easier to write, debug, maintain, and modify than would otherwise be the case. This writing style also promotes method reusability. 13. When implementing a large program, use the top-down and/or bottom-up coding approach. Do not write the entire program at once. This approach may seem to take more time for coding (because you are repeatedly compiling and running the program), but it actually saves time and makes debugging easier

Chapter 10

1. The procedural paradigm focuses on designing methods. The object-oriented paradigm couples data and methods together into objects. Software design using the object- oriented paradigm focuses on objects and operations on objects. The object-oriented approach combines the power of the procedural paradigm with an added dimension that integrates data with operations into objects. 2. Many Java methods require the use of objects as arguments. Java offers a convenient way to incorporate, or wrap, a primitive data type into an object (e.g., wrapping int into the Integer class, and wrapping double into the Double class). Java can automatically convert a primitive type value to its corresponding wrapper object in the context and vice versa. 4. The BigInteger class is useful for computing and processing integers of any size. The BigDecimal class can be used to compute and process floating-point numbers with any arbitrary precision. 5. A String object is immutable; its contents cannot be changed. To improve efficiency and save memory, the JVM stores two literal strings that have the same character sequence in a unique object. This unique object is called an interned string object. 6. A regular expression (abbreviated regex) is a string that describes a pattern for match- ing a set of strings. You can match, replace, or split a string by specifying a pattern. 7. The StringBuilder and StringBuffer classes can be used to replace the String class. The String object is immutable, but you can add, insert, or append new contents into StringBuilder and StringBuffer objects. Use String if the string contents do not require any change, and use StringBuilder or StringBuffer if they might change.

If today is Tuesday, what will be the day in 100 days?

2 + 100) % 7 = 4. So it is Thursday

Page29

8. A bit is a binary digit 0 or 1. 9. A byte is a sequence of 8 bits. 10. A kilobyte is about 1,000 bytes, a megabyte about 1 million bytes, a gigabyte about 1 billion bytes, and a terabyte about 1,000 gigabytes. 11. Memory stores data and program instructions for the CPU to execute. 12. A memory unit is an ordered sequence of bytes. 13. Memory is volatile, because information is lost when the power is turned off. 14. Programs and data are permanently stored on storage devices and are moved to memory when the computer actually uses them. 15. The machine language is a set of primitive instructions built into every computer. 16. Assembly language is a low-level programming language in which a mnemonic is used to represent each machine-language instruction. 17. High-level languages are English-like and easy to learn and program. 18. A program written in a high-level language is called a source program. 19. A compiler is a software program that translates the source program into a machine- language program. 20. Theoperatingsystem(OS)isaprogramthatmanagesandcontrolsacomputer'sactivities. 21. Java is platform independent, meaning that you can write a program once and run it on any computer. 22. Java programs can be embedded in HTML pages and downloaded by Web browsers to bring live animation and interaction to Web clients. 23. The Java source file name must match the public class name in the program. Java source code files must end with the .java extension. 24. Every class is compiled into a separate bytecode file that has the same name as the class and ends with the .class extension. 25. To compile a Java source-code file from the command line, use the javac command. 26. To run a Java class from the command line, use the java command. 27. Every Java program is a set of class definitions. The keyword class introduces a class definition. The contents of the class are included in a block. 28. A block begins with an opening brace ({) and ends with a closing brace (}). 29. Methods are contained in a class. To run a Java program, the program must have a main method. The main method is the entry point where the program starts when it is executed.

Chapter 31 Summary

Java supports stream sockets and datagram sockets. Stream sockets use TCP (Trans- mission Control Protocol) for data transmission, whereas datagram sockets use UDP (User Datagram Protocol). Since TCP can detect lost transmissions and resubmit them, transmissions are lossless and reliable. UDP, in contrast, cannot guarantee lossless transmission. 2. To create a server, you must first obtain a server socket, using new ServerSocket (port). After a server socket is created, the server can start to listen for connections, using the accept() method on the server socket. The client requests a connection to a server by using new Socket(serverName, port) to create a client socket. 3. Stream socket communication is very much like input/output stream communication after the connection between a server and a client is established. You can obtain an input stream using the getInputStream() method and an output stream using the getOutputStream() method on the socket. 4. A server must often work with multiple clients at the same time. You can use threads to handle the server's multiple clients simultaneously by creating a thread for each

Identify and fix the errors in the following code: 1 public class Test { 2 public void main(string[] args) { 3 double i = 50.0; 4 double k = i + 50.0; 5 double j = k + 1; 6 7 System.out.println("j is " + j + " and 8 k is " + k); 9 } 10 }

Line 2: Missing static for the main method. Line 2: string should be String. Lines 7-8: The string cannot be broken into two lines.

▼2.9.7 Write a statement to display the result of 2 3.5 .

Math.pow(2, 3.5)

Are there any performance differences between the following two import statements? import java.util.Scanner; import java.util.*;

No

Chapter 21

The Java Collections Framework supports sets, lists, queues, and maps. They are defined in the interfaces Set, List, Queue, and Map. 2. A list stores an ordered collection of elements. 3. All the concrete classes except PriorityQueue in the Java Collections Framework implement the Cloneable and Serializable interfaces. Thus, their instances can be cloned and serialized. 4. To allow duplicate elements to be stored in a collection, you need to use a list. A list not only can store duplicate elements but also allows the user to specify where they are stored. The user can access elements by an index. 5. Two types of lists are supported: ArrayList and LinkedList. ArrayList is a resizable-array implementation of the List interface. All the methods in ArrayList are defined in List. LinkedList is a linked-list implementation of the List interface. In addition to implementing the List interface, this class provides the methods for retrieving, inserting, and removing elements from both ends of the list. 6. Comparator can be used to compare the objects of a class that doesn't implement Comparable. 7. TheVectorclassextendstheAbstractListclass.StartingwithJava2,Vectorhas been the same as ArrayList, except that the methods for accessing and modifying the vector are synchronized. The Stack class extends the Vector class and provides several methods for manipulating the stack. 8. The Queue interface represents a queue. The PriorityQueue class implements Queue for a priority queue.

Chapter 5 Summary

There are three types of repetition statements: the while loop, the do-while loop, and the for loop. 2. The part of the loop that contains the statements to be repeated is called the loop body. 3. A one-time execution of a loop body is referred to as an iteration of the loop. 4. An infinite loop is a loop statement that executes infinitely. 5. In designing loops, you need to consider both the loop control structure and the loop body. 6. The while loop checks the loop-continuation-condition first. If the condition is true, the loop body is executed; if it is false, the loop terminates. 7. The do-while loop is similar to the while loop, except that the do-while loop exe- cutes the loop body first and then checks the loop-continuation-condition to decide whether to continue or to terminate. 8. The while loop and the do-while loop often are used when the number of repetitions is not predetermined. 9. A sentinel value is a special value that signifies the end of the loop. 10. The for loop generally is used to execute a loop body a fixed number of times. 11. The for loop control has three parts. The first part is an initial action that often ini- tializes a control variable. The second part, the loop-continuation-condition, determines whether the loop body is to be executed. The third part is executed after each iteration and is often used to adjust the control variable. Usually, the loop control variables are initialized and changed in the control structure. 12. The while loop and for loop are called pretest loops because the continuation condi- tion is checked before the loop body is executed. 13. The do-while loop is called a posttest loop because the condition is checked after the loop body is executed. 14. Two keywords, break and continue, can be used in a loop. 15. The break keyword immediately ends the innermost loop, which contains the break. 16. The continue keyword only ends the current iteration.

Chapter 32

This chapter introduced the concepts of database systems, relational databases, relational data models, data integrity, and SQL. You learned how to develop database applications using Java. 2. The Java API for developing Java database applications is called JDBC. JDBC provides Java programmers with a uniform interface for accessing and manipulating relational databases. 3. The JDBC API consists of classes and interfaces for establishing connections with data- bases, sending SQL statements to databases, processing the results of SQL statements, and obtaining database metadata. 4. Since a JDBC driver serves as the interface to facilitate communications between JDBC and a proprietary database, JDBC drivers are database specific. A JDBC-ODBC bridge driver is included in JDK to support Java programs that access databases through ODBC drivers. If you use a driver other than the JDBC-ODBC bridge driver, make sure it is in the classpath before running the program. 5. Four key interfaces are needed to develop any database application using Java: Driver, Connection, Statement, and ResultSet. These interfaces define a framework for generic SQL database access. The JDBC driver vendors provide implementation for them. 6. A JDBC application loads an appropriate driver using the Driver interface, connects to the database using the Connection interface, creates and executes SQL statements using the Statement interface, and processes the result using the ResultSet interface if the statements return results. 7. The PreparedStatement interface is designed to execute dynamic SQL statements with parameters. These SQL statements are precompiled for efficient use when repeatedly executed. 8. Database metadata is information that describes the database itself. JDBC provides the DatabaseMetaData interface for obtaining database-wide information and the ResultSetMetaData interface for obtaining information on the specific Resul

Chapter 24

You learned how to implement array lists, linked lists, stacks, and queues. 2. To define a data structure is essentially to define a class. The class for a data structure should use data fields to store data and provide methods to support operations such as insertion and deletion. 3. To create a data structure is to create an instance from the class. You can then apply the methods on the instance to manipulate the data structure, such as inserting an element into the data structure or deleting an element from the data structure. 4. You learned how to implement a priority queue using a heap.


Set pelajaran terkait

Commercial Law Chapters 9,10,11,12,13,14,(little)15,17,18 Test #2

View Set

International Business Test #3 - Chapter 8

View Set

Chapter 4: Identity and Access Management

View Set

PSYC 3610 Exam 1: Homework Questions

View Set

REPRODUCTIVE ANATOMY & PIISIOLOGY CH 5

View Set

Post Operative Nursing Management

View Set