expressions and data types csc 121 fall 2014 howard rosenthal€¦ · key terms and definitions (2)...

32
Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal

Upload: others

Post on 17-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Expressions and Data Types

CSC 121

Fall 2014

Howard Rosenthal

Page 2: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Lesson Goals Understand the basic constructs of a Java Program

Understand how to use basic identifiers

Understand simple Java data types and the operations on those types

Understand how to write and evaluate expressions

Understand the concept of casting

2

Page 3: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

public class Hello

{ public static void main ( String[] args )

{ System.out.println("Hello World!");

}

}

•Above is the source program (source file). The purpose of this program is to

type the characters Hello World! on the monitor.

•The file must be named Hello.java to match the name of the class. The upper

and lower case characters of the file name are important. (So if the file is

named hello.java with a small h it will not work). On all computers, upper and

lower case inside the program are important.

•The first line class Hello says that this source program defines a class called

Hello.

• A class is a section of a program. Small programs often consist of just one

class. When the program is compiled, the compiler will make a file of

bytecodes called Hello.class.

Key Terms and Definitions

3

Page 4: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Key Terms and Definitions (2)

Braces For every left brace { there is a right brace } that matches.

Usually there will be sets of matching braces inside other sets of matching braces. The first brace in a class (a left brace) will match the last brace in that class (a right brace). A brace can match just one other brace.

Use indenting to show how the braces match (and thereby show the logic of the program). Look at the example. Increase the indenting by three spaces for statements inside a left

and right brace. If another pair of braces is nested within those braces, increase the indenting for the statements they contain by another three spaces. Line up the braces vertically.

With Notepad++ the indent levels for both brackets and parentheses are color coded

4

Page 5: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

• Most classes contain many more lines than this one. Everything that makes up a class is placed between the first brace { and its matching last brace } .

• The name of the class (and therefore the name of the file) is up to you. By convention the first letter of a class is typically upper case. • A source file always end with .java in lower case. • Therefore the file name is Classname.java

• In programming, the name for something like a class is called an identifier. An identifier consists of alphabetical characters and digits. The first character must be alphabetical, the remaining characters can be mixed alphabetic characters and digits (plus the two characters '_' and '$' - underscore and dollar sign). No spaces are allowed inside the name.

• An expression is a sequence of symbols (identifiers, operators, constants, etc.) that denote a value

Key Terms and Definitions (3)

5

Page 6: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

