30
John Hurley Cal State LA CS 201 Lecture 3:

John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

Embed Size (px)

Citation preview

Page 1: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

John HurleyCal State LA

CS 201 Lecture 3:

Page 2: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

2

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.

Page 3: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

3

Assignments

x = 1 is an assignment that sets x to the value 1

To the computer, this means “go find the memory you set aside to keep track of x and replace the value there with 1”

x == 1 is a test that is true if x is equal to 1, otherwise false.

Usually used in a expression like if(x == 1) System.out.println(“x is equal to 1!”);

Page 4: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

4

More Fun With Data Typesboolean

Value that is either true or falseinequalities and tests in loop statements

evaluate to boolean values1 < 2 is true, so2 < 1 is false2 == 2 is true

int i = 2;System.out.println(i + " < " + 5 + "?" + (i < 5));

prints “true”

Page 5: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

5

More Fun With Data Typespublic class BooleanDemo{

public static void main(String[] args){

for(int i = 0; i < 10; i++) {

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))); }

}

Page 6: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

6

More Fun With Data Typeschar

One characterSet value using single quotes:

char myChar = ‘A’;‘A’ is not the same as ‘a’

Page 7: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

7

More Fun With Data TypesString

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.

Page 8: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

8

More Fun With Data Typespublic class CharStringDemo{

public static void main(String[] args){char myChar = 'a';String myString = "John Hurley";System.out.println(myChar);System.out.println(myString);

}}

Page 9: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

9

Math Operations

Java's math operations are easy to understandx = 1; // sets x to 1x = x + 1; // adds 1 to xx = x * y; // multiplies x by yx = 100.0/9.2; // x should be a floating point // type, not an integer x = y + 100;

Page 10: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

10

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

Page 11: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

11

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);}

}

Page 12: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

12

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);}

}

Page 13: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

13

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);}

}

Page 14: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

14

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);}

}

Page 15: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

15

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”

Page 16: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

16

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; sets x to 1, not 2!

Page 17: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

17

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.611.01.6

Page 18: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

18

ConstantsImagine you are writing aprogram which can

calculatethe circumference of a circle: 2πrthe area of a circle: πr2

the volume of a cylinder: πr2h

You could type in a value of pi each time you will use itdouble 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;

Page 19: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

19

Constants

Better idea: define a constant and set its value once

Less risk of errors or inconsistenciesClearer code; it’s easier to recognize the

constant name than the valueEasier to change precision

Used 3.14 before for simplicity, but results were not accurate enough. Now you want to use 3.14159

Page 20: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

20

Constants

Use all caps for constant namesUse final keywordfinal double PI = 3.14159;… code omitted…double circumference = 2 * PI * radius;

Page 21: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

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");}

}

Combining Operations

Page 22: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

22

Operator Precedence

3 + 4 * 4 + 5 * (4 + 3) - 1 3 + 4 * 4 + 5 * 7 – 1 3 + 16 + 5 * 7 – 1 3 + 16 + 35 – 1 19 + 35 – 1 54 - 1 53

(1) inside parentheses first

(2) multiplication

(3) multiplication

(4) addition

(6) subtraction

(5) addition

Page 23: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

23

Operator AssociativityBinary 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 expressiona = b += c = 5 is equivalent to a = (b += (c

= 5))x = 1X = 10 * b;

Page 24: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

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.

Page 25: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

25

Frequently-Used Specifiers

Specifier Output Example

%b a boolean value true or false

%c a character 'a'

%d a decimal integer 200

%f a floating-point number 45.460000

%e a number in standard scientific notation 4.556000e+01

%s a string "Java is cool"

int count = 5;

double amount = 45.56;

System.out.printf("count is %d and amount is %f", count, amount);

display count is 5 and amount is 45.560000

items

Page 26: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

Printfpublic 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

Page 27: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

27

Naming ConventionsChoose 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 computeArea.

Page 28: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

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

Page 29: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

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

Page 30: John Hurley Cal State LA CS 201 Lecture 3:. 2 Reserved Words Reserved words or keywords are words that have a specific meaning to the compiler and cannot

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 wantit 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