Copyright © 2014 by John Wiley & Sons. All rights reserved. 1
Chapter 4 – Fundamental Data Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 2
Chapter Goals
 To understand integer and floating-point numbers
 To recognize the limitations of the numeric types
 To become aware of causes for overflow and roundoff errors
 To understand the proper use of constants
 To write arithmetic expressions in Java
 To use the String type to manipulate character strings
 To write programs that read input and produce formatted output
Copyright © 2014 by John Wiley & Sons. All rights reserved. 3
Physical Memory Layout
https://en.wikipedia.org/wiki/6264
0x000
0x000
0x002
0x003
0x004
0x005
0x006
0x007
0x008
0x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
8 bits
12-bit
addresses
Copyright © 2014 by John Wiley & Sons. All rights reserved. 4
Memory Layout for 16-bit int’s
000100000x000
000001000x000
0x002
0x003
0x004
0x005
0x006
0x007
000001000x008
000100000x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
8 bits
int foo = 1040;
1040 (10) = 00000100 00010000 (2)
Little Endian (Intel)
Big Endian (Motorola)
Alignment is usually required to be at
addresses that are multiples of number
of bytes.
E.g. 2-byte objects aligned at even addresses
Copyright © 2014 by John Wiley & Sons. All rights reserved. 5
Memory Layout for 64-bit long’s
x000004100x000
x000000000x000
0x002
0x003
0x004
0x005
0x006
0x007
x000000000x008
x000004100x009
0x00A
0x00B
0x00C
0x00D
0x00E
0x00F
0x010
0x011
0x012
32 bits
long foo = 1040;
Alignment is usually required to be at
addresses that are multiples of number
of bytes.
E.g. 2-word objects aligned at even addresses
1040 (10) = 0x00000410(16)
Little Endian (Intel)
Big Endian (Motorola)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 6
Number Types
 Every value in Java is either:
• a reference to an object
• one of the eight primitive types
 Java has eight primitive types:
• four integer types
• two floating-point types
• two other
Copyright © 2014 by John Wiley & Sons. All rights reserved. 7
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
fooObject1
Object Reference
fooObject1
Object Itself
header
Copyright © 2014 by John Wiley & Sons. All rights reserved. 8
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = new Foo();
fooObject1
Object Reference
fooObject1
Object Itself
header
header
slot1 = 0x2
filler
slot2lo = 0x4
Slot2hi = 0x0
slot3lo = 0x0
header
0x0000000C
0x00000000
fooObject2
Object Reference
fooObject2
Object Itself
Copyright © 2014 by John Wiley & Sons. All rights reserved. 9
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = new Foo();
fooObject2 = fooObject1;
fooObject1
Object Reference
fooObject1
Object Itself
header
header
slot1 = 0x2
filler
slot2lo = 0x4
Slot2hi = 0x0
slot3lo = 0x0
header
0x00000008
0x00000000
fooObject2
Object Reference
“Garbage”
ALIASING
Multiple references to same object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 10
Memory Layout for Objects (Little Endian)
0x000000080x000
0x000000000x001
0x002
0x003
0x004
0x005
0x006
0x007
0x008
header
0x009
slot1 = 0x2
0x00A
filler
0x00B
slot2lo = 0x4
0x00C
Slot2hi = 0x0
0x00D
slot3lo = 0x0
0x00E
slot3hi = 0x0
0x00F
0x010
0x011
0x012
32 bits
Public class Foo {
public int slot1 = 2;
public long slot2 = 4;
public Foo slot3;
}
Foo fooObject1 = new Foo();
Foo fooObject2 = fooObject1;
fooObject1
Object Reference
fooObject1
Object Itself
header
0x00000008
0x00000000
fooObject2
Object Reference
ALIASING
Multiple references to same object
Copyright © 2014 by John Wiley & Sons. All rights reserved. 11
Primitive Types
Copyright © 2014 by John Wiley & Sons. All rights reserved. 12
Two’s Complement Encoding for Ints
Copyright © 2014 by John Wiley & Sons. All rights reserved. 13
Number Literals
 A number that appears in your code
 If it has a decimal, it is floating point
 If not, it is an integer
Copyright © 2014 by John Wiley & Sons. All rights reserved. 14
Number Literals
Copyright © 2014 by John Wiley & Sons. All rights reserved. 15
Overflow
 Generally use an int for integers
 Overflow occurs when
