Transcript Slide 1

CS 201 Lecture 3:
John Hurley
Cal State LA
Reserved Words
Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other
purposes in the program.
For example, when the compiler sees the word class, it
understands that the word after class is the name for the class.
Some other reserved words include public, private, static,
and void. Their use will be introduced later. Don’t use them
as names for variables or classes.
2
Assignments
radius = 1 is an assignment that sets radius to the
value 1
To the computer, this means “go find the memory you set
aside to keep track of radius and replace the value there
with 1”
radius == 1 is a test that is true if radius is equal to
1, otherwise false.
Usually used in a expression like
if(radius == 1)
System.out.println(“radius is equal to 1!”);
3
More Fun With Data Types
 boolean
 Value that is either true or false
 inequalities and tests in loop statements evaluate to boolean
values
 1 < 2 is true, so
 2 < 1 is false
 2 == 2 is true
 int i = 2;
System.out.println(i + " < " + 5 + " ? " + (i < 5));
prints "2 < 5 ? true"
4
More Fun With Data Types
package demos;
public class BooleanDemo {
public static void main(String[] args) {
int i = 1;
System.out.println(i + " < " + 5 + "? " + (i < 5));
System.out.println(i + " == " + 5 + "? " + (i == 5));
System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n");
i = 5;
System.out.println(i + " < " + 5 + "? " + (i < 5));
System.out.println(i + " == " + 5 + "? " + (i == 5));
System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n");
i = 6;
System.out.println(i + " < " + 5 + "? " + (i < 5));
System.out.println(i + " == " + 5 + "? " + (i == 5));
System.out.println(i + " > " + 5 + "? " + (i > 5) + "\n");
System.out.println("(1 == 1) == (2 == 1)? " + ((1 == 1) == (2 == 1)));
System.out.println("(1 < 2) == (2 < 3)? " + ((1 < 2) == (2 < 3)));
}
}
5
More Fun With Data Types
 char
 One character
 Set value using single quotes:
 char myChar = 'A';
 ‘A’ is not the same as ‘a’
6
More Fun With Data Types
 String
 Sequence of zero or more characters.
 Note the capital S
 String is a class; we will learn what that means later.
 Set values using double quotes:
 String myString = “Get your own String, This one is mine.”
 “” is called a null String or empty String.
7
More Fun With Data Types
public class CharStringDemo{
public static void main(String[] args){
char myChar = 'a';
String myString = "John Hurley";
System.out.println(myChar);
System.out.println(myString);
}
}
8
Math Operations
Java's math operations are easy to understand
x = 1;
// sets x to 1
x = x + 1; // adds 1 to x
x = x * y; // multiplies x by y
x = 100.0/9.2; // x should be a floating point
// type, not an integer
x = y + 100;
9
Math Operations: Modulo
 Modulo may be unfamiliar. It performs integer division
and yields the remainder. The modulo operator is the
symbol %
 x = y % 3; means "divide y by 3, ignore the quotient,
and assign the remainder as the new value of x." y
should be an integer.
 Modulo has many uses. The simplest one is that it tells
us whether an integer is evenly divisible by another
integer. If, for example a % b == 0, then a is evenly
divisible by b.
9 % 3 is 0
10 % 3 is 1


10
Math Operations and Data Type
 What will the output from this code be?
public class Mathematician{
public static void main(String[] args){
int total = 5;
int divisor = 4;
int result = total / divisor;
System.out.println( total + "/" +divisor + " = " + result);
}
}
11
Math Operations and Data Type
 What about this one?
public class Mathematician{
public static void main(String[] args){
int total = 5;
int divisor = 3;
int result = total / divisor;
System.out.println( total + "/" +divisor + " = " + result);
}
}
12
Math Operations and Data Type
 This one still doesn’t work!
public class Mathematician{
public static void main(String[] args){
int total = 5;
int divisor = 4;
double result = total / divisor;
System.out.println( total + "/" +divisor + " = " + result);
}
}
13
Math Operations and Data Type
 To get a floating point result from division, you must make at
least one of the operands a floating point type:
public class Mathematician{
public static void main(String[] args){
int total = 5;
double divisor = 4;
double result = total / divisor;
System.out.println( total + "/" +divisor + " = " + result);
}
}
14
Conversion Rules
When performing a binary* operation involving two
operands of different types, Java automatically converts
the operand based on the following rules:
1. If one of the operands is double, the other is converted into
double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.
* In this case binary means “involving two operands,” not “ in base 2”
15
Casting
Casting converts data types
You should rarely have to do this at this point
For primitive types, the syntax looks like this:



int x = (int) 5.1;

Casting a floating point type to an integer truncates, doesn’t
round!

int x = (int) 1.6;


16
sets x to 1, not 2!
Casting

