Object Java Oriented Programming Programming

From To Java CSC10 – Spring 2016

Object Oriented Programming Classes

. Many objects are related to . This means that your each other – having the same program consists of a series abilities and attributes of objects that will interact with each other . These objects belong to the same class – which is a . An object is very abstract can classification of related be anything objects

5/1/2016 Sacramento State - CSc 10A 3 5/1/2016 Sacramento State - CSc 10A 4

Classes Example Properties

. "Cat" Class properties can include: . A class describes what an • name object will store, how it behaves, etc… • fur color • breed . Properties contain data about the object . "Student" Class properties can include: • name . Methods describe how the • major treats data (its and others) • academic level – freshman, junior, …

5/1/2016 Sacramento State - CSc 10A 5 5/1/2016 Sacramento State - CSc 10A 6

1 Example Methods Class Inheritance

. "Cat" Class methods: • scratch . Classes can also "inherit" from classes • purr . When a class inherits another: • sleep • gets all the features of the original class . "Student" Class methods: • but can extend its functionality • study • allows work, created previously to become the • play on smart phone foundation of a more advanced class • sleep

5/1/2016 Sacramento State - CSc 10A 7 5/1/2016 Sacramento State - CSc 10A 8

Instances / Objects Instances / Objects

. Classes just describe the . Instances will have all the behavior of some "object" features of its class . They don't do anything . So, different instances of the . In object-oriented same class share the same programming, you will create features instances of these classes – . But, each instance is a i.e. objects different and unique

5/1/2016 Sacramento State - CSc 10A 9 5/1/2016 Sacramento State - CSc 10A 10

Example Classes & Instances

. "Game" Class can have instances of: • Pac-Man • Call of Duty Introduction to • World of Warcraft Java . "Food" Class can have instances of: • ice cream • pizza • top ramen Start the coffee maker – seriously...

5/1/2016 Sacramento State - CSc 10A 11

2 What is Java? History of Java

. The Java Programming Language was created by . Java followed a long Sun Microsystems evolutionary chain that started with the C . Currently, it is one of the programming language most popular languages . C was designed by Dennis . Although Sun collapsed Ritchie at Bell Laboratories in (purchased by Oracle), Java the1970's survived

5/1/2016 Sacramento State - CSc 10A 13 5/1/2016 Sacramento State - CSc 10A 14

C-riously Popular And Along Comes Java

. C became extremely popular . When Java was developed, • minimalistic C/C++ had been in use for • made efficient programs on early machines over 20 years . C++ extended the concepts of C . So, to aid programmers... • added object oriented programming • Java uses a syntax very similar • was backwards compatible... C++ could run C to C++ programs • Java as most of the same • still used today semantics as C++

5/1/2016 Sacramento State - CSc 10A 15 5/1/2016 Sacramento State - CSc 10A 16

However, it is different The Result...

. Java contains many advanced features . However, Java is not . But, has a very symbolic syntax compatible with C++ • contains very few "words" - not English-like . It removed the low-level • so, programs are not easy to read at first features of C++ . It is not a beginners language . But, it will still work on • syntax it can be intimidating snippets of code • you must type of bunch of "weird" stuff you won't understand at first

5/1/2016 Sacramento State - CSc 10A 17 5/1/2016 Sacramento State - CSc 10A 18

3 Structure of Java Programs

. Java programs consist of Structure of series of class definitions Java . Each class contains local variables (properties) and Programs functions . Each function contains its own local variables as well as What the heck am I looking at? statements

5/1/2016 Sacramento State - CSc 10A 20

What are Statements? What are Statements?

. Statements can be grouped together into a . A statement will carry out a specific task block . Statements are executed in order from the . Some types of statements… first listed to the last • calls to other functions . In Java, you can create your own and use • control – looping, etc… ones created for you • create variables

5/1/2016 Sacramento State - CSc 10A 21 5/1/2016 Sacramento State - CSc 10A 22

Structure of a Java Program

Data about class Java Data Types Used by Method

What information Java can hold

5/1/2016 Sacramento State - CSc 10A 23

4 Data in Java Integers

. Used to store whole numbers . Java classes are made of . Java has three data types other classes or some that store integers primitive types . Why three? . Primitive types are not really • more bytes you use to store a classes, but data that the value, the larger can be processor understands • however, it will take more memory