• The result of a computation exceeds the range for the number type
 Example
int n = 1000000;
System.out.println(n * n); // Prints –727379968, which is clearly wrong
• 1012 is larger that the largest int
• The result is truncated to fit in an int
• No warning is given
 Solution: use long instead
 Generally do not have overflow with the double data type
Copyright © 2014 by John Wiley & Sons. All rights reserved. 16
IEEE 754 Floating Point Standard
Images from: wikipedia.org
IEEE Single Precision = Java Float
IEEE Double Precision = Java Double
Copyright © 2014 by John Wiley & Sons. All rights reserved. 17
IEEE 754 Floating Point Standard
For a double-precision number, an exponent in the range −1022 .. +1023 is biased by
adding 1023 to get a value in the range 1 .. 2046 (0 and 2047 have special meanings).
http://www.binaryconvert.com/index.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 18
Rounding Errors
 Rounding errors occur when an exact representation of a
floating-point number is not possible.
 Floating-point numbers have limited precision. Not every value
can be represented precisely, and roundoff errors can occur.
 Example:
double f = 4.35;
System.out.println(100 * f); // Prints 434.99999999999994
 Use double type in most cases
Copyright © 2014 by John Wiley & Sons. All rights reserved. 19
IEEE 754 Floating Point Standard
Rounding errors may be caused by base-2 encoded mantissas
http://www.binaryconvert.com/index.html
Copyright © 2014 by John Wiley & Sons. All rights reserved. 20
Relative Precision of Float/Double
Copyright © 2014 by John Wiley & Sons. All rights reserved. 21
Constants: final
 Use symbolic names for all values, even those that appear obvious.
 A final variable is a constant
• Once its value has been set, it cannot be changed
 Named constants make programs easier to read and maintain.
 Convention: use all-uppercase names for constants:
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
final double NICKEL_VALUE = 0.05;
final double PENNY_VALUE = 0.01;
payment = dollars + quarters * QUARTER_VALUE +
dimes * DIME_VALUE + nickels * NICKEL_VALUE +
pennies * PENNY_VALUE;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 22
Constants: static final
 If constant values are needed in several methods,
• Declare them together with the instance variables of a class
• Tag them as static and final
• The static reserved word means that the constant belongs to the class
 Give static final constants public access to enable other classes
to use them.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 23
Constants: static final
 Declaration of constants in the Math class
