1 / 30

Java Programming: From the Beginning

Java Programming: From the Beginning. Chapter 9: Primitive Types. Summary of the Integer Types. Converting Strings to Integers. Methods that convert a string containing an integer into the actual value of the integer: Byte.parseByte Integer.parseInt Long.parseLong Short.parseShort

hong
Download Presentation

Java Programming: From the Beginning

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Programming: From the Beginning Chapter 9: Primitive Types

  2. Summary of the Integer Types

  3. Converting Strings to Integers • Methods that convert a string containing an integer into the actual value of the integer: Byte.parseByte Integer.parseInt Long.parseLong Short.parseShort • NumberFormatExceptionis thrown if the string doesn’t contain a valid integer or it represents a number outside the range of allowable values. • Byte.parseBytewould reject the string "128", because the largestbytevalue is 127.

  4. Floating-Point Types • The integer types aren’t suitable for variables that need to store numbers with digits after the decimal point, or numbers that are exceedingly large or small. • Java provides two types to use in this situation: float and double, the floating-point types.

  5. Floating-Point Types

  6. Floating-Point Types • float is suitable when accuracy isn’t critical. • double provides greater precision. • For numbers that must be stored even more precisely, Java provides a class named BigDecimal.

  7. Special Values • Java’s float and double types include three special values: +, –, and NaN (Not a Number). • Dividing a positive number by zero yields +. • Dividing a negative number by zero yields –. • NaN is the result of a mathematically undefined operation, such as dividing zero by zero. • Examples: 1.0/0.0 + -1.0/0.0 – 0.0/0.0 NaN

  8. Special Values • Expressions whose values are +, –, and NaN can be printed with System.out.print or System.out.println: System.out.println(1.0 / 0.0); //Prints"Infinity" System.out.println(-1.0 / 0.0); //Prints “-Infinity" System.out.println(0.0 / 0.0); //Prints "NaN"

  9. 9.4 The char Type • A variable of type char can be assigned any single character: char ch; ch = 'a'; // Lowercase a ch = 'A'; // Uppercase A ch = '0'; // Zero ch = ' '; // Space • Character literals are enclosed in single quotes.

  10. The Unicode Character Set • Instead of relying on ASCII to represent characters, Java uses a slightly different encoding known as Unicode. • A Unicode character requires 16 bits. • Unicode is compatible with ASCII. Adding eight zero bits to the beginning of the ASCII code for a character gives the character’s value in Unicode. • For example, the Unicode version of the character A would be 0000000001000001.

  11. The Unicode Character Set • A graphical depiction of the relationship between ASCII, Latin1, and Unicode:

  12. The Unicode Character Set • Unicode can support up to 65,536 characters. • Unicode contains the characters needed by all modern languages. • Java relies on Unicode both for writing programs and for storing character data within a program. • Although the use of Unicode is increasing rapidly, ASCII is still by far the most popular character set. • Some computers rely on even older character sets. • IBM mainframes use an 8-bit character set named EBCDIC.

  13. Characters Versus Strings • A character stored in a String object can be retrieved by calling the charAt method. • charAt requires a single argument, representing the position of the desired character. • A loop that visits all the characters in a string: for (int i = 0; i < str.length(); i++) … Inside the loop, the call str.charAt(i) would be used to access the character at position i.

  14. Characters Versus Strings • A loop that displays an ISBN number with the dashes removed. for (int i = 0; i < isbn.length(); i++) { char ch = isbn.charAt(i); if (ch != '-') System.out.print(ch); }

  15. The Character Class • The Character class, which belongs to the java.lang package, provides methods for testing and converting characters. • isDigit checks whether its argument is a digit: Character.isDigit('a')false Character.isDigit('0')true Character.isDigit(' ')false • isISOControl checks whether its argument is a control character: Character.isISOControl('a')false Character.isISOControl('0')false Character.isISOControl('\n')true

  16. The Character Class • isLetter checks whether its argument is a letter: Character.isLetter('a')true Character.isLetter('0')false Character.isLetter(' ')false • isLetterOrDigit checks whether its argument is a letter or a digit: Character.isLetterOrDigit('a')true Character.isLetterOrDigit('0')true Character.isLetterOrDigit(' ')false • “Letters” and “digits” include all Unicode letters and digits, not just the characters from A to Z and 0 to 9.

  17. The Character Class • isLowerCase checks whether its argument is a lowercase letter: Character.isLowerCase('a')true Character.isLowerCase('A')false • isUpperCase checks whether its argument is an uppercase letter: Character.isUpperCase('a')false Character.isUpperCase('A')true

  18. The Character Class • isWhitespace checks whether its argument is a white-space character—a character that’s invisible to the user. • Some control characters—including the tab character and the line feed—are white-space characters, as is the space character itself. Character.isWhitespace('a')false Character.isWhitespace(' ')true Character.isWhitespace('\n')true

  19. The Character Class • toLowerCase accepts any character as its argument. If the argument is an uppercase letter, the lowercase version of the letter is returned; otherwise, the argument itself is returned: Character.toLowerCase('a')'a' Character.toLowerCase('A')'a' Character.toLowerCase('5')'5' • toUpperCase is similar: Character.toUpperCase('a')'A' Character.toUpperCase('A')'A' Character.toUpperCase('5')'5'

  20. Implicit Conversions • If an int is added to a long, the compiler will arrange for the int value to be converted to 64 bits. • If an int and a float are added, the compiler will arrange for the int to be converted to float format. • The compiler handles these conversions automatically, so they’re known as implicit conversions. • Java also allows the programmer to perform explicit conversions.

  21. Implicit Conversions • Situations in which implicit conversions are performed: • When the operands in a numeric expression don’t have the same type. • When the type of the expression on the right side of an assignment doesn’t match the type of the variable on the left side.

  22. Numeric Promotion • Many Java operators allow operands of different types. If the operands have different types, they must be converted to some common type before the operation can be performed. • If f is a float variable and i is an int variable, it’s safer to convert i to type float rather than convert f to type int. • Java’s strategy is to convert operands to a type that will safely accommodate both values. • This process is called numeric promotion.

  23. Numeric Promotion • Rules for numeric promotion: • If either operand is of type double, the other is converted to double. • If either operand is of type float, the other is converted to float. • If either operand is of type long, the other is converted to long. • Otherwise, both operands are converted to int.

  24. Numeric Promotion • Examples: double + intdouble int + doubledouble float + intfloat long + floatfloat short + longlong byte + intint short + byteint

  25. Numeric Promotion • Numeric promotion tries to change the way a number is stored, without changing the number’s value. • However, when converting from int or long to float, or from long to double, some of the original number’s precision may be lost.

  26. Conversion During Assignment • In an assignment, Java converts the expression on the right side to the type of the variable on the left side, provided that the variable’s type is at least as “wide” as the expression’s type. • The numeric types, in order of increasing width:

  27. Conversion During Assignment • Examples of legal assignments: short s; int i; float f; double d; … i = s; // s is converted to int f = i; // i is converted to float d = f; // f is converted to double • In addition, a char value can be assigned to a variable of type int, long, float, or double.

  28. Conversion During Assignment • An assignment in which the expression on the right side has a wider type than the variable on the left side is an error: int i; float f; … i = f; // WRONG • The reason for this rule is that storing a value into a narrower variable can cause bugs in the program.

  29. Casting • A conversion that’s done at the programmer’s request is called a cast. • Casting is done by enclosing the desired type in parentheses and inserting it before the expression: int i; float f; … i = (int) f; // Cast f to int type • Casting a floating-point number to an integer type causes the number to be truncated. • General form of a cast: ( type-name ) expression

  30. Dividing Integers Without Truncation • Unary operators have higher precedence than binary operators, so the compiler interprets the expression (double) dividend / divisor as ((double) dividend) / divisor

More Related