5/1/2016 Sacramento State - CSc 10A 25 5/1/2016 Sacramento State - CSc 10A 26

Integer Examples Integer Data Types

Data Type Range of values Bytes . 1 byte -128 .. 127 1 . 5

. -100 short -32,768 .. 32,767 2 . 1846 -2,147,483,648 .. int 4 . 1947 2,147,483,647

. -12345 -9,223,372,036,854,775,808 .. long 8 9,223,372,036,854,775,807

5/1/2016 Sacramento State - CSc 10A 27 5/1/2016 Sacramento State - CSc 10A 28

Real Numbers Real Numbers

. Real numbers in Java are . Java has two data types for called "floating-point" storing real numbers . Why call it a float? . Why? • name is based on how it is • again, you might need to use actually stored more bytes to store larger • the decimal place is "floats values around" like it does in scientific • but, it will cost more memory notation

5/1/2016 Sacramento State - CSc 10A 29 5/1/2016 Sacramento State - CSc 10A 30

5 Floating-Point Examples Floating Point Data Types

Data Type Range of values Bytes . -6.78 . 3.1415 10-38 to 10+38 float Both positive and negative 4 . 1.618 About 6 digits precision . 2.71828 . -355.1234 10-308 to 10+308 double Both positive and negative 8 . 1234.0 Note the zero! About 15 digits precision

5/1/2016 Sacramento State - CSc 10A 31 5/1/2016 Sacramento State - CSc 10A 32

Character Data Type Character Examples

. Used to store letter individual . 'A' letters, digits, symbols, etc… . '4' Space . These are the keys you have . ' ' on your keyboard . '$' . In Java, chars are delimited . '&' by single quotes (also called apostrophes) . '^'

5/1/2016 Sacramento State - CSc 10A 33 5/1/2016 Sacramento State - CSc 10A 34

Boolean Data Type Primitive Data Type Summary

Data Type Range of values

byte -128 .. 127 . Used to store either a true or false value short -32,768 .. 32,767 . These are used with Boolean-Expressions int -2,147,483,648 .. 2,147,483,647 to store flags long -9,223,372,036,854,775,808 .. -9,223,372,036,854,775,807 . This is just how you did it in pseudocode float 10-38 to 10+38, positive or negative, about 6 digits precision and Flowgorithm double 10-308 to 10+308 , positive or negative, about 15 digits precision char Unicode characters (generally 16 bits per char)

boolean True or false

5/1/2016 Sacramento State - CSc 10A 35 5/1/2016 Sacramento State - CSc 10A 36

6 How do you store words? Examples of Strings

. What if you want to store a word? . "Sac State" • text is really just a long series of characters • so, Java implements these in memory using . "Computer Science" multiple chars called a string . "Joe Gunchy" . Java denotes a string literal with double . "Hornet" quotes . "1947" . These are stored using a class – so a . "Pac-Man" String is not a primitive data type

5/1/2016 Sacramento State - CSc 10A 37 5/1/2016 Sacramento State - CSc 10A 38

Characters

. Characters are actually More on integers . Each has a unique value Characters • characters and their matching values are a "character set" • there have been many characters sets developed over How Text is Stored time

5/1/2016 Sacramento State - CSc 10A 40

Java Escape Sequences Java Escape Sequences

. Java has help escape . Often you want to add a sequences start with a control character do your backslash program . This is followed by another . … but you can't type them character that represents the control character

5/1/2016 Sacramento State - CSc 10A 41 5/1/2016 Sacramento State - CSc 10A 42

7 Important Control Characters Adding characters you can't type

NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI Code Value Description \a DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 7 Alert (Bell)

sp ! " # $ % & ' ( ) * + , - . / \b 8 Backspace

0 1 2 3 4 5 6 7 8 9 : ; < = > ? \t 9 Tab

@ A B C D E F G H I J K L M N O \n 10 New Line (Line Feed)

P Q R S T U V W X Y Z [ \ ] ^ _ \v 11 Vertical tab

