Lecture 4 - 30-Jan-2025
Lecture 4 - 30-Jan-2025
2
Character strings
• A string of characters
• is an object in JAVA, defined by the class String
• Examples:
"This is a string
literal."
"123 Main Street"
"X"
The println Method
• In the Lincoln program from Chapter 1, we invoked
the println method to print a character string
• The System.out object represents a destination (the
monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
object method
information provided to the method
name
(parameters)
4
The print Method
• The System.out object provides another service as
well
• See Countdown.java
5
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
6
Output
//********************************************************************
// Countdown.java Author: Lewis/Loftus
// Three... Two... One... Zero... Liftoff!
Houston,
// Demonstrates the we have between
difference a problem.
print and println.
//********************************************************************
7
String Concatenation
• The string concatenation operator (+) is used to append one string to
the end of another
"Peanut butter " + "and jelly"
• It can also be used to append a number to a string
• A string literal cannot be broken across two lines in a program
• See Facts.java
8
//********************************************************************
// Facts.java Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************
System.out.println ();
continue
9
continue
10
Output
We present the following facts for your extracurricular edification:
11
String Concatenation
• The + operator is also used for arithmetic addition
• The function that it performs depends on the type of the
information on which it operates
• If both operands are strings, or if one is a string and one is a
number, it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but parentheses can be
used to force the order
• See Addition.java
12
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
13
Output
//********************************************************************
// Addition.java Author: Lewis/Loftus
// 24 and 45 concatenated: 2445
24the
// Demonstrates and 45 added:
difference between69
the addition and string
// concatenation operators.
//********************************************************************
14
Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
15
Quick Check
What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
X: 25
Y: 65
Z: 30050
16
Escape Sequences
• What if we wanted to print the quote character?
• The following line would confuse the compiler because it would
interpret the second quote as the end of the string
17
Escape Sequences
• Some Java escape sequences:
Escape Sequence Meaning
\b backspace
\t tab
\n newline
\r carriage return
\" double quote
\' single quote
\\ backslash
• See Roses.java
18
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
19
Output
//********************************************************************
Roses are Author:
// Roses.java red, Lewis/Loftus
//
Violets are blue,
// Demonstrates the use of escape sequences.
Sugar is sweet,
//********************************************************************
But I have "commitment issues",
public class Roses
{ So I'd rather just be friends
At this point in our relationship.
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,\n\tViolets are blue,\n" +
"Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" +
"So I'd rather just be friends\n\tAt this point in our " +
"relationship.");
}
}
20
Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.
21
Quick Check
Write a single println statement that produces the
following output:
"Thank you all for coming to my home
tonight," he said mysteriously.
22
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
Graphics
Applets
Drawing Shapes
23
Variables
• A variable is a name for a location in memory that holds a value
• A variable declaration specifies the variable's name and the type of
information that it will hold
int total;
int count, temp, result;
24
Variable Initialization
• A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;
25
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
26
Output
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
A piano has 88 keys.
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
27
int total;
28
Assignment
• An assignment statement changes the value of a variable
• The assignment operator is the = sign
total = 55;
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
30
Output
//********************************************************************
// Geometry.javaA heptagon has 7 sides.
Author: Lewis/Loftus
//
A decagon has 10 sides.
// Demonstrates the use of an assignment statement to change the
// value stored ain dodecagon
a variable. has 12 sides.
//********************************************************************
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
31
Constants
• A constant is an identifier that is similar to a variable except that it
holds the same value during its entire existence
• As the name implies, it is constant, not variable
• The compiler will issue an error if you try to change the value of a
constant
• In Java, we use the final modifier to declare a constant
final int MIN_HEIGHT = 69;
• They facilitate program maintenance
• If a constant is used in multiple places, its value need only be updated in one
place
32
final int MAX_LOAD = 100,
MAX_LOAD = 120;
33
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
34
Primitive Data
• There are eight primitive data types in Java
• Four of them represent integers:
• byte, short, int, long
36
Integers and floating point types
• By default
• JAVA assumes all integer literals are of type int
✔ Use int for general
calculations unless you
• To define a literal of type long expect very large values.
• L or l is appended to the end of the value ✔ Use long when dealing
with large numbers (e.g.,
• Example: long counted_Stars = 86827263927L; timestamps, IDs, big
counters).
• JAVA assumes floating point literals are of type double ✔ Use float when
memory is a concern and
precision is not critical
• If we need to treat a floating point as a float ✔ Use double for
• we append f or F to the end of the value financial, scientific, and
precise calculations.
• Example: float ratio = 0.2363F;
Characters
• A char variable stores a single character
• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n'
• Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
38
Character Sets
• A character set is an ordered list of characters, with
each character corresponding to a unique number
• A char variable in Java can store any character from
the Unicode character set
• The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters
• It is an international character set, containing symbols
and characters from many world languages
39
Boolean
• A boolean value represents a true or false condition
• The reserved words true and false are the only valid values for
a boolean type
boolean done = false;
• A boolean variable can also be used to represent any two states, such
as a light bulb being on or off
40
boolean flag = true;
41
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
42
Expressions
• An expression is a combination of one or more operators and operands
• Arithmetic expressions compute numeric results and make use of the
arithmetic operators:
Addition +
Subtraction -
Multiplication *
Division /
Remainder %
43
Division and Remainder
• If both operands to the division operator (/) are integers,
the result is an integer (the fractional part is discarded)
8 / 12 equals 0
44
Quick Check
What are the results of the following expressions?
12 / 2
12.0 / 2.0
10 / 4
10 / 4.0
4 / 10
4.0 / 10
12 % 3
10 % 3
3 % 10
45
Quick Check
What are the results of the following expressions?
12 / 2 = 6
12.0 / 2.0 = 6.0
10 / 4 = 2
10 / 4.0 = 2.5
4 / 10 = 0
4.0 / 10 = 0.4
12 % 3 = 0
10 % 3 = 1
3 % 10 = 0
46
Operator Precedence
• Operators can be combined into larger expressions
result = total + count / max - offset;
47
Quick Check
In what order are the operators evaluated in the
following expressions?
a + b + c + d + e a + b * c - d / e
a / (b + c) - d % e
a / (b * (c + (d - e)))
48
Quick Check
In what order are the operators evaluated in the
following expressions?
a + b + c + d + e a + b * c - d / e
1 2 3 4 3 1 4 2
a / (b + c) - d % e
2 1 4 3
a / (b * (c + (d - e)))
4 3 2 1
49
Expression Trees
• The evaluation of a particular expression can be shown
using an expression tree
• The operators lower in the tree have higher precedence
for that expression
+
a + (b – c) / d
a /
- d
b c
50
Assignment Revisited
• The assignment operator has a lower precedence than
the arithmetic operators
First the expression on the right hand
side of the = operator is evaluated
51
Assignment Revisited
• The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the
original value of count
count = count + 1;
52
Increment and Decrement
• The increment (++) and decrement (--) operators use only one operand
• The statement
count++;
is functionally equivalent to
count = count + 1;
53
Increment and Decrement
• The increment and decrement operators can be applied in postfix form:
count++
• or prefix form:
++count
• When used as part of a larger expression, the two forms can have
different effects
54
Postfix and prefix forms
• When used alone
• the prefix and postfix forms are equivalent
• It doesn’t matter if you write
• count++; or ++count;
• In a larger expression
• they can yield different results
• Total = count++;
• Total = ++count;
int i=100;
56
int i=100;
57
/100
Assignment Operators
• Often we perform an operation on a variable, and then store the
result back into that variable
• Java provides assignment operators to simplify that process
• For example, the statement
num += count;
is equivalent to
num = num + count;
59
Assignment Operators
• There are many assignment operators in Java, including the following:
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
60
Assignment Operators
• The right hand side of an assignment operator can be a complex
expression
• The entire right-hand expression is evaluated first, then the result is
combined with the original variable
• Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
61
not result = result / (total-MIN) % num;
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
62
Data Conversion
• Sometimes it is convenient to convert data from one type to another
• For example, in a particular situation we may want to treat an integer as
a floating point value
• These conversions do not change the type of a variable or the value
that's stored in it – they only convert a value as part of a computation
63
Data conversion
• Widening conversions From To
• It is safe
• to convert from a byte type to a short byte short,int,long,
type
float,double
• Since byte is stored in 8 bits short int, long, float,
• whereas short in 16 bits double
int long, float, or
• There is no loss of information, double
long float or double
• and the numeric value is preserved
exactly float double
Data conversion (cont’d)
/100
Assignment Conversion
• Assignment conversion occurs when a value of one type is assigned to
a variable of another
• Example:
int dollars = 20;
double money = dollars;
• Only widening conversions can happen via assignment
• Note that the value or type of dollars did not change
67
Promotion
• Promotion happens automatically when operators in expressions
convert their operands
• Example:
int count = 12;
double sum = 490.27;
double result = sum / count;
• The value of count is converted to a floating point value to perform
the division calculation
68
Casting
• Casting is the most powerful, and dangerous, technique for
conversion
• Both widening and narrowing conversions can be accomplished by
explicitly casting a value
• To cast, the type is put in parentheses in front of the value being
converted
int total = 50;
float result = (float) total / 6;
• Without the cast, the fractional part of the answer would be lost
69
Outline
Character Strings
Variables and Assignment
Primitive Data Types
Expressions
Data Conversion
Interactive Programs
70
Interactive Programs
• Programs generally need input on which to operate
• The Scanner class provides convenient methods for reading input
values of various types
• A Scanner object can be set up to read input from various sources,
including the user typing values on the keyboard
• Keyboard input is represented by the System.in object
71
Reading Input
• The following line creates a Scanner object that reads from the
keyboard:
Scanner scan = new Scanner (System.in);
72
Reading Input
• The Scanner class is part of the java.util class library, and must
be imported into a program to be used
• The nextLine method reads all of the input until the end of the line
is found
• See Echo.java
• The details of object creation and class libraries are discussed further
in Chapter 3
73
//********************************************************************
// Echo.java Author: Lewis/Loftus
//
// Demonstrates the use of the nextLine method of the Scanner class
// to read a string from the user.
//********************************************************************
import java.util.Scanner;
message = scan.nextLine();
74
Sample Run
//********************************************************************
// Echo.java Author: Lewis/Loftus
// Enter a line of text:
You want
// Demonstrates thefries with
use of the that?
nextLine method of the Scanner class
// to read a string from the user.
You entered: "You want fries with that?"
//********************************************************************
import java.util.Scanner;
message = scan.nextLine();
75
Input Tokens
• Unless specified otherwise, white space is used to separate the
elements (called tokens) of the input
• White space includes space characters, tabs, new line characters
• The next method of the Scanner class reads the next input token
and returns it as a string
• Methods such as nextInt and nextDouble read data of
particular types
• See GasMileage.java
76
//********************************************************************
// GasMileage.java Author: Lewis/Loftus
//
// Demonstrates the use of the Scanner class to read numeric data.
//********************************************************************
import java.util.Scanner;
continue
continue
continue
80
/100
/100