Casting the value back to the original type does not restore lost data, so if you need
the original value, go back to the original variable
public class Caster{
public static void main(String[] args){
double x = 1.6;
int y = (int) x;
System.out.println(x);
System.out.println(y);
System.out.println((double) y);
System.out.println(x);
}
}
outputs:
1.6
1
1.0
1.6
17
Constants
 Imagine you are writing aprogram which can calculate
 the circumference of a circle: 2πr
 the area of a circle: πr2
 the volume of a cylinder: πr2h
 You could type in a value of pi each time you will use it








18
double radius = 5.1;
double height = 3;
…
double circumference = 2 * 3.14 * radius;
…
double area = 3.14 * radius * radius;
…
double volume = 3.14 * radius * radius * height;
Constants
 Better idea: define a constant and set its value once
 Less risk of errors or inconsistencies
 Clearer code; it’s easier to recognize the constant name than
the value
 Easier to change precision
 Used 3.14 before for simplicity, but results were not accurate
enough. Now you want to use 3.14159
19
Constants
 Use all caps for constant names
 Use final keyword
 final double PI = 3.14159;
 … code omitted…
 double circumference = 2 * PI * radius;
20
Constants
21
Combining Operations
 Just as in arithmetic and algebra, you can combine simple operations
into complex calculations of any length
public class Converter{
public static void main(String[] args){
double celsius;
double fahrenheit = 212;
celsius = (fahrenheit -32) * 5.0/9;
System.out.println(fahrenheit + " degrees F = " +
celsius + " degrees C");
}
Operator Precedence
3 + 4 * 4 + 5 * (4 + 3) - 1
3 + 4 * 4 + 5 * 7 – 1
3 + 16 + 5 * 7 – 1
(1) inside parentheses first
(2) multiplication
(3) multiplication
3 + 16 + 35 – 1
19 + 35 – 1
54 - 1
53
23
(4) addition
(5) addition
(6) subtraction
Operator Associativity
 Binary operators are those that take two operands.
 Example: a - b
 All binary operators except assignment operators are
left-associative.
a – b + c – d is equivalent to ((a – b) + c) – d

 Assignment operators are right-associative. Therefore, the
expression
 a = b += c = 5 is equivalent to a = (b += (c = 5))
x = 1
 x = 10 * b;
24
Formatting Output
Use the printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings
and format specifiers. A format specifier specifies how
an item should be displayed. An item may be a
numeric value, character, boolean value, or a string.
Each specifier begins with a percent sign.
25
Frequently-Used Specifiers
Specifier Output
Example
%b
true or false
a boolean value
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
%s
a string
4.556000e+01
"Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display
26
count is 5 and amount is 45.560000
Printf
public class PrintfDemo{
public static void main(String[] args){
int intVar = 1;
double doubleVar = 3.14159;
double moonRadius = 1737000; // in meters
char charVar = 'a';
String stringVar = "Hi, Mom";
boolean boolVar = true;
System.out.printf("\nintVar: %d; \ndoubleVar: %f; \ndoubleVar to 4 places: %7.4f;
\nmoonRadius: %e; \ncharVar: %c; \nstringVar: %s",
intVar, doubleVar, doubleVar, moonRadius, charVar, stringVar);
} // end main()
} // end class
Naming Conventions
 Choose meaningful and descriptive names.
 Variables and method names:
 Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word, and
capitalize the first letter of each subsequent word in the name.
For example, the variables radius and area, and the
method computeAreaInSqCm().
28
Naming Conventions, cont.
 Class names:
 Capitalize the first letter of each word in the
name. For example, the class name
ComputeArea.
 Constants:
 Capitalize all letters in constants. Use
underscores to connect words or just run words
together. For example, the constant PI and
MAX_VALUE or MAXVALUE
29
What to Expect
 Programming is frustrating, but you will not experience anything that
every other programmer who ever lived has not also experienced.
 You will never get anything right on the first try, and rarely on the tenth.
 This is the real origin of the term “hacking”
 The problem is not that you are not smart enough, it is that programming requires
closer attention to detail than is normal for a human being.
 Rough guess: you will spend 5% of your time writing the frist draft of your
code and 95% of your time figuring out why it doesn’t work and fixing it
 Debugging = the process of finding and correcting defects in a piece of
software (definition adapted from Wikipedia)
 Professional software development organizations spend more time testing
than programming, and programming itself consists mostly of debugging.
What to Expect
 Programmers’ proverb: “A computer is like an idiot with a perfect
memory who never gets tired”
 it will do exactly what you say, but it is very hard for you to figure out how
to say what you want
 it does not understand your intentions or any kind of subtext. It will do
neither more nor less than what you tell it to do
 you will never be able to think out your programs well enough to account
for all possibilities
 Assume everything that goes wrong is your fault. At this stage in your
programming career, problems will almost always be caused by your
failure to think things out. You will be tempted to blame hardware
failures, problems with Java, or bugs in Windows/OSX/Linux; you’ll
almost always be wrong.
What to Expect
This joke is from Philogelos, the oldest known book of jokes, probably
compiled around 300 AD:
 A poor student went swimming and almost drowned. Now he swears he will never
go in the water again until he learns to swim