` a b c d e f g h i j k l m n o \f 12 Form feed (new printer page)

p q r s t u v w x y z { | } ~ DEL \c 13 Carriage return

5/1/2016 Sacramento State - CSc 10A 43 5/1/2016 Sacramento State - CSc 10A 44

Some Convenient Codes

Code Description \" Double quote. Allows double quotes inside string literals. Java \' Single quote. Allows you to define a single quote in a character literal. Identifiers

\\ Slash. Allows a slash (since it is used for special codes)

\xhh Any character with hexadecimal value hh Using Memory for Data

5/1/2016 Sacramento State - CSc 10A 45

Identifier Rules: Format Identifier Rules: Case Sensitive

. Java identifiers use the same de-facto standard used by . Identifiers are case sensitive most languages . Uppercase letters do not . They start with letter followed match lowercase letters by a series of letters, . e.g. Result is NOT the same numbers, or underscores as result . No spaces

5/1/2016 Sacramento State - CSc 10A 47 5/1/2016 Sacramento State - CSc 10A 48

8 Identifier Rules: Reserved Reserved Words of Java

abstract default goto package this

. Identifiers cannot be any of assert do if private throw Java's 50 reserved words boolean double implements protected throws and 3 reserved values break else import public transient byte enum instanceof return true . So, there are actually 53 case extends int short try

reserved words (although catch false interface static void Java books insist on 50) char final long strictfp volatile . These have a special class finally native super while meaning in the Java syntax const float new switch continue for null synchronized

5/1/2016 Sacramento State - CSc 10A 49 5/1/2016 Sacramento State - CSc 10A 50

Some Valid Variable Names Some invalid Variable Names

Dash – Not Valid

x first-name Starts with a evilMonkey 1040Form number

totalCost test 4 A space test4 break keyword

5/1/2016 Sacramento State - CSc 10A 51 5/1/2016 Sacramento State - CSc 10A 52

Identifier De-facto Standard

. Over the years, a de-facto standard emerged Java Variable . Identifiers should be written in Declaration all camel case . Put constants in all capital letters Using Memory for Data

5/1/2016 Sacramento State - CSc 10A 53

9 Java Variable Declaration Variable Declaration Syntax

. The syntax used, by Java, to int, float, char, etc… declare variables is incredibly terse . It basically consists of … type name ; • data type name (int, float, ...) • followed by the identifier identifier

5/1/2016 Sacramento State - CSc 10A 55 5/1/2016 Sacramento State - CSc 10A 56

What Happens? What Happens?

year pi Memory ? Memory ?

int year; float pi;

5/1/2016 Sacramento State - CSc 10A 57 5/1/2016 Sacramento State - CSc 10A 58

Assignment Statement

. Used to change the value of Storing Data a variable . Commonly known as an "assignment" statement . Used a lot!

Copying data into variables

5/1/2016 Sacramento State - CSc 10A 60

10 Assignment Statement Syntax What Happens?

Variable you declared Memory:

Target = Value; int year; year = 1947;

5/1/2016 Sacramento State - CSc 10A 61 5/1/2016 Sacramento State - CSc 10A 62

What Happens? What Happens?

year year Memory: ? Memory 1947?

int year; int year; year = 1947; year = 1947;

5/1/2016 Sacramento State - CSc 10A 63 5/1/2016 Sacramento State - CSc 10A 64

Syntax Overview

. Each statement is followed by a semicolon Statements . Why? • Java's syntax is free-flowing • you can put multiple statements on the same line • or indent them on the screen What the heck am I looking at?

5/1/2016 Sacramento State - CSc 10A 66

11 Function Call Syntax Syntax Overview

. To group statements, Name of function Semicolon Java uses curly-brackets . Sometimes, these are name ( Stuff ); also called "braces". Both terms are correct . Java uses these for any Parenthesis group of things as well

5/1/2016 Sacramento State - CSc 10A 67 5/1/2016 Sacramento State - CSc 10A 68

Behold… Java Code Behold… Java Code

Creates a class Start of program public class HelloWorld { public class HelloWorld { public static void main(String[] args) { public static void main(String[] args) { System.out.println("Hello, World"); System.out.println("Hello, World"); } } } } Output text

5/1/2016 Sacramento State - CSc 10A 69 5/1/2016 Sacramento State - CSc 10A 70

Documenting Your Code

. Java is very terse and cryptic Documenting . It is very easy to forget what your code actually does by Your Code looking at it . Remember, you might come back to your programs years after you wrote it Actually, very important to do!

5/1/2016 Sacramento State - CSc 10A 72

12 Documenting Your Code Comment Syntax

. Java allows you to insert your comments into a program . Basically, Java ignores all comments – so they don't affect your program in any way /* ... */ . They start with /* and end with */ . They can also span several lines Anything you want

5/1/2016 Sacramento State - CSc 10A 73 5/1/2016 Sacramento State - CSc 10A 74

Comments are helpful Line Comments

Ah, that helps! . It is common to put a comment after a statement /* My first program */ . So, Java also permits a line comment System.out.println("Hello, World"); . They start with // and take the rest of the line

5/1/2016 Sacramento State - CSc 10A 75 5/1/2016 Sacramento State - CSc 10A 76

Comment Syntax Comments are helpful

Line comment

// My first program // ... System.out.println("Hello, World");

That's a bit shorter

5/1/2016 Sacramento State - CSc 10A 77 5/1/2016 Sacramento State - CSc 10A 78

13 Whitespace Formatting guide

. Java ignores all spaces that are not inside single or double quotes . Indent each statement in a block . This is called whitespace – since it appears blank on a page of paper (or screen) • normally 3 or 4 spaces are used . Since whitespace is ignored • some people prefer to use the tab • programmers use it to format programs for readability • … but the tab can be problematic. A tab is displayed as a couple • basically, they indent statements inside a block spaces, but the number varies on • this is similar to how we display outlines different editors. • not only is it a good idea, I will enforce it

5/1/2016 Sacramento State - CSc 10A 79 5/1/2016 Sacramento State - CSc 10A 80

Formatting guide Proper Formatting

. Put one statement per line • Java allows you to put multiple statements one a single line public class HelloWorld { public HelloWorld { • … but it can get confusing int x = 0; . Comments are your friend System.out.println("Hello, World"); • add comments tell yourself (or } a reader) what you are doing } • also good to save who edited Indented! the file and when

5/1/2016 Sacramento State - CSc 10A 81 5/1/2016 Sacramento State - CSc 10A 82

Still Valid... Good Luck Reading This!

Mathematical public class HelloWorld {public HelloWorld {int x = 0;System.out.println Expressions ("Hello, World");}}

Wow, my computer can compute?

5/1/2016 Sacramento State - CSc 10A 83

14 Expressions Java vs. Other Languages

. Expressions are… . Not all programming • mathematical formulas languages have the same • follows the format you know precedence levels . Operator Precedence . They are pretty consistent for • order which operators are basic algebra computed . So, make sure to consult the • practically all languages have documentation precedence levels

5/1/2016 Sacramento State - CSc 10A 85 5/1/2016 Sacramento State - CSc 10A 86

Arithmetic Operators in Java Precedence Levels: Basic Math

Operator Name Operators Precedence Name * Multiplication Highest / Division - Unary Minus + Addition * / % Multiplication & Division % Modulus (remainder) - Subtraction & Unary Minus + - Addition & Subtraction Lowest

5/1/2016 Sacramento State - CSc 10A 87 5/1/2016 Sacramento State - CSc 10A 88

Tricky Example

"Usual Arithmetic float h;

Conversions" h = 5 + (11 / 12); System.out.println(h);

How Java does math - it is not "obvious"

5/1/2016 Sacramento State - CSc 10A 90

15 Tricky Example Output How Math Works in Java

5.0 . Every programming language has the "Usual Arithmetic Conversions" . These are the rules which specify how data is coerced when analyzing a mathematical 5.0? What happened to the inches? expression . You need to understand these or your program may fail like the last example

5/1/2016 Sacramento State - CSc 10A 91 5/1/2016 Sacramento State - CSc 10A 92

Basic Rules… Tricky Example

. When Java looks at an operator Both 11 and 12 are ints, so • result is based on the types of the operands float h; Java computes 0 • it only uses the highest precision that it sees . The basic rules are: • if either operand is a float, C will use a nice h = 5 + (11 / 12); floating point calculation System.out.println(h); • if both operands are int, C will use a integer calculation

5/1/2016 Sacramento State - CSc 10A 93 5/1/2016 Sacramento State - CSc 10A 94

Java vs. Other Languages Why the does Java do this?

. This behavior of C can cause problems for those not suspecting it . Java inherited this behavior from C . Other languages always use floating point • Visual Basic . C was designed… • • to be fast • Python • to be portable – be able to run on different processors without • Ruby many "issues" . … but not Java!

5/1/2016 Sacramento State - CSc 10A 95 5/1/2016 Sacramento State - CSc 10A 96

16 Why does Java do this? Tricky Example Fixed

. Floating point calculations take more time Now, this is a float to compute than integer math float h; literal . Many old processors • did not have floating point math h = 5 + (11.0 / 12); • … but they had simulate it (really slow) System.out.println(h); . So, this was a logical choice

5/1/2016 Sacramento State - CSc 10A 97 5/1/2016 Sacramento State - CSc 10A 98

Tricky Example: Fixed Output

5.916667 Casts

Much better!

Force Java to convert data

5/1/2016 Sacramento State - CSc 10A 99

Typecasting Typecasting

. Java has a "cast" unary . Java computations have operator some "gotchas" • forces Java to convert one data . However, Java also gives you type to another great control on how data will • syntax uses the name of the be analyzed data type surrounded by parenthesis

5/1/2016 Sacramento State - CSc 10A 101 5/1/2016 Sacramento State - CSc 10A 102

17 Okay, Let's get the Terminology Cast Operator Syntax Down…

int, float, etc… . Typecasting – when one type of data is converted to another . When the programming language converts the data implicitly, it is coerced (type) data . When the programmer explicitly specifies how data will be converted, it is cast

5/1/2016 Sacramento State - CSc 10A 103 5/1/2016 Sacramento State - CSc 10A 104

Precedence Levels: with Cast Tricky Example: Using a Cast

Operators Precedence Name Now, this is a float literal ( type ) Cast Highest float h;

- Unary Minus h = 5 + (float) 11 / 12; * / % Multiplication & Division System.out.println(h);

+ - Addition & Subtraction Lowest

5/1/2016 Sacramento State - CSc 10A 105 5/1/2016 Sacramento State - CSc 10A 106

Another Cast Example Cast Example Output

3.0 3.14 cast to int float pi;

pi = (int) 3.14159265; (int) converted 3.14 to System.out.println(h); 3 before assigning

5/1/2016 Sacramento State - CSc 10A 107 5/1/2016 Sacramento State - CSc 10A 108

18 Compound Assignments

Compound . The x = x + 1 notation … • is very cumbersome to write Assignments • and, it is not at all natural . Why not have a special notation for it?

Java makes complex tasks easy

5/1/2016 Sacramento State - CSc 10A 110

Compound Assignments Compound Assignments

Operator Name

. Well, Java does! += Increment the variable • Java has special assignment -= Decrement the variable operators that can increment, decrement, multiply and divide *= Multiply the variable • also made their way into Visual /= Basic Divide the variable %= Modulus the variable

5/1/2016 Sacramento State - CSc 10A 111 5/1/2016 Sacramento State - CSc 10A 112

Compound Increment Example Compound Increment Example Output

x = 5; 6

x += 1; Add 1 to x

System.out.println(h);

5/1/2016 Sacramento State - CSc 10A 113 5/1/2016 Sacramento State - CSc 10A 114

19 Compound Multiply Example Compound Multiply Example Output

20 x = 5; Multiply x by 4 x *= 4; System.out.println(h);

5/1/2016 Sacramento State - CSc 10A 115 5/1/2016 Sacramento State - CSc 10A 116

Increment / Decrement Operators Increment / Decrement Operators

Operator Name

. Incrementing or decrementing a variable by ++ Increment the variable by 1 1 is incredibly common . So, C offers another, even shorter, notation -- Decrement the variable by 1 for incrementing/decrementing a variable . It doesn't require a value, just the variable name and the operator

5/1/2016 Sacramento State - CSc 10A 117 5/1/2016 Sacramento State - CSc 10A 118

Wow, that is shortcut notation!

x += 1; Logical

The same Operators x++; Creating Powerful Logic

5/1/2016 Sacramento State - CSc 10A 119

20 Logical Operators in Java Logical Operators

. Logical operators in Java are Operator Name Rules very odd looking True only if both operands are True . They are very symbolic – and && And If either is False, the result is False are not as intuitive as "and", "or" and "not" True if either operand is True || Or . Don't worry... everyone gets False if both operands are False

confused by these True if the operand is False ! Not . In time, they will look natural False if the operand is True

5/1/2016 Sacramento State - CSc 10A 121 5/1/2016 Sacramento State - CSc 10A 122

Java Basic Precedence Levels Calculate The Result

7 - ! Highest ! (1 < 4) && 5 > 4 || ! (1 > 4) 6 * / ! True && 5 > 4 || ! False 5 + - ! False && 5 > 4 || ! True 4 == != > >= < <=

2 && False && True || True

1 || Lowest False || True

5/1/2016 Sacramento State - CSc 10A 123 5/1/2016 Sacramento State - CSc 10A 124

If Statement

. This statement ... • executes statements if the If Statements expression is true • can also contain a false branch . Uses blocks of statements . Found in virtually every programming language Allowing C to Make Decisions

5/1/2016 Sacramento State - CSc 10A 126

21 Basic Syntax Example

Either True or False age = 22; if (Condition) { if (age >= 21) { Statements printf("Kegger!"); } Multiple statements }

5/1/2016 Sacramento State - CSc 10A 127 5/1/2016 Sacramento State - CSc 10A 128

Example Output If Statement Syntax

Kegger! if ( Condition ) { Statements

} else { Processed if the Statements Condition is false }

5/1/2016 Sacramento State - CSc 10A 129 5/1/2016 Sacramento State - CSc 10A 130

Else Example Else Example Output

int age = 20 Milk! :(

if (age >= 21) { printf("Kegger! :)"); } else { printf("Milk! :("); }

5/1/2016 Sacramento State - CSc 10A 131 5/1/2016 Sacramento State - CSc 10A 132

22 While Statement Syntax

Loops while(condition) { Statements } Doing the same thing again and again … and again 5/1/2016 Sacramento State - CSc 10A 134

While Loop Example While Loop Example Output

int x = 0; 0 1 while(x <= 5) { 2 System.out.println(x); 3 x++; 4 } 5

5/1/2016 Sacramento State - CSc 10A 135 5/1/2016 Sacramento State - CSc 10A 136

For Statement Syntax Simple Loop Example

executed first

for (initial ; condition ; step) { for(x = 1; x <= 5; x++) { Statements System.out.println(x); } } executed after each block

5/1/2016 Sacramento State - CSc 10A 137 5/1/2016 Sacramento State - CSc 10A 138

23 Simple Loop Example Output

1 2 Running Your 3 Program 4 5 It's showtime

5/1/2016 Sacramento State - CSc 10A 139

How Programs are Executed Program Compilation

. Compiler • the computer actually can't understand code Compiler 100010011110 • so, this software translates it into the int year; 010100010111 year = 1974; 111010001000 processor's instructions 110000011110 x = y + z; 010101000100 . Interpreter 000011100010 • rather than translating the code, an application runs its own instructs to do the same thing • Javascript, for example, is interpreted

5/1/2016 Sacramento State - CSc 10A 141 5/1/2016 Sacramento State - CSc 10A 142

What? It didn't compile? Syntax Error

. Sometimes, the compiler will . Something you wrote doesn't tell you the program has errors follow the syntax rules of the language . Don't worry, even super- nerds get these . How do I fix it? . Common ones: • look to see which symbol you • syntax error forgot to type • non-defined error • in Java, it is common to forget • warnings the semicolon

5/1/2016 Sacramento State - CSc 10A 143 5/1/2016 Sacramento State - CSc 10A 144

24 Not Defined Error Warnings

. Not really an error, but the . You tried to call a function compiler thinks you are being that doesn't exist naughty . How do I fix it? . How do I fix it? • Java is case sensitive, make • understand why you are being sure you didn't use caps warned, there is a good reason • you might have forgot a letter • its best to have warning-free programs

5/1/2016 Sacramento State - CSc 10A 145 5/1/2016 Sacramento State - CSc 10A 146

25