• A reserved word is a word like class that has a special meaning to the system. For example, class means that a definition of a class immediately follows. You must use reserved words only for their intended purpose. (For example, you can't use the word class for any other purpose than defining a class.) Page 25 0f the text lists reserved words

• A statement in a programming language is a command for the computer to do something. It is like a sentence of the language.

• A statement in Java is always followed by a semicolon. • A group of statements within a set of braces is called a block • Methods are built out of statements. The statements in a method are

placed between braces { and } as in this example. • A method is a section of a class that performs a specific task • All programs start with the Main method

• The part "Hello World!" is called a string. A string is a sequence of characters. This program writes a string to the monitor and then stops.

Key Terms and Definitions (4)

6

Page 7: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Key Terms and Definitions (4)

7

abstract assert boolean break byte case

catch char class const* continue default

double do else enum extends false

final finally float for goto* if

implements import instanceof int interface long

native new null package private protected

public return short static strictfp super

switch synchronized this throw throws transient

true try void volatile while

The table below lists all the words that are reserved java:

*Even though goto and const are no longer used in the Java programming language, they still cannot be used.

Page 8: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Comments

A single line comment begins with //

This // can come at the beginning of the line or after a statement on the line :

System.out.println("On a withered branch" ); // Write first line of the poem

Multiline comments begin/* and end */ /* Program 1 Write out three lines of a poem. The poem describes a single moment in time, using 17 syllables. */

8

Page 9: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Data Types and Operators A data type is a set of values together with an associated set

of operators for manipulating those values. Who can think of some basic data types in the numerical

world? The logical world?

When an identifier is used as a variable it always has a defined data type

The meaning of the 0’s and 1’s in the computer depends on the data type being represented

We will begin by using the int, double, char and boolean data types – all lower case

Later in the course we’ll make use of additional data types including byte, short, long, and float

9

Page 10: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Data Types and Operators (2) All data in Java falls into one of two categories: primitive

data and objects. There are only eight primitive data types - int, double, char,

boolean, byte, short, long, and float. However, Java has many types of objects, and you can invent

as many others as you need. Any data type you invent will be a type of object.

Much more will be said about objects in future chapters (since Java is a object oriented programming language). The following is all you need to know, for now:

A primitive data value uses a small, fixed number of bytes. There are only eight primitive data types. A programmer can not create new primitive data types.

10

Page 11: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Some Notes on Objects

An object is a big block of data. An object may use many bytes of memory.

An object usually consists of many internal pieces.

The data type of an object is called its class.

Many classes are already defined in Java.

A programmer can invent new classes to meet the particular needs of a program.

11

Page 12: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Primitive Numeric Data Types Numbers are so important in Java that 6 of the 8 primitive data types are numeric types. There are both integer and floating point primitive types.

Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main

memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers.

Each primitive type uses a fixed number of bits. This means that if you are using a particular data type then the same number of bits will be used no matter what value is represented.

For example, all values represented using the short data type use 16 bits. The value zero (as a short) uses 16 bits and the value thirty thousand uses 16 bits.

All values represented using the long data type use 64 bits. The value zero (as a long) uses 64 bits, the value thirty thousand uses 64 bits, and the value eight trillion uses 64 bits.

Values that are large in magnitude (negative or positive) need more bits to be represented. This is similar to writing out numbers on paper: large numbers need more digits. If a value needs more bits than a particular data type uses, then it cannot be represented using that data type.

In the tables, E means "ten to the power of". So 3.5E38 means 3.5 x 1038

12

Page 13: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Primitive Numeric Data Types (2) Integer Primitive Data Types

Type Size Range

byte 8 bits -128 to +127

short 16 bits -32,768 to +32,767

int 32 bits -2 billion to +2 billion (approximately)

long 64 bits -9E18 to +9E18 (approximately)

Floating Point Primitive Data Types

Type Size Range

float 32 bits -3.4E38 to +3.4E38

double 64 bits -1.7E308 to 1.7E308

Remember: Integer data types reserve the leftmost bit to indicate positive (o) or negative (-1) in two’s complement format

13

Page 14: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Numeric Operators

Operator Meaning precedence

- unary minus highest

+ unary plus highest

* multiplication middle

/ division middle

% remainder /modulus middle

+ addition low

- subtraction low

14

Page 15: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Numeric Operators (2)

All of these operators can be used on floating point numbers and on integer numbers. The % operator is rarely used on floating point.

When mixing floating point numbers and integer numbers, floating point takes precedence – this is called casting

An integer operation is always done with 32 bits or more. If one or both operand is 64 bits (data type long) then the operation is done with 64 bits. Otherwise the operation is done with 32 bits, even if both operands are smaller than 32 bits. For example, with 16 bit short variables, the arithmetic is

done using 32 bits:

15

Page 16: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Integer Arithmetic

In integer arithmetic you always truncate

7/2 = 3

11/4 = 2

The modulus operator gives you the remainder

7%4 = 3

9%2 = ?

Any ideas on where the % can be helpful?

Note: the sign of the result of a%b is always the sign of a (the dividend).

16

Page 17: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Mixed Arithmetic Arithmetic

If both operands are integers, then the operation is an integer operation. If any operand is double, then the operation is double.

7.1+7.4 = 14.5

7.0+7.4 = 14.4

7+7.4 = 14.4

(15/2) +7.4 = ?

(15%2) + 7.4 = ?

Note: Unless otherwise declared all decimals are assumed

to be of type double

17

Page 18: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Type char Type char is the set of all characters found on the standard

keyboard, and thousands of other characters as well. Type char is denoted using single quotes ‘A’ , ‘5’ Characters are typically stored in ASCII code in single bytes Java uses Unicode – 2 byte representations that increases the

number of characters that can be represented from 255 to 65536 unique characters Note: Keyboard letters in ASCII Code and Unicode have the same

value – i.e. “A” = 65 ie 01000001 in ASCII or 00000000010000001 in Unicode

You can add and subtract type char – they are actually treated like integers when adding i.e. ‘A’ +1 = ‘B’ 0r 0000000001000010 i.e. 66

18

Page 19: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

String A String is an object, not a basic data type. A String is a sequence of characters enclosed in double quotes Java provides a string class Strings can be concatenated

“I am” + “ a man” = “I am a man”

Strings and values Everything depends on the order “The sum of two numbers is ” + (5*2) prints as

The sum of two numbers is 10

Why? You always work from inside the parentheses outwards

However (“The sum of two numbers is 5”) + 2 prints as

The sum of two numbers is 52

In Chapter 9 we do a lot more with String objects

19

Page 20: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Type boolean

Type boolean identifiers can have only one of two values – true or false.

There are three operators

&& - means and

|| - means or

! - means not

p q p&&q (and) p||q (or) !p (not

true true true true false

true false false true false

false true false true true

false false false false true

20

Page 21: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Switches and Boolean Logic

21

X A B Y

To get from A to B both X and Y must be closed – X&&Y

A B

X

Y

To get from A to B either X or Y must be closed – X||Y

A

A

Page 22: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Relational Operators Operator Description Example (with A=2, B=5

== Checks if the value of two operands are equal or not, if

yes then condition becomes true. (A == B) is not true.

!= Checks if the value of two operands are equal or not, if

values are not equal then condition becomes true. (A != B) is true.

>

Checks if the value of left operand is greater than the

value of right operand, if yes then condition becomes

true.

(A > B) is not true.

< Checks if the value of left operand is less than the value

of right operand, if yes then condition becomes true. (A < B) is true.

>=

Checks if the value of left operand is greater than or

equal to the value of right operand, if yes then condition

becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal

to the value of right operand, if yes then condition

becomes true.

(A <= B) is true.

The result of applying a relational operator is a true or false value

22

Page 23: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Operator Hierarchy Priority Operators Operation Associativity

1

[ ] array index

left () method call

. member access

2

++ pre- or postfix increment

right

-- pre- or postfix decrement

+ - unary plus, minus

~ bitwise NOT

! boolean (logical) NOT

(type) type cast

new object creation

3 * / % multiplication, division, remainder left

4 + - addition, subtraction

left + string concatenation

5

<< signed bit shift left

left >> signed bit shift right

>>> unsigned bit shift right

6

< <= less than, less than or equal to

left > >= greater than, greater than or equal to

instanceof reference test

7 == equal to

left != not equal to

8 & bitwise AND

left & boolean (logical) AND

9 ^ bitwise XOR

left ^ boolean (logical) XOR

10 | bitwise OR

left | boolean (logical) OR

11 && boolean (logical) AND left

12 || boolean (logical) OR left

13 ? : conditional right

14

= assignment

right

*= /= += -= %= <<= >>= >>>= &= ^= |=

combinated assignment

• When in doubt use parentheses

• The hierarchy is very similar to what you know from algebra

• When there is an equivalent hierarchy level and no parentheses you evaluate from left to right

23

Page 24: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Some Examples

5>4 – true

4>5 – false

‘A’ < ‘B’ – true

(5>4) || (4>5) - ?

(5>4) && (4>5) - ?

24

Page 25: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Casting

When evaluating any expression with operands of different types Java first promotes or casts the operand of the “smaller” data type

By smaller we mean the range

byte is smaller than short which is smaller than int which is smaller than long which is smaller than float which is smaller than double

boolean expressions are not cast

char automatically casts up to int, not to short

25

Page 26: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Mixing Data Types

Remember that without parentheses you follow the hierarchy

Mixed integer/decimal addition is cast to decimal when the mixing occurs

(10.0+5) = 15.0

10/4*(18.0) = 36.0

(5/9) *(212.0 -32.0) = 0

Note: Integers can be of type byte, short, int, long

Decimal can be of type double or float

26

Page 27: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Casting With Strings and Characters

‘A’ + ‘B’ = 131 (integer)

‘A’ + “B” = AB (String)

“A” + “B” = AB (String)

“” + ‘A’ + ‘B’ = AB (String) – ‘A’ gets cast to string

‘A’ + ‘B’ + “” = 131 (String)

3 + 4 + “” = 7 (String)

“” + 3 + 4 = 34 (String)

Key is that without parentheses we are reading left to right

27

Page 28: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Printing and Special Characters

System.out.println(“ abc”) // prints the string and a character return

System.out.print (“abc”) // prints a string without a character return

Escape sequences inside the string can be used control printing

Escape Sequence Character

\n newline

\t tab

\b backspace

\f form feed

\r return

\" " (double quote)

\' ' (single quote)

\\ \ (back slash)

\uDDDD character from the Unicode character set (DDDD is four hex digits) 28

Page 29: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Printing Example public class Printanode

{

public static void main (String[] args)

{

System.out.println (“He wrote his code”);

System.out.print(“\tHe indented well\n”);

System.out.println(“\tTill he was done”);

System.out.print(“\nThe Author”);

}

}

He wrote his code

He indented well

Till he was done

The Author

29

Page 30: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Some Other Examples Evaluate as true or false

true || false && 3 < 4 || !(5==7)

(true || (false && (3 < 4))) || !(5==7) – putting in the parentheses correctly always helps

(true || (false && true)) || !false

(true || false)|| true

true || true

true

30

Page 31: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Programming Exercise - Class (1) Exercise 6. Triangle

Write a program that prints the triangle:

*

**

***

****

*****

******

31

Page 32: Expressions and Data Types CSC 121 Fall 2014 Howard Rosenthal€¦ · Key Terms and Definitions (2) Braces For every left brace { there is a right brace } that matches. Usually there

Programming Exercise - Lab (1) Exercise 7. Triangle With Initials

Write a program that prints the triangle:

*

**

*H*

**G*

***R*

******

32