Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 4 – Fundamental Data Types
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
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.
2
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.
3
Primitive Types
1. Why 4 types of integers?
2. Positive and negative values can be represented
3. Wrapper classes for primitive types exist.
1. Static fields and methods can be called without creating objects
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
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.
5
Number Literals
Copyright © 2014 by John Wiley & Sons. All rights reserved.
6
Programming Question
Try following in the interactions panel in DrJava:
Do you get the expected output?
Why?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
Answer: Overflow
Overflow:
Generally use an int for integers
Occurs when he result of a computation exceeds the
range for the number type
Example
•
•
•
Correct answer 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.
8
It is important choosing the right data type for the
values.
Consider using long data type if int is not big enough to
hold the value you want to use.
The largest value that can be stored as a long is 263 – 1.
If that’s still not big enough, there’s a class named
BigInteger whose instances can store integers of any
size whatsoever.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
The Integer Classes
There is a corresponding class (Byte, Short, Integer,
or Long) for each Integer primitive type in the
java.lang package.
These classes are called wrapper classes.
Each class provides constants named MIN_VALUE and
MAX_VALUE, which represent the smallest and largest
values of the corresponding type.
For example, Byte.MIN_VALUE is –128 and
Byte.MAX_VALUE is 127.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
10
Integer Literals
Integers can be written in decimal (base 10), octal
(base 8), or hexadecimal (base 16) format.
Decimal literals :
• Contain digits between 0 and 9
• Should not begin with a zero:
123 10 32700
Octal literals :
• Contain digits between 0 and 7
• Must begin with a zero:
067 0367 077777
Hexadecimal literals :
• Contain digits between 0 and 9 and letters between a and f
• Always begin with 0x:
0xc
0xff
0x7ab6f
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Ref: Java Programming: From the Beginning, KN King
11
Integer Literals
Writing numbers in octal or hexadecimal has no effect
on how the numbers are actually stored.
For example, the literals 15, 017, or 0xf all represent
the same number (fifteen).
A program can switch from one notation to another at
any time, and even mix them: 10 + 015 + 0x20 has the
value 55 (decimal).
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
Ref: Java Programming: From the Beginning, KN King
12
Programming Question
Try following in the interactions panel in DrJava:
Do you get the expected output?
Why?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
13
Answer: Rounding Errors
Rounding errors occur when an exact representation of
a floating-point number is not possible.
Floating-point numbers have limited precision.
i.e. Not every value can be represented precisely
So roundoff errors can occur.
Example:
Use double type in most cases
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Constants: final
Represents values that do not change.
Use keyword final when declaring a variable as a
constant (precede data type)
• 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
• Words seperated by underscore(“_”)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
Programming Question
Modify BankAccount.java to
define a constant
MONTHLY_FEE that contains
monthly fee. Modify
monthlyFee method body
accordingly.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Answer
Notice the order:
1. constants
2. Variables
3. Constructors
4. methods
Also note that we intentionally
omit the access modifier to
avoid complexity.
• private:
•
private final double MONTHLY_FEE= 10.00;
• Can be accessed within class
only.
• public:
•
public final double MONTHLY_FEE= 10.00;
• Can be accessed outside class.
• Sometimes needed.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
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.
18
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;
Notice that we do not declare objects of type Math to use
constant PI.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
19
Syntax 4.1 Constant Declaration
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Programming Question
1. Implement a class CashRegister.
•
Declare following with suitable names and types:
•
Four constants:
–
•
Two instance variables:
–
•
Purchase amount and payment amount
One constructor:
–
•
Value of a quarter, dime, nickel and a penny
No argument constructor that initialize purchase and payment amounts to
zero.
Three instance methods:
–
Record purchase:
»
»
–
Receive payment:
»
»
»
–
Processes the payment received from the customer.
accepts four parameters: number of dollar bills, quarters, dimes, nickels and
pennies received.
Calculates the payment amount in dollars based on parameter input.
Return change to customer:
»
»
•
Records the purchase price of an item.
accepts amount as a parameter and add amount to purchase
Computes the change due and resets the machine for the next customer.
Accepts no parameters
Include javaDoc comments
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
CashRegister.java
/**
A cash register totals up sales and computes change due.
*/
public class CashRegister
{
public static final double
public static final double
public static final double
public static final double
QUARTER_VALUE = 0.25;
DIME_VALUE = 0.1;
NICKEL_VALUE = 0.05;
PENNY_VALUE = 0.01;
private double purchase;
private double payment;
/**
Constructs a cash register with no money in it.
*/
public CashRegister()
{
purchase = 0;
payment = 0;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
Records the purchase price of an item.
@param amount the price of the purchased item
*/
public void recordPurchase(double amount)
{
purchase = purchase + amount;
}
/**
Processes the payment received from the customer.
@param dollars the number of dollars in the payment
@param quarters the number of quarters in the payment
@param dimes the number of dimes in the payment
@param nickels the number of nickels in the payment
@param pennies the number of pennies in the payment
*/
public void receivePayment(int dollars, int quarters,
int dimes, int nickels, int pennies)
{
payment = dollars + quarters * QUARTER_VALUE + dimes * DIME_VALUE
+ nickels * NICKEL_VALUE + pennies * PENNY_VALUE;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
23
47
48
49
50
51
52
53
54
55
56
57
58
/**
Computes the change due and resets the machine for the next customer.
@return the change due to the customer
*/
public double giveChange()
{
double change = payment - purchase;
purchase = 0;
payment = 0;
return change;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
24
Programming Question
Write a class CashRegisterTester to test CashRegister
class. Place the following code inside main method:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
CashRegisterTester.java
/**
This class tests the CashRegister class.
*/
public class CashRegisterTester
{
public static void main(String[] args)
{
CashRegister register = new CashRegister();
register.recordPurchase(0.75);
register.recordPurchase(1.50);
register.receivePayment(2, 0, 5, 0, 0);
System.out.print("Change: ");
System.out.println(register.giveChange());
System.out.println("Expected: 0.25");
register.recordPurchase(2.25);
register.recordPurchase(19.25);
register.receivePayment(23, 2, 0, 0, 0);
System.out.print("Change: ");
System.out.println(register.giveChange());
System.out.println("Expected: 2.0");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Program Run:
Change: 0.25
Expected: 0.25
Change: 2.0
Expected: 2.0
26
QUESTION
What is wrong with the following statement sequence?
double diameter = 10.01;
double circumference = 3.14 * diameter;
Answer: Two things
• You should use a named constant, not the “magic number” 3.14
• 3.14 is not an accurate representation of π.
How do you correct the above code to use a constant for π ?
Answer:
The Math class also defines two constants, named E and PI, which
represent the familiar mathematical constants e and π.
These constants can be accessed by writing Math.E and Math.PI.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
Arithmetic Operators
Four basic operators:
• addition: +
• subtraction: • multiplication: *
• division: /
Expression:
• combination of variables, literals, operators, and/or method calls
(a + b) / 2
Parentheses control the order of the computation
(a + b) / 2
Multiplication and division have a higher precedence
than addition and subtraction
a + b / 2
Try following in interactive window: 2+3*4+1+4/2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
Arithmetic Operators
Parenthesis used:
• 2+(3*4)+1+(4/2)
highest precedence * and /
• ((2+(3+4))+1)+(4+2)) next in precedence +
Mixing integers and floating-point values in an arithmetic
expression yields a floating-point value
• 7 + 4.0 is the floating-point value 11.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
Increment and Decrement
The ++ operator adds 1 to a variable (increments)
counter++; // Adds 1 to the variable counter
The -- operator subtracts 1 from the variable
(decrements)
counter--; // Subtracts 1 from counter
Figure 1 Incrementing a Variable
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Integer Division and Remainder
If at least one of the numbers is a floating-point number,
result of division is a floating point number.
Example:
• all of the following evaluate to 1.75
7.0 / 4.0
7 / 4.0
7.0 / 4
If both numbers are integers, the result is an integer. The
remainder is discarded
• 7 / 4 evaluates to 1
Use % operator to get the remainder with (pronounced
“modulus”, “modulo”, or “mod”)
• 7 % 4 is 3
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Integer Division and Remainder
To determine the value in dollars and cents of 1729
pennies
• Obtain the dollars through an integer division by 100
int dollars = pennies / 100; // Sets dollars to 17
• To obtain the remainder, use the % operator
int cents = pennies % 100; // Sets cents to 29
Integer division and the % operator yield the dollar and
cent values of a piggybank full of pennies.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
Integer Division and Remainder
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
Programming Question
Write a tester class IntegerDivisionTester
(IntegerDivisionTester.java) to test integer division.
Place following code inside the main method:
Explain the output.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Answer
IntegerDivisionTester.java
Float and Double classes in the java.lang package provide
constants:
• POSITIVE_INFINITY,
• NEGATIVE_INFINITY, and
• NaN.
Expressions whose values are +∞, –∞, and NaN (as in above 3
statements) can be printed with System.out.print
http://docs.oracle.com/javase/7/docs/api/constant-values.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Powers and Roots
Math class is part of the java.lang package
Math class contains methods sqrt and pow to compute
square roots and powers
To take the square root of a number, use Math.sqrt; for
example, Math.sqrt(x)
To compute xn, you write Math.pow(x, n)
• To compute x2 it is significantly more efficient simply to compute
x * x
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Programming Question
In the DrJava interactive window define 3 integer
variables b,n,r. Then write a single statement that
implement following equation:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
ANSWER
In Java,
can be represented as
b * Math.pow(1 + r / 100, n)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Analyzing an Expression
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
Mathematical Methods
Refer JavaDoc Math class API
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Converting Floating-Point Numbers to
Integers - Cast
The compiler disallows the assignment of a double to an
int because it is potentially dangerous
• The fractional part is lost
• The magnitude may be too large
• This is an error:
double balance = total + tax;
int dollars = balance; // Error: Cannot assign double to int
Use the cast operator (int) to convert a floating-point
value to an integer.
double balance = total + tax;
int dollars = (int) balance;
Cast discards fractional part
You use a cast (typeName) to convert a value to a
different type.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Converting Floating-Point Numbers to
Integers - Rounding
Math.round converts a floating-point number to nearest
integer:
long rounded = Math.round(balance);
If balance is 13.75, then rounded is set to 14.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Syntax 4.2 Cast
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Arithmetic Expressions
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
QUESTION
The volume of a sphere is given by
If the radius is given by a variable radius of type
double, write a Java expression for the volume.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
ANSWER
Answer:
4 * PI * Math.pow(radius, 3) / 3
or (4.0 / 3) * PI * Math.pow(radius, 3),
but not (4 / 3) * PI * Math.pow(radius, 3)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
Class Methods/Static Methods
Not all methods require access to instance variables.
E.g. sqrt method in Math class:
• computes the square root of a number
• has nothing to do with objects.
Methods that don’t need access to instance variables
are known as class methods (or static methods.)
A class method—like all methods in Java—must belong
to a class.
Therefore static methods are declared inside classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Ref: Java Programming: From the Beginning, KN King
47
Calling Static Methods
A static method does not operate on an object:
double root = Math.sqrt(2); // Correct
Calling a static method (class method must be declared
public):
When a class method is called by another method in the
same class, the class name and dot can be omitted.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
main is a class method
Many classes in the Java API provide class methods,
including Math, System, and String.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
Writing static methods
Example:
Math.java
Copyright © 2014 by John Wiley & Sons. All rights reserved.
MathTester.java
50
Programming Question
Modify Rectangle class to include a static method
printArea that print the rectangle area given the width
and the height as parameters.
Modify RectangleTester.java to call printArea method
with some appropriate values.
E.g.
Rectangle.printArea(10,3);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
Answer
Rectangle.java
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
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.
53
Reading Input - Scanner
To obtain a Scanner object:
Scanner in = new Scanner(System.in);
By default, a scanner uses white space to separate tokens.
White space characters include blanks, tabs, and line terminators.
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.
54
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.
55
Syntax 4.3 Input Statement
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Programming Question
Write a tester class ScannerTester(ScannerTester.java)
that test the use of Scanner class. Inside main method
fill in code under following comments to add two
numbers together.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Answer
ScannerTester.java
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
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.
59
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.
60
Formatted Output
You use the printf method
to line up your output in
neat columns.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
Formatted Output
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
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.
63
section_3/Volume.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Scanner;
/**
This program prints the price per liter for a six-pack of cans and
a two-liter bottle.
*/
public class Volume
{
public static void main(String[] args)
{
// Read price per pack
Scanner in = new Scanner(System.in);
System.out.print("Please enter the price for a six-pack: ");
double packPrice = in.nextDouble();
// Read price per bottle
System.out.print("Please enter the price for a two-liter bottle: ");
double bottlePrice = in.nextDouble();
Continued
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64
section_3/Volume.java
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
final double CANS_PER_PACK = 6;
final double CAN_VOLUME = 0.355; // 12 oz. = 0.355 l
final double BOTTLE_VOLUME = 2;
// Compute and print price per liter
double packPricePerLiter = packPrice / (CANS_PER_PACK * CAN_VOLUME);
double bottlePricePerLiter = bottlePrice / BOTTLE_VOLUME;
System.out.printf("Pack price per liter:
System.out.println();
%8.2f", packPricePerLiter);
System.out.printf("Bottle price per liter: %8.2f", bottlePricePerLiter);
System.out.println();
}
}
Program Run
Please enter the price for a six-pack: 2.95
Please enter the price for a two-liter bottle: 2.85
Pack price per liter: 1.38
Bottle price per liter: 1.43
Copyright © 2014 by John Wiley & Sons. All rights reserved.
65
Programming Question
Using the printf method, print the values of the integer
variables bottles and cans so that the output looks like this:
Bottles: 8
Cans: 24
The numbers to the right should line up. (You may assume
that the numbers have at most 8 digits.)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
66
Answer
Answer: Here is a simple solution:
System.out.printf("Bottles: %8d\n", bottles);
System.out.printf("Cans: %8d\n", cans);
Note the spaces after Cans:.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
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“
The String class belongs to a package java.lang.
The java.lang package is automatically imported into
every program. (No other package has this property.)
String is the only class whose instances can be created
without the word new:
str1 = "abc";
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
String Type
A String object can be visualized as a series of
characters
Each character is identified/indexed by its position.
The first character is located at index = 0.
A visual representation of the string “Hello World!”:
length = 12
Indices =
H
e
l
l
o
0
1
2
3
4
Start index
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
W o
r
l
d
!
6
8
9
10
11
7
End index = length-1
69
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.
70
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.
71
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.
72
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.
73
Programming Question
What do following statements print?
System.out.println("Java" + 1 + 2);
System.out.println(1 + 2 + "Java");
Copyright © 2014 by John Wiley & Sons. All rights reserved.
74
Answer
In order for the + operator to mean string
concatenation, at least one of its two operands must
be a string:
System.out.println("Java" + 1 + 2);
// Prints "Java12"
System.out.println(1 + 2 + "Java");
// Prints "3Java"
Copyright © 2014 by John Wiley & Sons. All rights reserved.
75
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.
76
Escape Sequences
To include a quotation mark in a literal string, precede it
with a backslash ( \ )
"He said \"Hello\""
Indicates that the quotation mark that follows should be
a part of the string and not mark the end of the string
Called an escape sequence
To include a backslash in a string, use the escape
sequence \\
"C:\\Temp\\Secret.txt"
A newline character is denoted with the escape sequence
\n
E.g. String s = “first line\nsecond line”
A newline character is often added to the end of the
format string when using System.out.printf:
System.out.printf("Price: %10.2f\n", price);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
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
• E.g. char ch = ‘a’;
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.
78
Strings and Characters
String positions are counted starting with 0.
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); //set start value to ‘H’
char last = name.charAt(4); //set last value t ‘y’
Copyright © 2014 by John Wiley & Sons. All rights reserved.
79
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”
Retrieve substring in index range 0-4;
Index=5 is excluded
Copyright © 2014 by John Wiley & Sons. All rights reserved.
80
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.
81
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);
Result
Copy all characters from index 0 to end
• Sets tail to the string "World!".
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
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.
83
Programming Question
Write a tester class StringTester that test the use of
String class. The program should first prompt the user
for first name and store it in a appropriate variable.
Then it should prompt the user again to enter his/her
significant other’s first name and store it in a
appropriate variable. Finally program will display the
First Initials combined by & sign.
Following is sample 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.
84
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
StringTester.java
import java.util.Scanner;
/**
This program prints a pair of initials.
*/
public class StringTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Get the names of the couple
System.out.print("Enter your first name: ");
String first = in.next();
System.out.print("Enter your significant other's first name: ");
String second = in.next();
// Compute and display the inscription
String initials = first.substring(0, 1)
+ "&" + second.substring(0, 1);
System.out.println(initials);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued
85
String Operations
Copyright © 2014 by John Wiley & Sons. All rights reserved.
86
Programming Question
Modify StringTester class so that it include an input
statement to read a name of the form “John Q. Public”.
Sample run is shown below:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Answer
Answer:
String first = in.next();
String middle = in.next();
String last = in.next();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
88