Beginning Java 8 Fundamentals

Covers Java 8 features such as compact profiles, and the new date and time APIS.


Kishori Sharan


810 Pages

80699 Reads

41 Downloads

English

PDF Format

9.02 MB

Java Programming

Download PDF format


  • Kishori Sharan   
  • 810 Pages   
  • 23 Feb 2015
  • Page - 1

    www.it-ebooks.info read more..

  • Page - 2

    For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. www.it-ebooks.info read more..

  • Page - 3

    v Contents at a Glance Foreword .......................................................................................................................... xxv About the Author ............................................................................................................ xxvii About the Technical Reviewer ......................................................................................... xxix Acknowledgments read more..

  • Page - 4

    CONTENTS AT A GLANCE vi Chapter 16: Inheritance .................................................................................................583 Chapter 17: Interfaces ...................................................................................................643 Chapter 18: Enum Types ................................................................................................705 Appendix A: Character Encodings read more..

  • Page - 5

    xxxiii Introduction How This Book Came About My first encounter with the Java programming language was during a one-week Java training session in 1997. I did not get a chance to use Java in a project until 1999. I read two Java books and took a Java 2 Programmer certification examination. I did very well on the test, scoring 95 percent. The three questions that read more..

  • Page - 6

    INTRODUCTION xxxiv Structure of the Book This book contains 18 chapters and three appendixes. The chapters contain fundamental topics of Java such as syntax, data types, operators, classes, objects, etc. The chapters are arranged in an order that aids learning the Java programming language faster. The first chapter, “Programming Concepts,” explains basic concepts related read more..

  • Page - 7

    INTRODUCTION xxxv Readers are advised to use the API documentation for the Java programming language, as much as possible, while using this book. The Java API documentation is the place where you will find a complete list of documentation for everything available in the Java class library. You can download (or view) the Java API documentation from the official web site of read more..

  • Page - 8

    1 CHAPTER 1 Programming Concepts In this chapter, you will learn The general concept of programming Different components of programming Major programming paradigms The object-oriented paradigm and how it is used in Java What Is Programming? The term “programming” is used in many contexts. We will discuss its meaning in the context of human-to-computer interaction. In the read more..

  • Page - 9

    CHAPTER 1 PROGRAMMING CONCEPTS 2 adds two numbers, 15 and 12. The program to add two numbers in machine language will look similar to the one shown below. You do not need to understand the sample code written in this section. It is only for the purpose of discussion and illustration. 0010010010 10010100000100110 0001000100 01010010001001010 The above instructions read more..

  • Page - 10

    CHAPTER 1 PROGRAMMING CONCEPTS 3 You may notice that the programs written in a high-level language are easier and more intuitive to write, read, understand, and modify than the programs written in machine and assembly languages. You might have realized that computers do not understand programs written in high-level languages, as they understand only sequences of 0s and read more..

  • Page - 11

    CHAPTER 1 PROGRAMMING CONCEPTS 4 In a written language, you may form a grammatically correct sentence, which may not have any valid meaning. For example, “The stone is laughing.” is a grammatically correct sentence. However, it does not make any sense. In a written language, this kind of ambiguity is allowed. A programming language is meant to communicate instructions read more..

  • Page - 12

    CHAPTER 1 PROGRAMMING CONCEPTS 5 It is not enough just to have a solution to a problem. The solution must be practical and effective. Since the solution to a problem is always related to the way the problem and the solution are thought about, the paradigm becomes paramount. You can see that the solution provided by the monk may kill the hungry people read more..

  • Page - 13

    CHAPTER 1 PROGRAMMING CONCEPTS 6 int num = 15; // num holds 15 at this point int counter = 0; // counter holds 0 at this point while(counter < 10) { num = num + 1; // Modifying data in num counter = counter + 1; // Modifying data in counter } // num holds 25 at this point The first two lines read more..

  • Page - 14

    CHAPTER 1 PROGRAMMING CONCEPTS 7 Declarative Paradigm In the declarative paradigm, a program consists of the description of a problem and the computer finds the solution. The program does not specify how to arrive at the solution to the problem. It is the computer’s job to arrive at a solution when a problem is described to it. Contrast the declarative paradigm read more..

  • Page - 15

    CHAPTER 1 PROGRAMMING CONCEPTS 8 Logic Paradigm Unlike the imperative paradigm, the logic paradigm focuses on the “what” part of the problem rather than how to solve it. All you need to specify is what needs to be solved. The program will figure out the algorithm to solve it. The algorithm is of less importance to the programmer. The primary task of the read more..

  • Page - 16

    CHAPTER 1 PROGRAMMING CONCEPTS 9 Suppose you want to represent real-world people in your program. You will create a Person class and its instances will represent people in your program. The Person class can be defined as shown in Listing 1-1. This example uses the syntax of the Java programming language. You do not need to understand the syntax used in the read more..

  • Page - 17

    CHAPTER 1 PROGRAMMING CONCEPTS 10 The first object is called john with John Jacobs and Male as the initial values for its name and gender properties, respectively. The second object is called donna with Donna Duncan and Female as the initial values for its name and gender properties, respectively. Methods of a class represent behaviors of its objects. For read more..

  • Page - 18

    CHAPTER 1 PROGRAMMING CONCEPTS 11 To name a few, C++, Java and C# (pronounced as C sharp) are programming languages that support the object-oriented paradigm. Note that a programming language itself is not object-oriented. It is the paradigm that is object-oriented. A programming language may or may not have features to support the object-oriented paradigm. What Is read more..

  • Page - 19

    CHAPTER 1 PROGRAMMING CONCEPTS 12 machines connected through a network. Java has features that make it easy to develop concurrent applications. A concurrent application has multiple interacting threads of execution running in parallel. I will discuss these features of the Java platform in detail in subsequent chapters in this book. Robustness of a program refers to its read more..

  • Page - 20

    CHAPTER 1 PROGRAMMING CONCEPTS 13 Abstraction A program provides solutions to a real-world problem. The size of the program may range from a few lines to a few million lines. It may be written as a monolithic structure running from the first line to the millionth line in one place. A monolithic program becomes harder to write, understand, and maintain if its size is read more..

  • Page - 21

    CHAPTER 1 PROGRAMMING CONCEPTS 14 All of the above characteristics are achieved during decomposition of a problem (or program that solves a problem) using a process called abstraction. What is abstraction? Abstraction is a way to perform decomposition of a problem by focusing on relevant details and ignoring the irrelevant details about it in a particular context. Note read more..

  • Page - 22

    CHAPTER 1 PROGRAMMING CONCEPTS 15 This snippet of code will perform the sum of all integers between 40 and 60, and it will print 1050. Note the similarities and differences between the two snippets of code. The logic is the same in both. However, the lower limit and the upper limit of the range are different. If you can ignore the differences that exist read more..

  • Page - 23

    CHAPTER 1 PROGRAMMING CONCEPTS 16 To compute the sum all integers between 40 and 60, you can execute the following snippet of code: int s2 = getRangeSum(40, 60); System.out.println(s2); This snippet of code will print 1050, which is exactly the same result you had achieved before. The abstraction method that you used in defining the getRangeSum procedure is called read more..

  • Page - 24

    CHAPTER 1 PROGRAMMING CONCEPTS 17 * @param lowerLimit The lower limit of the integer range * @param upperLimit The upper limit of the integer range * @return The sum of all integers between lowerLimit (inclusive) * and upperLimit (inclusive) */ public static int getRangeSum(int lowerLimit, int upperLimit) { int sum = 0; read more..

  • Page - 25

    CHAPTER 1 PROGRAMMING CONCEPTS 18 words, you have hidden the details of implementation of getRangeSum procedure from its users by providing the above specification to them. That is, users of the getRangeSum procedure can ignore its implementation details for the purpose of using it. This is another concrete example of abstraction. The method of hiding implementation details read more..

  • Page - 26

    CHAPTER 1 PROGRAMMING CONCEPTS 19 Note that the body (implementation or the “how” part) of the getRangeSum procedure has changed between Listing 1-2 and Listing 1-3. However, the users of the getRangeSum procedure are not affected by this change at all because the details of the implementation of this procedure were kept hidden from its users by using abstraction. read more..

  • Page - 27

    CHAPTER 1 PROGRAMMING CONCEPTS 20 At this stage, you may be asking, “Where is the value 26, which is associated with the name n1, stored in memory?” You know from the definition of int data type that n1 will take 32-bit memory. However, you do not know, cannot know, and do not need to know where in the memory that 32-bit is allocated for n1. Do read more..

  • Page - 28

    CHAPTER 1 PROGRAMMING CONCEPTS 21 Users of the Person class must use only these four operations to work with data objects of Person type. Users of the Person type are oblivious to the type of data storage being used to store name and gender data elements. I am using three terms, “type,” “class,” and “interface,” interchangeably because they mean the read more..

  • Page - 29

    CHAPTER 1 PROGRAMMING CONCEPTS 22 You have seen two major benefits of data abstraction in this section. It lets you extend the programming language by letting you define new data types. The new data types you create depend on the application domain. For example, for a banking system, Person, Currency, and Account may be good choices for new data types whereas for read more..

  • Page - 30

    CHAPTER 1 PROGRAMMING CONCEPTS 23 Listing 1-6. The Definition of the Person2 Class in Which Data Elements Are Not Hidden by Declaring Them Public package com.jdojo.concepts; public class Person2 { public String name; // Not hidden from its users public String gender; // Not hidden from its users public Person2(String read more..

  • Page - 31

    CHAPTER 1 PROGRAMMING CONCEPTS 24 Inheritance allows you to use varying degrees of abstraction at different levels of hierarchy. In Figure 1-6, the Person class is at the top (highest level) of the inheritance hierarchy. Employee and Customer classes are at the second level of inheritance hierarchy. As you move up the inheritance level, you focus on more important read more..

  • Page - 32

    CHAPTER 1 PROGRAMMING CONCEPTS 25 Polymorphism The word “polymorphism” has its root in two Greek words: “poly” (means ma ny) and “morphos” (means form). In programming, polymorphism is the ability of an entity (e.g. variable, class, method, object, code, parameter, etc.) to take on different meanings in different contexts. The entity that takes on different meanings is read more..

  • Page - 33

    CHAPTER 1 PROGRAMMING CONCEPTS 26 The max() method of the MathUtil class is overloaded. It has three definitions and each of its definitions performs the same task of computing maximum, but on different types. The first definition computes a maximum of two numbers of int data type, the second one computes a maximum of two floating-point numbers of double data read more..

  • Page - 34

    CHAPTER 1 PROGRAMMING CONCEPTS 27 Consider the following snippet of code that shows a definition of a square() method, which accepts a parameter of double data type: double square(double num) { return num * num; } The square() method can be called with actual parameter of double data type as double d1 = 20.23; double result = square(d1); The read more..

  • Page - 35

    CHAPTER 1 PROGRAMMING CONCEPTS 28 Java supports inclusion polymorphism using inheritance, which is a subclassing mechanism. You can define a method in Java using a formal parameter of a type, for example, Person, and that method can be called on all its subtypes, for example, Employee, Student, Customer, etc. Suppose you have a method processDetails() as follows: void read more..

  • Page - 36

    CHAPTER 1 PROGRAMMING CONCEPTS 29 // Use List for String type List<String> sList = new ArrayList<String>(); sList.add("string 1"); sList.add("string 2"); String s2 = sList.get(1); // Use List for Integer type List<Integer> iList = new ArrayList<Integer>(); iList.add(10); iList.add(20); int i2 = iList.get(1); Summary Writing the set of instructions for a computer to read more..

  • Page - 37

    31 CHAPTER 2 Writing Java Programs In this chapter, you will learn How to write, compile, and run Java programs using command prompts and the NetBeans integrated development environment (IDE) How to set the CLASSPATH for running Java programs Briefly about the Java Virtual Machine (JVM) and the Java Platform What is a Java Program? A Java program, which is written using read more..

  • Page - 38

    CHAPTER 2 WRITING JAVA PROGRAMS 32 Note Java SE 8 is not supported on Windows XP. Writing the Source Code This section will cover the details of writing the source code. I will demonstrate this by using Notepad on Windows. You can use a text editor of your choice that is available on your system. Note I will cover using the NetBeans IDE in the following read more..

  • Page - 39

    CHAPTER 2 WRITING JAVA PROGRAMS 33 Package Declaration The general syntax for a package declaration is package <your-package-name>; A package declaration starts with the keyword package followed with a user-supplied package name. One or more whitespaces (spaces, tabs, new lines, carriage returns, tabs, and form-feeds) separate the keyword package and the package name. A read more..

  • Page - 40

    CHAPTER 2 WRITING JAVA PROGRAMS 34 Knowing just the package name is not enough to locate a class file, because it specifies only a partial path to the class file. The leading part of the class file path on the file system is obtained from an environment variable called CLASSPATH. I will discuss CLASSPATH in detail shortly. The package declaration is optional. What read more..

  • Page - 41

    CHAPTER 2 WRITING JAVA PROGRAMS 35 If you want to use a class named Person from com.jdojo.common package in the source code, you need to include one of the following two import declarations in your source code: import com.jdojo.common.Person; or import com.jdojo.common.*; The following import declarations do not include classes in the package com or com.jdojo: read more..

  • Page - 42

    CHAPTER 2 WRITING JAVA PROGRAMS 36 A class is declared by using the keyword class, which is followed by the name of the class. In this example, the name of the class is Welcome. The body of the class is placed between an opening brace and a closing brace. The body may be empty. However, you must include the two braces to mark the beginning and the end read more..

  • Page - 43

    CHAPTER 2 WRITING JAVA PROGRAMS 37 The following line is a single-line comment. It has a valid package declaration as the comment’s text. It will be treated as a comment, not as a package declaration. // package com.jdojo.intro; The second type of comment is called a multi-line comment. A multi-line comment may span multiple lines. It starts with a read more..

  • Page - 44

    CHAPTER 2 WRITING JAVA PROGRAMS 38 Class Declaration #2 class Welcome { } Class Declaration #3 class Welcome { } This book uses the following class declaration format: the opening brace is placed on the same line following the class name, and the closing brace is placed on a separate line and it is aligned with the first character of the first read more..

  • Page - 45

    CHAPTER 2 WRITING JAVA PROGRAMS 39 This method declaration contains four things: The method does not return anything as indicated by the keyword void. The name of the method is main. The method requires no arguments. The method does not do anything as its body is empty. The return value of a method is something that the method returns to its caller. The caller of read more..

  • Page - 46

    CHAPTER 2 WRITING JAVA PROGRAMS 40 it means that num is an identifier of the type int and it can hold one integer value. If you place two magic brackets ( []) after int, as in int[] num it means that num is an array of int and it can hold as many integer values as you want. There is a limit to the number of integers that num can read more..

  • Page - 47

    CHAPTER 2 WRITING JAVA PROGRAMS 41 For now, you can think of public and static just as two keywords, which must be present to declare the main method. Note that the JVM also requires that the name of the method must be main. This is the reason that I chose main as the name of the method from the very beginning. It is just a rule imposed by read more..

  • Page - 48

    CHAPTER 2 WRITING JAVA PROGRAMS 42 Compiling the Source Code Compiling is the process of translating the source code into a special binary format called bytecode. This is accomplished using a program (usually called a compiler) javac, which comes with JDK from Oracle Corporation. The process of compiling Java source code is shown in Figure 2-4. Java source code read more..

  • Page - 49

    CHAPTER 2 WRITING JAVA PROGRAMS 43 If you do not want to change the current working directory to C:\javaprograms\com\jdojo\intro, you can compile your source code using the full path for Welcome.java file as follows: C:\>C:\java8\bin\javac C:\javaprograms\com\jdojo\intro\Welcome.java It does not matter how you specify the path for the javac command and the Welcome.java read more..

  • Page - 50

    CHAPTER 2 WRITING JAVA PROGRAMS 44 Tip The JVM also allows you to use a forward slash in place of a dot in the fully qualified name of the class to run. For example, you can also use the following command to run the Welcome class: C:\javaprograms>java com/jdojo/intro/Welcome When you use forward slashes in place of dots in the fully qualified name of the read more..

  • Page - 51

    CHAPTER 2 WRITING JAVA PROGRAMS 45 Figure 2-5. Environment Variables dialog box for setting CLASSPATH on Windows Figure 2-6. New/Edit System variable dialog box for setting CLASSPATH on Windows www.it-ebooks.info read more..

  • Page - 52

    CHAPTER 2 WRITING JAVA PROGRAMS 46 Tip The value for CLASSPATH is a list of directories, JAR files, and ZIP files that are separated by a path-separator. The path-separator is operating system dependent. On a Windows operating system, the separator is a semicolon. On a UNIX-like operating systems, for example, Linux, Solaris, and Mac OS X, the read more..

  • Page - 53

    CHAPTER 2 WRITING JAVA PROGRAMS 47 or C:\>java –classpath C:\;C:\jbook;C:\javaprograms com.jdojo.intro.Welcome Can you run your Welcome class example without worrying about the CLASSPATH setting? The answer is yes and no. Sometimes, CLASSPATH setting becomes a bit tricky. If you don’t set any value for CLASSPATH as in SET CLASSPATH= the JVM uses the current working read more..

  • Page - 54

    CHAPTER 2 WRITING JAVA PROGRAMS 48 Using NetBeans IDE You can use the NetBeans IDE to write, compile, and run Java programs. In this section, you will walk through the steps of working with NetBeans. First, you will learn how to create a new Java project, write a simple Java program, compile, and run it. At the end, you will learn how to open the read more..

  • Page - 55

    CHAPTER 2 WRITING JAVA PROGRAMS 49 To create a new Java project, follow these steps. 1. Select the menu item New Project under the File menu. A New Project dialog is displayed, as shown in Figure 2-9. Figure 2-8. The NetBeans IDE with the startup page www.it-ebooks.info read more..

  • Page - 56

    CHAPTER 2 WRITING JAVA PROGRAMS 50 2. In the New Project dialog, select “Java” in the Categories list and “Java Application” in the Projects list. Click the Next button. A New Java Application dialog, shown in Figure 2-10, is displayed. Figure 2-9. A New Project dialog Figure 2-10. A New Java Application dialog www.it-ebooks.info read more..

  • Page - 57

    CHAPTER 2 WRITING JAVA PROGRAMS 51 3. In the New Java Application dialog, enter TestApp as the project name. Enter or browse for a location where you want to save the project files. Make sure the checkbox “Create Main Class” is selected and a class name com.jdojo.intro.Welcome is entered next to the checkbox. Click the Finish button when you are done. read more..

  • Page - 58

    CHAPTER 2 WRITING JAVA PROGRAMS 52 NetBeans lets you run a project or a single Java class. To run a project, you need to set a main class, which is the fully qualified name of a class with a main() method, as you had for the Welcome class. In this case, enter com.jdojo.intro.Welcome as the main class for the TestApp project. If you run the project, read more..

  • Page - 59

    CHAPTER 2 WRITING JAVA PROGRAMS 53 2. Select the New New Class menu item from the right-clicked menu list. Selecting the New Class menu option displays a New Java Class dialog, as shown in Figure 2-15. Figure 2-15. A New Java Class dialog Figure 2-14. Accessing new option to add a new class www.it-ebooks.info read more..

  • Page - 60

    CHAPTER 2 WRITING JAVA PROGRAMS 54 3. Enter the new class name in the Class Name field. If you accessed this dialog by selecting a package in the IDE, the Package field is pre-filled with the selected package in the IDE. If you accessed this dialog by selecting a project, this field is blank; you need to enter the package name for the new class. You can read more..

  • Page - 61

    CHAPTER 2 WRITING JAVA PROGRAMS 55 On the left side of the dialog is the list of categories of properties. When you select a property category, the details are displayed on the right side. The following are brief descriptions of each property category: Sources: It is used set source code-related properties, for example, source folder, format, profile, encoding, etc. read more..

  • Page - 62

    CHAPTER 2 WRITING JAVA PROGRAMS 56 3. Select the project and click the Open Project button. The project is opened the project in the IDE. Use the Project or Files tabs on the left to browse the source code for all chapters in this book. Behind the Scenes This section will answer some general questions related to compiling and running Java programs. For example, read more..

  • Page - 63

    CHAPTER 2 WRITING JAVA PROGRAMS 57 A Java program compiled into bytecode format has two advantages: You do not need to recompile your source code if you want to run it on another machine with a different operating system. It is also called platform independence in Java. It is also known as “write once, run anywhere” for Java code. If you are running a read more..

  • Page - 64

    CHAPTER 2 WRITING JAVA PROGRAMS 58 The term “JVM” is used in three contexts: The JVM specification: It is the specification or standard of an abstract machine for which a Java compiler can generate bytecode. The concrete realization of the JVM specification: If you want to run your Java program, you need to have a real JVM, which is developed using the abstract read more..

  • Page - 65

    CHAPTER 2 WRITING JAVA PROGRAMS 59 Summary Java programs are written in plain text format using a text editor or IDE. The Java source code is also known as a compilation unit and it is stored in a file with a .java extension. Several integrated development environments (IDEs) for Java, such as NetBeans, are freely available in the market. Using an IDE to develop read more..

  • Page - 66

    61 CHAPTER 3 Data Types In this chapter, you will learn: What data types are What identifiers are and detailed rules to declare them The difference between primitive and reference data types How to declare variables of a data type How to assign a value to a variable Detailed descriptions of all primitive data types in Java What literals of a data type are What read more..

  • Page - 67

    CHAPTER 3 DATA TYPES 62 Java provides many built-in primitive data types, such as int, float, boolean, char, etc. For example, the three components that define the int primitive data type in Java are as follows: An int data type consists of a set of all integers between -2,147,483,648 and 2,147,483,647. Operations such as addition, subtraction, multiplication, read more..

  • Page - 68

    CHAPTER 3 DATA TYPES 63 Examples of invalid identifiers are as follows: 2num // Cannot start with a number my name // Cannot have a space num1+num2 // Cannot have + sign num1-num2 // Cannot have hyphen or minus sign Java defines a list of words called keywords. Keywords are words that have predefined meanings in Java and they can only be used read more..

  • Page - 69

    CHAPTER 3 DATA TYPES 64 Now, if your friend wants you to tell him the difference of the same two numbers, he does not need to tell you those two numbers again. This is because these two numbers are stored in your memory, and your brain can recall and use them again. However, whether your brain can perform addition of those two numbers depends on many read more..

  • Page - 70

    CHAPTER 3 DATA TYPES 65 Because you have declared num1 and num2 variables of int data type, you cannot store a real number, such as 10.51, at these memory locations. The following piece of code stores 50 in num1 and 70 in num2: num1 = 50; num2 = 70; The memory states after execution of the above two lines of code have been depicted in Figure 3-1 read more..

  • Page - 71

    CHAPTER 3 DATA TYPES 66 You can also assign the reference of an object stored in one reference variable to another reference variable. In such cases, both reference variables refer to the same object in memory. This can be achieved as follows: // Declares String reference variable str1 and str2 String str1; String str2; // Assigns the reference of a String read more..

  • Page - 72

    CHAPTER 3 DATA TYPES 67 A String object is created using the new operator. However, strings are used so often that there is a shortcut to create a string object. All string literals, a sequence of characters enclosed in double quotes, are treated as String objects. Therefore, instead of using the new operator to create a String object, you can use read more..

  • Page - 73

    CHAPTER 3 DATA TYPES 68 The int Data Type The int data type is a 32-bit signed Java primitive data type. A variable of the int data type takes 32 bits of memory. Its valid range is -2,147,483,648 to 2,147,483,647 (-231 to 231 - 1). All whole numbers in this range are known as integer literals (or integer constants). For example, 10, -200, 0, 30, 19, read more..

  • Page - 74

    CHAPTER 3 DATA TYPES 69 An int literal can also be represented using the binary number format. All int literals in the binary number format start with 0b or 0B, that is, zero immediately followed by an uppercase or lowercase B. The following are examples of using int literals in the binary number format: int num1 = 0b10101; int num2 = 0b00011; int num3 read more..

  • Page - 75

    CHAPTER 3 DATA TYPES 70 When a long literal is assigned to a variable of type long, the Java compiler checks the value being assigned and makes sure that it is in the range of the long data type; otherwise it generates a compile time error. For example // One more than maximum positive value for long. This will generate a compiler error long num1 = read more..

  • Page - 76

    CHAPTER 3 DATA TYPES 71 Java has a class Long (note the upper case L in Long), which defines two constants to represent maximum and minimum values of long data type, L ong.MAX_VALUE and Long.MIN_VALUE. long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; The byte Data Type The byte data type is an 8-bit signed Java primitive integer data type. Its range is -128 read more..

  • Page - 77

    CHAPTER 3 DATA TYPES 72 However, irrespective of the value in the source int variable, the destination byte variable will always have a value between -128 and 127. Like int, since long is also a bigger data type than byte, you need to use explicit cast if you want to assign the value of a long variable to a byte variable. For example, byte b4 = read more..

  • Page - 78

    CHAPTER 3 DATA TYPES 73 Java has a class called Short (note the upper case S in Short), which defines two constants to represent maximum and minimum values of short data type, Short.MAX_VALUE and Short.MIN_VALUE. short max = Short.MAX_VALUE; short min = Short.MIN_VALUE; The char Data Type The char data type is a 16-bit unsigned Java primitive data type. It read more..

  • Page - 79

    CHAPTER 3 DATA TYPES 74 Table 3-2. List of Character Escape Sequences Character Escape Sequence Description '\n' A linefeed '\r' A carriage return '\f' A form feed '\b' A backspace '\t' A tab '\\' A backslash '\"' A double quote '\'' A single quote A character literal expressed in the form of a character escape sequence consists of two characters—a backslash and a character read more..

  • Page - 80

    CHAPTER 3 DATA TYPES 75 You can also assign an int literal to a char variable if int literal falls in the range 0-65535. When you assign an int literal to a char variable, the char variable represents the character whose Unicode code is equal to the value represented by that int literal. The Unicode code for the character 'a' (lowercase A) is 97. read more..

  • Page - 81

    CHAPTER 3 DATA TYPES 76 The boolean Data Type The boolean data type has only two valid values: true and false. These two values are called boolean literals. You can use boolean literals as boolean done; // Declares a boolean variable named done done = true; // Assigns true to done One important point to note is that a boolean variable cannot be cast read more..

  • Page - 82

    CHAPTER 3 DATA TYPES 77 All real numbers that end with f or F are called float literals. A float literal can be expressed in the following two formats: Decimal number format Scientific notation Examples of float literals in decimal number format are as follows: float f1 = 8F; float f2 = 8.F; float f3 = 8.0F; float f4 = 3.51F; float f5 = 0.0F; float f6 read more..

  • Page - 83

    CHAPTER 3 DATA TYPES 78 The value of all integral types ( int, long, byte, short, and char) can be assigned to a variable of the float data type without using an explicit cast. The following are some examples of using the float data type: int num1 = 15000; float salary = num1; // Ok. int variable to float salary = 12455; read more..

  • Page - 84

    CHAPTER 3 DATA TYPES 79 All real numbers are called double literals. A double literal may optionally end with d or D, for example, 19.27d. However, the suffix d or D is optional in double literals. That is, both 19.27 and 19.27d represent the same double literal. This book uses double literals without the suffix d or D. A double literal can be read more..

  • Page - 85

    CHAPTER 3 DATA TYPES 80 The value of all integral types ( int, long, byte, short, char) and float can be assigned to a variable of the double data type without using an explicit cast. int num1 = 15000; double salary = num1; // Ok. int to double assignment salary = 12455; // Ok. int literal to read more..

  • Page - 86

    CHAPTER 3 DATA TYPES 81 and 0b for binary format, and suffixes such as L for long literal and F for float literal. The following examples show the invalid uses of underscores in numeric literals: int y1 = _1969; // An error. Underscore in the beginning int y2 = 1969_; // An error. Underscore in the end int y3 = 0x_7B1; read more..

  • Page - 87

    CHAPTER 3 DATA TYPES 82 Even if this line is a comment line, it will generate a compiler error. The comment will be split into two lines before compilation, like so: // char c = ' '; The second line, which contains, ';, causes the compiler error. The multi-line comment syntax would not generate a compiler error in such a case. /* char c = '\u000A'; */ read more..

  • Page - 88

    CHAPTER 3 DATA TYPES 83 // Print some double constants System.out.println("Max double = " + Double.MAX_VALUE); System.out.println("Min double = " + Double.MIN_VALUE); System.out.println("Positive infinity for double = " + Double.POSITIVE_INFINITY); read more..

  • Page - 89

    CHAPTER 3 DATA TYPES 84 Figure 3-5. MSB and LSB in a binary number Table 3-5. Decimal-to-Binary Conversion Number Divided by 2 Result Remainder 13 13/2 6 1 6 6/2 3 0 3 3/2 1 1 1 1/2 0 1 The binary representation of decimal number 13 is 1101. A byte variable in Java occupies one byte. The value 13 in a byte variable is stored as 00001101. Note that read more..

  • Page - 90

    CHAPTER 3 DATA TYPES 85 In binary number system, the 1’s complement of a binary number is given by (2n-1) - N. Since 2n in binary number system consists of 1 followed by n zeros, (2n-1) consists of n 1s. For example, 1’s complement of 10110 (here, n is 5) can be computed as (25 -1) - 10110, which is 11111 - 10110 ( 25-1) is 31, which read more..

  • Page - 91

    CHAPTER 3 DATA TYPES 86 Figure 3-7. Storing the number 13 in 2’s complement forms Binary Representation of Floating-Point Numbers Any binary floating-point system can represent only a finite number of floating-point values in exact form. All other values must be approximated by the closest representable value. The IEEE 754-1985 is the most widely accepted floating-point read more..

  • Page - 92

    CHAPTER 3 DATA TYPES 87 According to this rule, the representation 0.1925 x 102 is the normalized form of 19.25. The floating-point number 19.25 (base 10) can be written as 10011.01 in binary form (base 2). The floating-point number 19.25 can be rewritten in many different binary forms. Some of the alternate binary representations of decimal 19.25 are as follows: read more..

  • Page - 93

    CHAPTER 3 DATA TYPES 88 In a normalized form, the significand can use all its storage bits to store significant digits (bits). For example, if you allocate only five bits to store the significand, for the number 0.0010110 x 210 only 0.00101 part of the significand will be stored. However, if you normalize this number as 1.0110 x 27, the significand can be read more..

  • Page - 94

    CHAPTER 3 DATA TYPES 89 Exponent The exponent takes 8 bits. The exponent can be positive or negative. The range of the exponent value that can be stored in 8-bit is -127 to 128. There must be a mechanism to represent the sign of the exponent. Note that the 1-bit sign field in the layout shown in Table 3-7 stores the sign of the floating-point number, read more..

  • Page - 95

    CHAPTER 3 DATA TYPES 90 Actual Significand: 1.fffffffffffffffffffffff (24 digits) Stored Significand: fffffffffffffffffffffff (23 digits) If you always represent the significand of a binary floating-point number in normalized form, there is a gap around zero on the number line. The minimum number in magnitude that can be represented in IEEE single-precision format can read more..

  • Page - 96

    CHAPTER 3 DATA TYPES 91 For comparison purposes, +0.0 and -0.0 are considered equal. Therefore, the expression 0.0 == -0.0 always returns true. Why does IEEE define two zeros if they are considered equal? The sign of zero is used to determine the result of an arithmetic expression involving multiplication and division. The result of 3.0 * 0.0 is a positive zero read more..

  • Page - 97

    CHAPTER 3 DATA TYPES 92 Table 3-11. A Binary Representation of a Quiet NaN Number Sign Exponent Significand Signaling NaN s 11111111 0bbbbbbbbbbbbbbbbbbbbbb Table 3-12. The Bits Pattern for a Denormalized Single-Precision Floating-Point Number Sign Exponent Significand s 000000000 fffffffffffffffffffffff Tip IEEE defines 224 - 2 distinct NaNs for the single-precision format and 253 read more..

  • Page - 98

    CHAPTER 3 DATA TYPES 93 Table 3-14. Examples of Rounding Towards Zero Original Number Available Number of Binary Points Rounded Number 1.1101 2 1.11 -0.1011 2 -0.10 0.1010 2 0.10 0.0011 2 0.00 Rounding Modes Not all real numbers can be exactly represented in binary floating-point format in finite number of bits. Therefore, real numbers that cannot be exactly represented in a read more..

  • Page - 99

    CHAPTER 3 DATA TYPES 94 Rounding Toward Negative Infinity In this rounding mode, numbers are rounded to a value closer to the negative infinity. Some examples of rounding towards negative infinity are shown in Table 3-16. Table 3-16. Examples of Rounding Towards Negative Infinity Original Number Available Number of Binary Points Rounded Number 1.1101 2 1.11 -0.1011 2 -0.11 0.1010 read more..

  • Page - 100

    CHAPTER 3 DATA TYPES 95 Division by Zero Exception A division by zero exception occurs when a non-zero number is divided by a floating-point zero. If no trap handler is installed, infinity of appropriate sign is delivered as the result. Invalid Operation Exception An invalid operation exception occurs when the operand is invalid for an operation being performed. If read more..

  • Page - 101

    CHAPTER 3 DATA TYPES 96 number. In case of an abrupt underflow, the result is zero. In case of a gradual underflow, the result is a denormalized number. The IEEE default is gradual underflow (denormalized numbers). Java supports gradual underflow. Inexact Exception The inexact exception is signaled if the rounded result of an operation is not identical to the infinitely read more..

  • Page - 102

    CHAPTER 3 DATA TYPES 97 Table 3-19. Vendors, Float Types, and Endian-ness Vendor Float Type Endian-ness ALPHA DEC/IEEE Little-endian IBM IBM Big-endian MAC IEEE Big-endian SUN IEEE Big-endian VAX DEC Little-endian PC IEEE Little-endian Difference in endian-ness can be a problem when transferring data between two machines. Table 3-19 lists some vendors, their float type, and the endian-ness read more..

  • Page - 103

    99 CHAPTER 4 Operators In this chapter, you will learn: What operators are The different types of operators available in Java Operator precedence, which determines the order in which operators are evaluated when multiple operators are used in the same expression What Is an Operator? An operator is a symbol that performs a specific kind of operation on one, two, or three read more..

  • Page - 104

    CHAPTER 4 OPERATORS 100 A binary operator uses infix notation. The operator appears in between the two operands. operand1 operator operand2 // Infix notation For example, 10 + 15; // 10 is operand1, + is a binary operator, and 15 is operand2 Like a binary operator, a ternary operator uses infix notation. operand1 operator1 operand2 operator2 operand3 // Infix read more..

  • Page - 105

    CHAPTER 4 OPERATORS 101 However, long to int and float to int assignments are not compatible and hence the following snippet of code generates compile-time errors: long big = 524L; float f = 1.19F; int i = 15; i = big; // A compile-time error. long to int, assignment incompatible i = f; // A compile-time error. float to int, assignment incompatible In read more..

  • Page - 106

    CHAPTER 4 OPERATORS 102 Suppose that there are two int variables, num1 and num2. The following assignment, num1 = num2, assigns the value 200 stored in num2 to num1: int num1 = 100; // num1 is 100 int num2 = 200; // num2 is 200 num1 = num2; // num1 is 200. num2 is 200 num2 = 500; // num2 is 500. num1 is still 200 When you say num1 = num2, read more..

  • Page - 107

    CHAPTER 4 OPERATORS 103 You can also declare more than one variable in one declaration, and initialize some or all. // Declaration of variables num1, num2 and num3. Initialization of only num1 and num3 int num1 = 10, num2, num3 = 200; // Declaration and initialization of variables num1, num2 and num3 int num1 = 10, num2 = 20, num3 = 30; Java will not let you read more..

  • Page - 108

    CHAPTER 4 OPERATORS 104 Addition Operator (+) The addition operator (+) is used in the form operand1 + operand2 The addition arithmetic operator (+) is used to add two numeric values represented by the two operands, for example, 5 + 3 results in 8. The operands may be any numeric literals, numeric variables, numeric expressions, or method calls. Every expression read more..

  • Page - 109

    CHAPTER 4 OPERATORS 105 You get a compile-time error when you try to assign the same value 5 to a byte variable b1, as shown in the following snippet of code: byte b1; byte b2 = 2; byte b3 = 3; b1 = b2 + b3; // A compile-time error. Trying to assign 5 to b1 Why does the above snippet of code result in a compile-time error? Do the expressions b1 = read more..

  • Page - 110

    CHAPTER 4 OPERATORS 106 by the compiler. Now you can see why Java didn’t give any errors for this expression. Because the int literal 5 is in the range of -128 to 127, b1 = 5 is a valid assignment according to the rule of assignment of int literal to a byte variable. However, if you try to write an expression as b1 = 127 + 10 , certainly read more..

  • Page - 111

    CHAPTER 4 OPERATORS 107 // An error. 2.0 and 3.2 are of the type double. The result of 2.0 + 3.2 is 5.2, // which is also of the type double. double to float assignment is not permitted. f1 = 2.0 + 3.2; // Ok. 2.0F and 3.2F are of the type float. The result of 2.0F + 3.2F, // which is 5.2F, is of the type float. f1 = 2.0F + 3.2F; // Ok. j is read more..

  • Page - 112

    CHAPTER 4 OPERATORS 108 // Ok. 20 * 6 will be replaced by 120 // b2 = 120 is ok, because 120 is in the range -128 and 127 b2 = 20 * 6; // An error. i2 * 12 is of the type int. int to byte assignment is not allowed. b2 = i2 * 12; b2 = (byte)(i2 * 12); // OK // Ok. i2 * b2 is of the type int and int to float assignment is allowed f2 read more..

  • Page - 113

    CHAPTER 4 OPERATORS 109 and the result is always an integer. If either or both of the operands of the division operator are float or double type, floating-point division is performed and the result is not truncated. For example, float f1; // 15.0F and 4.0F are of float type. So, the expression 15.0F/4.0F is of the type float. // The result 3.75F is assigned read more..

  • Page - 114

    CHAPTER 4 OPERATORS 110 // 5.0F is of the type float and 0 is of the type int. 5.0F/0 is of type float. // Float.POSITIVE_INFINITY is assigned to f1 f1 = 5.0F/0; // A compile-time error. 5.0F is of the type float and 0.0 is of the type double // 5.0F/0.0 is of the type double. double to float assignment is not allowed. f1 = 5.0F/0.0; f1 = (float)(5.0F/0.0); read more..

  • Page - 115

    CHAPTER 4 OPERATORS 111 Rule #1 The operation never results in an error even if the right-hand operand is a floating-point zero. Rule #2 The result is NaN if either operand is NaN. For example, float f1; double d1; f1 = Float.NaN % 10.5F; // Assigns Float.NaN to f1 f1 = 20.0F % Float.NaN; // Assigns Float.NaN to f1 f1 = Float.NaN % Float.NaN; // read more..

  • Page - 116

    CHAPTER 4 OPERATORS 112 Unary Plus Operator (+) The unary plus operator (+) is used in the form +operand The operand must be a primitive numeric type. If the operand is of the byte, short, or char type, the unary plus operator promotes it to int type. Otherwise, there is no effect of using this operator. For example, if there is an int variable num, read more..

  • Page - 117

    CHAPTER 4 OPERATORS 113 Compound Arithmetic Assignment Operators Each of the five basic arithmetic operators (+, -, *, /, and %) has a corresponding compound arithmetic assignment operator. These operators can be explained better with an example. Suppose you have two variables, num1 and num2. int num1 = 100; byte num2 = 15; If you want to add the value of num1 to read more..

  • Page - 118

    CHAPTER 4 OPERATORS 114 The compound assignment operator += can also be applied to String variables. In such cases, the operand1 must be of type String and the operand2 may be of any type including boolean. For example, String str1 = "Hello"; str1 = str1 + 100; // Assigns "Hello100" to str1 can be rewritten as str1 += 100; // Assigns read more..

  • Page - 119

    CHAPTER 4 OPERATORS 115 Suppose you declare an int variable called i. int i = 100; To increment the value of i by 1, you can use one of the four following expressions: i = i + 1; // Assigns 101 to i i += 1; // Assigns 101 to i i++; // Assigns 101 to i ++i; The increment operator ++ can also be used in a more complex read more..

  • Page - 120

    CHAPTER 4 OPERATORS 116 Here is a puzzle for Java beginners. The puzzle includes the use of the increment operator as follows: int i = 15; i = i++; // What will be the value of i after this assignment? What will be the value of i after i = i++ is executed? If your guess is 16, you are wrong. Here is the explanation of how the expression is read more..

  • Page - 121

    CHAPTER 4 OPERATORS 117 String Concatenation Operator (+) The + operator is overloaded. An operator is said to be overloaded if it is used to perform more than one function. So far, you have seen its use as an arithmetic addition operator to add two numbers. It can also be used to concatenate two strings. Two strings, such as "abc" and "xyz", read more..

  • Page - 122

    CHAPTER 4 OPERATORS 118 If a String variable contains the null reference, the concatenation operator uses a string "null". The follow ing examples illustrate the use of string representations of the values of primitive data types in string concatenation: boolean b1 = true; boolean b2 = false; int num = 365; double d = -0.0; char c = 'A'; String str1; String str2 = read more..

  • Page - 123

    CHAPTER 4 OPERATORS 119 Consider the following piece of code: int num1 = 12; int num2 = 15; String str1 = " men"; String str2; You want to create a string of “1215 men” using the three variables ( num1, num2, and str1) and the + operator. You want to assign the result to str2. The following is a first attempt: str2 = num1 + num2 + str1; read more..

  • Page - 124

    CHAPTER 4 OPERATORS 120 You use the println() and print() methods to print a message on the standard output, as follows: System.out.println("Prints a new line at the end of text"); System.out.print("Does not print a new line at the end of text"); If you use the System.out.println() method to print text to the console, after printing the text, it also prints a read more..

  • Page - 125

    CHAPTER 4 OPERATORS 121 // Print the value of test System.out.println ("test = " + test); // Print the maximum value of int type System.out.println ("Maximum int = " + Integer.MAX_VALUE); read more..

  • Page - 126

    CHAPTER 4 OPERATORS 122 Relational Operators All relational operators are binary operators. That is, they take two operands. The result produced by a relational operator is always a Boolean value true or false. Table 4-3 lists the relational operators available in Java. Table 4-3. List of Relational Operators in Java Operators Meaning Type Usage Result == Equal to Binary 3 read more..

  • Page - 127

    CHAPTER 4 OPERATORS 123 In this example, you tried to test whether the three variables i, j and k have the same value, and the expression (i == j == k) resulted in an error. Why did you get the error? The expression (i == j == k) is evaluated as follows: First, i == j is evaluated in expression i == j == k. Since both i and j have the same read more..

  • Page - 128

    CHAPTER 4 OPERATORS 124 Float and Double classes have an isNaN() method, which accepts a float and a double argument, respectively. It returns true if the argument is NaN, Otherwise, it returns false. For example, to test if d1 is NaN, the above expression can be rewritten as shown: double d1 = Double.NaN; // Assigns true to b. Correct way to test read more..

  • Page - 129

    CHAPTER 4 OPERATORS 125 Greater Than Operator (>) The greater than operator (>) is used in the form operand1 > operand2 The greater than operator returns true if the value of operand1 is greater than the value of operand2. Otherwise, it returns false. The greater than operator can be used only with primitive numeric data types. If either of the operand is read more..

  • Page - 130

    CHAPTER 4 OPERATORS 126 Less Than Operator (<) The less than operator ( <) is used in the form operand1 < operand2 The less than operator returns true if operand1 is less than operand2. Otherwise, it returns false. The operator can be used only with primitive numeric data types. If either operand is NaN ( float or double), the less than operator returns read more..

  • Page - 131

    CHAPTER 4 OPERATORS 127 Logical NOT Operator (!) The logical NOT operator ( !) is used in the form !operand The operator returns true if the operand is false, and false if the operand is true. boolean b; b = !true; // Assigns false to b b = !false; // Assigns true to b int i = 10; int j = 15; boolean b1 = true; b = !b1; read more..

  • Page - 132

    CHAPTER 4 OPERATORS 128 int i = 10; int j = 15; boolean b = (i > 5 && j > 10); // Assigns true to b In this expression, i > 5 is evaluated first and it returns true. Because the left hand operand evaluated to true, the right hand operand was also evaluated. The right-hand operand, j > 10, is evaluated, which also returns true. Now, the read more..

  • Page - 133

    CHAPTER 4 OPERATORS 129 System.out.println ("b = " + b); System.out.println ("i = " + i); System.out.println ("j = " + j); // Will print j = 10 The above piece of code will print b = false i = 10 j = 10 Logical AND Operator (&) The logical AND operator ( &) is used in the form operand1 & operand2 The logical AND operator returns true if both read more..

  • Page - 134

    CHAPTER 4 OPERATORS 130 In the above expression, i > 5 is evaluated first, and it returns true. Because the left-hand operand evaluated to true, the right hand operand is not evaluated, and the expression ( i > 5 || j > 10) returns true. Consider another example. int i = 10; int j = 15; boolean b = (i > 20 || j > 10); // Assigns true to b The read more..

  • Page - 135

    CHAPTER 4 OPERATORS 131 Compound Boolean Logical Assignment Operators There are three compound Boolean logical assignment operators. Note that Java does not have any operators like &&= and ||=. These operators are used in the form operand1 op= operand2 The operand1 must be a boolean variable and op may be &, |, or ^ . The above form is equivalent to read more..

  • Page - 136

    CHAPTER 4 OPERATORS 132 Suppose you have three integer variables: num1, num2, and minNum. You want to assign minNum the minimum of num1 and num2. You can use ternary operator to accomplish this. int num1 = 50; int num2 = 25; // Assigns num2 to minNum, because num2 is less than num1 int minNum = (num1 < num2 ? num1 : num2); Operator Precedence Consider the following read more..

  • Page - 137

    CHAPTER 4 OPERATORS 133 Table 4-6. Java Operators and Their Precedence Level Operator Symbol Action Performed 1 ++ Pre-or-post increment -- Pre-or-post decrement +, - Unary plus, unary minus ~ Bitwise complement ! Logical Not (type) Cast 2 *, /, % Multiplication, division, modulus 3 +, - Addition, subtraction + String concatenation 4 << Left shift >> Signed right shift >>> Unsigned read more..

  • Page - 138

    CHAPTER 4 OPERATORS 134 Bitwise Operators A bitwise operator manipulates individual bits of its operands. Bitwise operators are listed in Table 4-7. Table 4-7. List of Bitwise Operators Operators Meaning Type Usage Result & Bitwise AND Binary 25 & 24 24 | Bitwise OR Binary 25 | 2 27 ^ Bitwise XOR Binary 25 ^ 2 27 ~ Bitwise complement (1’s complement) Unary ~25 -26 << Left read more..

  • Page - 139

    CHAPTER 4 OPERATORS 135 The value of 13 | 3 can be computed as follows. The result of 13 | 3 is 15. 13 00000000 00000000 00000000 00001101 3 00000000 00000000 00000000 00000011 -------------------------------------------- 13 | 3 00000000 00000000 00000000 00001111 (Equal to decimal 15) The bitwise XOR ( ^) operates on corresponding bits of read more..

  • Page - 140

    CHAPTER 4 OPERATORS 136 What is the result of 13 << 35? You might have guessed zero. However, this is not true. In fact, only 32 bits are used to represent 13, because 13 is considered as int literal and int occupies 32 bits. You can shift all bits to the left only by 31 bits in an int. If the left-hand operand of bitwise left shift operator read more..

  • Page - 141

    CHAPTER 4 OPERATORS 137 The unsigned right shift operator ( >>>) works the same as the signed right shift operator (>>), except for one difference. It always fills the higher order bits with zero. The result of 13 >>> 4 is zero whereas the result of -13 >>> 4 is 268435455, as shown below. There is no unsigned left shift operator. 13 read more..

  • Page - 142

    139 CHAPTER 5 Statements In this chapter, you will learn: What statements are in Java About the different types of statements available in Java, for example, control flow statements, loop statements, and so on. What Is a Statement? A statement specifies an action in a Java program, such as assigning the sum of x and y to z, printing a message to the standard read more..

  • Page - 143

    CHAPTER 5 STATEMENTS 140 Expression Statement An expression with a semicolon at the end is called an expression statement. However, not all Java expressions can be converted to expression statements by appending a semicolon to them. If i and j are two int variables, i + j is an arithmetic expression. However, i + j; ( i + j with a semicolon) is not read more..

  • Page - 144

    CHAPTER 5 STATEMENTS 141 statement. You can think of a block statement as a compound statement that is treated as one statement. The following are examples of block statements: { // Start of a block statement. Block statement starts with { int num1 = 20; num1++; } // End of the block statement. Block statement ends with } read more..

  • Page - 145

    CHAPTER 5 STATEMENTS 142 // A compile-time error. num2 is local to the inner block. // So, it cannot be used outside the inner block. num2 = 200; } // End of the outer block One important thing to remember about nested block statement is that you cannot define a variable with the same name inside an inner read more..

  • Page - 146

    CHAPTER 5 STATEMENTS 143 Suppose you have three int variables, num1, num2, and num3. You want to add 10 to num2 and num3 if num1 is greater than 50. Otherwise, you want to subtract 10 from num2 and num3. You may try the following snippet of code, which is incorrect: if (num1 > 50) num2 = num2 + 10; num3 = read more..

  • Page - 147

    CHAPTER 5 STATEMENTS 144 The if-else statement can be nested, as shown: if (num1 > 50) { if (num2 < 30) { num3 = num3 + 130; } else { num3 = num3 - 130; } } else { num3 = num3 = 200; } Sometimes read more..

  • Page - 148

    CHAPTER 5 STATEMENTS 145 You cannot write an if statement like this: if (i = 5) /* A compile-time error */ statement This if statement will not compile because i = 5 is an assignment expression and it evaluates to an int value 5. The condition expression must return a Boolean value: true or false. Therefore, an assignment expression read more..

  • Page - 149

    CHAPTER 5 STATEMENTS 146 Another difference in using a ternary operator and an if-else statement is that you can use an expression, which uses a ternary operator as an argument to a method. However, you cannot use an if-else statement as an argument to a method. Suppose you have a calc() method that accepts an int as an argument. You have two integers, read more..

  • Page - 150

    CHAPTER 5 STATEMENTS 147 For example, int i = 10; switch (i) { case 10: // Found the match System.out.println("Ten"); // Execution starts here case 20: System.out.println("Twenty"); default: System.out.println read more..

  • Page - 151

    CHAPTER 5 STATEMENTS 148 Because the value of i is 50, which does not match any of the case labels, the execution starts at the first statement after default label. The control falls through the subsequent label case 20: and executes the statement following this case label, which prints "Twenty". Generally, you want to print "Ten" if the value of i read more..

  • Page - 152

    CHAPTER 5 STATEMENTS 149 Two case labels in a switch statement cannot be the same. The following piece of code would not compile because case label 10 is repeated: int num = 10; switch (num) { case 10: num++; case 10: // A compile-time error. Duplicate case label 10 read more..

  • Page - 153

    CHAPTER 5 STATEMENTS 150 // Using a switch statement switch (i) { case 10: System.out.println(“i is 10"); break; case 20: System.out.println("i is 20"); break; default: read more..

  • Page - 154

    CHAPTER 5 STATEMENTS 151 For example, the following for-loop statement will print all integers between 1 and 10, inclusive: for(int num = 1; num <= 10; num++) System.out.println(num); First, int num = 1 is executed, which declares an int variable num and initializes it to 1. It is important to note that variables declared in the initialization read more..

  • Page - 155

    CHAPTER 5 STATEMENTS 152 Initialization The initialization part of a for-loop statement can have a variable declaration statement, which may declare one or more variables of the same type, or it can have a list of expression statements separated by a comma. Note that the statements used in the initialization part do not end with a semicolon. The following snippet read more..

  • Page - 156

    CHAPTER 5 STATEMENTS 153 Infinite loop II for( ; true; ); // Explicit true is used here A break statement is used to stop the execution of a for-loop statement. When a break statement is executed, the control is transferred to the next statement, if any, after the for-loop statement. You can rewrite the for-loop statement to print all integers between 1 and read more..

  • Page - 157

    CHAPTER 5 STATEMENTS 154 The code to print the 3x3 matrix can be written as // Outer for-loop statement for(int i = 1; i <= 3; i++) { // Inner for-loop statement for(int j = 1; j <= 3; j++) { System.out.print(i + "" + j); // Prints a tab after read more..

  • Page - 158

    CHAPTER 5 STATEMENTS 155 14. The condition expression for the inner for-loop statement ( j <= 3) is evaluated for j equal to 4, which is false. At this point, the inner for loop is finished. 15. The last statement of the block statement for outer for-loop statement, which is System.out.println(), is executed, which prints a system-dependent line separator. read more..

  • Page - 159

    CHAPTER 5 STATEMENTS 156 The for-each Statement Java 5 introduced an enhanced for loop, which is called a for-each loop. It is used for iterating over elements of arrays and collections. This section is included here to complete the list of statements that lets you loop through a group values. Please refer to the chapters on arrays and collections for more detailed read more..

  • Page - 160

    CHAPTER 5 STATEMENTS 157 A for-loop statement: for (initialization; condition-expression; expression-list) Statement Equivalent while-loop Statements: Initialization while (condition-expression) { Statement Expression-list } You can print all integers between 1 and 10 using a while-loop as shown: int i = 1; while (i <= 10) { read more..

  • Page - 161

    CHAPTER 5 STATEMENTS 158 The do-while Statement The do-while statement is another loop statement. It is similar to the while-loop statement with one difference. The statement associated with a while loop statement may not be executed even once if the condition-expression evaluates to false for the first time. However, the statement associated with a do-while statement is read more..

  • Page - 162

    CHAPTER 5 STATEMENTS 159 You have already seen the use of the unlabeled break statement inside switch, for-loop, while-loop, and do-while statements. It transfers control out of a switch, for-loop, while-loop, and do-while statement in which it appears. In case of nested statements of these four kinds, if an unlabeled break statement is used inside the inner read more..

  • Page - 163

    CHAPTER 5 STATEMENTS 160 The output of the above snippet of code will be 11. Why did it print only one element of the 3x3 matrix? This time you have used a labeled break statement inside the inner for-loop statement. When i == j evaluates to true for the first time, the labeled break statement is executed. It transfers control out of the block, which has read more..

  • Page - 164

    CHAPTER 5 STATEMENTS 161 An example of an unlabeled continue statement is continue; An example of a labeled continue statement is continue label; When a continue statement is executed inside a for loop, the rest of the statements in the body of the loop are skipped and the expressions in the expression-list are executed. You can print all odd integers between read more..

  • Page - 165

    CHAPTER 5 STATEMENTS 162 The main difference in using a continue statement inside a for loop and a while loop is the place where the control is transferred. Inside a for loop, control is transferred to the expression-list, and in a while loop, the control is transferred to the condition-expression. This is why a for-loop statement cannot always be converted to a read more..

  • Page - 166

    CHAPTER 5 STATEMENTS 163 It is a personal choice, which of the above piece of code to use. Finally, note that if you type two or more semicolons where only one was required, it would not cause any errors, because each extra semicolon is considered as an empty statement. For example, i++; // Ok. Here, semicolon is part of statement i++;; // Still Ok. The read more..

  • Page - 167

    165 CHAPTER 6 Classes and Objects In this chapter, you will learn: What classes are in Java How to declare classes in Java How to declare class members such as fields and methods and their access levels How to create objects of a class How to declare import statements in a compilation unit The meaning of the pronouns this and super in a Java program Different read more..

  • Page - 168

    CHAPTER 6 CLASSES AND OBJECTS 166 You can list all properties and behaviors for you and your friend separately and examine them separately as if there is no connection between you and your friend. You can list the properties and behaviors for you and your friend that are in common and then examine them as properties and behavior for an entity without naming you and read more..

  • Page - 169

    CHAPTER 6 CLASSES AND OBJECTS 167 Here, <<modifiers>> are keywords that associate special meanings to the class declaration. A class declaration may have zero or more modifiers. The keyword class is used to declare a class. The <<class name>> is a user-defined name of the class, which should be a valid identifier. Each class has a body, which read more..

  • Page - 170

    CHAPTER 6 CLASSES AND OBJECTS 168 Java lets you declare two types of fields for a class: Class fields Instance fields Class fields are also known as class variables. Instance fields are also known as instance variables. In the above snippet of code, name and gender are two instance variables of the Human class. Java has a different way to declare class read more..

  • Page - 171

    CHAPTER 6 CLASSES AND OBJECTS 169 The figure shows that memory is allocated for instance variables name and gender. You can create as many instances of the Human class as you want. Each time you create an instance of the Human class, Java runtime allocates memory for name and gender instance variables. How much memory is allocated for an instance of the read more..

  • Page - 172

    CHAPTER 6 CLASSES AND OBJECTS 170 You can think of the jack variable as a remote controller for a Human instance in memory. You can refer to the Human instance in memory using the jack variable. I will discuss how to use a reference variable in the next section. You can also combine the above two statements into one. Human jack = new Human(); The null read more..

  • Page - 173

    CHAPTER 6 CLASSES AND OBJECTS 171 Tip Java has a special reference type that is called null type. The null type does not have a name. The null type has a literal value, which is represented by null. The null type is assignment compatible with all other reference types. You can assign any reference type variable a null value. You can cast null value read more..

  • Page - 174

    CHAPTER 6 CLASSES AND OBJECTS 172 Tip You can use the class name or a reference variable of the class type to refer to a class variable. Since the class variable belongs to the class and it is shared by all instances of the class, it is logical to refer to it using the class name. However, you always use a reference variable of a class type to refer read more..

  • Page - 175

    CHAPTER 6 CLASSES AND OBJECTS 173 The following statement needs some explanation: // Increase count by one Human.count++; It uses the increment operator (++) on the count class variable. After the count class variable is incremented by 1, you read and print its value. The output shows that after incrementing its value by 1, its value becomes 1. It means that read more..

  • Page - 176

    CHAPTER 6 CLASSES AND OBJECTS 174 Listing 6-3. Default Initialization of Class Fields // DefaultInit.java package com.jdojo.cls; class DefaultInit { byte b; short s; int i; long l; float f; double d; boolean bool; String str; read more..

  • Page - 177

    CHAPTER 6 CLASSES AND OBJECTS 175 Let’s create a class ClassAccessTest in the com.jdojo.common package. Note that the package for the ClassAccessTest class is different from the package for the Human class. The code for the ClassAccessTest class is // ClassAccessTest.java package com.jdojo.common; public class ClassAccessTest { public static void read more..

  • Page - 178

    CHAPTER 6 CLASSES AND OBJECTS 176 This time, the compiler is not saying that it does not understand the Human type. It is saying that it knows what com.jdojo.cls.Human type is; however, it is accessible only inside the com.jdojo.cls package in which it has been declared. In other words, the Human type is not accessible inside the com.jdojo.common package. read more..

  • Page - 179

    CHAPTER 6 CLASSES AND OBJECTS 177 Import Declarations You learned two rules in the previous section: You must declare a class public to use it in a package other than the package in which it is declared. You need to use the fully qualified name of a class to use it in a package other than the one in which it is declared. A class can be referred to using read more..

  • Page - 180

    CHAPTER 6 CLASSES AND OBJECTS 178 Single-Type Import Declaration A single-type import declaration is used to import a single type (e.g. a class) from a package. It is of the form import <<fully qualified name of a type>>; The following import declaration imports the Human class from the com.jdojo.cls package: import com.jdojo.cls.Human; A single-type import read more..

  • Page - 181

    CHAPTER 6 CLASSES AND OBJECTS 179 public class ClassAccessTest { public static void main(String[] args) { Human jack; // Use simple name of the Human class } } The modified version of the ClassAccessTest class compiles fine. When the compiler comes across the simple name of the Human class in the read more..

  • Page - 182

    CHAPTER 6 CLASSES AND OBJECTS 180 import p1.*; imports all types only from p1 package. It will not import the p1.p2.C2 class because the C2 class is not in the p1 package; rather it is in the p2 package, which is a sub-package of p1. The asterisk at the end of an import-on-demand declaration means all types only from the specified package. The read more..

  • Page - 183

    CHAPTER 6 CLASSES AND OBJECTS 181 The one import-on-demand declaration in the above code has the same effect as the following two single- type-import declarations: import com.jdojo.cls.Human; // Import Human class import com.jdojo.cls.Table; // Import Table class Which type of import declaration is better to use in your Java program: single-type import or import-on-demand? It read more..

  • Page - 184

    CHAPTER 6 CLASSES AND OBJECTS 182 Import Declarations and Type Search Order Import declarations are used to resolve simple names of types to their fully qualified names during compilation. The compiler uses predefined rules to resolve the simple names. Suppose the following statement appears in a Java program that uses a simple name A: A var; The Java compiler must read more..

  • Page - 185

    CHAPTER 6 CLASSES AND OBJECTS 183 Suppose you want to use class A from package p2 in the previous example. That is, there is a class p2.A and you want to declare the instance variable var of type p2.A in class B instead of p1.A. Let’s try to solve it by importing class p2.A using a single-type-import declaration, like so: // B.java – read more..

  • Page - 186

    CHAPTER 6 CLASSES AND OBJECTS 184 Let’s go back to the problem of importing the p2.A class in a compilation unit, which already declares a class A. The following code produces a compile-time error: // B.java – Includes a new import declaration package p1; import p2.A; class B { A var1; // We want to use p2.A when you use A } class A read more..

  • Page - 187

    CHAPTER 6 CLASSES AND OBJECTS 185 Tip It is a compile-time error to import a type using a single-type-import declaration into a compilation unit, if a type with the same simple name exists in the same compilation unit. Let’s resolve the compiler error with the code that needs to use classes from different packages with the same simple name. The code is as read more..

  • Page - 188

    CHAPTER 6 CLASSES AND OBJECTS 186 Let’s discuss some of the rules about using import-on-demand declarations. The compiler uses the import-on- demand declarations in resolving a simple name of a type after it has used all other means to resolve the simple name. It is valid to import a class with the same simple name using a single-type import declaration as well as read more..

  • Page - 189

    CHAPTER 6 CLASSES AND OBJECTS 187 Below is a list of some more rules about import declarations. Duplicate single-type import and import-on-demand declarations are ignored. The following code is valid: // D.java package p4; import p1.A; import p1.A; // Ignored. A duplicate import declaration. import p2.*; import p2.*; // Ignored. A duplicate import declaration. class D { read more..

  • Page - 190

    CHAPTER 6 CLASSES AND OBJECTS 188 It is not an error to use an import declaration to import types from java.lang package. They will be simply ignored by the compiler. The following code will compile without errors: package p1; import java.lang.*; // Will be ignored because it is automatically done for you public class G { String read more..

  • Page - 191

    CHAPTER 6 CLASSES AND OBJECTS 189 A static import declaration also comes in two flavors: single-static import and static-import-on-demand. A single- static import declaration imports one static member from a type. A static-import-on-demand declaration imports all static members of a type. The general syntax of static import declaration is as follows: Single-static-import read more..

  • Page - 192

    CHAPTER 6 CLASSES AND OBJECTS 190 Let’s look at another example of using static import declarations. The Math class in the java.lang package has many utility constants and static methods. For example, it has a class variable named PI, whose value is equal to 22/7 (the pi in mathematics). If you want to use any of the static variables or methods of the Math read more..

  • Page - 193

    CHAPTER 6 CLASSES AND OBJECTS 191 public class Test { public static void main(String[] args) { m1(); // C1.m1() will be called } } Static Import Rule #2 Using single-static-import declaration to import two static members with the same simple name is not allowed. The following static import read more..

  • Page - 194

    CHAPTER 6 CLASSES AND OBJECTS 192 There is a hidden danger in using static import declarations in such cases. Suppose you did not have a test() static method in the p2.Test class. In the beginning, the test() method call will call p1.A.test() method. Later, you add a test() method in the Test class. Now the test() method call will start calling read more..

  • Page - 195

    CHAPTER 6 CLASSES AND OBJECTS 193 The method name must be a valid Java identifier. Conventionally, a Java method starts with a lowercase and subsequently a word cap is used. For example, getName, setName, getHumanCount, and createHuman are valid method names. AbCDeFg is also a valid method name; it just doesn’t follow standard conventions. A method may take input values read more..

  • Page - 196

    CHAPTER 6 CLASSES AND OBJECTS 194 The above call to the add method passes 10 and 12 as the values for parameters n1 and n2, respectively. The two values, 10 and 12, that are used to call the add method are called actual parameters. Java copies the actual parameters to the formal parameters before it executes the code inside the body of the method. In the read more..

  • Page - 197

    CHAPTER 6 CLASSES AND OBJECTS 195 The printPoem method specifies void as its return type, which means that it does not return a value to its caller. It does not specify any parameters, which means it does not accept any input values from its caller. If you need to call the printPoem method, you need to write the following statement: printPoem(); Note read more..

  • Page - 198

    CHAPTER 6 CLASSES AND OBJECTS 196 The modified printPoem() method knows how to print stanza #1 and #2. If its caller passes a stanza number outside this range, it prints a message and ends the method call. This is accomplished by using a return statement in the first if statement. You could have written the above printPoem() method without writing any return read more..

  • Page - 199

    CHAPTER 6 CLASSES AND OBJECTS 197 Rule #2 This rule is an offshoot of the first rule. A local variable cannot be accessed in the program until it is assigned a value. The following snippet of code will generate a compiler error because it tries to print the value of the local variable, sum, before it is assigned a value. Note that Java runtime has to read (or read more..

  • Page - 200

    CHAPTER 6 CLASSES AND OBJECTS 198 What happens when two variables, say one instance variable and one local variable, are in scope in the same part of a program? Let’s consider the following code for the NameHidingTest2 class: class NameHidingTest2 { int n1 = 10; // An instance variable /// m1 is a method read more..

  • Page - 201

    CHAPTER 6 CLASSES AND OBJECTS 199 /* Only the instance variable n1 is in scope here. The local variable n2 is also in scope here, which you are ignoring for our discussion for now */ int n1 = 20; /* A local variable n1 */ read more..

  • Page - 202

    CHAPTER 6 CLASSES AND OBJECTS 200 When a static method of a class is called, an instance of that class may not exist. Therefore, it is not allowed to refer to instance variables from inside a static method. Class variables exist as soon as the class definition is loaded into memory. The class definition is always loaded into memory before the first instance of read more..

  • Page - 203

    CHAPTER 6 CLASSES AND OBJECTS 201 Invoking a Method Executing the code in the body of a method is called invoking (or calling) a method. Instance methods and class methods are invoked differently. An instance method is invoked on an instance of the class using dot notation. <<instance reference>>.<<instance method name>>(<<actual parameters>>) Note that read more..

  • Page - 204

    CHAPTER 6 CLASSES AND OBJECTS 202 // Invoke the class method using the class name MethodType.printM(); System.out.println("Invoking class method on an instance..."); // Invoke the class method using the instance reference read more..

  • Page - 205

    CHAPTER 6 CLASSES AND OBJECTS 203 Why do you need to declare the main() method as static? The main() method serves as the entry point for a Java application. It is invoked by the JVM when you run a class. The JVM does not know how to create an instance of a class. It needs a standard way to start a Java application. Specifying all details about the read more..

  • Page - 206

    CHAPTER 6 CLASSES AND OBJECTS 204 Listing 6-9. A MainTest1 Class, Which Declares a main() Method // MainTest1.java package com.jdojo.cls; public class MainTest1 { public static void main(String[] args) { System.out.println("Inside main() method of the MainTest1 class."); } } Listing 6-10. A MainTest2 Class, read more..

  • Page - 207

    CHAPTER 6 CLASSES AND OBJECTS 205 What Is this? Java has a keyword called this. It is a reference to the current instance of a class. It can be used only in the context of an instance. It can never be used in the context of a class because it means the current instance, and no instance exists in the context of a class. The keyword this is used in read more..

  • Page - 208

    CHAPTER 6 CLASSES AND OBJECTS 206 You can also qualify a class variable with a class name, as shown in the CorrectThisTest3 class: public class CorrectThisTest3 { static int varU = 555; static int varV = varU; static int varW = CorrectThisTest3.varU; } Tip Most of the time you can use the simple name of read more..

  • Page - 209

    CHAPTER 6 CLASSES AND OBJECTS 207 void printNum() { System.out.println("Instance variable num: " + num); } public static void main(String[] args) { ThisTest4 tt4 = new ThisTest4(); tt4.printNum(); } } read more..

  • Page - 210

    CHAPTER 6 CLASSES AND OBJECTS 208 Listing 6-13. Using the this Keyword to Refer to an Instance Variable Whose Name Is Hidden by a Local Variable // ThisTest6.java package com.jdojo.cls; public class ThisTest6 { int num = 1982; // An instance variable void printNum(int num) { read more..

  • Page - 211

    CHAPTER 6 CLASSES AND OBJECTS 209 public void setId(int id) { this.id = id; } public int getId() { return this.id; { } The Student class declares an instance variable id. In its setId() method, it also read more..

  • Page - 212

    CHAPTER 6 CLASSES AND OBJECTS 210 You can also use the keyword this to qualify an instance method name, although it is never required. The following snippet of code shows the m1() method invoking the m2() method using the keyword this. Note that both methods are instance methods and they could use the simple name to invoke each other. public class ThisTestMethod read more..

  • Page - 213

    CHAPTER 6 CLASSES AND OBJECTS 211 The following is a sample class that declares many class members with different access levels: // AccessLevelSample.java package com.jdojo.cls; // Class AccessLevelSample has public access level public class AccessLevelSample { private int num1; // private access level int num2; // read more..

  • Page - 214

    CHAPTER 6 CLASSES AND OBJECTS 212 Let’s discuss some examples of using the access level modifiers for class members, and their effects. Consider the code for the AccessLevel class shown in Listing 6-14. Listing 6-14. An AccessLevel Class with Class Members Having Different Access Levels // AccessLevel.java package com.jdojo.cls; public class AccessLevel { read more..

  • Page - 215

    CHAPTER 6 CLASSES AND OBJECTS 213 Listing 6-15. A Test Class Loated in the Same Package as the AccessLevel Class // AccessLevelTest1.java package com.jdojo.cls; public class AccessLevelTest1 { public static void main(String[] args) { AccessLevel al = new AccessLevel(); // int a = al.v1; /* read more..

  • Page - 216

    CHAPTER 6 CLASSES AND OBJECTS 214 The AccessLevel and AccessLevelTest1 classes are in the same package. AccessLevelTest1 can access all class members of the AccessLevel class, except the ones declared private. You cannot access the instance variable v1 and the instance method m1() of the AccessLevel class from the AccessLevelTest1 class because their access level read more..

  • Page - 217

    CHAPTER 6 CLASSES AND OBJECTS 215 //int a = al.v1; /* A compile-time error */ //int b = al.v2; /* A compile-time error */ //int c = al.v3; /* A compile-time error */ int d = al.v4; read more..

  • Page - 218

    CHAPTER 6 CLASSES AND OBJECTS 216 Note that there is no access level modifier used for the AccessLevel2 class, which gives it a package-level access by default. That is, the AccessLevel2 class is accessible only within the com.jdojo.cls package. The AccessLeve2 class is simple. It declares only one member, which is the public static variable v1. Let’s read more..

  • Page - 219

    CHAPTER 6 CLASSES AND OBJECTS 217 A bank account holds the balance in the account. The above definition of the Account class does just that. In the real world, a bank account can hold many more pieces of information, for example, account number, account holder name, address, etc. Let’s keep the Account class simple so you can focus on the discussion of read more..

  • Page - 220

    CHAPTER 6 CLASSES AND OBJECTS 218 The modified version of the Account class is not acceptable in this form because you can create an account, but you cannot read or manipulate its balance. The Account class must provide some interface for the outside world to access and manipulate its balance in a controlled way. For example, if you have money and want to share read more..

  • Page - 221

    CHAPTER 6 CLASSES AND OBJECTS 219 public int debit(double amount) { // Make sure the debit amount is not negative, NaN or infinity */ if (amount < 0.0 || Double.isNaN(amount) || Double.isInfinite(amount)) { System.out.println("Invalid read more..

  • Page - 222

    CHAPTER 6 CLASSES AND OBJECTS 220 balance = ac.getBalance(); System.out.println("Balance = " + balance); // Attempt to debit more than the balance ac.debit(2000.00); read more..

  • Page - 223

    CHAPTER 6 CLASSES AND OBJECTS 221 validates the amount to a private method, isValidAmount(),which is used internally by the Account class. It checks if an amount being used for credit or debit is not a negative number, not a NaN, and not infinity. These three criteria for a number to be a valid number apply only to the Account class, and no other class needs read more..

  • Page - 224

    CHAPTER 6 CLASSES AND OBJECTS 222 else { /* print error here */ return –1; { You could use the simpler logic to implement the credit() method, which checks if the amount is valid, instead of checking if the amount is invalid. I did not use this logic because I wanted to demonstrate in the same example how to use a private read more..

  • Page - 225

    CHAPTER 6 CLASSES AND OBJECTS 223 In Figure 6-4, you see that the actual data of the variable id is stored at the memory address. You can also store a data at a memory address, which is not the actual value for the variable; rather it is the memory address of the location where the actual value is stored. In this case, the value stored at the read more..

  • Page - 226

    CHAPTER 6 CLASSES AND OBJECTS 224 Figure 6-6 depicts the memory state when a method is called using the pass by value mechanism. It is to be emphasized that once the formal parameter gets its value, which is a copy of the actual parameter, the two parameters have nothing to do with each other. The formal parameter is discarded at the end of the method read more..

  • Page - 227

    CHAPTER 6 CLASSES AND OBJECTS 225 Table 6-4. Description of Memory States for Actual and Formal Parameters When the increment( ) Method is Called and the Parameter is Passed by Value Point of Execution Memory State of Actual Parameter id Memory State of Formal Parameter num #1 The id variable exists in memory and its value is 57. The num variable does not exist read more..

  • Page - 228

    CHAPTER 6 CLASSES AND OBJECTS 226 You can call the above swap() method using the following snippet of code: int u = 75; int v = 53; swap(u, v); /*At this point, u and v will be still 75 and 53, respectively */ By this time, you should be able to figure out why the values of u and v were not swapped when they were passed to the swap() read more..

  • Page - 229

    CHAPTER 6 CLASSES AND OBJECTS 227 Formal parameter is associated with the address of actual parameter in the beginning of the method call Formal Parameter Name Actual Parameter Name Actual Parameter Address Actual Parameter Value Figure 6-7. Memory states of actual and formal parameters when the parameters are passed by reference Many books use the phrase “pass by reference.” read more..

  • Page - 230

    CHAPTER 6 CLASSES AND OBJECTS 228 Pass by reference allows you to have two-way communication between the caller environment and the called method. You can pass multiple parameters by reference to a method and the method can modify all parameters. All modifications to formal parameters are reflected back to the caller’s environment instantaneously. It lets you share read more..

  • Page - 231

    CHAPTER 6 CLASSES AND OBJECTS 229 Suppose you call the getNumber() method as follows: int w = 100; int s = getNumber(w, w); /* What is value of s at this point: 200, 8, 10 or something else? */ When the getNumber() method returns, what value will be stored in the variable s? Note that both parameters to the getNumber() method are passed by reference read more..

  • Page - 232

    CHAPTER 6 CLASSES AND OBJECTS 230 Pass By Reference Value The mechanism of passing parameters to a method using a pass by reference value is different from that of pass by reference. However, both mechanisms have the same effects. In the pass by reference value, the reference of the actual parameter is copied to the formal parameter. The formal parameter uses a read more..

  • Page - 233

    CHAPTER 6 CLASSES AND OBJECTS 231 Pass by Result You can think of pass by result as the opposite of pass by value. In pass by value, the value of the actual parameter is copied to the formal parameter. In pass by result, the value of the actual parameter is not copied to the formal parameter. The formal parameter is considered an uninitialized local read more..

  • Page - 234

    CHAPTER 6 CLASSES AND OBJECTS 232 It achieves the effect of pass by reference in a different way. In pass by reference, any modification made to the formal parameter is visible to the actual parameter immediately. In a pass by value result, any modification to the formal parameter is visible to the actual parameter only when the method call returns. If the read more..

  • Page - 235

    CHAPTER 6 CLASSES AND OBJECTS 233 Consider the following declaration for a method squareDivide(): int squareDivide(int x, int y) { int z = x * x/y * y; return z; } Consider the following snippet of code that calls the squareDivide() method: squareDivide((4+4), (2+2)); You can visualize the execution of the above call as if you read more..

  • Page - 236

    CHAPTER 6 CLASSES AND OBJECTS 234 The value 754 is directly stored at the memory address 131072, which is associated with the id variable name. What happens if you execute the following statement, which assigns a new value of 351 to the id variable? id = 351; When a new value 351 is assigned to the id variable, the old value of 754 is replaced read more..

  • Page - 237

    CHAPTER 6 CLASSES AND OBJECTS 235 262144 model Unknown year 2000 price 0.0 Memory address Object stored at the address Figure 6-13. Memory state when a Car object is created using the new Car() statement At this point, there is no way to refer to the newly created Car object from a Java program even though it exists in memory. The new operator (as used in new read more..

  • Page - 238

    CHAPTER 6 CLASSES AND OBJECTS 236 xyCar 10240 null Figure 6-16. Memory state of xyCar reference variable myCar 8192 9216 9216 model Unknown year 2000 price 0.0 Car object The reference variable, myCar, stores reference of Car object Figure 6-15. Memory states for the myCar reference variable and the new Car object when the myCar = new Car() statement is executed The statement read more..

  • Page - 239

    CHAPTER 6 CLASSES AND OBJECTS 237 At this time, you can use reference variables myCar or xyCar to access the Car object in memory. The following snippet of code will access the same object in memory: myCar.model = "Civic LX"; /* Use myCar to change model */ myCar.year = 1999; /* Use myCar to change year */ xyCar.price = 16000.00; /* read more..

  • Page - 240

    CHAPTER 6 CLASSES AND OBJECTS 238 Let’s make one more change and set the xyCar reference variable to null as shown: xyCar = null; /* #6 */ Figure 6-20 shows the memory state after statement #6 is executed. myCar 8192 5120 5120 model Unknown year 2000 price 0.0 9216 model Civic LX year 1999 price 16000.0 xyCar 10240 9216 Figure 6-19. Memory state of reference variables read more..

  • Page - 241

    CHAPTER 6 CLASSES AND OBJECTS 239 This brief statement causes a lot of confusion. Does it mean that when a parameter is a reference type, a copy of the object the actual parameter refers to is made and assigned to the formal parameter? It is important to elaborate on the phrase “All parameters in Java are passed by value” with examples. Even veteran Java read more..

  • Page - 242

    CHAPTER 6 CLASSES AND OBJECTS 240 #1: a = 19, b = 37 #2: x = 19, y = 37 #3: x = 37, y = 19 #4: a = 19, b = 37 A primitive type parameter is passed by value. However, you can modify the value of the formal parameter inside the method without affecting the actual parameter value. Java also lets you use pass by constant value. In this case, the read more..

  • Page - 243

    CHAPTER 6 CLASSES AND OBJECTS 241 #1: a = 19, b = 37 #2: x = 19, y = 37 #3: x = 19, y = 223 #4: a = 19, b = 37 Let’s discuss the parameter passing mechanism for reference type parameters. Java lets you use the pass by reference value and pass by constant reference value mechanisms to pass reference type parameters to a method. When a parameter is read more..

  • Page - 244

    CHAPTER 6 CLASSES AND OBJECTS 242 At this point, there are two Car objects in memory. The xyCar formal parameter references the new Car object and not the one whose reference was passed to the method. Note that the actual parameter myCar still references the Car object that you created in the main() method. The fact that the xyCar formal parameter read more..

  • Page - 245

    CHAPTER 6 CLASSES AND OBJECTS 243 Tip When a reference type parameter is passed to a method in Java, the formal parameter can access the object the same way the actual parameter can access the object. The formal parameter can modify the object by directly changing the values of the instance variables or by calling methods on the object. Any modification made on read more..

  • Page - 246

    CHAPTER 6 CLASSES AND OBJECTS 244 What will be the content of s1 at #4? String is a reference type in Java. At #1, s1 is referencing a String object whose content is "hi". When the changeString(s1) method is called, s1 is passed to s2 by reference value. At #2, s1 and s2 are referencing the same String object in memory whose content read more..

  • Page - 247

    CHAPTER 6 CLASSES AND OBJECTS 245 Constructors A constructor is a named block of code that is used to initialize an object of a class immediately after the object is created. The structure of a constructor looks similar to a method. However, the similarity between the two stops right there, in their looks. They are two different constructs and they are used for read more..

  • Page - 248

    CHAPTER 6 CLASSES AND OBJECTS 246 Tip The name of a constructor must match the simple name, not the fully qualified name, of the class. Unlike a method, a constructor does not have a return type. You cannot even specify void as a return type for a constructor. Consider the following declaration of a class Test2: public class Test2 { // read more..

  • Page - 249

    CHAPTER 6 CLASSES AND OBJECTS 247 Listing 6-26. A Cat Class with a Constructor // Cat.java package com.jdojo.cls; public class Cat { public Cat() { System.out.println("Meow..."); } } The Cat class declares a constructor. Inside the constructor’s body, it prints a message "Meow..." in the read more..

  • Page - 250

    CHAPTER 6 CLASSES AND OBJECTS 248 Listing 6-28. A Dog Class with Two Constructors, One with No Parameter and One with a String Parameter // Dog.java package com.jdojo.cls; public class Dog { // Constructor #1 public Dog() { System.out.println("A dog is created."); } read more..

  • Page - 251

    CHAPTER 6 CLASSES AND OBJECTS 249 Tip A constructor is called once per object creation expression. You can execute the code for one constructor only once in the process of an object creation. If the code for a constructor is executed N times, it means N number of objects of that class will be created and you must use N number of object creation read more..

  • Page - 252

    CHAPTER 6 CLASSES AND OBJECTS 250 public String getName() { return this.name; } public void setPrice(double price) { this.price = price; } public double getPrice() { read more..

  • Page - 253

    CHAPTER 6 CLASSES AND OBJECTS 251 Listing 6-31. A Test Class to Demonstrate the Use of the SmartDog Class // SmartDogTest.java package com.jdojo.cls; public class SmartDogTest { public static void main(String[] args) { // Create two SmartDog objects SmartDog sd1 = new SmartDog(); read more..

  • Page - 254

    CHAPTER 6 CLASSES AND OBJECTS 252 Calling a Constructor from another Constructor A constructor may call another constructor of the same class. Let’s consider the following Test class. It declares two constructors; one accepts no parameters and one accepts an int parameter. public class Test { Test() { } Test(int read more..

  • Page - 255

    CHAPTER 6 CLASSES AND OBJECTS 253 public class Test { Test() { int k = 10; // First statement this(k); // Second statement. A compile-time error } Test(int x) { } } An attempt to compile the code for the above Test class will generate the read more..

  • Page - 256

    CHAPTER 6 CLASSES AND OBJECTS 254 System.out.println("Using SmartDog() constructor"); } public SmartDog(String name, double price) { // Initialize name and price to specified name and price this.name = name; read more..

  • Page - 257

    CHAPTER 6 CLASSES AND OBJECTS 255 // Constructor #2 - public access level public Test(int x) { } // Constructor #3 - private access level private Test(int x, int y) { } // Constructor #4 - protected access level protected read more..

  • Page - 258

    CHAPTER 6 CLASSES AND OBJECTS 256 You can combine the above two statements into one in the code in any package. // Code inside any package T1 t = new T1(); Let’s consider the following code for the class T2, which has a public access level and has a constructor with a private access level: // T2.java package com.jdojo.cls.p1; public class T2 { read more..

  • Page - 259

    CHAPTER 6 CLASSES AND OBJECTS 257 public static T2 getInstance() { return T2.instance; } /* Other code goes here */ } You can use the T2.getInstance() method to get the reference of an object of the T2 class. Internally, the T2 class does not create a new object every time you call the read more..

  • Page - 260

    CHAPTER 6 CLASSES AND OBJECTS 258 public class T3Child extends T3 { public T3Child() { super(); // Ok. Calls T3() constructor, which is declared protected. } } The T3 class is called the parent class of the T3Child class. An object of a child class cannot be created until the object of its read more..

  • Page - 261

    CHAPTER 6 CLASSES AND OBJECTS 259 Table 6-6. Examples of Classes for Which a Default Constructor Is Added by the Java Compiler Source Code for Your Class Compiled Version of Your Class Comments public class Test { } public class Test { public Test() { } } The compiler adds a default constructor with public access level. class Test { } class Test { read more..

  • Page - 262

    CHAPTER 6 CLASSES AND OBJECTS 260 Instance Initialization Block You have seen that a constructor is used to initialize an instance of a class. An instance initialization block, also called instance initializer, is also used to initialize objects of a class. Why does Java provide two constructs to perform the same thing? Not all classes in Java can have a constructor. Are read more..

  • Page - 263

    CHAPTER 6 CLASSES AND OBJECTS 261 public InstanceInitializer() { System.out.println("Inside no-args constructor."); } public static void main(String[] args) { InstanceInitializer ii = new InstanceInitializer(); } } Inside instance initializer 1. read more..

  • Page - 264

    CHAPTER 6 CLASSES AND OBJECTS 262 // Constructor public StaticInitializer() { System.out.println("Inside constructor."); } public static void main(String[] args) { System.out.println("Inside main() #1. num: " + num); read more..

  • Page - 265

    CHAPTER 6 CLASSES AND OBJECTS 263 The final Keyword The final keyword is used in many contexts in a Java program. It takes on different meanings in different contexts. However, as its name suggests, its primary meaning is the same in all contexts. Its primary meaning is The construct with which the final keyword is associated does not allow modifying or replacing read more..

  • Page - 266

    CHAPTER 6 CLASSES AND OBJECTS 264 final int multiplier; // A blank final variable /* Do something here... */ // Set the value of multiplier first time multiplier = 3; // Ok to read the multiplier variable int value = 100 * multiplier; Let’s go through examples of each type of variable and how to declare them final. final Local Variables You can declare a read more..

  • Page - 267

    CHAPTER 6 CLASSES AND OBJECTS 265 final Instance Variables You can declare an instance variable final and blank final. An instance variable is a part of an object’s state. A final instance variable specifies part of the object’s state that does not change after the object is created. A blank final instance variable must be initialized when an object is read more..

  • Page - 268

    CHAPTER 6 CLASSES AND OBJECTS 266 The following code would not compile because it initializes y more than once inside two instance initializers: public class Test2 { private final int y; { y = 10; // Initialized y for the first time } { read more..

  • Page - 269

    CHAPTER 6 CLASSES AND OBJECTS 267 The above code for the Test2 class would not compile. The compiler generates an error message, which reads as variable y might already have been assigned. Let’s consider creating an object of the Test2 class as Test2 t = new Test2(30); There is no issue in creating an object of the Test2 class by invoking the one-arg read more..

  • Page - 270

    CHAPTER 6 CLASSES AND OBJECTS 268 final Reference Variables Any type of variable (primitive and reference) can be declared final. The primary meaning of the final keyword is the same in both cases. That is, the value stored in a final variable cannot be changed once it has been set. I will look at the final reference variable in a little more detail in read more..

  • Page - 271

    CHAPTER 6 CLASSES AND OBJECTS 269 Consider the following statement: int x = 100 * Constants.MULTIPLIER; When you compile the above statement, the compiler will replace Constants.MULTIPLIER with its value 12 and your statement is compiled as int x = 100 * 12; Now, 100 * 12 is also a compile-time constant expression. The compiler will replace it with its value read more..

  • Page - 272

    CHAPTER 6 CLASSES AND OBJECTS 270 The above logic works fine. It computes the maximum of two integers, and then computes the maximum of the two and the third integer. Suppose you want to compute maximum of ten integers. You might repeat the above logic and that will work, although the code may not be readable. You need a better way of doing this. Let’s read more..

  • Page - 273

    CHAPTER 6 CLASSES AND OBJECTS 271 You can write the following snippet of code that will compute the maximum of two and three integers using the MathUtil3.max() method: int[] num1 = new int[] {10, 1}; int max1 = MathUtil3.max(num1); int[] num2 = new int[] {10, 8, 18} ; int max2 = MathUtil3.max(num2); You can pass an arbitrary number of integers to the read more..

  • Page - 274

    CHAPTER 6 CLASSES AND OBJECTS 272 The variable-length argument of a varargs method must be the last argument in the argument list. The following declaration for m2() method is invalid because the variable-length argument n1 is not declared as the last argument: // Invalid declaration void m2(int...n1, String str) { // Code goes here } You can fix the above read more..

  • Page - 275

    CHAPTER 6 CLASSES AND OBJECTS 273 The body of the MathUtil4.max() method is exactly the same as if the num argument is declared as an int array. You are right in thinking so. The Java compiler implements a variable-length argument of a method using an array. The above declaration of the MathUtil4.max() method is changed by the compiler. The declaration part read more..

  • Page - 276

    CHAPTER 6 CLASSES AND OBJECTS 274 public static void main(String[] args) { System.out.println("max(7, 9) = " + MathUtil5.max(7, 9)); System.out.println("max(70, 19, 30) = " + MathUtil5.max(70, 19, 30)); System.out.println("max(-7, -1, 3) = " + MathUtil5.max(-70, -1, read more..

  • Page - 277

    CHAPTER 6 CLASSES AND OBJECTS 275 Tip If a varargs method is overloaded, Java uses the more specific version of the method instead of using a varargs method. Java uses varargs method as the last resort to resolve a method call. Sometimes a call to an overloaded varargs method may cause confusion to the Java compiler. The overloading of the method itself may be read more..

  • Page - 278

    CHAPTER 6 CLASSES AND OBJECTS 276 Generic Classes Abstraction and polymorphism are at the heart of object-oriented programming. Defining a variable is an example of abstraction where the variable hides the actual values. Defining a method hides the details of its implementation logic, which is another form of abstraction. Defining parameters for a method is part of polymorphism read more..

  • Page - 279

    CHAPTER 6 CLASSES AND OBJECTS 277 It is customary, not a requirement, to give one-character names to the formal type parameters, for example, T, R, U, V, etc. Typically, T stands for “Type,” R for “Return,” etc. One-character names ma ke the code more readable. However, nothing stops you from declaring a generic class as follows, which has four formal type read more..

  • Page - 280

    CHAPTER 6 CLASSES AND OBJECTS 278 The program in Listing 6-36 shows how to use the generic Wrapper<T> class. Listing 6-36. Using a Generic Class in Your Code // WrapperTest.java package com.jdojo.cls; public class WrapperTest { public static void main(String[] args) { Wrapper<String> w1 = new Wrapper<>("Hello"); read more..

  • Page - 281

    CHAPTER 6 CLASSES AND OBJECTS 279 Different mechanisms to pass parameters to methods and constructors exist. Java uses pass by value and pass by constant value mechanisms to pass parameters of primitive data types. Pass by reference value and pass by constant reference value are used to pass parameters of reference types. You can define a class and its members read more..

  • Page - 282

    281 CHAPTER 7 The Object and Objects Classes In this chapter, you will learn About the hierarchical class structure in Java About the Object class being the superclass of classes How to use methods of the Object class with detailed examples How to reimplement methods of the Object class in your class How to check two objects for equality The difference between immutable read more..

  • Page - 283

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 282 // Can assign a reference of an object of the Object class obj = new Object(); // Can assign a reference of an object of the Account class Account act = new Account(); obj = act; // Can assign a reference of object of any class. Assume that the AnyClass class exists obj = new AnyClass(); The opposite of the above read more..

  • Page - 284

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 283 Rule #2 The Object class has nine methods, which are available to be used in all classes in Java. We can put the methods into two categories. Methods in the first category have been implemented in the Object class. You are supposed to use them as they have been implemented. You cannot reimplement (the technical term read more..

  • Page - 285

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 284 To reimplement a method of the Object class, you need to declare the method the same way as it has been declared in the Object class, and then write your own code in its body. There are more rules to reimplement a method. I will cover all rules in Chapter 16 on inheritance. You can reimplement the toString() read more..

  • Page - 286

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 285 By default, the class definition is loaded only once, and there is only one Class object per Java class. You are not considering those cases where you have written code to load the same class more than once. If you use the getClass() method on different objects of the same class, you will get the reference of the read more..

  • Page - 287

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 286 Computing a hash code is a one-way process. Getting the original piece of information from a hash code is not an easy task and it is not the goal of the hash code computation either. The piece of information that could be used to generate a hash code could be an arbitrary sequence of bytes, characters, numbers, read more..

  • Page - 288

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 287 If your class is mutable, you should not be using objects of your class as keys in hash-based collections. If the object has been used as a key changes after their use, you will not be able to locate the object in the collection because locating an object in a hash based collection is based on its hash code. In read more..

  • Page - 289

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 288 The above method is one of the many ways, not the only way, to compute hash code of an object in Java. Consult a good textbook on computing hash codes if you need a stronger hash function. All primitive wrapper classes and String class override the hashCode() method to provide reasonably good implementations of hash read more..

  • Page - 290

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 289 // Use price long priceBits = Double.doubleToLongBits(price); code = (int)(priceBits ^ (priceBits >>>32)); hash = hash * 59 + code; return hash; read more..

  • Page - 291

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 290 Sometimes you want to treat two objects as equal if they have the same state based on some or all of their instance variables. If you want to compare two objects of your class for equality based on criteria other than their references (identities), your class needs to reimplement the equals() method of the Object read more..

  • Page - 292

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 291 Listing 7-2. A SmartPoint Class That Reimplements equals() and hashCode() Methods // SmartPoint.java package com.jdojo.object; public class SmartPoint { private int x; private int y; public SmartPoint(int x, int y) { this.x = x; read more..

  • Page - 293

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 292 The only requirement for a hashCode() method is that if the m.equals(n) method returns true, m.hashCode() must return the same value as n.hashCode(). Because your equals() method uses (x, y) coordinates to test for equality, you return the sum of x and y coordinates from the hashCode() method, which fulfills the technical read more..

  • Page - 294

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 293 It is time to test your reimplementation of the equals() method in the SmartPoint class. Listing 7-3 is your test class. You can observe in the output that you have two ways of comparing two SmartPoint objects for equality. The equality operator ( ==) compares them based on identity and the equals() method compares read more..

  • Page - 295

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 294 Reflexivity: It should be reflexive. The expression x.equals(x) should return true. That is, an object must be equal to itself. Symmetry: It should be symmetric. If x.equals(y) returns true, y.equals(x) must return true. That is, if x is equal to y, y must be equal to x. Transitivity: It should be transitive. If read more..

  • Page - 296

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 295 // Is otherObject a null reference? if (otherObject == null) { return false; } // Do they belong to the same class? read more..

  • Page - 297

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 296 // Print the string representations System.out.println(objStr); System.out.println(intHolderStr); java.lang.Object@360be0 com.jdojo.object.IntHolder@45a877 Note that your IntHolder class does not have a toString() method. Still, you were able to call the toString() method using the intHolder reference variable because all methods in the Object read more..

  • Page - 298

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 297 The following snippet of code shows you how to use the toString() method of the SmartIntHolder class: // Create an object of the SmartIntHolder class SmartIntHolder intHolder = new SmartIntHolder(234); String intHolderStr = intHolder.toString(); System.out.println(intHolderStr); // Change the value in SmartIntHolder object read more..

  • Page - 299

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 298 When you concatenate a string and an object like String str = "Hello" + new Point(10, 20); Java calls the toString() method on the Point object and concatenate the returned value to the "Hello" string. The above statement will assign a "Hello(10, 20)" string to the str variable. The above statement read more..

  • Page - 300

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 299 Cloning Objects Java does not provide an automatic mechanism to clone (make a copy) an object. Recall that when you assign a reference variable to another reference variable, only the reference of the object is copied, not the content of the object. Cloning an object means copying the content of the object bit by read more..

  • Page - 301

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 300 One important thing that you must do is add an "implements Cloneable" clause in your class declaration. Cloneable is an interface declared in the java.lang package. You will learn about interface in Chapter 17. For now, just add this clause in your class declaration. Otherwise, you will get a runtime error when read more..

  • Page - 302

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 301 DoubleHolder dh = new DoubleHolder(100.00); DoubleHolder dhClone = (DoubleHolder) dh.clone(); At this point, there are two separate objects of the DoubleHolder class. The dh variable references the original object and dhClone variable references the cone of the original object. The original as well as the cloned object hold read more..

  • Page - 303

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 302 // DoubleHolder.java package com.jdojo.object; public class DoubleHolder implements Cloneable { /* The same code goes here as before... */ public DoubleHolder clone() { Object copy = null; /* The same code goes here as read more..

  • Page - 304

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 303 When the contained objects are copied rather than their references during cloning of a compound object, it is called deep cloning. You must clone all the objects referenced by all reference variables of an object to get a deep cloning. A compound object may have multiple levels of chaining of contained objects. For example, read more..

  • Page - 305

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 304 An object of the ShallowClone class is composed of an object of the DoubleHolder class. The code in the clone() method of the ShallowClone class is the same as for the clone() method of the DoubleHolder class. The difference lies in the type of instance variables that are used for the two classes. The DoubleHolder read more..

  • Page - 306

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 305 Listing 7-11. A DeepClone Class That Performs Deep Cloning // DeepClone.java package com.jdojo.object; public class DeepClone implements Cloneable { private DoubleHolder holder = new DoubleHolder(0.0); public DeepClone(double value) { this.holder.setValue(value); read more..

  • Page - 307

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 306 Listing 7-12. A Test Class to Test Deep Cloning of Objects // DeepCloneTest.java package com.jdojo.object; public class DeepCloneTest { public static void main(String[] args) { DeepClone sc = new DeepClone(100.00); DeepClone scClone = read more..

  • Page - 308

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 307 The finalize() method in the Object class does not do anything. You need to override the method in your class. The finalize() method of your class will be called by the garbage collector before an object of your class is destroyed. Listing 7-13 has code for the Finalize class. It overrides the finalize() method of read more..

  • Page - 309

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 308 Finalizing 15247 Finalizing 15248 Finalizing 15246 The program creates 20,000 objects of the Finalize class without storing their references. It is important that you do not store the references of the objects you create. As long as you hold the reference of an object, it will not be destroyed and its finalizer will not read more..

  • Page - 310

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 309 public void setValue(int value) { this.value = value; } public int getValue() { return value; } } The value instance variable defines the state of an IntHolder object. You create read more..

  • Page - 311

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 310 At this point, the wrapper object holds 101 and there is no way to change it. Therefore, the IntWrapper class is an immutable class and its objects are immutable objects. You might have noticed that two changes were made to the IntHolder class to convert it to the IntWrapper class. The setValue() method read more..

  • Page - 312

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 311 The String class in the Java class library is an example of an immutable class. It uses the caching technique discussed for the IntWrapper2 class. The String class computes hash code for its content when its hashCode() method is called for the first time and caches the value. Thus, a String object changes its read more..

  • Page - 313

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 312 #1 value = 101 #2 value = 207 The output shows that the IntHolderWrapper class is mutable. Two calls to its getValue() method return different values. The culprit is its getIntHolder() method. It returns the instance variable valueHolder, which is a reference variable. Note that the valueHolder instance variable represents read more..

  • Page - 314

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 313 Creating an immutable class is a little trickier than it seems. I have covered some of the cases in this section. Here is another case where you need to be careful. Suppose you have designed an immutable class that has a reference type instance variable. Suppose it accepts the initial value of its reference type instance read more..

  • Page - 315

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 314 <T> T requireNonNull(T obj) <T> T requireNonNull(T obj, String message) <T> T requireNonNull(T obj, Supplier<String> messageSupplier) String toString(Object o) String toString(Object o, String nullDefault) The compare() method is used to compare two objects for sorting purpose. It returns 0 if both arguments are identical. Otherwise, it read more..

  • Page - 316

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 315 public class ObjectsTest { public static void main(String[] args) { // Compute hash code for two integers, a char, and a string int hash = Objects.hash(10, 8900, '\u20b9', "Hello"); read more..

  • Page - 317

    CHAPTER 7 THE OBJECT AND OBJECTS CLASSES 316 public static void printNameWithSuplier(String name, Supplier<String> messageSupplier) { // Test name for not null. Generate a NullPointerException if it is null. Objects.requireNonNull(name, messageSupplier); // Print read more..

  • Page - 318

    317 CHAPTER 8 Wrapper Classes In this chapter, you will learn: About the wrapper classes and how to use them How primitive values are automatically boxed into wrapper objects when needed How wrapper objects are automatically unboxed into primitive values when needed Wrapper Classes In previous chapters, you learned that primitive and reference types are not assignment compatible. read more..

  • Page - 319

    CHAPTER 8 WRAPPER CLASSES 318 All wrapper classes are immutable. They provide two ways to create their objects: Using constructors Using the valueOf() factory methods Each wrapper class, except Character, provides at least two constructors: one takes a value of the corresponding primitive type and another takes a String. The Character class provides only one constructor that read more..

  • Page - 320

    CHAPTER 8 WRAPPER CLASSES 319 Listing 8-1 demonstrates the difference in using constructors and valueOf() methods for the Integer wrapper class. Listing 8-1. The Difference Between Using Constructors and valueOf( ) Method to Create Integer Objects // CachedWrapperObjects.java package com.jdojo.wrapper; public class CachedWrapperObjects { public static void main(String[] read more..

  • Page - 321

    CHAPTER 8 WRAPPER CLASSES 320 Tip The new operator always creates a new object. If you do not need new objects of the primitive values, use the valueOf() factory method of the wrapper class instead of using the constructors. The equals() methods in the wrapper classes have been reimplemented to compare the wrapped primitive values in wrapper objects, not read more..

  • Page - 322

    CHAPTER 8 WRAPPER CLASSES 321 intObj = 100 byte from intObj = 100 double from intObj = 100.0 doubleObj = 329.78 double from doubleObj = 329.78 float from doubleObj = 329.78 int from doubleObj = 329 long from doubleObj = 329 Java 8 has added some methods like sum(), max(), and min() in some of the numeric wrapper classes such as Integer, Long, Float, and Double. For read more..

  • Page - 323

    CHAPTER 8 WRAPPER CLASSES 322 Typically, you receive strings from external sources, for example, a file. If strings cannot be converted to numbers, wrapper classes will throw a NumberFormatException. It is common to place the string parsing logic inside a try-catch block and handle the exceptions. The following snippet of code attempts to parse two strings into double read more..

  • Page - 324

    CHAPTER 8 WRAPPER CLASSES 323 // Using the factory method - preferred Character c2 = Character.valueOf('2'); Character c3 = Character.valueOf('ñ'); // Getting the wrapped char values char cc1 = c1.charValue(); char cc2 = c2.charValue(); char cc3 = c3.charValue(); System.out.println("c1 = " + c1); System.out.println("c2 = " + c2); System.out.println("c3 = " + c3); // Using some read more..

  • Page - 325

    CHAPTER 8 WRAPPER CLASSES 324 // Using constructors Boolean b11True = new Boolean(true); Boolean b21True = new Boolean("true"); Boolean b31True = new Boolean("tRuE"); Boolean b41False = new Boolean("false"); Boolean b51False = new Boolean("how is this"); // false // Using the factory methods Boolean b12True = read more..

  • Page - 326

    CHAPTER 8 WRAPPER CLASSES 325 indicates that it is a negative number. The 2's complement of the first 7 bits (1110110) would be 001010, which is 10 in decimal. If you consider the actual bits, 11110110, in a byte as an unsigned integer, its value is 246 (128 + 64 + 32 + 16 + 0 + 4 + 2 + 0). The following snippet of code shows how to get the value read more..

  • Page - 327

    CHAPTER 8 WRAPPER CLASSES 326 Signed x = -10 Signed y = -2 Signed x/y = 5 Unsigned x = 4294967286 Unsigned y = 4294967294 Unsigned x/y = 0 The Long class contains methods to perform unsigned operations. The methods are similar to the ones in the Integer class. Note that you cannot convert the value stored in a long to an unsigned value as you would need read more..

  • Page - 328

    CHAPTER 8 WRAPPER CLASSES 327 Did you notice the complexity that is involved when you changed the same method to use Integer objects? You had to perform three things to add two int values in the Integer objects. Unwrap the methods arguments, a and b, from Integer objects to int values using their intValue() method. int aValue = a.intValue(); int bValue = read more..

  • Page - 329

    CHAPTER 8 WRAPPER CLASSES 328 // Display the result using int variables System.out.println(iValue + " + " + jValue + " = " + kValue); } } 200 + 300 = 500 Note the amount of code needed just to add two int values. Wrapping/unwrapping an int value to an Integer and read more..

  • Page - 330

    CHAPTER 8 WRAPPER CLASSES 329 In this snippet of code, suppose you do not control the assignment of null to n. You might get a null Integer object as a result of a method call, for example, int a = getSomeValue(), where getSomeValue() returns an Integer object. A NullPointerException in such places may be a surprise for you. However, it will happen, read more..

  • Page - 331

    CHAPTER 8 WRAPPER CLASSES 330 If you apply these rules to the above snippet of code, it will print int=101 Integer=101 Suppose you have two test() methods. public void test(Integer iObject) { System.out.println("Integer=" + iObject); } public void test(long iValue) { System.out.println("long=" + iValue); } What will be printed if you use the following read more..

  • Page - 332

    CHAPTER 8 WRAPPER CLASSES 331 Are you surprised by looking at the above output? Apply the rules that I have listed and you will find that the above output followed those rules. The call to test(101) is clear because it widens 101 from int to long and executes the test(long) method. To call test(new Integer(101)), it looks for a method test(Integer) and read more..

  • Page - 333

    CHAPTER 8 WRAPPER CLASSES 332 System.out.println("a >= b: " + (a >= b)); System.out.println("a < b: " + (a < b)); System.out.println("a <= b: " + (a <= b)); a : 100 b : 100 a > b: false a >= b: true a < b: false a <= b: true There is no surprise in the above output. If you mix the two types, reference and primitive, with these read more..

  • Page - 334

    CHAPTER 8 WRAPPER CLASSES 333 Now, here’s a surprise: consider the following snippet of code. This time you are relying on autoboxing. Integer aaa = 100; // Boxing – Integer.valueOf(100) Integer bbb = 100; // Boxing – Integer.valueOf(100) Integer ccc = 505; // Boxing – Integer.valueOf(505) Integer ddd = 505; // Boxing – Integer.valueOf(505) System.out.println(aaa == bbb); read more..

  • Page - 335

    CHAPTER 8 WRAPPER CLASSES 334 All collection classes are generic classes. They declare formal type parameters. Specifying the Integer type in angle brackets ( <Integer>), while creating the List object, tells the compiler that the List will hold object of only Integer type. This gives the compiler freedom to wrap and unwrap your primitive int values while you read more..

  • Page - 336

    335 CHAPTER 9 Exception Handling In this chapter, you will learn About error handling in Java using exceptions How to use try-catch blocks to handle exceptions How to use finally blocks to clean up resources The different between checked and unchecked exceptions How to create a new exception type and use it in your code How to use auto-closeable resources using a read more..

  • Page - 337

    CHAPTER 9 EXCEPTION HANDLING 336 // Report the abnormal/error condition here } else { // Perform division here z = x/y; } You may observe that this snippet of code does two things: it handles the error condition and performs the intended action. It mixes the code for performing error handling and the action. One read more..

  • Page - 338

    CHAPTER 9 EXCEPTION HANDLING 337 Notice that when you added error handling to your four lines of pseudocode, the code bloated to over twenty lines. The worst thing about the above code is that the code that performs the action has been cluttered with error- handling code. It has also introduced many nested if-else statements resulting in spaghetti code. In the read more..

  • Page - 339

    CHAPTER 9 EXCEPTION HANDLING 338 When we talk about throwing an exception, we are talking about three things. Occurrence of an exceptional condition Creation of a Java object to represent the exceptional condition Throwing (or passing) the exception object to the exception handler The throwing of an exception is the same as passing an object reference to a method. Here, you read more..

  • Page - 340

    CHAPTER 9 EXCEPTION HANDLING 339 It includes the location where the exception occurred. The second line in the output indicates that the exception has occurred inside the main() method of the com.jdojo.exception. DivideByZero class. The source code is contained in the DivideByZero.java file. The line number in the source code that caused the exception is 7. You may read more..

  • Page - 341

    CHAPTER 9 EXCEPTION HANDLING 340 Note that a catch block’s declaration is exactly like a method declaration. It starts with the keyword catch, followed by a pair of parentheses. Within the parentheses, you declare a parameter, as you do in a method. The parameter type is the name of the exception class that it is supposed to catch. The parameterName is a read more..

  • Page - 342

    CHAPTER 9 EXCEPTION HANDLING 341 The output of Listing 9-2 is nicer than that of Listing 9-1. It tells you exactly what happened when the program was executed. Notice that the program did not terminate when the exception occurred because you handled the exception. The program executed the last statement that printed the “At the end of the program” message. read more..

  • Page - 343

    CHAPTER 9 EXCEPTION HANDLING 342 The exception class hierarchy starts at the java.lang.Throwable class. Recall that the Object class is the superclass for all classes in Java. It is also the superclass of the Throwable class. This is the reason that the figure shows the Object class at the top of the class hierarchy. It is to be emphasized that the read more..

  • Page - 344

    CHAPTER 9 EXCEPTION HANDLING 343 // Exception is a valid exception class because it is a subclass of Throwable catch(Exception e) { } // IOException class is a valid exception class because it is a subclass of Throwable catch(IOException t) { } // ArithmeticException is a valid exception class because it is a subclass of Throwable catch(ArithmeticException t) { } You can read more..

  • Page - 345

    CHAPTER 9 EXCEPTION HANDLING 344 With this rule of assignment in mind, let’s consider the following try-catch block: try { statement1; statement2; // Exception of class MyException is thrown here statement3; } catch (Exception1 e1) { // Handle Exception1 } catch(Exception2 e2) { // Handle read more..

  • Page - 346

    CHAPTER 9 EXCEPTION HANDLING 345 Consider the following try-catch block: try { // Exception1, Exception2 or Exception 3 could be thrown here } catch (Exception1 e1) { // Handle Exception1 } catch (Exception2 e2) { // Handle Exception2 } catch (Exception3 e3) { // Handle Exception3 } If you try to apply read more..

  • Page - 347

    CHAPTER 9 EXCEPTION HANDLING 346 The following snippet of code uses a valid sequence of multiple catch blocks. The ArithmeticException class is a subclass of the RuntimeException class. If both of these exceptions are handled in catch blocks for the same try block, the most specific type, which is ArithmeticException, must appear before the most generic type, which is read more..

  • Page - 348

    CHAPTER 9 EXCEPTION HANDLING 347 There is something missing in this statement. The compiler error also tells you that there is an uncaught exception, which must be caught or declared. You know about catching an exception using a try-catch block. However, you probably do not understand how to declare an exception. You will learn about declaring an exception in the read more..

  • Page - 349

    CHAPTER 9 EXCEPTION HANDLING 348 All exceptions that are not checked exceptions are called unchecked exceptions. The Error class, all subclasses of the Error class, the RuntimeException class, and all its subclasses are unchecked exceptions. They are called unchecked exceptions because the compiler does not check if they are handled in the code. However, you are free to read more..

  • Page - 350

    CHAPTER 9 EXCEPTION HANDLING 349 Enter some text and press Enter key: Hello First character you entered is: H Checked Exception - Catch or Declare If a piece of code may throw a checked exception, you must do one of the following: Handle the checked exception by placing the piece of code inside a try-catch block. Specify in your method/constructor declaration that it read more..

  • Page - 351

    CHAPTER 9 EXCEPTION HANDLING 350 If you want to use different logic, you might need more than one try-catch block. For example, if your logic states that you must attempt to execute all three statements, even if the previous statement throws an exception, your code would look as follows: public void m1() { try { read more..

  • Page - 352

    CHAPTER 9 EXCEPTION HANDLING 351 public void m1() throws Exception1, Exception3 { statement-1; // May throw Exception1 try { statement-2; // May throw Exception2 } catch(Exception2 e){ // Handle Exception2 here } read more..

  • Page - 353

    CHAPTER 9 EXCEPTION HANDLING 352 The compiler error may not be very clear to you at this point. The readChar() method of the ReadInput2 class declares that it may throw an IOException. The IOException is a checked exception. Therefore, the following piece of code in the main() method of ReadInput2Test may throw a checked IOException: char c = read more..

  • Page - 354

    CHAPTER 9 EXCEPTION HANDLING 353 The program includes a throws clause with an IOException for the main() method. Can you run the ReadInput2Test3 class as you have been running other classes using the java command? Yes. You can run the ReadInput2Test3 class the same way you run other classes in Java. The requirement to run a class is that it should read more..

  • Page - 355

    CHAPTER 9 EXCEPTION HANDLING 354 The compiler is very particular about checked exceptions being handled by programmers. If the code in a try block cannot throw a checked exception and its associated catch blocks catch checked exceptions, the compiler will generate an error. Consider the following code, which uses a try-catch block. The catch block specifies an read more..

  • Page - 356

    CHAPTER 9 EXCEPTION HANDLING 355 Exception is also a checked exception type in Java as is IOException. If a catch block should not catch a checked exception unless it is thrown in the corresponding try block, how does the code for CatchNonExistentException2 compile fine? Should it not generate the same compiler error? At first thought, you are right. It should read more..

  • Page - 357

    CHAPTER 9 EXCEPTION HANDLING 356 public Test(int x) throws CException { // Code goes here } // Rest of the code goes here } You must handle the CException when you create an object of the Test class using any of its constructors as Test t = null; try { read more..

  • Page - 358

    CHAPTER 9 EXCEPTION HANDLING 357 Throwing an Exception A Java exception is not something that is always thrown by the runtime. You can also throw an exception in your code using a throw statement. The syntax for a throw statement is throw <<A throwable object reference>>; Here, throw is a keyword, which is followed by a reference to a throwable read more..

  • Page - 359

    CHAPTER 9 EXCEPTION HANDLING 358 Listing 9-8. A MyException Class That Extends the Exception Class // MyException.java package com.jdojo.exception; public class MyException extends Exception { public MyException() { super(); } public MyException(String message) { read more..

  • Page - 360

    CHAPTER 9 EXCEPTION HANDLING 359 Listing 9-9 demonstrates the use of the printStackTrace() method for an exception class. The main() method calls the m1() method, which in turn calls the m2() method. The stack frame for this call starts with the main() method, which will be at the bottom of the stack. The top of the stack contains the m2() method. The read more..

  • Page - 361

    CHAPTER 9 EXCEPTION HANDLING 360 public static void m1() throws MyException { m2(); } public static void m2() throws MyException { throw new MyException("Some error has occurred."); } } com.jdojo.exception.MyException: Some error has read more..

  • Page - 362

    CHAPTER 9 EXCEPTION HANDLING 361 public static void m2() throws MyException { throw new MyException("Some error has occurred."); } public static String getStackTrace(Throwable e) { StringWriter strWriter = new StringWriter(); read more..

  • Page - 363

    CHAPTER 9 EXCEPTION HANDLING 362 try { // Code for try block goes here } finally { // Code for finally block goes here } When you use a try-catch-finally block, your intention is to execute the following logic: Try executing the code in the try. If the code in the try block throws any exception, execute the matching catch read more..

  • Page - 364

    CHAPTER 9 EXCEPTION HANDLING 363 Typically, you use a finally block to write cleanup code. For example, you may obtain some resources in your program that must be released when you are done with them. A try-finally block lets you implement this logic. Your code structure would look as follows: try { // Obtain and use some resources here } finally read more..

  • Page - 365

    CHAPTER 9 EXCEPTION HANDLING 364 System.out.println("-------------------------------"); try { System.out.println("Inside try block - 3."); } finally { read more..

  • Page - 366

    CHAPTER 9 EXCEPTION HANDLING 365 Rethrowing an Exception An exception that is caught can be rethrown. You may want to rethrow an exception for different reasons. One of the reasons could be to take an action after catching it, but before propagating it up the call stack. For example, you may want to log the details about the exception and then rethrow it to read more..

  • Page - 367

    CHAPTER 9 EXCEPTION HANDLING 366 /* #2 - Arranging nested try-catch */ try { try { // May throw Exception1 } catch(Exception1 e1) { // Handle Exception1 here // May throw Exception2 } } read more..

  • Page - 368

    CHAPTER 9 EXCEPTION HANDLING 367 to rethrow to hide the location of the original exception. The following snippet of code shows how to rethrow an exception by hiding the location of the original exception: try { // Code that might throw MyException } catch(MyException e) { // Re-package the stack frames in the exception object read more..

  • Page - 369

    CHAPTER 9 EXCEPTION HANDLING 368 Analysis of Rethrown Exceptions Java 7 improved the mechanism of rethrowing exceptions. Consider the following snippet of code for a method declaration: public void test() throws Exception { try { // May throw Exception1, or Exception2 } catch (Exception e) read more..

  • Page - 370

    CHAPTER 9 EXCEPTION HANDLING 369 You can redesign the m1() method to throw only one exception, say MyException, as follows: public void m1() throws MyException { try { // Code for m1() method goes here } catch(Exception1 e1){ throw new read more..

  • Page - 371

    CHAPTER 9 EXCEPTION HANDLING 370 The figure shows three books placed on a stack. Book-1 was placed first, Book-2 second, and Book-3 third. Book-3, which is added last onto the stack, represents the top of the stack. Book-1, which is added first onto the stack, represents the bottom of the stack. Adding an element to a stack is called a push operation and read more..

  • Page - 372

    CHAPTER 9 EXCEPTION HANDLING 371 Listing 9-13 demonstrates how to get to the stack frames of a thread. A Throwable object captures the stack of the thread at the point it is created. If you have a Throwable object and want to capture the snapshot of the stack of a thread at a different point where the Throwable object was created, you can call the read more..

  • Page - 373

    CHAPTER 9 EXCEPTION HANDLING 372 System.out.println("Line Number: " + lineNumber); System.out.println("---------------------------"); } } } Frame count: 4 Frame Index: 0 File Name: StackFrameTest.java Class Name: read more..

  • Page - 374

    CHAPTER 9 EXCEPTION HANDLING 373 finally { // Let us try to close the resource try { if (aRes != null) { aRes.close(); // Close the resource } } catch(Exception e) { read more..

  • Page - 375

    CHAPTER 9 EXCEPTION HANDLING 374 Listing 9-14. An AutoCloseable Resource Class // MyResource.java package com.jdojo.exception; public class MyResource implements AutoCloseable { private int level; private boolean exceptionOnClose; public MyResource(int level, boolean exceptionOnClose) { this.level = level; read more..

  • Page - 376

    CHAPTER 9 EXCEPTION HANDLING 375 Creating MyResource. Level = 2 Using MyResource level 2 Using MyResource level 1 Closing MyResource... When a resource is being closed automatically, an exception may be thrown. If a try-with-resources block completes without throwing an exception and the call to the close() method throws the exception, the runtime reports the exception thrown read more..

  • Page - 377

    CHAPTER 9 EXCEPTION HANDLING 376 Creating MyResource. Level = 2 Using MyResource level 2 Using MyResource level 1 Low in level. Suppressed exception messages are... Error in closing A Multi-Catch Block Java 7 added support for a multi-catch block to handle multiple types of exceptions in a catch block. Suppose you want to catch three exceptions: Exception1, Exception2, and read more..

  • Page - 378

    CHAPTER 9 EXCEPTION HANDLING 377 Java 7 added support for catching multiple exceptions using a multi-catch block. You can specify multiple exceptions types in a multi-catch block. Multiple exceptions are separated by a vertical bar ( |). In Java 7, the above code can be written as follows: try { // May throw Exception1, Exception2, or Exception3 } catch read more..

  • Page - 379

    379 CHAPTER 10 Assertions In this chapter, you will learn: What an assertion is in Java How to use assertions in Java programs How to enable and disable assertions How to check the status of an assertion What Is an Assertion? The literal meaning of assertion is to state something in a strong, confident, and forceful way. When you assert “something,” you believe that read more..

  • Page - 380

    CHAPTER 10 ASSERTIONS 380 In this code, you have made an assertion that the value of the variable unitPrice will be greater than 0.0 after the second statement is executed. What is the probability that the value of unitPrice will be greater than 0.0 after the second statement is executed? It is difficult to answer this question by just looking at the read more..

  • Page - 381

    CHAPTER 10 ASSERTIONS 381 Note that the errorMessageExpression in the second form of assert statement could be of any data type excluding void. The above snippet of code provides x as the value of errorMessageExpression, which evaluates to an int. The runtime will use the string representation of the value of x when it throws an AssertionError. At this point, you read more..

  • Page - 382

    CHAPTER 10 ASSERTIONS 382 Enabling/Disabling Assertions The goal in using assertions is to detect logic errors in programs. Typically, assertions should be enabled in development and test environments. Assertions help programmers find the location and type of problems in code quickly. Once an application is tested, it is very unlikely that the assertions will fail. Java designers read more..

  • Page - 383

    CHAPTER 10 ASSERTIONS 383 The following are examples of using assertion switches with different arguments. All examples assume that you are enabling assertions when you are running the com.jdojo.assertion.AssertTest class. The examples show you only how to enable assertions. By default, all assertions are disabled. /* Enable assertions in all system classes */ java –esa read more..

  • Page - 384

    CHAPTER 10 ASSERTIONS 384 Using Assertions Confusion may arise as to when to use assertions in a program. An assertion is implemented in Java by adding a new class, java.lang.AssertionError, into the existing exception class hierarchy. Sometimes programmers mistake an assertion as another exception. This may be true when you just look at the class hierarchy and you may say read more..

  • Page - 385

    CHAPTER 10 ASSERTIONS 385 You can use assertions to implement class invariants. Class invariants are conditions that always hold true about the values that determine the state of an object of a class. Class invariants may not be true for brief moments when an object is transitioning from one state to another. Suppose you have a BankAccount class with four instance read more..

  • Page - 386

    CHAPTER 10 ASSERTIONS 386 Listing 10-2. A Program to Check Whether Assertion is Enabled // AssertionStatusTest.java package com.jdojo.assertion; public class AssertionStatusTest { public static void main(String[] args) { boolean enabled = false; assert enabled = true; read more..

  • Page - 387

    387 CHAPTER 11 Strings In this chapter, you will learn: What a String object is How to create String objects How to use String literals How to manipulate Strings How to use Strings in a switch statement How to use StringBuilder and StringBuffer objects to work with mutable strings What is a String? A sequence of zero or more characters is known as a read more..

  • Page - 388

    CHAPTER 11 STRINGS 388 A string literal cannot be broken into two lines. "He llo" // Cannot continue "He in this line. A compiler error If you want to break "Hello" in two lines, you must break it using the string concatenation operator ( +), as shown: "He" + "llo" or "He" + "llo" Another read more..

  • Page - 389

    CHAPTER 11 STRINGS 389 and a carriage return, respectively. This violates the rule that a string literal cannot be continued in two lines. For example, in the early stages of compilation " Hel\u000Alo" is translated into the following, which is an invalid string literal and generates a compiler error: "Hel lo" Tip It is a compile-time error to use read more..

  • Page - 390

    CHAPTER 11 STRINGS 390 Length of a String The String class contains a length() method that returns the number of characters in the String object. Note that the length() method returns the number of characters in the string, not the number of bytes used by the string. The return type of the method length() is int. Listing 11-1 demonstrates how to compute read more..

  • Page - 391

    CHAPTER 11 STRINGS 391 String Objects Are Immutable String objects are immutable. That is, you cannot modify the content of a String object. This leads to an advantage that strings can be shared without worrying about them getting modified. For example, if you need two objects of the String class with the identical content (the same sequence of characters), you read more..

  • Page - 392

    CHAPTER 11 STRINGS 392 If you do not want str to refer to any other String object after it has been initialized, you can declare it final, like so: final String str = new String("str cannot refer to other object"); str = new String("Let us try"); // A compile-time error. str is final Tip It is the String object in memory that is immutable, read more..

  • Page - 393

    CHAPTER 11 STRINGS 393 It is very important to note that the compareTo() method compares two strings based on the Unicode values of their characters. The comparison may not be the same as the dictionary order comparison. This is fine for English and some other languages in which the Unicode values for characters are in the same order as the dictionary order of read more..

  • Page - 394

    CHAPTER 11 STRINGS 394 When Java encounters the string literal "Hello" in the program, it tries to find a match in the string pool. If there is no String object with the content "Hello" in the string pool, a new String object with "Hello" content is created and added to the string pool. The string literal "Hello" will be read more..

  • Page - 395

    CHAPTER 11 STRINGS 395 // Concatenated string will not be added to the string pool String s2 = varStr + " is not pooled"; After executing the above snippet of code, "Constant is pooled" == s1 will return true, whereas "Variable is not pooled" == s2 will return false. Tip All string literals and string literals resulting from compile-time constant read more..

  • Page - 396

    CHAPTER 11 STRINGS 396 Note that the index of the first character H is 0 (zero), the second character E is 1, and so on. The index of the last character O is 4, which is equal to the length of the string " Hello" minus 1. The following snippet of code will print the index value and the character at each index in a string of " HELLO": read more..

  • Page - 397

    CHAPTER 11 STRINGS 397 Testing a String to be Empty Sometimes you need to test whether a String object is empty. The length of an empty string is zero. There are three ways to check for an empty string: Use the isEmpty() method. Use the equals() method. Get the length of the String and check if it is zero. The following snippet of code shows how to use the read more..

  • Page - 398

    CHAPTER 11 STRINGS 398 Searching for a String You can get the index of a character or a string within another string using the indexOf() and lastIndexOf() methods. For example, String str = new String("Apple"); int index; index = str.indexOf('p'); // index will have a value of 1 index = str.indexOf("pl"); // index will have a value read more..

  • Page - 399

    CHAPTER 11 STRINGS 399 Note that the trim() method removes only leading and trailing whitespaces. It does not remove any whitespace or control characters if they appear in the middle of the string. For example, " he\nllo ".trim() will return "he\nllo" because \n is inside the string. "h ello".trim() will return "h ello" because the read more..

  • Page - 400

    CHAPTER 11 STRINGS 400 Splitting and Joining Strings It is often useful to split a string around a specified delimiter and join multiple strings into one string using a specified delimiter. Use the split() method to split a string into multiple strings. Splitting is performed using a delimiter. The split() method returns an array of String. You will learn about read more..

  • Page - 401

    CHAPTER 11 STRINGS 401 Strings in a switch Statement I discussed the switch statement in Chapter 5. Java 7 added support for strings in a switch statement. The switch-expression uses a String type. If the switch-expression is null, a NullPointerException is thrown. The case labels must be String literals. You cannot use String variables in the case labels. The read more..

  • Page - 402

    CHAPTER 11 STRINGS 402 Listing 11-3. Using Strings in a switch Statement // StringInSwitch.java package com.jdojo.string; public class StringInSwitch { public static void main(String[] args) { operate("on"); operate("off"); operate("ON"); read more..

  • Page - 403

    CHAPTER 11 STRINGS 403 Testing a String for Palindrome If you are an experienced programmer, you may skip this section. This is meant to serve as a simple exercise for beginners. A palindrome is a word, a verse, a sentence, or a number that reads the same in forward and backward directions. For example, “Able was I ere I saw Elba” and 1991 are examples of read more..

  • Page - 404

    CHAPTER 11 STRINGS 404 if (len <= 1) { return true; } // Convert the string into uppercase, // so we can make the comparisons case insensitive read more..

  • Page - 405

    CHAPTER 11 STRINGS 405 You can use objects of the StringBuilder class, instead of the String class, in situations where content of a string changes frequently. Recall that because of the immutability of the String class, string manipulations using a String object result in many new String objects, which in turn degrade the performance. A StringBuilder object can read more..

  • Page - 406

    CHAPTER 11 STRINGS 406 // Append " Java" to the StringBuilder's content sb.append(" Java"); // Now, sb contains "Hello Java" // Get a String from the StringBuilder String s2 = sb.toString(); // s2 contains "Hello Java" Unlike String, StringBuilder has a setLength() method, which takes its new length as an argument. If the new length is greater than the read more..

  • Page - 407

    CHAPTER 11 STRINGS 407 // Reverse the content sb.reverse(); printDetails(sb); } public static void printDetails(StringBuilder sb) { System.out.println("Content: \"" + sb + "\""); read more..

  • Page - 408

    CHAPTER 11 STRINGS 408 String Concatenation Operator (+) You will often use the + operator to concatenate a strings, and a primitive type value or an object to another string. For example, String str = "X" + "Y" + 12.56; If concatenation were performed by creating intermediate string objects, the concatenation operation would create a big overhead. To read more..

  • Page - 409

    CHAPTER 11 STRINGS 409 System.out.print("Comparing using String class: "); diff = str1.compareTo(str2); print(diff, str1, str2); } public static void print(int diff, String str1, String str2) { if (diff read more..

  • Page - 410

    411 CHAPTER 12 Dates and Times In this chapter, you will learn What the new Date-Time API is About the design principles behind the Date-Time API About the evolution of timekeeping, time zones, and Daylight Saving Time About the ISO-8601 standard for date, time, and date-time keeping How to represent date, time, and date-time using the Date-Time API classes and how to read more..

  • Page - 411

    CHAPTER 12 DATES AND TIMES 412 Is the third time the charm? Here is a third attempt to provide a correct, powerful, and extensible Date-Time API. At least, so we say at the time of this writing! The new API is not a free ride, however. It has a steep learning curve if you want to use its full potential. It consists of about 80 classes. Do not read more..

  • Page - 412

    CHAPTER 12 DATES AND TIMES 413 In the Date-Time API, classes representing date, time, and datetime have a now() method that returns the current date, time, or datetime, respectively. The following snippet of code creates date-time objects representing a date, a time, and a combination of them with and without a time zone: LocalDate dateOnly = LocalDate.now(); LocalTime read more..

  • Page - 413

    CHAPTER 12 DATES AND TIMES 414 // Construct a birth date and time from date-time components LocalDate myBirthDate = LocalDate.of(1968, JANUARY, 12); LocalTime myBirthTime = LocalTime.of(7, 30); System.out.println("My Birth Date: " + read more..

  • Page - 414

    CHAPTER 12 DATES AND TIMES 415 times, there was the concept of two-part clocks for timekeeping. The rotation of Earth provided the first component of the clock in terms of the periodic events of sunrise and sunset; a calendar provided the second component of the clock to count days, months, and years. Based on Earth’s rotation on its axis, several time scales, known read more..

  • Page - 415

    CHAPTER 12 DATES AND TIMES 416 You might think, because we have been adding leap seconds to UTC, UTC should be ahead of TAI. That is not true. Adding a leap second to UTC makes that hour on UTC scale 61 seconds long instead of 60 seconds. TAI is a continuous time scale; it keeps ticking all the time. When UTC completes the 61st second of the hour, TAI read more..

  • Page - 416

    CHAPTER 12 DATES AND TIMES 417 In practice, time zones have been divided based on political regions: countries and regions within countries. Local time in each time zone is an offset from UTC. The offset, the difference in UTC and local time in a time zone, is called a zone offset. The regions east of the prime meridian use a positive zone offset. A negative read more..

  • Page - 417

    CHAPTER 12 DATES AND TIMES 418 A lunar calendar is based on lunar phase cycle. It is not aligned to a tropical year. In a year, it drifts by 11 to 12 days from a tropical year. A lunar calendar takes about 33 years to catch up with a tropical year, to drift again for another 33 years. A lunar month, which is also called a synodic month, is read more..

  • Page - 418

    CHAPTER 12 DATES AND TIMES 419 For example, 4, 8, 12, 400, and 800 are known as leap years, and 1, 2, 3, 5, 300, and 100 are known as common years. Year 0 (1 B. C.) is considered a leap year. With a new definition of a leap year, the average length of a year in the Gregorian calendar is 365.2425 days, which is very close to the length of a read more..

  • Page - 419

    CHAPTER 12 DATES AND TIMES 420 Date and time components are separated by a character T. A time component consists of fields: hour, minute, and second. A colon separates two fields in a time component. A time is represented in the format hour:minute:second ISO-8601 uses a 24-hour timekeeping system. The hour element can be between 00 and 24. The hour 24 is used read more..

  • Page - 420

    CHAPTER 12 DATES AND TIMES 421 P12Y // A duration of 12 years PT15:30 // A duration of 15 hours and 30 minutes PT20S // A duration of 20 seconds P4Y2MT30M // A duration of 4 years 2 months and 30 minutes Tip The Date-Time API provides Duration and Period classes to deal with an amount of time. A Duration represents an amount read more..

  • Page - 421

    CHAPTER 12 DATES AND TIMES 422 The from( ) Methods A from() method is a static factory method, similar to an of() method, that is used to derive a datetime object from the specified argument. Unlike an of() method, a from() method requires data conversion on the specified argument. To understand what a from() method does, think of it named as deriveFrom() read more..

  • Page - 422

    CHAPTER 12 DATES AND TIMES 423 LocalDate ld = LocalDate.of(2012, 5, 2); // 2012-05-02 // Convert the date to epoch days. The epoch days is the number of days from // 1970-01-01 to a date. A date before 1970-01-01 returns a negative integer. long epochDays = ld.toEpochDay(); // 15462 // Convert a LocalDateTime to a LocalTime using the toLocalTime() method LocalDateTime ldt read more..

  • Page - 423

    CHAPTER 12 DATES AND TIMES 424 The multipliedBy( ), dividedBy( ), and negated( ) Methods Multiplication, division, and negation do not make sense on dates and times. They are applicable to the datetime types that denote an amount of time such as Duration and Period. Durations and periods can be added and subtracted. The Date-Time API supports negative durations and read more..

  • Page - 424

    CHAPTER 12 DATES AND TIMES 425 An object of the Duration class represents an amount of time between two instants on the timeline. The Duration class supports a directed duration. That is, it allows a positive as well as negative duration. Figure 12-1 shows durations with arrows to signify that they are directed durations. You can create an instance of the read more..

  • Page - 425

    CHAPTER 12 DATES AND TIMES 426 Listing 12-2 demonstrates use of some operations that can be performed on instants and durations. Listing 12-2. Using Instant and Duration Classes // InstantDurationTest.java package com.jdojo.datetime; import java.time.Duration; import java.time.Instant; public class InstantDurationTest { public static void main(String[] args) { read more..

  • Page - 426

    CHAPTER 12 DATES AND TIMES 427 Human-Scale Time In the previous section, I discussed the use of Instant and Duration classes whose instances are more suited to dealing with machine-scale time. Humans deal with time in terms of fields such as year, month, day, hour, minute, and second. Recall the following format for specifying date and time in ISO-8601 format: read more..

  • Page - 427

    CHAPTER 12 DATES AND TIMES 428 Listing 12-3. Creating Instances of the ZoneOffset Class // ZoneOffsetTest.java package com.jdojo.datetime; import java.time.ZoneOffset; public class ZoneOffsetTest { public static void main(String[] args) { // Create zone offset using hour, minute, and second ZoneOffset read more..

  • Page - 428

    CHAPTER 12 DATES AND TIMES 429 The ZoneId Class An instance of the ZoneId class represents a combination of a zone offset and the rules for changing the zone offset for observed Daylight Saving Time. Not all time zones observe Daylight Saving Time. To simplify your understanding about the ZoneId, you can think of it as ZoneId = ZoneOffset + ZoneRules Tip A read more..

  • Page - 429

    CHAPTER 12 DATES AND TIMES 430 Asia/Aden Africa/Cairo Pacific/Honolulu America/Chicago Europe/Athens ... A ZoneId object gives you access to zone rules for the time zone represented by the ZoneId. You can use the getRules() method of the ZoneId class to get an instance of the ZoneRules class to work with rules such as transitions for Daylight Saving Time, the zone read more..

  • Page - 430

    CHAPTER 12 DATES AND TIMES 431 ZoneOffset offset = rules.getOffset(now); System.out.println("Zone offset: " + offset); List<ZoneOffsetTransition> transitions = rules.getTransitions(); System.out.println(transitions); } } Current Date read more..

  • Page - 431

    CHAPTER 12 DATES AND TIMES 432 Most of the time, you will use the constants in these enums directly as arguments to methods or receive them as return values from methods. Some enums include methods to compute useful date times values using the constant itself as input. Representing Months The Month enum has 12 constants to represents the 12 months of the year. The read more..

  • Page - 432

    CHAPTER 12 DATES AND TIMES 433 JULY, FEBRUARY, MARCH, JULY, 2 Representing the Day of Week The DayOfWeek enum has seven constants to represent seven days of the week. The constants are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY. Its getValue() method returns an int value: 1 for Monday, 2 for Tuesday, and so on, which follows ISO-8601 standards. read more..

  • Page - 433

    CHAPTER 12 DATES AND TIMES 434 Tip Constants for some datetime fields that are specific to the ISO-8601 calendar system are declared in the IsoFields class. For example, IsoFields.DAY_OF_QUARTER represents ISO-8601 based day-of-quarter. The following snippet of code demonstrates how to use a ChronoField to extract a field value from a datetime and whether the datetime read more..

  • Page - 434

    CHAPTER 12 DATES AND TIMES 435 Representing the Units of Datetime Fields Time is measured in units such as years, months, days, hours, minutes, seconds, weeks, etc. An instance of the TemporalUnit interface in the java.time.temporal package represents a unit of time. The ChronoUnit in the same package contains the following constants to represent units of time: read more..

  • Page - 435

    CHAPTER 12 DATES AND TIMES 436 Current Datetime: 2014-01-03T22:47:47.375 4 days ago: 2013-12-30T22:47:47.375 4 days ago: 2013-12-30T22:47:47.375 4 hours after: 2014-01-04T02:47:47.375 4 hours after: 2014-01-04T02:47:47.375 Local Date, Time, and Datetime An instance of the LocalDate class represents a date without a time or time zone. Several methods in the class let you convert a read more..

  • Page - 436

    CHAPTER 12 DATES AND TIMES 437 The following snippet of code creates some LocalDateTime objects: // Get the current local datetime LocalDateTime ldt1 = LocalDateTime.now(); // A local datetime 2012-05-10T16:14:32 LocalDateTime ldt2 = LocalDateTime.of(2012, Month.MAY, 10, 16, 14, 32); // Construct a local datetime from a local date and a local read more..

  • Page - 437

    CHAPTER 12 DATES AND TIMES 438 // Derive the local date and time from teh localdatetime LocalDate ld2 = LocalDate.from(ldt2); LocalTime lt2 = LocalTime.from(ldt2); System.out.println("ld2: " + ld2); read more..

  • Page - 438

    CHAPTER 12 DATES AND TIMES 439 Offset Time and Datetime An instance of the OffsetTime and OffsetDateTime classes represents a time and a datetime, respectively, with a fixed zone offset from UTC. An offset time and datetime have no knowledge of a time zone. Examples of an offset time and an offset datetime in the ISO-8601 format are 10:50:11+5:30 and read more..

  • Page - 439

    CHAPTER 12 DATES AND TIMES 440 // Create an offset datetime OffsetDateTime odt2 = OffsetDateTime.of(2012, 5, 11, 18, 10, 30, 0, read more..

  • Page - 440

    CHAPTER 12 DATES AND TIMES 441 2012-05-11T07:30-05:00[America/Chicago] Not all combinations of a LocalDateTime and a ZoneId result in a valid ZonedDateTime. There may be a gap or overlap on the local timeline in a time zone because of the Daylight Saving Time change. For example, in the America/Chicago time zone on March 10, 2013 at 02:00, the clock was moved an read more..

  • Page - 441

    CHAPTER 12 DATES AND TIMES 442 The ZonedDateTime class contains a static factory method ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset). You can use this method to create a ZonedDateTime by specifying the preferred zone offset in case there are two zone offsets available for the local time in the specified zone. If the specified referred zone read more..

  • Page - 442

    CHAPTER 12 DATES AND TIMES 443 // Create some zoned datetimes ZoneId usCentralZone = ZoneId.of("America/Chicago"); ZonedDateTime zdt2 = ZonedDateTime.of(ldt, usCentralZone); System.out.println(zdt2); read more..

  • Page - 443

    CHAPTER 12 DATES AND TIMES 444 Listing 12-10. Converting a Datetime in a Time Zone to Another Time Zone // DateTimeZoneConversion.java package com.jdojo.datetime; import java.time.LocalDateTime; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; public class DateTimeZoneConversion { public static void main(String[] args) { read more..

  • Page - 444

    CHAPTER 12 DATES AND TIMES 445 // Get the current instant of the clock Instant instant1 = clock.instant(); // Get the current instant using the clock and the Instant class Instant instant2 = Instant.now(clock); // Get the local date using the clock LocalDate ld = LocalDate.now(clock); read more..

  • Page - 445

    CHAPTER 12 DATES AND TIMES 446 An instance of the Period class represents a period. Use one of the following static factory methods to create a Period: static Period of(int years, int months, int days) static Period ofDays(int days) static Period ofMonths(int months) static Period ofWeeks(int weeks) static Period ofYears(int years) The following snippet of code creates some read more..

  • Page - 446

    CHAPTER 12 DATES AND TIMES 447 p1: P2Y3M5D p2: P1Y15M28D p1.plus(p2): P3Y18M33D p1.plus(p2).normalized(): P4Y6M33D p1.minus(p2): P1Y-12M-23D There is a big difference in the way the Date-Time API treats computations based on periods and durations. Computations including periods behave the way humans would expect. For example, when you add a period of one day to a ZonedDateTime, the read more..

  • Page - 447

    CHAPTER 12 DATES AND TIMES 448 Start Datetime: 2012-03-10T07:30-06:00[America/Chicago] After 1 Day period: 2012-03-11T07:30-05:00[America/Chicago] After 24 Hours duration: 2012-03-11T08:30-05:00[America/Chicago] Period Between Two Dates and Times It is a common requirement to compute the amount of time elapsed between two dates, times, and datetimes. For example, you may need to compute the read more..

  • Page - 448

    CHAPTER 12 DATES AND TIMES 449 // Using the until() method long days2 = ld1.until(ld2, DAYS); long hours2 = lt1.until(lt2, HOURS); long minutes2 = lt1.until(lt2, MINUTES); System.out.println("Using read more..

  • Page - 449

    CHAPTER 12 DATES AND TIMES 450 Listing 12-13. Using Year, YearMonth, and MonthDay Partials // Partials.java package com.jdojo.datetime; import java.time.Month; import java.time.MonthDay; import java.time.Year; import java.time.YearMonth; public class Partials { public static void main(String[] args) { // Use Year read more..

  • Page - 450

    CHAPTER 12 DATES AND TIMES 451 Finally, Listing 12-14 contains an example of combining two partials to get another partial. It’s the complete program to compute Christmas days for the next five years. Listing 12-14. Combining a Year and MonthDay to get a LocalDate // ChristmasDay.java package com.jdojo.datetime; import java.time.LocalDate; import java.time.Month; import read more..

  • Page - 451

    CHAPTER 12 DATES AND TIMES 452 Adjusting Dates Sometimes you want to adjust a date and time to have a particular characteristic, for example, the first Monday of the month, the next Tuesday, etc. You can perform adjustments to a date and time using an instance of the TemporalAdjuster interface. The interface has one method, adjustInto(), that takes a Temporal and read more..

  • Page - 452

    CHAPTER 12 DATES AND TIMES 453 The TemporalAdjuster class provides a dayOfWeekInMonth() method. This method returns a date adjuster that adjusts a date to the specified ordinal day of week, for example, the first Sunday of month, the third Friday of month, etc. The specified ordinal value may be between 1 and 5. If the ordinal is 5 and the month does not read more..

  • Page - 453

    CHAPTER 12 DATES AND TIMES 454 // Create an adjuster that retruns a date after 3 months and 2 days TemporalAdjuster adjuster = TemporalAdjusters.ofDateAdjuster((LocalDate date) -> date.plusMonths(3).plusDays(2)); // Use the adjuster LocalDate today = LocalDate.now(); LocalDate dayAfter3Mon2Day = today.with(adjuster); System.out.println("Today: " + today); read more..

  • Page - 454

    CHAPTER 12 DATES AND TIMES 455 Today: 2014-01-08 Next Monday: 2014-01-13 Last day of month: 2014-01-31 Date after adding 3 months and 2 days: 2014-04-10 Let’s create a custom date adjuster. If the date being adjusted is on weekends or Friday 13, it returns the next Monday. Otherwise, it returns the original date. That is, the adjuster will return only weekdays, read more..

  • Page - 455

    CHAPTER 12 DATES AND TIMES 456 Listing 12-17 demonstrates how to use the custom date adjuster. December 12, 2013 was on Thursday. You use the adjuster to adjust December 12, 13, and 14 in 2013. December 12, 2013 is returned without any adjustments. The other two dates are adjusted to next Monday, which is December 16, 2013. Note that the adjuster can be used on read more..

  • Page - 456

    CHAPTER 12 DATES AND TIMES 457 Querying Datetime Objects All datetime classes support queries. A query is a request for information. Note that you can obtain the components of a datetime object, for example, the year from a LocalDate, using the get(TemporalField field) method of the datetime object. Use a query to request information that is not available as read more..

  • Page - 457

    CHAPTER 12 DATES AND TIMES 458 // Query a LocalDate LocalDate ld = LocalDate.now(); TemporalUnit precision = ld.query(precisionQuery); LocalDate queryDate = ld.query(localDateQuery); System.out.println("Precision read more..

  • Page - 458

    CHAPTER 12 DATES AND TIMES 459 import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import static java.time.DayOfWeek.FRIDAY; public class Friday13Query implements TemporalQuery<Boolean> { public final static Friday13Query IS_FRIDAY_13 = new Friday13Query(); // Prevent outside code from read more..

  • Page - 459

    CHAPTER 12 DATES AND TIMES 460 Listing 12-20. A CustomQueries Class with a IsFriday13 Method That Can Be Used a Query // CustomQueries.java package com.jdojo.datetime; import java.time.DayOfWeek; import static java.time.DayOfWeek.FRIDAY; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_WEEK; import java.time.temporal.TemporalAccessor; public class read more..

  • Page - 460

    CHAPTER 12 DATES AND TIMES 461 Listing 12-21. Multiple Ways of Getting the LocalTime from a ZonedDateTime // LocalTimeFromZonedDateTime.java package com.jdojo.datetime; import java.time.LocalTime; import java.time.ZonedDateTime; import java.time.temporal.TemporalQueries; public class LocalTimeFromZonedDateTime { public static void main(String[] args) { read more..

  • Page - 461

    CHAPTER 12 DATES AND TIMES 462 Which method is the correct way? Most of the time, all methods will execute the same logic. However, some methods are more readable than others. In this case, the code calling the toLocalTime() method of the ZonedDateTime class should be used as it is straightforward and most readable. At least, you should not extract the time read more..

  • Page - 462

    CHAPTER 12 DATES AND TIMES 463 // Convert Thai Buddhist date to ISO date and vice versa ThaiBuddhistDate thaiBuddhistNow2 = ThaiBuddhistDate.from(isoNow); LocalDate isoNow2 = LocalDate.from(thaiBuddhistNow); System.out.println("Thai Buddhist Current Date read more..

  • Page - 463

    CHAPTER 12 DATES AND TIMES 464 Table 12-5. List of Predefined Datetime Formatters Formatter Description Example BASIC_ISO_DATE An ISO date formatter to format and parse a date without using a separator between two date components. 20140109, 20140109-0600 ISO_DATE, ISO_TIME, ISO_DATE_TIME Date, time, and datetime formatters to format and parse dates, times, and datetimes using the ISO read more..

  • Page - 464

    CHAPTER 12 DATES AND TIMES 465 // Format dates using the ISO_DATE formatter String ldStr = ISO_DATE.format(LocalDate.now()); String odtStr = ISO_DATE.format(OffsetDateTime.now()); String zdtStr = ISO_DATE.format(ZonedDateTime.now()); System.out.println("Local Date; " + ldStr); System.out.println("Offset Datetime: " + odtStr); System.out.println("Zoned Datetime: " + zdtStr); Local Date; 2014-01-09 Offset read more..

  • Page - 465

    CHAPTER 12 DATES AND TIMES 466 Using User-Defined Patterns One of the most commonly used methods in the DateTimeFormatter class is the ofPattern() method, which returns a DateTimeFormatter object with the specified format pattern and locale. static DateTimeFormatter ofPattern(String pattern) static DateTimeFormatter ofPattern(String pattern, Locale locale) The following snippet obtains two read more..

  • Page - 466

    CHAPTER 12 DATES AND TIMES 467 Table 12-6. Datetime Formatting Symbols, Their Descriptions with Examples Symbol Description Examples Pattern Output G Era GAD GGGG Anno Domini GGGGG A u Year It can be a positive or negative number. After an era start date, it is a positive number. Before an era start date, it is a negative number. For example, the year value for 2014 AD is read more..

  • Page - 467

    CHAPTER 12 DATES AND TIMES 468 Symbol Description Examples F Day of week in month F1 a AM/PM of day aAM h Clock hour of AM/PM (1-12) h7 K Hour of AM/PM (0-11) K7 k Clock hour of AM/PM (1-24) k7 H Hour of day (0-23) H7 HH 07 m Minute of hour mm 30 s Second of minute ss 12 S Fraction of second SSSSSSSSS 000000789 A Millisecond of day A 27012000 n Nanosecond of second n 789 N read more..

  • Page - 468

    CHAPTER 12 DATES AND TIMES 469 You can have optional sections in a pattern string. The symbols [ and ] denote the start and the end of an optional section, respectively. A pattern enclosed within an optional section is output only if information is available for all its elements. Otherwise, an optional section is skipped. An optional section may be nested inside another read more..

  • Page - 469

    CHAPTER 12 DATES AND TIMES 470 05/30/2012 05/30/2012 at 17:30:12 Listing 12-24 shows how to use different patterns to format dates and times. Listing 12-24. Using Patterns to Format Dates and Times // FormattingDateTime.java package com.jdojo.datetime; import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.ZoneId; import java.time.ZonedDateTime; import read more..

  • Page - 470

    CHAPTER 12 DATES AND TIMES 471 Formatting date: 2012-04-30 M/d/yyyy: 4/30/2012 MM/dd/yyyy: 04/30/2012 MMM dd, yyyy: Apr 30, 2012 MMMM dd, yyyy: April 30, 2012 EEEE, MMMM dd, yyyy: Monday, April 30, 2012 'Month' q 'in' QQQ: Month 2 in Q2 [MM-dd-yyyy][' at' HH:mm:ss]: 04-30-2012 Formatting time:16:30:05.000078899 HH:mm:ss: 16:30:05 KK:mm:ss a: 04:30:05 PM [MM-dd-yyyy][' at' HH:mm:ss]: at read more..

  • Page - 471

    CHAPTER 12 DATES AND TIMES 472 import static java.time.format.FormatStyle.LONG; import static java.time.format.FormatStyle.MEDIUM; import static java.time.format.FormatStyle.SHORT; import java.util.Locale; public class LocalizedFormats { public static void main(String[] args) { LocalDate ld = LocalDate.of(2012, Month.APRIL, 19); read more..

  • Page - 472

    CHAPTER 12 DATES AND TIMES 473 Formatter Default Locale: en_US Short Date: 4/19/12 Medium Date: Apr 19, 2012 Long Date: April 19, 2012 Full Date: Thursday, April 19, 2012 Short Time: 4:30 PM Short Datetime: 4/19/12 4:30 PM Medium Datetime: Apr 19, 2012 4:30:20 PM German Medium Datetime: 19.04.2012 16:30:20 Indian(en) Short Datetime: 19/4/12 4:30 PM Indian(en) Medium Datetime: 19 Apr, read more..

  • Page - 473

    CHAPTER 12 DATES AND TIMES 474 LocalDate ld = LocalDate.of(2014, 12, 25); String pattern = "'Christmas in' yyyy 'is on' EEEE"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern); String str = ld.format(formatter); System.out.println(str); Christmas in 2014 is on Thursday Parsing Dates and Times Parsing is the process of creating a date, time, or datetime object from a read more..

  • Page - 474

    CHAPTER 12 DATES AND TIMES 475 The DateTimeFormatter class contains several parse() methods to facilitate parsing of strings into datetime objects. The DateTimeFormatter class does not know the type of datetime object that can be formed from the strings. Therefore, most of them return a TemporalAccessor object that you can query to get the datetime components. You read more..

  • Page - 475

    CHAPTER 12 DATES AND TIMES 476 The method will try to parse the text as the specified types in order and return the first successful result. Typically, a call to the parseBest() method is followed by a series of if-else statement with an instanceof operator to check what type of object was returned. Listing 12-26 shows how to use the parseBest() method. Notice read more..

  • Page - 476

    CHAPTER 12 DATES AND TIMES 477 LocalDate: 2012-05-31 LocalDateTime: 2012-05-31T16:30:12 OffsetDateTime: 2012-05-31T16:30:12-05:00 Text '2012-05-31Hello' could not be parsed, unparsed text found at index 10 Legacy Datetime Classes I’ll refer to the datetime-related classes that were available before Java 8 as legacy datetime classes. The main legacy classes are Date, Calendar, and read more..

  • Page - 477

    CHAPTER 12 DATES AND TIMES 478 A Date object works with a 1900-based year. When you call the setYear() method of this object to set the year as 2012, you will need to pass 112 (2012 - 1900 = 112). Its getYear() method returns 112 for the year 2012. Months in this class range from 0 to 11 where January is 0, February is 2 . . . and December is read more..

  • Page - 478

    CHAPTER 12 DATES AND TIMES 479 // day will contain day of month of the current date int day = gc.get(Calendar.DAY_OF_MONTH); // hour will contain hour value int hour = gc.get(Calendar.HOUR); // minute will contain minute value int minute = gc.get(Calendar.MINUTE); // second will contain second values int second = gc.get(Calendar.SECOND); You can set the date interpretation to read more..

  • Page - 479

    CHAPTER 12 DATES AND TIMES 480 Listing 12-28. Using the GregorianCalendar Class // GregorianDate .java package com.jdojo.datetime; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class GregorianDate { public static void main(String[] args) { GregorianCalendar gc = new GregorianCalendar(); read more..

  • Page - 480

    CHAPTER 12 DATES AND TIMES 481 Interoperability with Legacy Datetime Classes The legacy datetime classes have been around for over 18 years. The new Date-Time API is not going to replace them overnight. As a Java developer, you will be tasked to maintain applications that use the legacy classes. Java 8 provides interoperability between the legacy classes and the new read more..

  • Page - 481

    CHAPTER 12 DATES AND TIMES 482 Listing 12-29. Converting a Date to an Instant and Vice Versa // DateAndInstant.java package com.jdojo.datetime; import java.util.Date; import java.time.Instant; public class DateAndInstant { public static void main(String[] args) { // Get the current date Date dt read more..

  • Page - 482

    CHAPTER 12 DATES AND TIMES 483 import java.time.OffsetTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.GregorianCalendar; import java.util.TimeZone; public class GregorianCalendarAndNewDateTime { public static void main(String[] args) { // Create a GC for the default time zone read more..

  • Page - 483

    CHAPTER 12 DATES AND TIMES 484 Gregorian Calendar: Tue Feb 11 15:45:50 CST 2014 Local Date: 2014-02-11 Local Time: 15:45:50 Local DateTime: 2014-02-11T15:45:50 Offset Date: 2014-02-11T15:45:50-06:00 Offset Time: 15:45:50-06:00 Zoned DateTime: 2014-02-11T15:45:50-06:00[America/Chicago] Zone ID: America/Chicago Time Zone ID: America/Chicago Gregorian Calendar: Tue Feb 11 15:45:50 CST 2014 Summary Through the read more..

  • Page - 484

    485 CHAPTER 13 Formatting Data Java provides a rich set of APIs for formatting data. The data may include simple values such as a numbers or objects such as strings, dates, and other types of objects. In this chapter, you will learn How to format and parse dates and numbers How to use the printf-style formatting How to create a class that uses a custom read more..

  • Page - 485

    CHAPTER 13 FORMATTING DATA 486 The program listed in Listing 13-1 displays dates in short and medium formats for locales as default (which is US for the JVM running this example), France, and Germany. The program prints the current date. It will print different formats of the same date when you run this program. Your results will be different than those displayed read more..

  • Page - 486

    CHAPTER 13 FORMATTING DATA 487 // Print the locale info System.out.println("Language: " + languageName + "(" + languageCode + "); " + read more..

  • Page - 487

    CHAPTER 13 FORMATTING DATA 488 Tip Use the Locale.getDefault() method to get the default Locale for your system. If you want to use custom date formats, use the SimpleDateFormat class. Formatting using the SimpleDateFormat class is locale-sensitive. Its default constructor creates a formatter with the default locale and default date format for that locale. You can read more..

  • Page - 488

    CHAPTER 13 FORMATTING DATA 489 You can embed literals inside formatted dates. Suppose you have your birth date (September 19, 1969) stored in a date object and now you want to print it as “I was born on the Day 19 of the month September in 1969”. Some parts in the message come from the birth date and others are literals, which are intended to appear in read more..

  • Page - 489

    CHAPTER 13 FORMATTING DATA 490 // Create simple date format SimpleDateFormat simpleFormatter = new SimpleDateFormat(pattern); // Print the date System.out.println(simpleFormatter.format(birthDate)); I was born on the Day 19 of the month September in 1969 So far, you have converted date objects into formatted text. Let’s look at converting text into Date objects. This is accomplished read more..

  • Page - 490

    CHAPTER 13 FORMATTING DATA 491 for the first date text, the ParsePosition object will point to the third X in the text. You just need to increment its index by two to point to the first character of the second date text. The following snippet of code illustrates the steps: // Our text to be parsed String text = "XX01/01/1999XX12/31/2000XX"; // Create a read more..

  • Page - 491

    CHAPTER 13 FORMATTING DATA 492 SimpleDateFormat sdf = new SimpleDateFormat(pattern); // Parse the text into a Date object Date dt = sdf.parse(input, new ParsePosition(0)); System.out.println(dt); // Get read more..

  • Page - 492

    CHAPTER 13 FORMATTING DATA 493 // Get number formatter for French locale formatter = NumberFormatter.getNumberInstance(Locale.FRENCH); // Get currency formatter for German formatter = NumberFormatter.getCurrencyInstance(Locale.GERMAN); Listing 13-3 illustrates how to format numbers in default format for the current locale (the United States is the default locale for this example), French read more..

  • Page - 493

    CHAPTER 13 FORMATTING DATA 494 To perform more advanced formatting, you can use the DecimalFormat class. It allows you to supply your own format pattern. Once you create an object of the DecimalFormat class, you can change the format pattern using its applyPattern() method. You can specify different patterns for positive and negative numbers. The two patterns are read more..

  • Page - 494

    CHAPTER 13 FORMATTING DATA 495 // Format the number String formattedNumber = formatter.format(value) ; System.out.println("Number:" + value + ", Pattern:" + read more..

  • Page - 495

    CHAPTER 13 FORMATTING DATA 496 System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 1, 10, 100); System.out.printf("%1$-4d, %2$-4d, %3$-4d %n", 10, 100, 1000); // Formatting date and time Date dt = new Date(); read more..

  • Page - 496

    CHAPTER 13 FORMATTING DATA 497 // Create an Appendable data storage for our formatted output StringBuilder sb = new StringBuilder(); // Create a Formatter that will ??? its output to the StringBuffer Formatter fm = new Formatter(sb); // Formatting strings fm.format("%1$s, %2$s, and %3$s %n", "Fu", "Hu", "Lo"); fm.format("%3$s, %2$s, and %1$s %n", read more..

  • Page - 497

    CHAPTER 13 FORMATTING DATA 498 finally { if (fm != null) { fm.close(); } } The format() method of the Formatter class is overloaded. Its declarations are as follows. Formatter format(String format, Object... args) Formatter format(Locale l, String format, Object... args) The first version of the format() read more..

  • Page - 498

    CHAPTER 13 FORMATTING DATA 499 Note All outputs in this section are in the US locale unless specified otherwise. The above text contains fixed text and formatted text. The fixed text should appear in the output literally. The formatted text will depend on the inputs. You can convert the above text into a template as shown: <month> <day>, <year> is read more..

  • Page - 499

    CHAPTER 13 FORMATTING DATA 500 The <conversion> denotes how the output should be formatted. Its value depends on the data type of the argument, which the format specifier refers to. It is mandatory. There are two special format specifiers: "%%" and "%n". The "%%" format specifier outputs "%" (a percent sign) and "%n" read more..

  • Page - 500

    CHAPTER 13 FORMATTING DATA 501 Figure 13-1 shows how indices are mapped in the above example. The first "%s" format specified refers to the first argument, "Ken". The second "%s" format specified refers to the second argument, "Lola". And, the thir d "%s" format specified refers to the third argument, "Matt". If the number read more..

  • Page - 501

    CHAPTER 13 FORMATTING DATA 502 The following snippet of code is not valid because it uses an array type argument that has only two elements and there are three format specifiers. A MissingFormatArgumentException will be thrown when the following snippet of code is run. String[] names = {"Ken", "Matt"}; System.out.printf("%s, %s, and %s", names); // Throws read more..

  • Page - 502

    CHAPTER 13 FORMATTING DATA 503 Consider the following snippet of code and its output, which uses relative indexing: System.out.printf("%1$s, %<s, %<s, %2$s, and %<s", "Ken", "Matt"); Ken, Ken, Ken, Matt, and Matt This snippet of code uses five format specifiers: "%1$s", "%<s", "%<s", "%2$s", and "%<s". It uses two read more..

  • Page - 503

    CHAPTER 13 FORMATTING DATA 504 Using Flags in a Format Specifier Flags act as modifiers. They modify the formatted output. Table 13-3 lists all flags that can be used in a format specifier. Table 13-3. List of Valid Flags, Their Descriptions, and Examples of Their Usage Flag Description Examples Format String Argument Formatted Text ‘-’ The result is left justified. read more..

  • Page - 504

    CHAPTER 13 FORMATTING DATA 505 Conversion Characters Different conversion characters are used to format values of different data types. For example, 's' is used to format a value as a string. The valid values for other parts in a format specifier are also determined by the conversion character in the format specifier and the data type of the argument that the read more..

  • Page - 505

    CHAPTER 13 FORMATTING DATA 506 The width denotes the minimum number of characters to be written to the output. If the length of the string representation of the argument is less than the width value, the result will be padded with spaces. The space padding is performed to the left of the argument value. If ‘-’ flag is used, space padding is performed to the right. The value read more..

  • Page - 506

    CHAPTER 13 FORMATTING DATA 507 // String conversion System.out.printf("'%s', '%5s', '%.3s'%n", "Ken", "Matt", "Lola"); System.out.printf("'%S', '%5S', '%.3S'%n", "Ken", "Matt", "Lola"); // Use '-' flag to left-justify the result. You must use width when you specify the '-' flag System.out.printf("'%S', '%-5S', '%.3S'%n", "Ken", read more..

  • Page - 507

    CHAPTER 13 FORMATTING DATA 508 Listing 13-6. Implementing a Custom Formatter Using the Formattable Interface // FormattablePerson.java package com.jdojo.format; import java.util.Formattable; import java.util.Formatter; import java.util.FormattableFlags; public class FormattablePerson implements Formattable { private String firstName = "Unknown"; private String read more..

  • Page - 508

    CHAPTER 13 FORMATTING DATA 509 else { // Left-justified flag '-' is not used } You can use your FormattablePerson objects with format specifiers using string conversion 's' and 'S' as shown below: FormattablePerson fp = new FormattablePerson("Ken", "Smith"); System.out.printf("%s %n", fp ); System.out.printf("%#s %n", fp ); read more..

  • Page - 509

    CHAPTER 13 FORMATTING DATA 510 Many locale-specific formatting are automatically applied when a numeric value is formatted. For example, the numeric digits that are used for number formatting are always locale-specific. If the formatted number contains a decimal separator or group separators, they are always replaced with locale-specific decimal separator or group separators, read more..

  • Page - 510

    CHAPTER 13 FORMATTING DATA 511 The general syntax for a format specifier for integral number formatting is as follows: %<argument_index$><flags><width><conversion> Note that precision part in a format specifier is not applicable to integral number formatting. The following snippet of code demonstrates the use of the 'd' conversion with various flags to read more..

  • Page - 511

    CHAPTER 13 FORMATTING DATA 512 The following snippet of code shows some more examples of 'o' and 'x' conversions for int and BigInteger argument types: System.out.printf("%o %n", 1969); System.out.printf("%o %n", -1969); System.out.printf("%o %n", new BigInteger("1969")); System.out.printf("%o %n", new BigInteger("-1969")); System.out.printf("%x read more..

  • Page - 512

    CHAPTER 13 FORMATTING DATA 513 The general syntax for a format specifier for floating-point number formatting is %<argument_index$><flags><width><.precision><conversion> The precision has different meanings. The meanings depend on the conversion character. By default, the value of precision is 6. For 'e' and 'f' conversions, the precision is the number of read more..

  • Page - 513

    CHAPTER 13 FORMATTING DATA 514 1.020000e+01 10.200000 10.2000 2.079000e-06 0.000002 2.07900e-06 '1.97e+03' 0x1.1709e564a6d14p-19 The following snippet of code shows the effects of using width and precision in floating-point number formatting: System.out.printf("%.2e %n", 1969.27); System.out.printf("%.2f %n", 1969.27); System.out.printf("%.2g %n", 1969.27); read more..

  • Page - 514

    CHAPTER 13 FORMATTING DATA 515 If the argument value for a floating-point conversion is NaN or Infinity, the output contains the strings "NaN" and "Infinity", respectively. The follow ing snippet of code shows the formatting of floating-point numbers when their values are NaN or infinities: System.out.printf("%.2e %n", Double.NaN); System.out.printf("%.2f %n", read more..

  • Page - 515

    CHAPTER 13 FORMATTING DATA 516 Table 13-8. List of Suffix Characters for Date Formatting Conversion Suffix Description 'B' Locale-specific full name of the month, such as “January”, “F ebruary”, etc. for US locale. 'b' Locale-specific abbreviated month name, such as “Jan”, “F eb”, etc. for US locale. 'h' Same as ‘b’ 'A' Locale-specific full name of the day of the read more..

  • Page - 516

    CHAPTER 13 FORMATTING DATA 517 The data/time conversion applies localization wherever it is applicable. The following snippet of code formats the same date and time, January 25, 2014 11:48:16 AM, in US, Indian, and Thai locales. Note the use of the '<' flag in the format specifier. It lets you use the argument that holds the date and time value in multiple read more..

  • Page - 517

    CHAPTER 13 FORMATTING DATA 518 The following snippet of code formats the current date and time in the default locale (US in this case). You will get different output when you run the code. It uses a ZonedDateTime argument that holds the current date/time with time zone. ZonedDateTime currentTime = ZonedDateTime.now(); System.out.printf("%tA %<tB %<te, %<tY read more..

  • Page - 518

    519 CHAPTER 14 Regular Expressions In this chapter, you will learn How to create regular expressions How to use convenience methods in the String class to perform regular expression-based find-and-replace How to use the Pattern class to compile regular expressions How to use the Matcher class to match a regular expression against an input string How to use groups in regular read more..

  • Page - 519

    CHAPTER 14 REGULAR EXPRESSIONS 520 To validate these kinds of strings, you need to recognize the pattern you are looking for. For example, in the simplest form of e-mail address validation, the string should consist of some text (at least one character) plus an @ sign followed by some text for domain name. Let’s ignore any other details for now. You need a way read more..

  • Page - 520

    CHAPTER 14 REGULAR EXPRESSIONS 521 a@k matches the regex .@. webmaster@jdojo.com does not match the regex .@. r@j matches the regex .@. a%N does not match the regex .@. .@. matches the regex .@. Some important points to note are the following: The regular expression ".@." did not match “ webmaster@jdojo.com”, because a dot means only one character and the read more..

  • Page - 521

    CHAPTER 14 REGULAR EXPRESSIONS 522 The replaceFirst() method replaces the first occurrence of the match with the replacementString. It returns the new string after replacement. Some examples of using the replaceFirst() method are as follows: String regex = ".@."; // newStr will contain "webmaste***dojo.com" String newStr = read more..

  • Page - 522

    CHAPTER 14 REGULAR EXPRESSIONS 523 Character Classes The metacharacters [ and ] (left and right brackets) are used to specify a character class inside a regular expression. A character class is a set of characters. The regular expression engine will attempt to match one character from the set. Note that a character class has no relation with a class construct or read more..

  • Page - 523

    CHAPTER 14 REGULAR EXPRESSIONS 524 If you allow all uppercase and lowercase letters, underscore and digits in your e-mail address validations, the regular expression to validate e-mail addresses of only three characters would be "\w@\w". Now you are one step ahead in your e-mail address validation process. Instead of allowing only A, B, or C in the first part of read more..

  • Page - 524

    CHAPTER 14 REGULAR EXPRESSIONS 525 Table 14-3. List of Flags Defined in the Pattern Class Flag Description Pattern.CANON_EQ Enables canonical equivalence. If this flag is set, two characters match only if their full canonical decompositions match. Pattern.CASE_INSENSITIVE Enables case-insensitive matching. This flag sets the case-insensitive matching only for US-ASCII charset. For read more..

  • Page - 525

    CHAPTER 14 REGULAR EXPRESSIONS 526 The following snippet of code compiles a regular expression setting the CASE_INSENSTIVE and DOTALL flags, so the matching will be case-insensitive for US-ASCII charset and the expression. will match a line terminator. For example, “A@\n” will be m atched by the following pattern: // Prepare a regular expression String regex = "[a-z]@."; read more..

  • Page - 526

    CHAPTER 14 REGULAR EXPRESSIONS 527 The end() method returns the index of the last character in the matched string plus one. Therefore, after a successful invocation of the find() method, the difference between the values returned by the end() and start() methods will give you the length of the matched string. Using the substring() method of the String class, you read more..

  • Page - 527

    CHAPTER 14 REGULAR EXPRESSIONS 528 public static void findPattern(String regex, String source) { // Compile regex into a Pattern object Pattern p = Pattern.compile(regex); // Get a Matcher object Matcher m = read more..

  • Page - 528

    CHAPTER 14 REGULAR EXPRESSIONS 529 Beware of Backslashes Beware of using backslashes in regular expressions. The character class \w (that is, a backslash followed by a “ w”) represents a word character. Recall that a backslash character is also used as a part of an escape character. Therefore, \w must be written as \\w as a string literal. You can read more..

  • Page - 529

    CHAPTER 14 REGULAR EXPRESSIONS 530 Matching Boundaries Until now, you did not care about the location of the pattern match in the text. Sometimes, you may be interested in knowing if the match occurred in the beginning of a line. You may be interested in finding and replacing a particular match only if the match was found in a word, not as part of any word. For read more..

  • Page - 530

    CHAPTER 14 REGULAR EXPRESSIONS 531 Listing 14-3. Matching a Word Boundary // MatchBoundary.java package com.jdojo.regex; public class MatchBoundary { public static void main(String[] args) { // Prepare regular expression. Use \\b to get \b inside the string literal. String regex = read more..

  • Page - 531

    CHAPTER 14 REGULAR EXPRESSIONS 532 You can also back reference group numbers in a regular expression. Suppose you want to match text that starts with "ab" followed by "xy", which is follo wed by "ab". You can write a regular expression as "abxyab". You can also achieve the same result by forming a group that contains "ab" and read more..

  • Page - 532

    CHAPTER 14 REGULAR EXPRESSIONS 533 However, to get the first three digits (the area code), you will have to write extra code. If you form a regular expression using groups, you can get the area code using the group number. The regular expression placing the first three digits of a phone number in a group would be \b(\d{3})\d{7}\b. If m is the reference to a read more..

  • Page - 533

    CHAPTER 14 REGULAR EXPRESSIONS 534 String source = "3342449027, 2339829, and 6152534734"; // Get Matcher object Matcher m = p.matcher(source); // Start match and display formatted phone numbers while(m.find()) { System.out.println("Phone: " + m.group() + ", Formatted Phone: (" + m.group(1) + ") " + read more..

  • Page - 534

    CHAPTER 14 REGULAR EXPRESSIONS 535 Text: 3342449027, 2339829, and 6152534734 Formatted Text: (334) 244-9027, 2339829, and (615) 253-4734 You can also achieve the same result by using the String class. You do not need to use the Pattern and Matcher classes at all. The following snippet of code illustrates the same concept as above, using the String class instead. The read more..

  • Page - 535

    CHAPTER 14 REGULAR EXPRESSIONS 536 When you name a group, the group still gets a group number, as discussed in the previous section. You can still refer to a group by its group number even though it has a name. The above snippet code is rewritten as follows in which the third group, which has been named lineNumber, is referenced using its group number in as read more..

  • Page - 536

    CHAPTER 14 REGULAR EXPRESSIONS 537 After a successful match using the find() method of the Matcher class, you can use its start() and end() methods to know the match boundary for groups. These methods are overloaded: int start() int start(int groupNumber) int start(String groupName) int end() int end(int groupNumber) int end(String groupName) The methods that take no arguments read more..

  • Page - 537

    CHAPTER 14 REGULAR EXPRESSIONS 538 Resetting the Matcher If you have finished matching a pattern against input text and you want to restart matching from the beginning of the input text again, you need to use the reset() method of the Matcher class. After a call to the reset() method, the next call to match a pattern will start from the beginning of the input read more..

  • Page - 538

    CHAPTER 14 REGULAR EXPRESSIONS 539 Let’s consider the following text: “A train carrying 125 men and women was traveling at the speed of 100 miles per hour. The train fare was 75 dollars per person.” You want to find all numbers in the text (e.g., 125, 100, and 75) and replace them as follows: “100” by “a hundred” “> 100” by “more than a read more..

  • Page - 539

    CHAPTER 14 REGULAR EXPRESSIONS 540 Start using the find() method on the Matcher object to find a match. When you invoke the find() method for the first time, the number 125 will match the pattern. At this point, you would like to prepare the replacement text depending on the matched text as: String replacementText = ""; // Get the matched text. read more..

  • Page - 540

    CHAPTER 14 REGULAR EXPRESSIONS 541 Again, it checks if there was a previous match. Since this was the second call to the find() method, it will find a previous match and it will use the append position saved by the last appendReplacement() call as the starting position. The last character to be appended will be the character just before the second match. It will read more..

  • Page - 541

    CHAPTER 14 REGULAR EXPRESSIONS 542 // Convert the text into an integer for comparing int num = Integer.parseInt(matchedText); // Prepare the replacement text if (num == read more..

  • Page - 542

    543 CHAPTER 15 Arrays In this chapter, you will learn: How to declare array variables How to create arrays How to access elements of an array How to use a for loop and a for-each loop to iterate through elements an array How to copy elements of one array to another array How to copy primitive and reference types arrays How to use multi-dimensional arrays How to read more..

  • Page - 543

    CHAPTER 15 ARRAYS 544 What makes a variable an array? Placing [] (empty brackets) after the data type or after the variable name in a variable declaration makes the variable an array. For example, int empId; is a simple variable declaration. Here, int is the data type and empId is the variable name. This declaration means that the empId variable can hold read more..

  • Page - 544

    CHAPTER 15 ARRAYS 545 Continuing with our discussion, you can now create an array to store five int employee ids as follows: new int[5]; In this expression, 5 is the length of the array (also called the dimension of the array). The word “dimension” is also used in another context. You can have an array of dimension one, two, three, or more. An array read more..

  • Page - 545

    CHAPTER 15 ARRAYS 546 Accessing Array Elements Once you create an array object using the new operator, you can refer to each individual element of the array using an element’s index enclosed in brackets. The index for the first element is 0, the second element 1, the third element 2, and so on. This is called zero-based indexing. The index for the last element read more..

  • Page - 546

    CHAPTER 15 ARRAYS 547 // A runtime error. salary is not referring to any array object yet. int len = salary.length; // Create an int array of length 1000 and assign its reference to salary salary = new int[1000]; // Correct. len2 has a value 1000 int len2 = salary.length; Typically, elements of arrays are accessed using loops. If you want to do any processing read more..

  • Page - 547

    CHAPTER 15 ARRAYS 548 Array elements are always initialized irrespective of the scope in which the array is created. Array elements of primitive data type are initialized to the default value for their data types. For example, the numeric array elements are initialized to zero, boolean elements to false, and the reference type elements to null. The following snippet of read more..

  • Page - 548

    CHAPTER 15 ARRAYS 549 String[] name = new String[3]; // A local array variable for (int i = 0; i < name.length; i++) { System.out.println("name[" + i + "]:" + name[i]); } } } int array read more..

  • Page - 549

    CHAPTER 15 ARRAYS 550 It is a common mistake to refer to the elements of an array of reference type just after creating the array and before assigning a valid object reference to each element. The following code illustrates this common mistake: // Create an array of String String[] name = new String[5]; // A runtime error as name[0] is null int len = read more..

  • Page - 550

    CHAPTER 15 ARRAYS 551 All elements of an array are stored contiguously in memory. In case of a reference type array, the array elements store the references of the objects. Those references in the elements are stored contiguously, not the objects they are referring to. The objects are stored on heap and their locations are, typically, not contiguous. Explicit Array read more..

  • Page - 551

    CHAPTER 15 ARRAYS 552 Limitations of Using Arrays An array in Java cannot be expanded or shrunk after it is created. Suppose you have an array of 100 elements, and later, you need to keep only 15 elements. You cannot get rid of the remaining 85 elements. If you need 135 elements, you cannot append 35 more elements to it. You can deal with the first limitation read more..

  • Page - 552

    CHAPTER 15 ARRAYS 553 Here, sourceArray is the reference to the source array. sourceStartPosition is the starting index in the source array from where the copying of elements will start. destinationArray is the reference to the destination array. destinationStartPosition is the start index in the destination array from where new elements from source array will be copied. read more..

  • Page - 553

    CHAPTER 15 ARRAYS 554 System.out.println("Using System.arraycopy() method..."); System.out.println("Original Array: " + Arrays.toString(data)); System.out.println("Expanded Array: " + Arrays.toString(eData)); System.out.println("Truncated Array: " + read more..

  • Page - 554

    CHAPTER 15 ARRAYS 555 ArrayList and Vector classes work the same way, except that the methods in the Vector class are synchronized, whereas methods in ArrayList are not. If your object list is accessed and modified by multiple threads simultaneously, use the Vector class, which will be slower but thread safe. Otherwise, you should use the ArrayList class. For read more..

  • Page - 555

    CHAPTER 15 ARRAYS 556 You can make one important observation from the above output. You can print the list of all elements in an ArrayList just by passing its reference to the System.out.println() method. The toString() method of the ArrayList class returns a string that is a comma-separated string representation of its elements enclosed in brackets ( []). read more..

  • Page - 556

    CHAPTER 15 ARRAYS 557 Listing 15-3. Iterating Through Elements of an ArrayList // NameIterator.java package com.jdojo.array; import java.util.ArrayList; public class NameIterator { public static void main(String[] args) { // Create an ArrayList of String ArrayList<String> nameList = new read more..

  • Page - 557

    CHAPTER 15 ARRAYS 558 Passing an Array as a Parameter You can pass an array as a parameter to a method or a constructor. The type of array you pass to the method must be assignment compatible to the formal parameter type. The syntax for an array type parameter declaration for a method is the same as for the other data types. That is, parameter declaration read more..

  • Page - 558

    CHAPTER 15 ARRAYS 559 The above method may be called as follows: int[] ids = {10, 15, 19}; String str = arrayToString(ids); // Pass ids int array to arrayToString() method Because an array is an object, the array reference is passed to the method. The method, which receives an array parameter, can modify the elements of the array. Listing 15-4 illustrates how a read more..

  • Page - 559

    CHAPTER 15 ARRAYS 560 Recall, in Chapter 6, that we were not able to implement a method for swapping two integers using method’s parameters of primitive types. It was so, because, for primitive types, the actual parameters are copied to the formal parameter. Here, we were able to swap two integers inside the swap() method, because we used an array as read more..

  • Page - 560

    CHAPTER 15 ARRAYS 561 X clonedId Memory state after the following statements are executed. int[ ] ids = {1,2,3}; int[ ] clonedIds; 12 3 X ids Figure 15-2. The ids array is populated and the clonedIds array is declared Memory state after the following statements are executed. String names = {"Lisa", "Pat", "Kathy"}; String[ ] clonedNames; X clonedNames names X read more..

  • Page - 561

    CHAPTER 15 ARRAYS 562 Notice that when the names array is cloned, the clonedNames array elements refer to the same String objects in memory. When you mention a method of modifying an array parameter passed to it, you may mean one or all of the following three things: Array parameter reference Elements of the array parameter The object referred by the array read more..

  • Page - 562

    CHAPTER 15 ARRAYS 563 // Create and store a new int array in num num = new int[]{10, 20}; System.out.println("Inside method–2:" + Arrays.toString(num)); } } Before method call:[101, 307, 78] Inside method-1:[101, 307, 78] Inside method–2:[10, 20] After read more..

  • Page - 563

    CHAPTER 15 ARRAYS 564 public static void tryElementChange(int[] num) { // If array has at least one element, store 1116 in // its first element if (num != null && num.length > 0) { num[0] = read more..

  • Page - 564

    CHAPTER 15 ARRAYS 565 public void setPrice(double newPrice ) { this.price = newPrice; } public String toString() { return "[" + this.name + ", " + this.price + "]"; } } Listing 15-8 illustrates this. The main() read more..

  • Page - 565

    CHAPTER 15 ARRAYS 566 If you store the state of an object in an array instance variable, you should think carefully before returning the reference of that array from any methods of your class. The caller of that method will get the handle of the array instance variable and will be able to change the state of the objects of that class outside the class. This read more..

  • Page - 566

    CHAPTER 15 ARRAYS 567 as a separator. It creates an array of String whose length is the same as the number of arguments in the list. It populates the String array with the items in the arguments list sequentially. Finally, the JVM passes this String array to the main()method of the Test class that you are running. This is the time when you use the read more..

  • Page - 567

    CHAPTER 15 ARRAYS 568 To sort employee.txt file in ascending order: java com.jdojo.array.SortFile employee.txt asc To sort department.txt file in descending order: java com.jdojo.array.SortFile department.txt desc To sort salary.txt in ascending order: java com.jdojo.array.SortFile salary.txt Depending on the second element, if any, of the String array passed to the read more..

  • Page - 568

    CHAPTER 15 ARRAYS 569 String operation = args[1]; double result = compute(n1, n2, operation); // Print the result System.out.println(args[0] + args[1] + args[2] + "=" + result); } public static double read more..

  • Page - 569

    CHAPTER 15 ARRAYS 570 You may get an error when you try to use * (asterisk) to multiply two numbers. The operating system may interpret it as all files names in the current directory. To avoid such errors, you can enclose the operator in double quotes or the escape character provided by the operating system. java com.jdojo.array.Calc 7 "*" 8 Tip If read more..

  • Page - 570

    CHAPTER 15 ARRAYS 571 The indexes of each dimension in a multi-dimensional array are zero-based. Each element of the table array can be accessed as table[rownumber][columnNumber]. The row number and the column number always starts at zero. For example, you can assign a value to the first row and the second column in the table array as shown: table[0][1] = 32; You read more..

  • Page - 571

    CHAPTER 15 ARRAYS 572 You must specify the dimension of at least the first level array at the time you create a multi-dimensional array. For example, when you create a two-dimensional array, you must specify at least the first dimension, which is the number of rows. You can achieve the same results as the above code fragment as follows: table = new int[3][]; read more..

  • Page - 572

    CHAPTER 15 ARRAYS 573 // Print all elements. One row at one line System.out.println(raggedArr[0][0] + "\t" + raggedArr[0][1]); System.out.println(raggedArr[1][0]); System.out.println(raggedArr[2][0] + "\t" + raggedArr[2][1] + "\t" + read more..

  • Page - 573

    CHAPTER 15 ARRAYS 574 // Add a new line after each row is printed System.out.println(); } } } 0 1 1 2 3 4 Initializing Multi-Dimensional Arrays You may initialize the elements of a read more..

  • Page - 574

    CHAPTER 15 ARRAYS 575 The for-each loop uses the same for keyword used by the basic for loop. Its body is executed as many times as the number of elements in the array. DataType e is a variable declaration, where e is the variable name and DataType is its data type. The data type of the variable e should be assignment-compatible with the type of the read more..

  • Page - 575

    CHAPTER 15 ARRAYS 576 Java also allows you to mix two syntaxes. In the same array declaration, you can place some brackets after the data type and some after the variable name. For example, you can declare a two-dimensional array of int as follows: int[] points2D[]; You can declare a two-dimensional and a three-dimensional array of int in one declaration read more..

  • Page - 576

    CHAPTER 15 ARRAYS 577 Assigning 12 to the first element Assigning 79 to the fourth element Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at com.jdojo.array.ArrayBounds.main(ArrayBounds.java:14) It is good practice to check for array length before accessing its elements. The fact that array bounds violation throws an exception may be misused as read more..

  • Page - 577

    CHAPTER 15 ARRAYS 578 String[] sArr = {"A", "B"} ; String[][] ssArr = {{"AA"}, {"BB"}} ; String[][][] sssArr = {} ; // A 3D empty array of string // Print the class name for all arrays read more..

  • Page - 578

    CHAPTER 15 ARRAYS 579 The class names of arrays are not available at compile time for declaring or creating them. You must use the syntax described in this chapter to create an array. That is, you cannot write the following to create an int array: [I myIntArray; Rather, you must write the following to create an int array: int[] myIntArray; Array Assignment read more..

  • Page - 579

    CHAPTER 15 ARRAYS 580 You need to perform a cast at the time you read back the object from the array, as shown: /* Compiler will flag an error for the following statement. genericArray is of Object type and an Object reference cannot be assigned to a String reference variable. Even though genericArray[0] contains a String object reference, we need to cast it to read more..

  • Page - 580

    CHAPTER 15 ARRAYS 581 Converting an ArrayList/Vector to an Array An ArrayList can be used when the number of elements in the list is not precisely known. Once the number of elements in the list is fixed, you may want to convert an ArrayList to an array. You may do this for one of the following reasons: The program semantics may require you to use an array, read more..

  • Page - 581

    CHAPTER 15 ARRAYS 582 // s1 has enough space to copy all ArrayList elements. // al.toArray(s1) returns s1 itself System.out.println("s1 == s2:" + (s1 == s2)); System.out.println("s1:" + Arrays.toString(s1)); read more..

  • Page - 582

    583 CHAPTER 16 Inheritance In this chapter, you will learn What inheritance is How to inherit a class from another class The difference between early binding and late binding What method overriding is and how to override methods What field hiding and method hiding are and how to use them in your code What abstract classes are and where to use them How to declare read more..

  • Page - 583

    CHAPTER 16 INHERITANCE 584 between humans for inheritance to occur. Similarly, there exists a relationship between objects of the superclass and the subclass. The relationship that must exist between the superclass and the subclass in order for inheritance to be effective is called an “is-a” re lationship. You need to ask yourself a simple question before you should inherit read more..

  • Page - 584

    CHAPTER 16 INHERITANCE 585 Let’s look at the simplest example of inheritance in Java. Let’s start with an Employee class as listed in Listing 16-1. Listing 16-1. An Employee Class // Employee.java package com.jdojo.inheritance; public class Employee { private String name = "Unknown"; public void setName(String name) { read more..

  • Page - 585

    CHAPTER 16 INHERITANCE 586 Listing 16-3. Testing the Manager Class // SimplestInheritanceTest.java package com.jdojo.inheritance; public class SimplestInheritanceTest { public static void main(String[] args) { // Create an object of the Manager class Manager mgr = new Manager(); read more..

  • Page - 586

    CHAPTER 16 INHERITANCE 587 // #2 – "extends Object" is explicitly added for class P public class P extends Object { // Code for class P goes here } In the previous chapters, you did not use the extends clause to declare your classes. They were implicitly inherited from the Object class. This is the reason that objects of those classes read more..

  • Page - 587

    CHAPTER 16 INHERITANCE 588 Sometimes, the term “immediate superclass” is used to mean the ancestor class, which is one level up in the inheritance hierarchy whereas the term “superclass” is used to mean an ancestor class at any level. This book uses the term “superclass” to mean ancestor of a class, which is one level up in the inheritance hierarchy. For example, Programmer read more..

  • Page - 588

    CHAPTER 16 INHERITANCE 589 If a class member is declared protected, it is accessible in the package in which it is declared. A protected class member is always accessible inside the body of a subclass whether the subclass is in the same package as the class or in a different package. A protected class member is inherited by a subclass. The protected access read more..

  • Page - 589

    CHAPTER 16 INHERITANCE 590 With the point in mind that a subclass guarantees at least the same behavior (methods) as its superclass, let’s consider the following snippet of code: Employee emp; emp = new Manager(); // A Manager object assigned to an Employee variable emp.setName("Richard Castillo"); String name = emp.getName(); The compiler will compile the above read more..

  • Page - 590

    CHAPTER 16 INHERITANCE 591 Listing 16-4. A Utility Class That Uses Employee Type Parameter in Its printName() Method // EmpUtil.java package com.jdojo.inheritance; public class EmpUtil { public static void printName(Employee emp){ // Get the name of employee String name = emp.getName(); read more..

  • Page - 591

    CHAPTER 16 INHERITANCE 592 Assigning a superclass reference to a subclass variable is called downcasting (or narrowing conversion). Downcasting is the opposite of upcasting. In upcasting, the assignment moves up the class hierarchy whereas in downcasting the assignment moves down the class hierarchy. The Java compiler cannot make sure at compile time that downcasting is legal read more..

  • Page - 592

    CHAPTER 16 INHERITANCE 593 Tip The Object class is at the top of every class hierarchy in Java. This allows you to assign a reference of any class type to a variable of the Object type. The following type of assignment is always allowed: Object obj = new AnyJavaClass(); // Upcasting Whether downcasting from an Object type to another class type will read more..

  • Page - 593

    CHAPTER 16 INHERITANCE 594 mango with an employee? You would say no. The compiler adds checks for this kind of illogical comparison using the instanceof operator. It makes sure that it is possible for the left-hand operand of the instanceof operator to hold a reference of an object of the right-hand operand type. If it is not possible, the compiler generates an read more..

  • Page - 594

    CHAPTER 16 INHERITANCE 595 object is passed to the equals() method of the Employee class? Since a manager is also an employee, it should compare the two for equality. The following snippet of code shows you a possible implementation of the equals() method for the Employee class: // Employee.java package com.jdojo.inheritance; public class Employee { read more..

  • Page - 595

    CHAPTER 16 INHERITANCE 596 Binding Classes have methods and fields; we write code to access them as follows. Assume that myMethod() and xyz are members of the MyClass class, which is the declared type of the myObject reference variable. MyClass myobject = get an object reference; myObject.myMethod(); // Which myMethod() to call? int a = myObject.xyz; // Which read more..

  • Page - 596

    CHAPTER 16 INHERITANCE 597 Listing 16-7. An EarlyBindingSub Class, Which Inherits from EarlyBindingSuper Class and Has a Static Field, an Instance Field, and a Static Method, Which Are of the Same Type as in Its Superclass // EarlyBindingSub.java package com.jdojo.inheritance; public class EarlyBindingSub extends EarlyBindingSuper{ // An instance variable read more..

  • Page - 597

    CHAPTER 16 INHERITANCE 598 // Will access EarlyBindingSub.print() ebSub.print(); System.out.println("------------------------------"); // Will access EarlyBindingSuper.str read more..

  • Page - 598

    CHAPTER 16 INHERITANCE 599 The main() method creates an object of each type EarlyBindingSuper and EarlyBindingSub. EarlyBindingSuper ebSuper = new EarlyBindingSuper(); EarlyBindingSub ebSub = new EarlyBindingSub(); According to early binding rules, the statements ebSuper.str, ebSuper.count, and ebSuper.print() will always access the str and count fields, and the print() method of read more..

  • Page - 599

    CHAPTER 16 INHERITANCE 600 The compiler performs only one check for the emp.setName() method call in the above code. It makes sure that the declared type of the emp variable, which is Employee, has a method called setName(String s). The compiler detects that the setName(String s) method in the Employee class is an instance method, which is not final. For an read more..

  • Page - 600

    CHAPTER 16 INHERITANCE 601 // Will access LateBindingSuper.print() lbSuper.print(); // #1 // Will access LateBindingSub.print() lbSub.print(); // #2 // Will access LateBindingSub.print() read more..

  • Page - 601

    CHAPTER 16 INHERITANCE 602 When statement #3 is ready to execute, at that time the expression with the typecast still refers to an object of LateBindingSub type, and therefore, the print() method of the LateBindingSub class will be called. This is confirmed by the third line in the output. Let’s consider two lines of code to discuss statement #4: lbSuper = read more..

  • Page - 602

    CHAPTER 16 INHERITANCE 603 redefine it my way, without affecting your print() method in any way. You can keep using your print() method.” If a class overrides a method, it affects the overriding class and its subclasses. Consider the following declaration of class C: public class C extends B { // Inherits B.print() } Class C does not read more..

  • Page - 603

    CHAPTER 16 INHERITANCE 604 Let’s consider the following definitions of two classes S and T: public class S { public void print() { System.out.println("S"); } } public class T extends S { public void print(String msg) { System.out.println(msg); read more..

  • Page - 604

    CHAPTER 16 INHERITANCE 605 public class Q extends P { public Employee getEmp() { // code goes here } } public class R extends P { public Manager getEmp() { // code goes here } } Class P defines a getEmp() method that read more..

  • Page - 605

    CHAPTER 16 INHERITANCE 606 If a class overrides m1() method of class G, it must not add any new checked exception to it. The following code will not compile, because it has added a new checked exception CheckException3 in the overridden method m1(): public class H extends G { public void m1() throws CheckedException1, CheckedException2, CheckedException3 read more..

  • Page - 606

    CHAPTER 16 INHERITANCE 607 You can write the following snippet of code: P p = // get an object reference of P or its descendant; try { Employee emp = p.getEmp(10); } catch (EmpNotFoundException e) { // Handle the exception here } There are two points that need to be considered in the above snippet of code. First, the variable read more..

  • Page - 607

    CHAPTER 16 INHERITANCE 608 Suppose the code, which was written in terms of P type, gets a reference of a Q2 object as follows: P p = new Q2(); try { Employee emp = p.getEmp(10); } catch(EmpNotFoundException e) { // Handle exception here } Note that the try-catch block is not prepared to handle the BadEmpIdException, which the read more..

  • Page - 608

    CHAPTER 16 INHERITANCE 609 Listing 16-12. An AOSuper Class // AOSuper.java package com.jdojo.inheritance; public class AOSuper { public void print() { System.out.println("Inside AOSuper.print()"); } } The code in Listing 16-13 contains the declaration for an AOSub class, which inherits from the AOSuper read more..

  • Page - 609

    CHAPTER 16 INHERITANCE 610 Inside AOSuper.print() Inside AOSub.print() Inside AOSuper.print() There is no way to directly call a method of the superclass of the superclass. You can call the overridden method of the superclass (only the immediate ancestor) using the keyword super. Suppose there are three classes: A, B, and C, where class B inherits from class A, and class C read more..

  • Page - 610

    CHAPTER 16 INHERITANCE 611 The following is an example of an incorrect attempt to overload the m2() method in class OME2: // Won't compile public class OME2 { public void m2(int p1) { // Code goes here } public void m2(int p2) { // Code read more..

  • Page - 611

    CHAPTER 16 INHERITANCE 612 You should realize that the results for the m2() method in class OME2 are the same for both versions and hence OME2.m2() is not overloaded. Table 16-2 lists some important differences between method overriding and method overloading. Table 16-2. Some Important Differences Between Method Overriding and Method Overloading Method Overriding Method read more..

  • Page - 612

    CHAPTER 16 INHERITANCE 613 public void test(Employee e) { System.out.println("Inside test(Employee e)"); } public void test(Manager e) { System.out.println("Inside test(Manager m)"); } public static void main(String[] read more..

  • Page - 613

    CHAPTER 16 INHERITANCE 614 Still, the second parameter type does not match; the actual type is short and the formal type is double. Java allows automatic widening from short to double. The compiler converts the short type to the double type and binds add(f1, s2) call to add(double, double) method. When ot.test(mgr) is called, the compiler looks for an exact read more..

  • Page - 614

    CHAPTER 16 INHERITANCE 615 Inheritance and Constructors An object has two things: state and behavior. Instance variables in a class represent the state of its objects. Instance methods represent the behavior of its objects. Each object of a class maintains its own state. When you create an object of a class, memory is allocated for all instance variables declared in the read more..

  • Page - 615

    CHAPTER 16 INHERITANCE 616 Listing 16-18. A CSuper Class with a no-args Constructor // CSuper.java package com.jdojo.inheritance; public class CSuper { public CSuper() { System.out.println("Inside CSuper() constructor."); } } Listing 16-19. A CSub Class, Which Inherits from the CSuper Class and Has a no-args read more..

  • Page - 616

    CHAPTER 16 INHERITANCE 617 followed by parentheses, it refers to the constructor of the superclass. If superclass constructor accepts parameters, you can pass a list of parameters within parentheses similar to a method call. The following are examples of calling constructor of a superclass: // Call no-args constructor of superclass super(); // Call superclass constructor with read more..

  • Page - 617

    CHAPTER 16 INHERITANCE 618 Listing 16-23. Employee2 Class, Which Is a Modified Version of the Original Employee Class. It Has Added a Constructor That Accepts a String Argument // Employee2.java package com.jdojo.inheritance; public class Employee2 { private String name = "Unknown"; public Employee2(String name) { read more..

  • Page - 618

    CHAPTER 16 INHERITANCE 619 So, how do you fix the Manager2 class? There are many ways to fix it. Some of the ways you can fix the Manager2 class are as follows. You can add a no-args constructor to the Employee2 class, like so: public class Employee2 { // A no-args constructor public Employee2() { } read more..

  • Page - 619

    CHAPTER 16 INHERITANCE 620 Listing 16-25. A Test Class to Test the Manager2 Class // Manager2Test.java package com.jdojo.inheritance; public class Manager2Test { public static void main(String[] args) { Manager2 mgr = new Manager2("John Jacobs"); String name = mgr.getName(); read more..

  • Page - 620

    CHAPTER 16 INHERITANCE 621 The error states that the no-args constructor in class X has a package-level access. Therefore, it cannot be accessed from class Y, which is in a different package. You received this error because the compiler will modify class Y definition as follows: // Compiler modified version of class Y // Y.java package com.jdojo.inheritance.pkg2; read more..

  • Page - 621

    CHAPTER 16 INHERITANCE 622 Method Hiding A class also inherits all non-private static methods from its superclass. Redefining an inherited static method in a class is known as method hiding. The redefined static method in a subclass is said to hide the static method of its superclass. Recall that redefining a non-static method in a class is called method overriding. read more..

  • Page - 622

    CHAPTER 16 INHERITANCE 623 System.out.println("#1"); // #1 MHidingSuper.print(); mhSuper.print(); System.out.println("#2"); // #2 read more..

  • Page - 623

    CHAPTER 16 INHERITANCE 624 The first two calls in section #2 are similar to the two calls in section #1. They are bound to the print() method of the MHidingSub class. The third call, ((MHidingSuper)mhSub).print(), needs a little explanation. The compile-time type of the mhSub variable is MHidingSub. When you use a typecast ( MHidingSuper) on the mhSub variable, the read more..

  • Page - 624

    CHAPTER 16 INHERITANCE 625 the field z in class H hides the field z in class G. The simple names of fields x, y, and z in class H refer to the hiding fields, not inherited fields. Therefore, if you use the simple name x in class H, it refers to the field x declared in class H, not in class G. If you want to refer to the field x in read more..

  • Page - 625

    CHAPTER 16 INHERITANCE 626 Listing 16-32. A FHidingSub2 Class That Inherits from FHidingSuper and Declares Two Variables with the Same Name as Declared in Its Superclass // FHidingSub2.java package com.jdojo.inheritance; public class FHidingSub2 extends FHidingSuper { // Hides num field in FHidingSuper class private int num = 200; read more..

  • Page - 626

    CHAPTER 16 INHERITANCE 627 Listing 16-34. A FHidingSub3 Class That Demonstrates How to Access Hidden Fields of Superclass Using the super Keyword // FHidingSub3.java package com.jdojo.inheritance; public class FHidingSub3 extends FHidingSuper { // Hides the num field in FHidingSuper class private int num = 200; // read more..

  • Page - 627

    CHAPTER 16 INHERITANCE 628 Let’s summarize the field hiding rules: Field hiding occurs when a class declares a variable with the same name as an inherited variable from its superclass. Field hiding occurs only based on the name of the field. Access level, data type, and the type of field ( static or non-static) are not considered for field hiding. For example, a static read more..

  • Page - 628

    CHAPTER 16 INHERITANCE 629 public class A { public final void m1() { // Code goes here } public void m2() { // Code goes here } } public class B extends A { // Cannot override A.m1() here because it is read more..

  • Page - 629

    CHAPTER 16 INHERITANCE 630 If you look at the definition of the Shape class, it looks the same as any other concrete classes, except the use of the abstract keyword in the declaration. A class has instance variables and instance methods to define the state and behavior of its objects. By declaring a class abstract, you indicate that the class has some incomplete read more..

  • Page - 630

    CHAPTER 16 INHERITANCE 631 public Shape(String name) { this.name = name; } public String getName() { return this.name; } public void setName(String name) { this.name = name; read more..

  • Page - 631

    CHAPTER 16 INHERITANCE 632 // Provide an implementation for inherited abstract getArea() method public double getArea() { return width * height; } // Provide an implementation for inherited abstract getPerimeter() method public double getPerimeter() { read more..

  • Page - 632

    CHAPTER 16 INHERITANCE 633 It is time to use your abstract Shape class along with its concrete subclasses Rectangle and Circle. Note that the only restriction that is applied to an abstract class, when it is used in code, is that you cannot create its objects. Apart from this restriction, you can use it the same way you can use a concrete class. For read more..

  • Page - 633

    CHAPTER 16 INHERITANCE 634 // Print details System.out.println("Name: " + name); System.out.println("Area: " + area); System.out.println("Perimeter: " + perimeter); read more..

  • Page - 634

    CHAPTER 16 INHERITANCE 635 Drawing a rectangle... Drawing a circle... Name: Rectangle Area: 8.0 Perimeter: 12.0 Name: Circle Area: 78.53981633974483 Perimeter: 31.41592653589793 You have finished discussing the main rules of declaring classes and methods abstract. However, there are many other rules that govern the use of abstract classes and methods in a Java program. Most of those read more..

  • Page - 635

    CHAPTER 16 INHERITANCE 636 An abstract method in a class can override an abstract method in its superclass without providing an implementation. The subclass abstract method may refine the return type or exception list of the overridden abstract method. Let’s consider the following code. Class B overrides the abstract m1() method of class A and it does not provide read more..

  • Page - 636

    CHAPTER 16 INHERITANCE 637 Listing 16-41. A Sample Class That Uses Generic Type Parameters // GenericSuper.java package com.jdojo.inheritance; public class GenericSuper<T> { public void m1(T a) { // Code goes here } public <P extends Employee> void m2(P a) { read more..

  • Page - 637

    CHAPTER 16 INHERITANCE 638 In the GenericSub class, the m1() and m2() methods override the corresponding methods in the GenericSuper class. If you compare the methods m1() and m2() between Listing 16-41 and Listing 16-43 for overriding rules, you would think that they do not have the same signature because the code in Listing 16-41 uses generics. The rules for read more..

  • Page - 638

    CHAPTER 16 INHERITANCE 639 code is bound at runtime because m1() is an instance method. The compiler does not decide which m1() method’s code will be executed for c.m1(10). Keep in mind that the compiler’s decision is solely based on its knowledge about class C1. When c.m1(10) is compiled, the compiler does not know (or care) about the existence of any read more..

  • Page - 639

    CHAPTER 16 INHERITANCE 640 Sometimes an object of a class contains an object of another class, which indicates a whole-part relationship. This relationship is called aggregation. It is also known as has-a relationship. The example of has-a relationship is “A person has an address.” As a whole-part relationship, the person represents the whole and the address represents read more..

  • Page - 640

    CHAPTER 16 INHERITANCE 641 public class Computer { private CPU cpu = new CPU(); // CPU is an inner class of Computer private class CPU { // Code goes here } // Other code goes here for Computer class } read more..

  • Page - 641

    CHAPTER 16 INHERITANCE 642 abstract methods in Java defines a specification whereas declaring a concrete (non-abstract) method defines an implementation. For example, the Shape class has specification for a draw() method, which is inherited by its subclasses (e.g. Rectangle and Circle). It does not provide any implementation for the draw() method. All concrete subclasses of read more..

  • Page - 642

    643 CHAPTER 17 Interfaces In this chapter, you will learn What interfaces are How to declare interfaces How to declare abstract, default, and static methods in interfaces How to fully and partially implement interfaces in a class How to evolve interfaces after they are published How to inherit an interface from other interfaces Using the instanceof operator with interfaces What read more..

  • Page - 643

    CHAPTER 17 INTERFACES 644 An object of the Person class will have a name that will be set in its constructor. When it receives a “walk” message, that is, when its walk() method is called, it prints a message in the standard output. Let’s create a utility class named Walkables, which is used to send a specific message to a collection of objects. Let’s read more..

  • Page - 644

    CHAPTER 17 INTERFACES 645 You may notice that there is a similarity between the Person and Duck classes. An object of both classes can respond to a “walk” message as both of them pr ovide a walk() method. However, the similarity between the two classes ends right there. They are not linked in any other ways at all, except for the fact that both of them have read more..

  • Page - 645

    CHAPTER 17 INTERFACES 646 if (walkMethod != null) { try { // Invoke the walk() method read more..

  • Page - 646

    CHAPTER 17 INTERFACES 647 Let’s reject this solution for the very simple reason that you used reflection to invoke the walk() method on all objects passed in and you relied on the fact that all objects that know how to walk will have a method named “walk.” This solution is easily and silently broken if you change the method name, say in the Person read more..

  • Page - 647

    CHAPTER 17 INTERFACES 648 Suppose you go forward with this solution. You add a new class called Fish, which inherits the Animal class. An object of the Fish class does not know how to walk. Because the Fish class is inherited from the Animal class, it will also inherit the walk() method, which is the ability to walk. Definitely, you will need to override read more..

  • Page - 648

    CHAPTER 17 INTERFACES 649 public Person(String name) { this.name = name; } public void walk() { System.out.println(name + " (a person) is walking."); } } Listing 17-3. The Revised Duck Class, Which Implements the Walkable read more..

  • Page - 649

    CHAPTER 17 INTERFACES 650 What can you do with the reference variable of an interface type? You can access any members of the interface using its reference type variable. Since your Walkable interface has only one member, which is the walk() method, you can write code as shown: // Let the person walk w1.walk(); // Let the duck walk w2.walk(); When you invoke read more..

  • Page - 650

    CHAPTER 17 INTERFACES 651 Jack (a person) is walking. Jeff (a duck) is walking. John (a person) is walking. How will your existing code change if you want to create a new class called Cat whose objects should have the ability to walk? You will be surprised to see that you do not need to change anything in your existing code at all. The Cat class read more..

  • Page - 651

    CHAPTER 17 INTERFACES 652 It is time to go over details of how to create and use interfaces in a Java program. As I discuss the technical details of interfaces, I will also go over proper uses and common misuses of interfaces. Declaring an Interface An interface can be declared as a top-level interface, a nested interface, or an annotation type. I will discuss read more..

  • Page - 652

    CHAPTER 17 INTERFACES 653 abstract interface Updatable { } public abstract interface ReadOnly { } Note Interfaces in Java are implicitly abstract. Using the keyword abstract in their declarations is obsolete and it should not be used in new programs. The above examples are only for illustration purpose. Declaring Interface Members An interface can have three types of read more..

  • Page - 653

    CHAPTER 17 INTERFACES 654 You can use Choices.YES and Choices.NO to access the values of YES and NO fields in the Choices interface. Listing 17-8 demonstrates how to use the dot notation to access fields of an interface. Listing 17-8. Accessing Fields of an Interface // ChoicesTest.java package com.jdojo.interfaces; public class ChoicesTest { public static read more..

  • Page - 654

    CHAPTER 17 INTERFACES 655 Tip It is a convention to use all uppercase letters in the name of a field in an interface to indicate that they are constants. However, Java does not impose any restrictions on naming the fields of an interface as long as they follow the naming rules for identifiers. Fields of an interface are always public. However, the read more..

  • Page - 655

    CHAPTER 17 INTERFACES 656 The body of the abstract method is always represented by a semicolon, not by a pair of braces. The following snippet of code declares an interface named Player: public interface Player { public abstract void play(); public abstract void stop(); public abstract void forward(); read more..

  • Page - 656

    CHAPTER 17 INTERFACES 657 utility classes along with interfaces. From Java 8, you can have static methods in interfaces. A static method contains the static modifier. They are implicitly public. You can redefine the Walkable interface as shown in Listing 17-9 to include the letThemWalk() method and get rid of the Walkables class altogether. Listing 17-9. The Revised read more..

  • Page - 657

    CHAPTER 17 INTERFACES 658 The default methods are a new, exciting feature in Java 8. Prior to Java 8, interfaces could have only abstract methods. Why were default methods added in Java 8? The short answer is that they were added so the existing interfaces may evolve. At this point, the answer may be hard to understand. Let’s look at an example to read more..

  • Page - 658

    CHAPTER 17 INTERFACES 659 public double getX() { return x; } public double getY() { return y; } public String toString() { return "Pen(" + x + ", read more..

  • Page - 659

    CHAPTER 17 INTERFACES 660 Java libraries have published hundreds of interfaces, which were used thousands of times by customers worldwide. Java designers were in a dire need of a way to evolve the existing interfaces without breaking the existing code. They explored several solutions. Default methods were the accepted solution to evolve interfaces. A default method can be read more..

  • Page - 660

    CHAPTER 17 INTERFACES 661 // Move the Pen using relative cocordinates p1.move(5.0, 2.0); System.out.println(p1); } } Another common use of default methods is to declare optional methods in an interface. Consider a Named interface as shown in Listing read more..

  • Page - 661

    CHAPTER 17 INTERFACES 662 Needless to say that both types of methods can use their parameters. Both methods can have a throws clause. You are not done with default methods yet. I will discuss their roles in inheritance shortly. Nested Type Declarations A nested type declaration in an interface defines a new reference type. You can declare a class, interface, enum, and read more..

  • Page - 662

    CHAPTER 17 INTERFACES 663 Suppose each department must submit a job every day, even if they do not have something to run. It suggests that sometimes you need an empty job or a job with nothing real to do. The developer of the Job interface may provide a constant, which represents a trivial implementation of the Job interface as listed in Listing 17-15. It read more..

  • Page - 663

    CHAPTER 17 INTERFACES 664 An Interface Defines a New Type An interface defines a new reference type. You can use an interface type anywhere you can use a reference type. For example, you can use an interface type to declare a variable (instance, static, or local), to declare a parameter type in a method, as a return type of a method, etc. Consider the read more..

  • Page - 664

    CHAPTER 17 INTERFACES 665 The SwimmableTest class uses the new type defined by the Swimmable interface in a number of ways. The purpose of the class is just to demonstrate the use of an interface as a new type. It uses the Swimmable interface as a type to declare An instance variable named iSwimmable. A parameter named aSwimmable for its constructor. The return read more..

  • Page - 665

    CHAPTER 17 INTERFACES 666 Let’s answer the second question. What can you do with the variable of an interface type? All rules for a reference type variable equally apply to a variable of an interface type. A few important things that you can do with a variable of a reference type are as follows: You can assign a reference of an object in memory including a read more..

  • Page - 666

    CHAPTER 17 INTERFACES 667 An interface specifies a protocol that an object guarantees to offer when it interacts with other objects. It specifies the protocol in terms of abstract and default methods. A specification is implemented at some time by someone, and so is the case with an interface. An interface is implemented by a class. When a class implements an read more..

  • Page - 667

    CHAPTER 17 INTERFACES 668 In your case, the only requirement for the Fish class is that it must have a swim() method, which accepts no parameters and returns void as declared in the Swimmable interface. The following code defines two swim() methods in the Fish class. The first one with no parameters implements the swim() method of the Swimmable read more..

  • Page - 668

    CHAPTER 17 INTERFACES 669 class, which happened by default. Since an object of the Fish class has two types, Fish and Swimmable, you can assign the reference of a Fish object to a variable of the Fish type as well as to a variable of the Swimmable type. The following code summarizes this: Fish guppi = new Fish("Guppi"); Swimmable hilda = new read more..

  • Page - 669

    CHAPTER 17 INTERFACES 670 The compiler will not complain about the above statement. It assumes that you have made sure that the hilda variable is referring to a Fish object and the cast (Fish)hilda will succeed at runtime. If, by any chance, the hilda variable is not referring to a Fish object, the Java runtime will throw a ClassCastException. For read more..

  • Page - 670

    CHAPTER 17 INTERFACES 671 The Banker interface declares two methods called withdraw() and deposit(). Let’s consider the following implementation of the Banker interface in the MinimumBalanceBank class. The overridden methods in this class have exactly the same constraints as defined in the Banker interface. Both methods are declared public and both of them throw the read more..

  • Page - 671

    CHAPTER 17 INTERFACES 672 never be a problem if the runtime throws a fewer number of exceptions or no exceptions than expected in the code, Consider the following implementation of the Banker interface by the UnstablePredictableBank class: // The following code will not compile public class UnstablePredictableBank implements Banker { public double read more..

  • Page - 672

    CHAPTER 17 INTERFACES 673 Tip Use a general rule of thumb to check if adding or dropping a constraint is allowed in a class method, which overrides an interface's method. Write code using an interface type variable that is assigned an object of the class that implements the interface. If the code makes sense to you (of course, it has to make sense to read more..

  • Page - 673

    CHAPTER 17 INTERFACES 674 There is no limit on the maximum number of interfaces implemented by a class. When a class implements an interface, its objects get an additional type. If a class implements multiple interfaces, its objects get as many new types as the number of implemented interfaces. Consider the object of the ArithOps class, which can be created by read more..

  • Page - 674

    CHAPTER 17 INTERFACES 675 Listing 17-22 shows using a Turtle object as a Turtle type, Walkable type, and Swimmable type. Listing 17-22. Using the Turtle Class // TurtleTest.java package com.jdojo.interfaces; public class TurtleTest { public static void main(String[] args) { Turtle turti = new Turtle("Turti"); read more..

  • Page - 675

    CHAPTER 17 INTERFACES 676 Partially Implementing an Interface A class agrees to provide an implementation for all abstract methods of the interfaces it implements. However, a class does not have to provide implementations for all methods. In other words, a class can provide partial implementations of the implemented interfaces. Recall that an interface is implicitly abstract read more..

  • Page - 676

    CHAPTER 17 INTERFACES 677 The implication of declaring a class as abstract is that it cannot be instantiated. The following code will generate a compile-time error: new ABCImpl(); // A compile-time error. ABCImpl is abstract The only way to use the ABCImpl class is to inherit another class from it and provide the missing implementations for the m2() and m3() read more..

  • Page - 677

    CHAPTER 17 INTERFACES 678 The above code establishes supertype-subtype relationship between three the interfaces J, K, and L, and the class C. Recall that an interface declaration defines a new type. Suppose that you have already declared three interfaces: J, K, and L. The three interface declarations define three types: type J, type K, and type L. The declaration of read more..

  • Page - 678

    CHAPTER 17 INTERFACES 679 default double getRate() { return 300.0; } } All three types of professionals (singers, writers, and players) perform their jobs and they are paid. The three interfaces contain two types of methods. One type of method signifies the job they do, for example, sing(), write(), and play(). Another type of method read more..

  • Page - 679

    CHAPTER 17 INTERFACES 680 @Override default double getRate() { return 0.0; } } The setRate() method is a no-op. The getRate() method returns zero. The class that implements the CharitySinger interface will need to implement the sing() method and provide an implementation for it. read more..

  • Page - 680

    CHAPTER 17 INTERFACES 681 @Override public double getRate() { return rate; } @Override public void write() { System.out.println(name + " is writing"); } } The following snippet of code shows read more..

  • Page - 681

    CHAPTER 17 INTERFACES 682 This time, the error is because of two reasons: The interface inherits two default getRate() methods, one from the CharitySinger interface and one from the Player interface. The interface inherits a default setRate() method from the CharitySinger interface and an abstract setRate() method from the Player interface. This type of conflict was not read more..

  • Page - 682

    CHAPTER 17 INTERFACES 683 Sometimes an interface may want to access the override default methods of its superinterfaces. Java 8 introduced a new syntax for calling the overridden default methods of direct superinterfaces from an interface. The new syntax uses the keyword super as shown: SuperInterfaceName.super.superInterfaceDefaultMethod(arg1, arg2...) Tip Using the keyword super, read more..

  • Page - 683

    CHAPTER 17 INTERFACES 684 default double getRate() { return Player.super.getRate(); } } The Superinterface-Subinterface Relationship Interface inheritance establishes a superinterface-subinterface (also called supertype-subtype) relationship. When the interface CharitySinger inherits from the Singer interface, the Singer read more..

  • Page - 684

    CHAPTER 17 INTERFACES 685 Inheriting Conflicting Implementations Before Java 8, it was not possible for a class to inherit multiple implementations (non-abstract methods) from multiple supertypes. Introduction of default methods made it possible for a class to inherit conflicting implementations from its superclass and superinterfaces. When a class inherits a method with the same signature read more..

  • Page - 685

    CHAPTER 17 INTERFACES 686 The default CharitySinger.getRate() method The abstract Employee.setRate() method The concrete Employee.getRate() method There is no conflict for the sing() method. Therefore, the Manager class inherits the sing() method from the CharitySinger interface. There are two choices for the setRate() and getRate() methods. The two methods are available in read more..

  • Page - 686

    CHAPTER 17 INTERFACES 687 Let’s consider a Sizeable interface and a Bag class that implement the interface. public interface Sizeable { int size(); } public class Bag implements Sizeable { private int size; @Override public int size() { return read more..

  • Page - 687

    CHAPTER 17 INTERFACES 688 I1.m() and I2.m(). In this case, I2.m() is considered most specific as it overrides I1.m(). I will summarize this rule as follows: Make a list of all choices of the method with the same signature that are available from different superinterfaces. Remove all methods from the list that have been overridden by others in the list. If you are read more..

  • Page - 688

    CHAPTER 17 INTERFACES 689 The above class declaration will not compile. The class inherits the sing(), play(), and setRate() methods without any conflicts. There are two choices to inherit the getRate() method: The abstract Singer.getRate() method The default Player.getRate() method None of the two versions of the getRate() method are more specific than others. In this read more..

  • Page - 689

    CHAPTER 17 INTERFACES 690 public interface Generous { void give(); } public interface Munificent extends Generous { void giveALot(); } public class Giver { } public class GenerousGiver extends Giver implements Generous { public void give() { } } public class MunificentGiver extends Giver implements Munificent read more..

  • Page - 690

    CHAPTER 17 INTERFACES 691 else { System.out.println("false"); } Looking at the compile-time type of john, which is Munificent, the compiler is assured that john will refer to either null or an object whose class implements the Munificent interface. Therefore, the compiler will not complain about "john instanceof Munificent" expression. Let’s read more..

  • Page - 691

    CHAPTER 17 INTERFACES 692 else { System.out.println("false"); } This time, the compiler will refuse to compile the above code. Let’s apply the logic and try to figure out what is wrong with the code. The compiler will generate an error about the jim instanceof Munificent expression. It is saying that it knows for sure that there is read more..

  • Page - 692

    CHAPTER 17 INTERFACES 693 marker interface? Why would any class implement a marker interface? As the name suggests, a marker interface is used to mark the class with a special meaning that can be used in a particular context. The meaning added to a class by a marker interface depends on the context. The developer of the marker interface has to document the read more..

  • Page - 693

    CHAPTER 17 INTERFACES 694 Comparing Objects When you have a group of objects, sometimes you may want to order them based on some criteria. The java.lang.Comparable and java.util.Comparator are two commonly used interfaces for the purpose of ordering objects. I will discuss both interfaces in this section. Using the Comparable Interface A class implements the Comparable read more..

  • Page - 694

    CHAPTER 17 INTERFACES 695 Listing 17-33. A ComparablePerson Class That Implements the Comparable Interface // ComparablePerson.java package com.jdojo.interfaces; public class ComparablePerson implements Comparable<ComparablePerson> { private String firstName; private String lastName; public ComparablePerson(String firstName, String lastName) { read more..

  • Page - 695

    CHAPTER 17 INTERFACES 696 Listing 17-34. A Test Class to Test the ComparablePerson Class and the Comparable Interface // ComparablePersonTest.java package com.jdojo.interfaces; import java.util.Arrays; public class ComparablePersonTest { public static void main(String[] args) { ComparablePerson[] persons = new ComparablePerson[] { read more..

  • Page - 696

    CHAPTER 17 INTERFACES 697 ordering on objects of any class. Typically, the Java API dealing with a collection of objects requires a Comparator object to specify a custom ordering. The Comparator interface is a generic interface. public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); // read more..

  • Page - 697

    CHAPTER 17 INTERFACES 698 Using a Comparator is easy. Create its object and pass it to the methods that take a collection of objects and a comparator to compare them. For example, to sort an array of ComparablePerson objects, pass the array and a FirstNameComparator to the static sort() method of the Arrays class. ComparablePerson[] persons = create and read more..

  • Page - 698

    CHAPTER 17 INTERFACES 699 These methods take a Comparator and return a null-friendly Comparator place the null values first or last. // Sort using first name, then last name, placing null values first Comparator nullFirstComparator = Comparator.nullsFirst(firstLastComparator); Arrays.sort(persons, nullFirstComparator); Listing 17-37 uses an object of this class to sort objects of the read more..

  • Page - 699

    CHAPTER 17 INTERFACES 700 Arrays.sort(persons, firstLastReverseComparator); System.out.println("\nAfter sorting on first, then last name in reversed..."); print(persons); // Sort using first name, then last name using null first read more..

  • Page - 700

    CHAPTER 17 INTERFACES 701 After sorting on first, then last name using null first... null null Jacobs, Jeff Jacobs, John Inman, Wally Polymorphism—One Object, Many Views Polymorphism refers to the ability of an object to take on many forms. I will use the term “view” instead of the term “form.” The term “view” gives better understanding of polymorphism in the context of read more..

  • Page - 701

    CHAPTER 17 INTERFACES 702 What defines a particular view of a Java object and how do you get that view of the object? A view is something that is available for an outsider (in technical terms, for clients or users of the class). The set of methods (accessible to clients) defined in a type (a class or an interface) defines a view of an object of that read more..

  • Page - 702

    CHAPTER 17 INTERFACES 703 Dynamic Binding and Interfaces Java uses dynamic binding (also known as runtime binding or late binding) when a method is invoked using a variable of an interface type. Consider the following code: Walkable john = a Walkable object reference... john.walk(); The variable john has two types: a compile-time type and a runtime type. Its compile-time read more..

  • Page - 703

    CHAPTER 17 INTERFACES 704 Summary An interface is a specification that is meant to be implemented by classes. An interface may contain members that are static constants, abstract methods, default methods, static methods, and nested types. An interface cannot have instance variables. An interface cannot be instantiated. An interface with no members is known as a market read more..

  • Page - 704

    705 CHAPTER 18 Enum Types In this chapter, you will learn What enum types are How to declare enum types and enum constants How to use enums in switch statements How to associate data and methods to enum constants How to declare nested enums How to implement interfaces to an enum type How to perform a reverse lookup for enum constants How to use EnumSet to work read more..

  • Page - 705

    CHAPTER 18 ENUM TYPES 706 switch (severity) { case Severity.LOW: days = 30; break; case read more..

  • Page - 706

    CHAPTER 18 ENUM TYPES 707 You would agree that representing the severity types using integer constants is difficult to maintain. That was the only easily implemented solution available before Java 5 to define enumerated constants. You could have solved this problem effectively before Java 5. However, the amount of code you had to write was disproportionate to the problem. read more..

  • Page - 707

    CHAPTER 18 ENUM TYPES 708 You declare a variable of an enum type the same way you declare a variable of a class type. // Declare defectSeverity variable of the Severity enum type Severity defectSeverity; You can assign null to an enum type variable, like so: Severity defectSeverity = null; What other values can you assign to an enum type variable? An enum read more..

  • Page - 708

    CHAPTER 18 ENUM TYPES 709 Listing 18-2. Listing Name and Ordinal of Enum Type Constants // ListEnumConstants.java package com.jdojo.enums; public class ListEnumConstants { public static void main(String[] args) { for(Severity s : Severity.values()) { String name = s.name(); read more..

  • Page - 709

    CHAPTER 18 ENUM TYPES 710 // Create constants when class is loaded static { LOW = new Severity("LOW", 0); MEDIUM = new Severity("MEDIUM", 1); HIGH = new Severity("HIGH", 2); read more..

  • Page - 710

    CHAPTER 18 ENUM TYPES 711 Table 18-1. List of Methods in the Enum Class That Are Available in All Enum Types Method Name Description public final String name() Returns the name of the enum constant exactly as declared in the enum type declaration. public final int ordinal() Returns the order (or position) of the enum constant as declared in the enum type declaration. public read more..

  • Page - 711

    CHAPTER 18 ENUM TYPES 712 An enum type is implicitly final. In some situations (discussed later), the compiler cannot declare it as final as it has done in the sample code for the Severity class. The compiler adds two static methods, values() and valueOf(), to every enum type. The values() method returns the array of enum constants in the same order they are read more..

  • Page - 712

    CHAPTER 18 ENUM TYPES 713 case MEDIUM: days = 15; break; case HIGH: read more..

  • Page - 713

    CHAPTER 18 ENUM TYPES 714 It defines a private constructor, which accepts an int parameter. It stores the value of its parameter in the instance variable. You can add multiple constructors to an enum type. If you do not add a constructor, a no-args constructor is added. You cannot add a public or protected constructor to an enum type. All constructors in an read more..

  • Page - 714

    CHAPTER 18 ENUM TYPES 715 name=LOW, ordinal=0, days=30 name=MEDIUM, ordinal=1, days=15 name=HIGH, ordinal=2, days=7 name=URGENT, ordinal=3, days=1 Associating a Body to an Enum Constant SmartSeverity is an example of adding data and methods to an enum type. The code in the getProjectedTurnaroundDays() method is the same for all enum constants. You can also associate a different body read more..

  • Page - 715

    CHAPTER 18 ENUM TYPES 716 The body of the ETemp enum type declares three constants: C1, C2, and C3. You have added a body to the C1 constant. The compiler will transform the code for ETemp into something like the following code: public enum ETemp { public static final ETemp C1 = new ETemp() { // Body of read more..

  • Page - 716

    CHAPTER 18 ENUM TYPES 717 public enum ETemp { C1 { // Body of constant C1 public int getValue() { return 100; } }, C2 { read more..

  • Page - 717

    CHAPTER 18 ENUM TYPES 718 // Declare instance variables private String description; private int projectedTurnaroundDays; // Declare a private constructor private SuperSmartSeverity(String description, int read more..

  • Page - 718

    CHAPTER 18 ENUM TYPES 719 The code in Listing 18-6 demonstrates the use of the new features added to the SuperSmartSeverity enum type. Listing 18-6. A Test Class to Test the SuperSmartSeverity Enum Type // SuperSmartSeverityTest.java package com.jdojo.enums; public class SuperSmartSeverityTest { public static void main(String[] args) { read more..

  • Page - 719

    CHAPTER 18 ENUM TYPES 720 -3 Suppose you have another enum called BasicColor. public enum BasicColor { RED, GREEN, BLUE; } The following snippet of code will not compile because it tries to compare the two enum constants, belonging to different enum types: int diff = BasicColor.RED.compareTo(Severity.URGENT); // A compile-time error You can use the read more..

  • Page - 720

    CHAPTER 18 ENUM TYPES 721 local enum type (e.g. inside a method’s body). You can use any of the access modifiers ( public, private, protected, or package) level for a nested enum type. Listing 18-7 shows the code that declares a nested public enum type named Gender inside a Person class. Listing 18-7. A Gender Enum Type as a Nested Enum Type Inside a Person read more..

  • Page - 721

    CHAPTER 18 ENUM TYPES 722 You can also nest an enum type inside another enum type or an interface. The following are valid enum type declarations: public enum OuterEnum { C1, C2, C3; public enum NestedEnum { C4, C5, C6; } } public interface MyInterface { read more..

  • Page - 722

    CHAPTER 18 ENUM TYPES 723 public void execute() { System.out.println("Running..."); } }, JUMP { public void execute() { read more..

  • Page - 723

    CHAPTER 18 ENUM TYPES 724 LOW LOW true The reverse lookup for enum constants is case-sensitive. If you use an invalid constant name with the valueOf() method, an IllegalArgumentException is thrown. For example, Severity.valueOf("low") will throw an IllegalArgumentException stating that no enum constant “low” ex ists in the Severity enum. Range of Enum Constants The read more..

  • Page - 724

    CHAPTER 18 ENUM TYPES 725 public static void print(EnumSet<Day> days, String msg) { System.out.print(msg); for(Day d : days) { System.out.print(d + " "); } read more..

  • Page - 725

    727 APPENDIX A Character Encodings A character is the basic unit of a writing system, for example, a letter of the English alphabet, and an ideograph of an ideographic writing system such as Chinese and Japanese ideographs. In the written form, a character is identified by its shape, also known as glyph. The identification of a character with its shape is not read more..

  • Page - 726

    APPENDIX A CHARACTER ENCODINGS 728 To define a coded character set, you need to specify three things: A set of code points A set of characters The mapping between the set of code points and the set of characters The number of bits used to represent a character determines how many distinct characters can be represented in a coded character set. Some widely used coded read more..

  • Page - 727

    APPENDIX A CHARACTER ENCODINGS 729 Table A-1. ASCII Character Set Decimal Hexadecimal Binary Character Official Name 00 0 NUL NULL 1 1 1 SOH Start of heading 2 2 10 STX Start of text 3 3 11 ETX End of text 4 4 100 EOT End of transmission 5 5 101 ENQ Enquiry 6 6 110 ACK Acknowledge 7 7 111 BEL Bell 8 8 1000 BS Backspace 9 9 1001 TAB Horizontal tab 10 0A 1010 LF Line feed (new line) 11 0B read more..

  • Page - 728

    APPENDIX A CHARACTER ENCODINGS 730 Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 32 20 100000 SP Space 33 21 100001 ! Exclamation mark 34 22 100010 " Quotation mark 35 23 100011 # Number sign 36 24 100100 $ Dollar sign 37 25 100101 % Percent sign 38 26 100110 & Ampersand 39 27 100111 ' Apostrophe 40 28 101000 ( Left parenthesis 41 29 101001 ) Right parenthesis 42 2A read more..

  • Page - 729

    APPENDIX A CHARACTER ENCODINGS 731 Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 64 40 1000000 @ Commercial at 65 41 1000001 A Latin capital letter A 66 42 1000010 B Latin capital letter B 67 43 1000011 C Latin capital letter C 68 44 1000100 D Latin capital letter D 69 45 1000101 E Latin capital letter E 70 46 1000110 F Latin capital letter F 71 47 1000111 G Latin read more..

  • Page - 730

    APPENDIX A CHARACTER ENCODINGS 732 Table A-1. (continued) Decimal Hexadecimal Binary Character Official Name 96 60 1100000 ` Grave accent 97 61 1100001 a Latin small letter A 98 62 1100010 b Latin small letter B 99 63 1100011 c Latin small letter C 100 64 1100100 d Latin small letter D 101 65 1100101 e Latin small letter E 102 66 1100110 f Latin small letter F 103 67 1100111 g Latin small read more..

  • Page - 731

    APPENDIX A CHARACTER ENCODINGS 733 8-bit Character Sets The ASCII character set worked fine for the English language. Representing the alphabets from other languages, for example, French and German, led to the development of an 8-bit character set. An 8-bit character set defines 28 (or 256) character positions whose numeric values range from 0 to 255. The bit combination read more..

  • Page - 732

    APPENDIX A CHARACTER ENCODINGS 734 O-zone: It is used for Korean Hangul syllabic scripts and for other scripts, like ?. Its range is A000-D7FF, so 14336 code positions are available in this zone. S-zone: It is reserved for use with transformation format UTF-16. The transformation format UTF-16 will be described shortly. Its range is D800-DFFF, so 2048 code positions are read more..

  • Page - 733

    APPENDIX A CHARACTER ENCODINGS 735 Table A-2. List of Legal UTF-8 Sequences Number of Octets Bit Patterns Used UCS Code 1 Octet 1: 0xxxxxxx 00000000-0000007F 2 Octet 1: 110xxxxx Octet 2: 10xxxxxx 00000080-000007FF 3 Octet 1: 1110xxxx Octet 2: 10xxxxxx Octet 3: 10xxxxxx 00000800-0000FFFF 4 Octet 1: 11110xxx Octet 2: 10xxxxxx Octet 3: 10xxxxxx Octet 4: 10xxxxxx read more..

  • Page - 734

    APPENDIX A CHARACTER ENCODINGS 736 Java supports UTF-8 format with the following two significant modifications: Java uses 16 bits to represent a NUL character in a class file whereas standard UTF-8 uses only 8 bits. This compromise has been made to make it easier for other languages to parse a Java class file where a NUL character is not allowed within a string. read more..

  • Page - 735

    APPENDIX A CHARACTER ENCODINGS 737 The following command converts all characters in the Source.java file into Unicode-encoded characters and places the output in the Destination.java file. It is assumed that the Source.java file has been written using Chinese Big5 encoding. native2ascii -encoding Big5 Source.java Destination.java The following command performs the reverse read more..

  • Page - 736

    739 APPENDIX B Documentation Comments The Java programming language lets you include comments in the source code that can be used to prepare documentation for the application. Such comments are known as documentation comments or Javadoc comments. JDK provides a javadoc command-line tool to extract the documentation comments from the source codes and generate documentation in read more..

  • Page - 737

    APPENDIX B DOCUMENTATION COMMENTS 740 * Xyz class declaration. Note that a documentation comment for a package * declaration is written differently and it is not written in the * source code. */ package com.jdojo.utility; public class Xyz { /* Code for Xyz class goes here */ } /* Example #2 */ package com.jdojo.utility; /** * This documentation read more..

  • Page - 738

    APPENDIX B DOCUMENTATION COMMENTS 741 A block tag starts with an @ character, which is followed by the tag name. The tag text follows the tag name. The following is an example of a block tag, which uses @author block tag and "Kishori Sharan" as the tag text: @author Kishori Sharan A block tag must appear in the beginning of a line in a read more..

  • Page - 739

    APPENDIX B DOCUMENTATION COMMENTS 742 List of Block and Inline Tags Not all tags can be used for the documentation comment in all contexts. Table B-1 has the list of all block tags and inline tags, and the contexts in which they can be used. Table B-1. List of Block and Inline Tags, and the Contexts in Which They Can Be Used Tag Overview Package Class, read more..

  • Page - 740

    APPENDIX B DOCUMENTATION COMMENTS 743 Table B-2. The Effects of Using One and Multiple @author Tags in Documentation Comments Documentation Comment Generated Author Entry /** * A dummy class. * * @author Kishori Sharan */ Author: Kishori Sharan /** * A dummy class. * * @author Kishori Sharan * @author Greg Langham * @author John Jacobs */ Author: Kishori Sharan, Greg Langham, John read more..

  • Page - 741

    APPENDIX B DOCUMENTATION COMMENTS 744 * @param n1 The multiplicand * @param n2 The multiplier * @return Returns the result of multiplication of <code>n1</code> and <code>n2</code> */ public static int multiply(int n1, int n2) { return n1 * n2; } The following is an example of using the @param tags to document the type parameters of read more..

  • Page - 742

    APPENDIX B DOCUMENTATION COMMENTS 745 The following is an example of how to use different forms of the @see tag. It assumes that Calc class is in the same package as the Dummy class and the Calc class contains add() and multiply() methods. package com.jdojo.utility; /** * A dummy class. * * @see "Online Java Tutorial" * @see <a read more..

  • Page - 743

    APPENDIX B DOCUMENTATION COMMENTS 746 You may include or exclude a package or a class from appearing on the Serialized Form page by using the include or exclude argument with the @serial tag. If the @serial tag is used at both package and class levels, the class level tag takes precedence. By default, a serializable class that is public or protected is read more..

  • Page - 744

    APPENDIX B DOCUMENTATION COMMENTS 747 private static final ObjectStreamField[] serialPersistentFields = {new ObjectStreamField("name", String.class), new ObjectStreamField("height", double.class) read more..

  • Page - 745

    APPENDIX B DOCUMENTATION COMMENTS 748 @version <version-text> The @version tag adds a Version section to the generated documentation. The version text should contain the current version of the program element. The @since tag is used to specify the version of the software when a program element was added whereas the @version tag is used to specify the current read more..

  • Page - 746

    APPENDIX B DOCUMENTATION COMMENTS 749 The following documentation comment demonstrates the use of {@ inheritDoc} tag. It is used inside the documentation comment for the getId() method of the SmartPerson class. It is used inside the main description as well as the text section of the @return tag. Note that the @param tag is missing from the getId() method of read more..

  • Page - 747

    APPENDIX B DOCUMENTATION COMMENTS 750 {@link <package.class#member> <label>} It inserts an inline link with the specified label as the text for the link. This tag generates a link that is similar to the link generated by one of the forms of the @see tag. The main difference between the two are that this tag is an inline tag, whereas the @see tag is read more..

  • Page - 748

    APPENDIX B DOCUMENTATION COMMENTS 751 * The value of DIVISOR is {@value}. */ public final static int DIVISOR = 1000; } The following is the generated documentation comment that shows the effects of using {@value} tag: MULTIPLIER public static final int MULTIPLIER The MULTIPLIER is 2000 DIVISOR public static final read more..

  • Page - 749

    APPENDIX B DOCUMENTATION COMMENTS 752 com/jdojo/utility/package.html file It is a regular HTML file with HTML tags. The HTML contents within the <body> and </body> tags is used as the package documentation. It does not contain a package declaration. It does not use /** and */ characters as start and end of the documentation comment. However, you can use read more..

  • Page - 750

    APPENDIX B DOCUMENTATION COMMENTS 753 An Example of Documentation Comments Listing B-1 has the source code for a Calc class. It is a trivial class. Its purpose is only to demonstrate how to write documentation comments. It uses many of the tags, which we discussed earlier. Figure B-1 shows the generated HTML page (partially shown) for the Calc class documentation. read more..

  • Page - 751

    APPENDIX B DOCUMENTATION COMMENTS 754 public static long add(long n1, long n2) { return n1 + n2; } /** * Returns the result of <code>n1 - n2</code>. * * @param n1 The first number read more..

  • Page - 752

    APPENDIX B DOCUMENTATION COMMENTS 755 Running the javadoc Tool You need to run the javadoc command-line tool to generate HTML pages for your documentation comments in the source files ( .java files). For these examples of running the javadoc tool, I assume that the following files contain documentation comments: C:\projects\src\overview.html read more..

  • Page - 753

    APPENDIX B DOCUMENTATION COMMENTS 756 The syntax to run the javadoc tool is javadoc <options> <package-names> <source-files-paths> <-subpackages pkg1:pkg2...> <@args-file-paths> The <options> is zero or more command-line options for the javadoc tool. Options are used to customize the output. For example, a –d option lets you specify the output directory read more..

  • Page - 754

    APPENDIX B DOCUMENTATION COMMENTS 757 The following command will generate documentation for only Dummy.java source file: C:\projects>javadoc -d docs src/com/jdojo/utility/Dummay.java The following command is entered on one line even though it is shown on two lines. It will generate documentation for all source code under the com.jdojo package and its subpackages. It will read more..

  • Page - 755

    APPENDIX B DOCUMENTATION COMMENTS 758 The tool generates one HTML file per class/interface/enum/annotation. The files are placed in directories that mimic the package hierarchies of classes, interfaces, enums, and annotations. The file names are the same as the program elements for which they contain the documentation. A package-summary.html file is included in every package read more..

  • Page - 756

    759 APPENDIX C Compact Profiles The Java Development Kit (JDK) consists of the Java Language, development tools such as Java compiler, debugger, etc., and the Java Runtime Environment (JRE). The JRE is a subset of JDK and it consists of libraries, the Java virtual machine, and deployment toolkits. Libraries in the JRE can be subdivided into the following four categories: Lang read more..

  • Page - 757

    APPENDIX C COMPACT PROFILES 760 Tip The full JRE (the complete Java SE platform) is not considered a profile. A profile, even the smallest one, implements the entire JVM and the entire Java language. Sub-setting for a profile happens only for the packages from the Java libraries, not other parts of the JRE. Table C-2 contains the list of packages added in read more..

  • Page - 758

    APPENDIX C COMPACT PROFILES 761 Table C-2. List of Packages in the compact1, compact2, and compact3 Profiles compact3 Additions java.lang.instrument javax.management.monitor javax.security.sasl java.lang.management javax.management. openmbean javax.sql.rowset java.security.acl javax.management.relation javax.sql.rowset.serial java.util.prefs javax.management.remote javax.sql.rowset.spi javax.annotation.processing javax.management.remote. rmi read more..

  • Page - 759

    APPENDIX C COMPACT PROFILES 762 The JDK 8 contains several enhancements to development tools to support developing applications targeting a specific compact profile. It has also added new tools such as jdeps to analyze the Java source code for dependencies on compact profiles. I will discuss those enhancements in subsequent sections. Before the Java SE Embedded 8, different read more..

  • Page - 760

    APPENDIX C COMPACT PROFILES 763 If the Java source code uses Java SE APIs outside the specified profile, the javac command generates an error. Consider the code for the SwingTest and RowSetTest classes as shown in Listing C-1 and Listing C-2, respectively. Listing C-1. A SwingTest Class That Uses a Class from the javax.swing Package // SwingTest.java package read more..

  • Page - 761

    APPENDIX C COMPACT PROFILES 764 Listing C-2. A RowSetTest Class That Uses Classes from the javax.sql Package // RowSetTest.java package com.jdojo.profiles; import java.sql.SQLException; import javax.sql.rowset.JdbcRowSet; import javax.sql.rowset.RowSetFactory; import javax.sql.rowset.RowSetProvider; public class RowSetTest { public static void main(String[] args) { read more..

  • Page - 762

    APPENDIX C COMPACT PROFILES 765 Enhancement in Java API Documentation The API documentation for Java SE 8 has some enhancements that let you browse the APIs by profiles and show the profiles in which packages and classes are included. Figure C-2 shows a screenshot of the new look of the Java API documentation page. Now you can browse the Java SE APIs for read more..

  • Page - 763

    APPENDIX C COMPACT PROFILES 766 Here, <classes> can be a pathname to a .class file, a directory, a JAR file, or a fully qualified class name. Table C-3 lists all the options for the jdeps tool. Table C-3. List of Options for the jdeps Tool Option Description -dotoutput <dir> Specifies the destination directory for DOT file output. -s –summary Prints read more..

  • Page - 764

    APPENDIX C COMPACT PROFILES 767 The following command prints the dependencies with the profile information for the SwingTest class: jdeps -profile SwingTest.class SwingTest.class -> C:\java8\jre\lib\rt.jar (Full JRE) com.jdojo.profiles (SwingTest.class) -> java.lang compact1 -> javax.swing read more..

  • Page - 765

    APPENDIX C COMPACT PROFILES 768 Creating Custom JREs Using the EJDK Oracle provides Java development kits for Java SE Embedded 8 (also called EJDK 8), enabling you to create custom JRE bundles containing packages for a specific compact profile. Note that the EJDK is not a development kit used for Java application development; rather, it is a tool to create a compact read more..

  • Page - 766

    APPENDIX C COMPACT PROFILES 769 Running the jrecreate Command The ejdk1.8.0 directory contains three subdirectories: bin lib target (e.g. named linux_i586 for EJDK on Linux/x86) On Linux, you can use the ls command to list the contents of the ejdk1.8.0 directory: [/home/ksharan]$ ls ejdk1.8.0 bin lib linux_i586 The bin directory contains the following files: read more..

  • Page - 767

    APPENDIX C COMPACT PROFILES 770 The jrecreate command takes several options. One of the options is required that specifies the destination directory in which the custom JRE files are generated. The option to specify the destination directory is -d (or --dest) and its value is the path of a directory. Table C-4 lists all the options for the jrecreate command read more..

  • Page - 768

    APPENDIX C COMPACT PROFILES 771 The following command creates the full JRE in the fulljre directory: [/home/ksharan]$ ejdk1.8.0/bin/jrecreate.sh -d fulljre Building JRE using Options { ejdk-home: /home/ksharan/ejdk1.8.0 dest: /home/ksharan/compact1jre target: linux_i586 vm: all runtime: jre debug: false keep-debug-info: false read more..

  • Page - 769

    APPENDIX C COMPACT PROFILES 772 The destination directory for the custom JRE contains several files and sub-directories. You can list them as follows: [/home/ksharan]$ ls compact1jre bin COPYRIGHT README THIRDPARTYLICENSEREADME.txt bom lib release Welcome.html The bin directory contains the java command that you will use to run your Java classes. read more..

  • Page - 770

    APPENDIX C COMPACT PROFILES 773 Caused by: java.lang.ClassNotFoundException: java.sql.SQLException at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at read more..

  • Page - 771

    A          Abstract data types (ADT), 20 Abstract methods declarations, 655 Ad hoc polymorphism, 25 Application programming interface (API), 58 applyPattern() method, 494 ArithmeticException class, 346 Arithmetic operators addition operator (+) comments, 106–107 compile-time error, 105 data type conversion, 106 expressions, 105 numeric values, 104 rules, 104 compound read more..

  • Page - 772

    Autoboxing/unboxing wrapper class add() method, 327 collections, 333 comparison operators, 331 overloaded methods, 329 B          bark()method, 250 Barycentric Dynamical Time (TDB), 415 Basic Multilingual Plane (BMP), 733 Beginning Java Language Features, 321 Bias, 89 Biased exponent, 89 Big-endian, 96 Binary number system floating-point number denormals, 87, 92 exponent, read more..

  • Page - 773

    AccessLevelTest2 class, 214 AccessLevelTest3 class, 216 Account class, 216 balance instance variable, 217 compiler error, 214 credit() method, 218, 221 debit() method, 218, 220 getBalance() method, 218 getV1() and setV1() methods, 214 isValidAmount() method, 221 modified Account class, 218 package-level access, 210, 220 private access level, 220 private keyword, 210 protected keyword, 210 public read more..

  • Page - 774

    jrecreate command bin directory, 769 destination directory, 772 -d option value, 770 HelloCompact1 class, 772 JAVA_HOME environment variable, 769 lib directory, 769 -p option value, 771 RowSetTest class, 772 size, 771 target directory, 769 running java command, 773 D          Data abstraction ADT, 20 benefits, 22 constructor operation, 20 definition, 20 Java language, 20 read more..

  • Page - 775

    definition, 708 EnumSet class, 724–725 equality operator (==), 720 equals() method, 720 MALE and FEMALE, 707 name() and ordinal() methods, 708 nested enum type, 720 public class, 707 reverse lookup, 723 severity type, 705–706 SmartSeverity enum type anonymous class, 715 constants, 714 ETemp, 716 fields, constructors, and methods, 713 getProjectedTurnaroundDays() method, 715 getValue() method, read more..

  • Page - 776

    for-each statement, 156 for-loop statement condition-expression, 152 expression-list, 153 initialization, 152 loop of execution, 150 format() method, 492, 496, 498 Format specifier, 499–500 explicit indexing, 502 ordinary indexing, 500 relative indexing, 502–503 valid flags, 504 format() static method, 496 Formatting data formatting dates DateFormat class, 485 formatting symbols, 489 read more..

  • Page - 777

    CSub class, 616 CSuper class, 616 Employee2 class, 618–619 instance variables, 615 Manager2 class, 618–619 memory allocation, 615 no-args constructor, 616–618 NoSubclassingAllowed class, 621 superclass constructor, 617, 621 Test class, 616 definition, 583 downcasting ClassCastException, 592 compile-time, 592–593 definition, 592 PartTimeManager, 592 runtime type, 592–593 verification purpose, 592 Employee read more..

  • Page - 778

    instanceof operator class diagram, 689 compile-time type, 690 Munificent interface, 691–692 StingyGiver class, 692 letDucksWalk() method, 647 letThemWalk() method, 645–647 marker interface, 692 members abstract methods declarations, 655 constant fields declarations, 653 default methods (see Default methods declarations) nested type declaration, 662 static methods declarations, 656 new reference type read more..

  • Page - 779

    initialization, 574 int, 570 ragged array, 572 row and column, 570 table, 571 zero-based, 571 MyException class, 358 N          NetBeans IDE adding class, 52 Java project creation main() method, 51–52 New Java Application dialog, 50 New Project dialog, 50 startup page, 49 TestApp Java project, 51 opening NetBeans project, 55 project properties, 54–55 NetBeans read more..

  • Page - 780

    integral data type byte, 71 char, 73 int, 68 long, 69 short, 72 Numeric formatting floating-point number formatting, 512 integral number formatting, 510 Numeric wrapper class, 320 O          Object class, 586 binary class format, 284 ClassLoader class, 284 clone() method CloneNotSupportedException, 299 container object, 302 declaration, 299 DeepClone class, read more..

  • Page - 781

    parametric, 28 universal, 25 Octal escape sequence, 74 OffsetTime and OffsetDateTime classes, 439 Operators arithmetic operators (see Arithmetic operators) assignment operator (=) compile-time errors, 101 expression, 101 left-hand operand, 100 reference variable, 102 right-hand operand, 100 binary operator, 100 bitwise operator bitwise AND (&) oper ator, 134 bitwise left shift operator (<<), 136 read more..

  • Page - 782

    increment() method, 227 swap() method, 228 pass by reference value, 230, 242, 244 pass by result, 231 pass by value, 240 actual and formal parameters, 224 advantages, 226 disadvantages, 226 increment() method, 224 result, 231 smartIncrement() method, 225 swap() method, 225 primitive data type, 233 variable components, 222 variable vs. reference variable, 223 parseDouble() method, 322 read more..

  • Page - 783

    group name, 535–536 replacement text reference, 535–536 Pattern class, 524 PatternSyntaxException class, 524 quantifiers, 529 replaceAll() method, 521 replaceFirst() method, 522 reset() method, 538 Regular expression engine, 520 Relational operators equality operator (==) floating-point types, 123 isNaN() method, 124 NaN, 123 positive and negative infinity, 123 rules, 122 strings, 124 variables, read more..

  • Page - 784

    string literals, 390 escape sequence characters, 388 multiple string literals, 387 string concatenation operator (+), 388 unicode escapes, 388 string operation, 397 charAt() method, 395 endsWith() method, 399 equalsIgnoreCase() method, 396 indexOf() and lastIndexOf() methods, 398 isEmpty() method, 397 replace() method, 399 startsWith() method, 399 substring() method, 398 trim() method, 398 valueOf() read more..

  • Page - 785

    INDEX 789 collections, 333 comparison operators, 331 overloaded methods, 329 boolean wrapper class, 323 character wrapper class, 322 Integer Object, 319 java.lang package, 317 null values, 328 numeric wrapper class, 320 primitive types, 317 unsigned numeric operations, 324 valueOf() method, 318 Write once, run anywhere (WORA), 11 Z          ZonedDateTime class, 412 read more..

  • Page - 786

    Beginning Java 8 Fundamentals Language Syntax, Arrays, Data Types, Objects, and Regular Expressions Kishori Sharan www.it-ebooks.info read more..

  • Page - 787

    Beginning Java 8 Fundamentals: Language Syntax, Arrays, Data Types, Objects, and Regular Expressions Copyright © 2014 b y Kishori Sharan This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction read more..

  • Page - 788

    To My parents, Ram Vinod Singh and Pratibha Devi www.it-ebooks.info read more..

  • Page - 789

    vii Contents Foreword .......................................................................................................................... xxv About the Author ............................................................................................................ xxvii About the Technical Reviewer ......................................................................................... xxix Acknowledgments read more..

  • Page - 790

    CONTENTS viii Chapter 2: Writing Java Programs ..................................................................................31 What is a Java Program? ............................................................................................................31 System Requirements .................................................................................................................31 Writing the Source Code read more..

  • Page - 791

    CONTENTS ix Binary Representation of Floating-Point Numbers ......................................................................86 32-bit Single-Precision Floating-Point Format .................................................................................................... 88 Special Floating-Point Numbers ..................................................................................................90 Signed Zeros read more..

  • Page - 792

    CONTENTS x Modulus Operator (%) ........................................................................................................................................ 110 Unary Plus Operator (+) .................................................................................................................................... 112 Unary Minus Operator (-) read more..

  • Page - 793

    CONTENTS xi A Block Statement .....................................................................................................................140 The if-else Statement ................................................................................................................142 The switch Statement ...............................................................................................................146 The for Statement read more..

  • Page - 794

    CONTENTS xii Static Import Declarations .........................................................................................................188 Declaring Methods of a Class ....................................................................................................192 Local Variables ..........................................................................................................................196 Instance Method and Class Method read more..

  • Page - 795

    CONTENTS xiii Instance Initialization Block ......................................................................................................260 static Initialization Block ...........................................................................................................261 The final Keyword......................................................................................................................263 final Local Variables read more..

  • Page - 796

    CONTENTS xiv Chapter 8: Wrapper Classes ..........................................................................................317 Wrapper Classes .......................................................................................................................317 Numeric Wrapper Classes ................................................................................................................................. 320 The Character Wrapper Class read more..

  • Page - 797

    CONTENTS xv Accessing the Stack of a Thread ...............................................................................................369 The try-with-resources Block ....................................................................................................372 A Multi-Catch Block ...................................................................................................................376 Summary read more..

  • Page - 798

    CONTENTS xvi Searching for a String ........................................................................................................................................ 398 Representing Values as Strings ......................................................................................................................... 398 Getting a Substring read more..

  • Page - 799

    CONTENTS xvii The toXXX( ) Methods ......................................................................................................................................... 422 The atXXX( ) Methods ......................................................................................................................................... 423 The plusXXX( ) and minusXXX( ) Methods read more..

  • Page - 800

    CONTENTS xviii Legacy Datetime Classes ..........................................................................................................477 The Date Class ................................................................................................................................................... 477 The Calendar Class read more..

  • Page - 801

    CONTENTS xix Groups and Back Referencing ...................................................................................................531 Using Named Groups .................................................................................................................535 Resetting the Matcher ...............................................................................................................538 Final Words on E-mail Validations read more..

  • Page - 802

    CONTENTS xx Array Assignment Compatibility ................................................................................................579 Converting an ArrayList/Vector to an Array ...............................................................................581 Summary ...................................................................................................................................582 Chapter 16: Inheritance read more..

  • Page - 803

    CONTENTS xxi Is-a, has-a, and part-of Relationships .......................................................................................639 No Multiple Inheritance of Classes ............................................................................................641 Summary ...................................................................................................................................642 Chapter 17: Interfaces read more..

  • Page - 804

    CONTENTS xxii Comparing Objects ....................................................................................................................694 Using the Comparable Interface ........................................................................................................................ 694 Using the Comparator Interface ......................................................................................................................... 696 read more..

  • Page - 805

    CONTENTS xxiii Appendix B: Documentation Comments ........................................................................739 Writing Documentation Comments ...........................................................................................740 List of Block and Inline Tags ......................................................................................................742 @author <author-name(s)> read more..

  • Page - 806

    CONTENTS xxiv Generated Documentation Files ................................................................................................757 Viewing Generated HTML Documentation .................................................................................758 Summary ...................................................................................................................................758 Appendix C: Compact Profiles read more..

  • Page - 807

    xxv Foreword Java is a very versatile programming language. It began over 20 years ago in the depths of Sun Microsystems, which has since been taken over by Oracle. The original version of Java—including the compiler, runtime, source code, and documentation—could fit onto a single 720KB floppy disk. Nowadays, the closest thing to a floppy disk one can find is one of read more..

  • Page - 808

    xxvii About the Author Kishori Sharan is a senior software consultant at Doozer, Inc. He holds a Master of Science in Computer Information Systems from Troy State University in Montgomery, Alabama. He is a Sun Certified Java programmer and Sybase Certified PowerBuilder Developer Professional. He specializes in developing enterprise application using Java SE, Java EE, read more..

  • Page - 809

    xxix About the Technical Reviewer John Zukowski is currently a software engineer with TripAdvisor, the world’s largest travel site ( www.tripadvisor.com). He has been playing with Java technologies for 20 years now and is the author of 10 Java-related books. His books cover Java 6, Java Swing, Java Collections, and JBuilder from Apress, Java AWT from O’Reilly, and read more..

  • Page - 810

    xxxi Acknowledgments My heartfelt thanks are due to my father-in-law, Mr. Jim Baker, for displaying extraordinary patience in reading the initial draft of the book. I am very grateful to him for spending so much of his valuable time teaching me quite a bit of English grammar that helped me produce better material. I would like to thank my friend Richard Castillo read more..

Write Your Review