public class Math
{
. . .
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
 Using a constant
double circumference = Math.PI * diameter;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34
Java Operators and their Precedence
Copyright © 2014 by John Wiley & Sons. All rights reserved. 40
Integer Division and Remainder
Copyright © 2014 by John Wiley & Sons. All rights reserved. 43
Mathematical Methods
Copyright © 2014 by John Wiley & Sons. All rights reserved. 46
Syntax 4.2 Cast
Copyright © 2014 by John Wiley & Sons. All rights reserved. 47
Arithmetic Expressions
Copyright © 2014 by John Wiley & Sons. All rights reserved. 53
Calling Static Methods
 Can not call a method on a number type double
root = 2.sqrt(); // Error
 Use a static method instead.
 A static method does not operate on an object:
double root = Math.sqrt(2); // Correct
 static methods are declared inside classes
 Calling a static method:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 54
Reading Input
 When a program asks for user input
• It should first print a message that tells the user which input is expected
System.out.print("Please enter the number of bottles: "); // Display prompt
 This message is called a prompt
• Use the print method, not println, to display the prompt
• Leave a space after the colon
 System.in has minimal set of features
• Must be combined with other classes to be useful
 Use a class called Scanner to read keyboard input.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 55
Reading Input - Scanner
 To obtain a Scanner object:
Scanner in = new Scanner(System.in);
 Use the Scanner's nextInt method to read an integer value:
System.out.print("Please enter the number of bottles: ");
int bottles = in.nextInt();
 When the nextInt method is called,
• The program waits until the user types a number and presses the Enter
key;
• After the user supplies the input, the number is placed into the bottles
variable;
• The program continues.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 56
Reading Input - Scanner
 Use the nextDouble method to read a floating-point number:
System.out.print("Enter price: ");
double price = in.nextDouble();
 To use the Scanner class, import it by placing the following at
the top of your program file:
import java.util.Scanner;
Copyright © 2014 by John Wiley & Sons. All rights reserved. 58
Syntax 4.3 Input Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved. 59
Formatted Output
 Use the printf method to specify how values should be
formatted.
 printf lets you print this
Price per liter: 1.22
 Instead of this
Price per liter: 1.215962441314554
 This command displays the price with two digits after the
decimal point:
System.out.printf("%.2f", price);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 60
Formatted Output
 You can also specify a field width:
System.out.printf("%10.2f", price);
 This prints 10 characters
• Six spaces followed by the four characters 1.22
 This command
System.out.printf("Price per liter:%10.2f", price);
 Prints
Price per liter: 1.22
Copyright © 2014 by John Wiley & Sons. All rights reserved. 62
Formatted Output
Copyright © 2014 by John Wiley & Sons. All rights reserved. 63
Formatted Output
 You can print multiple values with a single call to the printf
method.
 Example
System.out.printf("Quantity: %d Total: %10.2f",
quantity, total);
 Output explained:
Copyright © 2014 by John Wiley & Sons. All rights reserved. 83
String Type
 A string is a sequence of characters.
 You can declare variables that hold strings
String name = "Harry";
 A string variable is a variable that can hold a string
 String literals are character sequences enclosed in quotes
 A string literal denotes a particular string
"Harry"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 84
String Type
 String length is the number of characters in the string
• The length of "Harry" is 5
 The length method yields the number of characters in a string
• int n = name.length();
 A string of length 0 is called the empty string
• Contains no characters
• Is written as ""
Copyright © 2014 by John Wiley & Sons. All rights reserved. 85
Concatenation
 Concatenating strings means to put them together to form a
longer string
 Use the + operator
 Example:
String fName = "Harry”;
String lName = "Morgan”;
String name = fName + lName;
 Result:
"HarryMorgan"
 To separate the first and last name with a space
String name = fName + " " + lName;
 Results in
"Harry Morgan"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 86
Concatenation
 If one of the arguments of the + operator is a string
• The other is forced to become to a string:
• Both strings are then concatenated
 Example
String jobTitle = "Agent”;
int employeeId = 7;
String bond = jobTitle + employeeId;
 Result
"Agent7"
Copyright © 2014 by John Wiley & Sons. All rights reserved. 87
Concatenation in Print Statements
 Useful to reduce the number of System.out.print instructions
System.out.print("The total is "); System.out.println(total);
versus
System.out.println("The total is " + total);
Copyright © 2014 by John Wiley & Sons. All rights reserved. 88
String Input
 Use the next method of the Scanner class to read a string
containing a single word.
System.out.print("Please enter your name: ");
String name = in.next();
 Only one word is read.
 Use a second call to in.next to get a second word.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 90
Strings and Characters
 A string is a sequences of Unicode characters.
 A character is a value of the type char.
• Characters have numeric values
 Character literals are delimited by single quotes.
• 'H' is a character. It is a value of type char
 Don't confuse them with strings
• "H" is a string containing a single character. It is a value of type String.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 91
Strings and Characters
 String positions are counted starting with 0.
 The position number of the last character is always one less
than the length of the string.
 The last character of the string "Harry" is at position 4
 The charAt method returns a char value from a string
 The example
String name = "Harry”;
char start = name.charAt(0);
char last = name.charAt(4);
• Sets start to the value 'H' and last to the value 'y'.
Copyright © 2014 by John Wiley & Sons. All rights reserved. 92
Substrings
 Use the substring method to extract a part of a string.
 The method call str.substring(start, pastEnd)
• returns a string that is made up of the characters in the string str,
• starting at position start, and
• containing all characters up to, but not including, the position pastEnd.
 Example:
String greeting = "Hello, World!”;
String sub = greeting.substring(0, 5); // sub is "Hello”
Copyright © 2014 by John Wiley & Sons. All rights reserved. 93
Substrings
 To extract "World"
String sub2 = greeting.substring(7, 12);
 Substring length is “past the end” - start
Copyright © 2014 by John Wiley & Sons. All rights reserved. 94
Substrings
 If you omit the end position when calling the substring method,
then all characters from the starting position to the end of the
string are copied.
 Example
String tail = greeting.substring(7); // Copies all characters from position 7 on
 Result
• Sets tail to the string "World!".
Copyright © 2014 by John Wiley & Sons. All rights reserved. 95
Substrings
 To make a string of one character, taken from the start of first
first.substring(0, 1)
Copyright © 2014 by John Wiley & Sons. All rights reserved. 96
section_5/Initials.java
1 import java.util.Scanner;
2
3 /**
4 This program prints a pair of initials.
5 */
6 public class Initials
7 {
8 public static void main(String[] args)
9 {
10 Scanner in = new Scanner(System.in);
11
12 // Get the names of the couple
13
14 System.out.print("Enter your first name: ");
15 String first = in.next();
16 System.out.print("Enter your significant other's first name: ");
17 String second = in.next();
18
19 // Compute and display the inscription
20
21 String initials = first.substring(0, 1)
22 + "&" + second.substring(0, 1);
23 System.out.println(initials);
24 }
25 } Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved. 97
section_5/Initials.java
Program Run
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S
Copyright © 2014 by John Wiley & Sons. All rights reserved. 98
String Operations

Icom4015 lecture3-f16

  • 1.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 1 Chapter 4 – Fundamental Data Types
  • 2.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 2 Chapter Goals  To understand integer and floating-point numbers  To recognize the limitations of the numeric types  To become aware of causes for overflow and roundoff errors  To understand the proper use of constants  To write arithmetic expressions in Java  To use the String type to manipulate character strings  To write programs that read input and produce formatted output
  • 3.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 3 Physical Memory Layout https://en.wikipedia.org/wiki/6264 0x000 0x000 0x002 0x003 0x004 0x005 0x006 0x007 0x008 0x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 8 bits 12-bit addresses
  • 4.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 4 Memory Layout for 16-bit int’s 000100000x000 000001000x000 0x002 0x003 0x004 0x005 0x006 0x007 000001000x008 000100000x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 8 bits int foo = 1040; 1040 (10) = 00000100 00010000 (2) Little Endian (Intel) Big Endian (Motorola) Alignment is usually required to be at addresses that are multiples of number of bytes. E.g. 2-byte objects aligned at even addresses
  • 5.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 5 Memory Layout for 64-bit long’s x000004100x000 x000000000x000 0x002 0x003 0x004 0x005 0x006 0x007 x000000000x008 x000004100x009 0x00A 0x00B 0x00C 0x00D 0x00E 0x00F 0x010 0x011 0x012 32 bits long foo = 1040; Alignment is usually required to be at addresses that are multiples of number of bytes. E.g. 2-word objects aligned at even addresses 1040 (10) = 0x00000410(16) Little Endian (Intel) Big Endian (Motorola)
  • 6.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 6 Number Types  Every value in Java is either: • a reference to an object • one of the eight primitive types  Java has eight primitive types: • four integer types • two floating-point types • two other
  • 7.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 7 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); fooObject1 Object Reference fooObject1 Object Itself header
  • 8.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 8 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = new Foo(); fooObject1 Object Reference fooObject1 Object Itself header header slot1 = 0x2 filler slot2lo = 0x4 Slot2hi = 0x0 slot3lo = 0x0 header 0x0000000C 0x00000000 fooObject2 Object Reference fooObject2 Object Itself
  • 9.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 9 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = new Foo(); fooObject2 = fooObject1; fooObject1 Object Reference fooObject1 Object Itself header header slot1 = 0x2 filler slot2lo = 0x4 Slot2hi = 0x0 slot3lo = 0x0 header 0x00000008 0x00000000 fooObject2 Object Reference “Garbage” ALIASING Multiple references to same object
  • 10.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 10 Memory Layout for Objects (Little Endian) 0x000000080x000 0x000000000x001 0x002 0x003 0x004 0x005 0x006 0x007 0x008 header 0x009 slot1 = 0x2 0x00A filler 0x00B slot2lo = 0x4 0x00C Slot2hi = 0x0 0x00D slot3lo = 0x0 0x00E slot3hi = 0x0 0x00F 0x010 0x011 0x012 32 bits Public class Foo { public int slot1 = 2; public long slot2 = 4; public Foo slot3; } Foo fooObject1 = new Foo(); Foo fooObject2 = fooObject1; fooObject1 Object Reference fooObject1 Object Itself header 0x00000008 0x00000000 fooObject2 Object Reference ALIASING Multiple references to same object
  • 11.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 11 Primitive Types
  • 12.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 12 Two’s Complement Encoding for Ints
  • 13.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 13 Number Literals  A number that appears in your code  If it has a decimal, it is floating point  If not, it is an integer
  • 14.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 14 Number Literals
  • 15.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 15 Overflow  Generally use an int for integers  Overflow occurs when • The result of a computation exceeds the range for the number type  Example int n = 1000000; System.out.println(n * n); // Prints –727379968, which is clearly wrong • 1012 is larger that the largest int • The result is truncated to fit in an int • No warning is given  Solution: use long instead  Generally do not have overflow with the double data type
  • 16.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 16 IEEE 754 Floating Point Standard Images from: wikipedia.org IEEE Single Precision = Java Float IEEE Double Precision = Java Double
  • 17.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 17 IEEE 754 Floating Point Standard For a double-precision number, an exponent in the range −1022 .. +1023 is biased by adding 1023 to get a value in the range 1 .. 2046 (0 and 2047 have special meanings). http://www.binaryconvert.com/index.html
  • 18.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 18 Rounding Errors  Rounding errors occur when an exact representation of a floating-point number is not possible.  Floating-point numbers have limited precision. Not every value can be represented precisely, and roundoff errors can occur.  Example: double f = 4.35; System.out.println(100 * f); // Prints 434.99999999999994  Use double type in most cases
  • 19.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 19 IEEE 754 Floating Point Standard Rounding errors may be caused by base-2 encoded mantissas http://www.binaryconvert.com/index.html
  • 20.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 20 Relative Precision of Float/Double
  • 21.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 21 Constants: final  Use symbolic names for all values, even those that appear obvious.  A final variable is a constant • Once its value has been set, it cannot be changed  Named constants make programs easier to read and maintain.  Convention: use all-uppercase names for constants: final double QUARTER_VALUE = 0.25; final double DIME_VALUE = 0.1; final double NICKEL_VALUE = 0.05; final double PENNY_VALUE = 0.01; payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE + nickels * NICKEL_VALUE + pennies * PENNY_VALUE;
  • 22.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 22 Constants: static final  If constant values are needed in several methods, • Declare them together with the instance variables of a class • Tag them as static and final • The static reserved word means that the constant belongs to the class  Give static final constants public access to enable other classes to use them.
  • 23.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 23 Constants: static final  Declaration of constants in the Math class public class Math { . . . public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846; }  Using a constant double circumference = Math.PI * diameter;
  • 24.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 34 Java Operators and their Precedence
  • 25.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 40 Integer Division and Remainder
  • 26.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 43 Mathematical Methods
  • 27.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 46 Syntax 4.2 Cast
  • 28.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 47 Arithmetic Expressions
  • 29.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 53 Calling Static Methods  Can not call a method on a number type double root = 2.sqrt(); // Error  Use a static method instead.  A static method does not operate on an object: double root = Math.sqrt(2); // Correct  static methods are declared inside classes  Calling a static method:
  • 30.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 54 Reading Input  When a program asks for user input • It should first print a message that tells the user which input is expected System.out.print("Please enter the number of bottles: "); // Display prompt  This message is called a prompt • Use the print method, not println, to display the prompt • Leave a space after the colon  System.in has minimal set of features • Must be combined with other classes to be useful  Use a class called Scanner to read keyboard input.
  • 31.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 55 Reading Input - Scanner  To obtain a Scanner object: Scanner in = new Scanner(System.in);  Use the Scanner's nextInt method to read an integer value: System.out.print("Please enter the number of bottles: "); int bottles = in.nextInt();  When the nextInt method is called, • The program waits until the user types a number and presses the Enter key; • After the user supplies the input, the number is placed into the bottles variable; • The program continues.
  • 32.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 56 Reading Input - Scanner  Use the nextDouble method to read a floating-point number: System.out.print("Enter price: "); double price = in.nextDouble();  To use the Scanner class, import it by placing the following at the top of your program file: import java.util.Scanner;
  • 33.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 58 Syntax 4.3 Input Statement
  • 34.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 59 Formatted Output  Use the printf method to specify how values should be formatted.  printf lets you print this Price per liter: 1.22  Instead of this Price per liter: 1.215962441314554  This command displays the price with two digits after the decimal point: System.out.printf("%.2f", price);
  • 35.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 60 Formatted Output  You can also specify a field width: System.out.printf("%10.2f", price);  This prints 10 characters • Six spaces followed by the four characters 1.22  This command System.out.printf("Price per liter:%10.2f", price);  Prints Price per liter: 1.22
  • 36.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 62 Formatted Output
  • 37.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 63 Formatted Output  You can print multiple values with a single call to the printf method.  Example System.out.printf("Quantity: %d Total: %10.2f", quantity, total);  Output explained:
  • 38.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 83 String Type  A string is a sequence of characters.  You can declare variables that hold strings String name = "Harry";  A string variable is a variable that can hold a string  String literals are character sequences enclosed in quotes  A string literal denotes a particular string "Harry"
  • 39.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 84 String Type  String length is the number of characters in the string • The length of "Harry" is 5  The length method yields the number of characters in a string • int n = name.length();  A string of length 0 is called the empty string • Contains no characters • Is written as ""
  • 40.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 85 Concatenation  Concatenating strings means to put them together to form a longer string  Use the + operator  Example: String fName = "Harry”; String lName = "Morgan”; String name = fName + lName;  Result: "HarryMorgan"  To separate the first and last name with a space String name = fName + " " + lName;  Results in "Harry Morgan"
  • 41.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 86 Concatenation  If one of the arguments of the + operator is a string • The other is forced to become to a string: • Both strings are then concatenated  Example String jobTitle = "Agent”; int employeeId = 7; String bond = jobTitle + employeeId;  Result "Agent7"
  • 42.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 87 Concatenation in Print Statements  Useful to reduce the number of System.out.print instructions System.out.print("The total is "); System.out.println(total); versus System.out.println("The total is " + total);
  • 43.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 88 String Input  Use the next method of the Scanner class to read a string containing a single word. System.out.print("Please enter your name: "); String name = in.next();  Only one word is read.  Use a second call to in.next to get a second word.
  • 44.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 90 Strings and Characters  A string is a sequences of Unicode characters.  A character is a value of the type char. • Characters have numeric values  Character literals are delimited by single quotes. • 'H' is a character. It is a value of type char  Don't confuse them with strings • "H" is a string containing a single character. It is a value of type String.
  • 45.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 91 Strings and Characters  String positions are counted starting with 0.  The position number of the last character is always one less than the length of the string.  The last character of the string "Harry" is at position 4  The charAt method returns a char value from a string  The example String name = "Harry”; char start = name.charAt(0); char last = name.charAt(4); • Sets start to the value 'H' and last to the value 'y'.
  • 46.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 92 Substrings  Use the substring method to extract a part of a string.  The method call str.substring(start, pastEnd) • returns a string that is made up of the characters in the string str, • starting at position start, and • containing all characters up to, but not including, the position pastEnd.  Example: String greeting = "Hello, World!”; String sub = greeting.substring(0, 5); // sub is "Hello”
  • 47.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 93 Substrings  To extract "World" String sub2 = greeting.substring(7, 12);  Substring length is “past the end” - start
  • 48.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 94 Substrings  If you omit the end position when calling the substring method, then all characters from the starting position to the end of the string are copied.  Example String tail = greeting.substring(7); // Copies all characters from position 7 on  Result • Sets tail to the string "World!".
  • 49.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 95 Substrings  To make a string of one character, taken from the start of first first.substring(0, 1)
  • 50.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 96 section_5/Initials.java 1 import java.util.Scanner; 2 3 /** 4 This program prints a pair of initials. 5 */ 6 public class Initials 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 12 // Get the names of the couple 13 14 System.out.print("Enter your first name: "); 15 String first = in.next(); 16 System.out.print("Enter your significant other's first name: "); 17 String second = in.next(); 18 19 // Compute and display the inscription 20 21 String initials = first.substring(0, 1) 22 + "&" + second.substring(0, 1); 23 System.out.println(initials); 24 } 25 } Continued
  • 51.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 97 section_5/Initials.java Program Run Enter your first name: Rodolfo Enter your significant other's first name: Sally R&S
  • 52.
    Copyright © 2014by John Wiley & Sons. All rights reserved. 98 String Operations