1
Java
Programming
From Flowcharts To Java
(CSUS, Fall 2015)
Object
Oriented
Programming
Programming with "class"
This means that your
program consists of a series
of objects that will interact
with each other
An object is very abstract can
be anything
12/5/2015 Sacramento State - CSc 10A 3
Object Oriented Programming
Many objects are related to
each other – having the same
abilities and attributes
These objects belong to the
same class – which is a
classification of related
objects
12/5/2015 Sacramento State - CSc 10A 4
Classes
A class describes what an
object will store, how it
behaves, etc…
Properties contain data about
the object
Methods describe how the
treats data (its and others)
12/5/2015 Sacramento State - CSc 10A 5
Classes
"Cat" Class properties can include:
• name
• fur color
• breed
"Student" Class properties can include:
• name
• major
• academic level – freshman, junior, …
12/5/2015 Sacramento State - CSc 10A 6
Example Properties
2
"Cat" Class methods:
• eat
• purr
• sleep
"Student" Class methods:
• study
• play on smart phone
• sleep
12/5/2015 Sacramento State - CSc 10A 7
Example Methods
Classes can also "inherit" from classes
When a class inherits another:
• gets all the features of the original class
• but can extend its functionality
• allows work, created previously to become the
foundation of a more advanced class
12/5/2015 Sacramento State - CSc 10A 8
Class Inheritance
Classes just describe the
behavior of some "object"
They don't do anything
In object-oriented
programming, you will create
instances of these classes –
i.e. objects
12/5/2015 Sacramento State - CSc 10A 9
Instances / Objects
Instances will have all the
features of its class
So, different instances of the
same class share the same
features
But, each instance is a
different and unique
12/5/2015 Sacramento State - CSc 10A 10
Instances / Objects
"Game" Class can have instances of:
• Pac-Man
• Call of Duty
• Fallout 4
"Food" Class can have instances of:
• ice cream
• pizza
• top ramen
12/5/2015 Sacramento State - CSc 10A 11
Example Classes & Instances
Introduction to
Java
Start the coffee maker – seriously...
3
The Java Programming is
currently one of the most
popular languages in the
World
Java followed a long
evolutionary chain that
started with C (later C++)
12/5/2015 Sacramento State - CSc 10A 13
What is Java?
When Java was developed,
C/C++ had been in use for
over 20 years
So, to aid programmers...
• Java syntax very close to C++
• Java has most of the same
semantics as C++
12/5/2015 Sacramento State - CSc 10A 14
And Along Comes Java
However, Java is not
compatible with C++
It removed the low-level
features of C++
But, it will still work on
snippets of code
12/5/2015 Sacramento State - CSc 10A 15
However, it is different
Java contains many advanced features
But, has a very symbolic syntax
• contains very few "words" - not English-like
• so, programs are not easy to read at first
It is not a beginners language
• syntax it can be intimidating
• you must type of bunch of "weird" stuff you
won't understand at first
12/5/2015 Sacramento State - CSc 10A 16
The Result...
Structure of
Java
Programs
What the heck am I looking at?
Java programs consist of
series of class definitions
Each class contains local
variables (properties) and
functions
Each function contains its
own local variables as well as
statements
12/5/2015 Sacramento State - CSc 10A 18
Structure of Java Programs
4
A statement will carry out a specific task
Statements are executed in order from the
first listed to the last
In Java, you can create your own and use
ones created for you
12/5/2015 Sacramento State - CSc 10A 19
What are Statements?
Statements can be grouped together into a
block
Some types of statements…
• calls to other functions
• control – looping, etc…
• create variables
12/5/2015 Sacramento State - CSc 10A 20
What are Statements?
12/5/2015 Sacramento State - CSc 10A 21
Structure of a Java Program
Data about class
Used by Method
Java Data
Types
What information Java can hold
Java classes are made of
other classes or some
primitive types
Primitive types are not really
classes, but data that the
processor understands
12/5/2015 Sacramento State - CSc 10A 23
Data in Java
Used to store whole numbers
Java has three data types
that store integers
Why three?
• more bytes you use to store a
value, the larger can be
• however, it will take more
memory
12/5/2015 Sacramento State - CSc 10A 24
Integers
5
1
5
-100
1846
1947
-12345
12/5/2015 Sacramento State - CSc 10A 25
Integer Examples
Data Type Range of values Bytes
byte -128 .. 127 1
short -32,768 .. 32,767 2
int-2,147,483,648 ..
2,147,483,647 4
long-9,223,372,036,854,775,808 ..
9,223,372,036,854,775,8078
12/5/2015 Sacramento State - CSc 10A 26
Integer Data Types
Real numbers in Java are
called floating-point
Why?
• the name is based on how it is
actually stored
• the decimal place "floats
around" like it does in scientific
notation
12/5/2015 Sacramento State - CSc 10A 27
Real Numbers
Java has two data types for
storing real numbers
Why?
• again, you might need to use
more bytes to store larger
values
• but, it will cost more memory
12/5/2015 Sacramento State - CSc 10A 28
Real Numbers
-6.78
3.1415
1.618
2.71828
-355.1234
1234.0
12/5/2015 Sacramento State - CSc 10A 29
Floating-Point Examples
Note the zero!
Data Type Range of values Bytes
float
10-38 to 10+38
Both positive and negative
About 6 digits precision
4
double
10-308 to 10+308
Both positive and negative
About 15 digits precision
8
12/5/2015 Sacramento State - CSc 10A 30
Floating Point Data Types
6
Used to store letter individual
letters, digits, symbols, etc…
These are the keys you have
on your keyboard
In Java, chars are delimited
by single quotes (also called
apostrophes)
12/5/2015 Sacramento State - CSc 10A 31
Character Data Type
'A'
'4'
' '
'$'
'&'
'^'
12/5/2015 Sacramento State - CSc 10A 32
Character Examples
Space
Characters are combined
(into arrays) to form strings
Java denotes a string literal
with double quotes
These are stored using a
class – so a String is not a
primitive data type
12/5/2015 Sacramento State - CSc 10A 33
Strings
"Sac State"
"Computer Science"
"Joe Gunchy"
"Hornet"
"1947"
"Cheese"
12/5/2015 Sacramento State - CSc 10A 34
Examples of Strings
Often you want to add a control character do your program
Java has help escape sequences start with a backslash
This is followed by another character that represents the control character
12/5/2015 Sacramento State - CSc 10A 35
Java Escape Sequences
NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI
DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US
sp ! " # $ % & ' ( ) * + , - . /
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z [ \ ] ^ _
` a b c d e f g h i j k l m n o
p q r s t u v w x y z { | } ~ DEL
12/5/2015 Sacramento State - CSc 10A 36
Important Control Characters
7
12/5/2015 Sacramento State - CSc 10A 37
Adding characters you can't type
Code Value Description
\a 7 Alert (Bell)
\b 8 Backspace
\t 9 Tab
\n 10 New Line (Line Feed)
\v 11 Vertical tab
\f 12 Form feed (new printer page)
\c 13 Carriage return
Code Description
\" Double quote. Allows double quotes inside string literals.
\'Single quote. Allows you to define a single quote in a
character literal.
\\ Slash. Allows a slash (since it is used for special codes)
\xhh Any character with hexadecimal value hh
12/5/2015 Sacramento State - CSc 10A 38
Some Convenient Codes
Used to store either a true or false value
These are used with Boolean-Expressions
to store flags
This is just how you did it in pseudocode
and Flowgorithm
12/5/2015 Sacramento State - CSc 10A 39
Boolean Data Type
Java
Identifiers
Using Memory for Data
Java identifiers use the same
de-facto standard used by
most languages
They start with letter followed
by a series of letters,
numbers, or underscores
No spaces
12/5/2015 Sacramento State - CSc 10A 41
Identifier Rules: Format
Identifiers are case sensitive
Uppercase letters do not
match lowercase letters
e.g. Result is NOT the same
as result
12/5/2015 Sacramento State - CSc 10A 42
Identifier Rules: Case Sensitive
8
Identifiers cannot be any of
Java's 50 reserved words
and 3 reserved values
So, there are actually 53
reserved words (although
Java books insist on 50)
These have a special
meaning in the Java syntax
12/5/2015 Sacramento State - CSc 10A 43
Identifier Rules: Reserved
abstract default goto package this
assert do if private throw
boolean double implements protected throws
break else import public transient
byte enum instanceof return true
case extends int short try
catch false interface static void
char final long strictfp volatile
class finally native super while
const float new switch
continue for null synchronized
12/5/2015 Sacramento State - CSc 10A 44
Reserved Words of Java
x
evilMonkey
totalCost
test4
12/5/2015 Sacramento State - CSc 10A 45
Some Valid Variable Names
first-name
1040Form
test 4
break
12/5/2015 Sacramento State - CSc 10A 46
Some invalid Variable Names
Dash – Not Valid
Starts with a
number
A space
keyword
Over the years, a de-facto
standard emerged
Identifiers should be written in
all camel case
Put constants in all capital
letters
12/5/2015 Sacramento State - CSc 10A 47
Identifier De-facto Standard
Java Variable
Declaration
Using Memory for Data
9
The syntax used, by Java, to
declare variables is incredibly
terse
It basically consists of …
• data type name (int, float, ...)
• followed by the identifier
12/5/2015 Sacramento State - CSc 10A 49
Java Variable Declaration
type name ;
12/5/2015 Sacramento State - CSc 10A 50
Variable Declaration Syntax
int, float, char, etc…
identifier
12/5/2015 Sacramento State - CSc 10A 51
int year;
What Happens?
Memory ?
year
12/5/2015 Sacramento State - CSc 10A 52
float pi;
What Happens?
Memory ?
pi
Storing Data
Copying data into variables
Used to change the value of
a variable
Commonly known as an
"assignment" statement
Used a lot!
12/5/2015 Sacramento State - CSc 10A 54
Assignment Statement
10
Target = Value;
12/5/2015 Sacramento State - CSc 10A 55
Assignment Statement Syntax
Variable you declared
12/5/2015 Sacramento State - CSc 10A 56
int year;
year = 1947;
What Happens?
Memory:
12/5/2015 Sacramento State - CSc 10A 57
int year;
year = 1947;
What Happens?
Memory: ?
year
?
year
12/5/2015 Sacramento State - CSc 10A 58
int year;
year = 1947;
What Happens?
Memory 1947
Statements
What the heck am I looking at?
Each statement is followed by
a semicolon
Why?
• Java's syntax is free-flowing
• you can put multiple
statements on the same line
• or indent them on the screen
12/5/2015 Sacramento State - CSc 10A 60
Syntax Overview
11
name ( Stuff );
12/5/2015 Sacramento State - CSc 10A 61
Function Call Syntax
Name of function
Parenthesis
Semicolon To group statements,
Java uses curly-brackets
Sometimes, these are
also called "braces".
Both terms are correct
Java uses these for any
group of things as well
12/5/2015 Sacramento State - CSc 10A 62
Syntax Overview
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
12/5/2015 Sacramento State - CSc 10A 63
Behold… Java Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
12/5/2015 Sacramento State - CSc 10A 64
Behold… Java Code
Creates a class
Start of program
Output text
Documenting
Your Code
Actually, very important to do!
Java is very terse and cryptic
It is very easy to forget what
your code actually does by
looking at it
Remember, you might come
back to your programs years
after you wrote it
12/5/2015 Sacramento State - CSc 10A 66
Documenting Your Code
12
12/5/2015 Sacramento State - CSc 10A 67
Documenting Your Code
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
/* ... */
12/5/2015 Sacramento State - CSc 10A 68
Comment Syntax
Anything you want
/* My first program */
System.out.println("Hello, World");
12/5/2015 Sacramento State - CSc 10A 69
Comments are helpful
Ah, that helps!
It is common to put a comment after a
statement
So, Java also permits a line comment
They start with // and take the rest of the
line
12/5/2015 Sacramento State - CSc 10A 70
Line Comments
// ...
12/5/2015 Sacramento State - CSc 10A 71
Comment Syntax
That's a bit shorter
// My first program
System.out.println("Hello, World");
12/5/2015 Sacramento State - CSc 10A 72
Comments are helpful
Line comment
13
Java ignores all spaces that are not inside single
or double quotes
This is called whitespace – since it appears blank
on a page of paper (or screen)
Since whitespace is ignored
• programmers use it to format programs for readability
• basically, they indent statements inside a block
• this is similar to how we display outlines
• not only is it a good idea, I will enforce it
12/5/2015 Sacramento State - CSc 10A 73
Whitespace
Indent each statement in a
block
• normally 3 or 4 spaces are used
• some people prefer to use the tab
• … but the tab can be problematic.
A tab is displayed as a couple
spaces, but the number varies on
different editors.
12/5/2015 Sacramento State - CSc 10A 74
Formatting guide
Put one statement per line
• Java allows you to put multiple
statements one a single line
• … but it can get confusing
Comments are your friend
• add comments tell yourself (or
a reader) what you are doing
• also good to save who edited
the file and when
12/5/2015 Sacramento State - CSc 10A 75
Formatting guide
public class HelloWorld {
public HelloWorld {
int x = 0;
System.out.println("Hello, World");
}
}
12/5/2015 Sacramento State - CSc 10A 76
Proper Formatting
Indented!
public class HelloWorld {public HelloWorld
{int x = 0;System.out.println
("Hello, World");}}
12/5/2015 Sacramento State - CSc 10A 77
Still Valid... Good Luck Reading
This!
Mathematical
Expressions
Wow, my computer can compute?
14
Expressions are…
• mathematical formulas
• follows the format you know
Operator Precedence
• order which operators are
computed
• practically all languages have
precedence levels
12/5/2015 Sacramento State - CSc 10A 79
Expressions
Not all programming
languages have the same
precedence levels
They are pretty consistent for
basic algebra
So, make sure to consult the
documentation
12/5/2015 Sacramento State - CSc 10A 80
Java vs. Other Languages
Operator Name
* Multiplication
/ Division
+ Addition
% Modulus (remainder)
- Subtraction & Unary Minus
12/5/2015 Sacramento State - CSc 10A 81
Arithmetic Operators in Java
12/5/2015 Sacramento State - CSc 10A 82
Precedence Levels: Basic Math
Operators Precedence Name
- Unary Minus
* / % Multiplication & Division
+ - Addition & Subtraction
Highest
Lowest
"Usual
Arithmetic
Conversions"
How Java does math - it is not "obvious"
float h;
h = 5 + (11 / 12);
System.out.println(h);
12/5/2015 Sacramento State - CSc 10A 84
Tricky Example
15
5.0
12/5/2015 Sacramento State - CSc 10A 85
Tricky Example Output
5.0? What happened
to the inches?
Every programming language has the
"Usual Arithmetic Conversions"
These are the rules which specify how data
is coerced when analyzing a mathematical
expression
You need to understand these or your
program may fail like the last example
12/5/2015 Sacramento State - CSc 10A 86
How Math Works in Java
When Java looks at an operator
• result is based on the types of the operands
• it only uses the highest precision that it sees
The basic rules are:
• if either operand is a float, C will use a nice
floating point calculation
• if both operands are int, C will use a integer
calculation
12/5/2015 Sacramento State - CSc 10A 87
Basic Rules…
float h;
h = 5 + (11 / 12);
System.out.println(h);
12/5/2015 Sacramento State - CSc 10A 88
Tricky Example
Both 11 and 12 are ints, so
Java computes 0
12/5/2015 Sacramento State - CSc 10A 89
Java vs. Other Languages
This behavior of C can cause problems for
those not suspecting it
Other languages always use floating point
• Visual Basic
• Delphi
• Python
• Ruby
… but not Java!
Java inherited this behavior
from C
C was designed…
• to be fast
• to be portable – be able to run
on different processors without
many "issues"
12/5/2015 Sacramento State - CSc 10A 90
Why the does Java do this?
16
Floating point calculations take more time
to compute than integer math
Many old processors
• did not have floating point math
• … but they had simulate it (really slow)
So, this was a logical choice
12/5/2015 Sacramento State - CSc 10A 91
Why does Java do this?
float h;
h = 5 + (11.0 / 12);
System.out.println(h);
12/5/2015 Sacramento State - CSc 10A 92
Tricky Example Fixed
Now, this is a float
literal
5.916667
12/5/2015 Sacramento State - CSc 10A 93
Tricky Example: Fixed Output
Much better!
Compound
Assignments
Java makes complex tasks easy
The x = x + 1 notation …
• is very cumbersome to write
• and, it is not at all natural
Why not have a special
notation for it?
12/5/2015 Sacramento State - CSc 10A 95
Compound Assignments
Well, Java does!
• Java has special assignment
operators that can increment,
decrement, multiply and divide
• also made their way into Visual
Basic
12/5/2015 Sacramento State - CSc 10A 96
Compound Assignments
17
Operator Name
+= Increment the variable
-= Decrement the variable
*= Multiply the variable
/= Divide the variable
%= Modulus the variable
12/5/2015 Sacramento State - CSc 10A 97
Compound Assignments
x = 5;
x += 1;
System.out.println(h);
12/5/2015 Sacramento State - CSc 10A 98
Compound Increment Example
Add 1 to x
6
12/5/2015 Sacramento State - CSc 10A 99
Compound Increment Example
Output
x = 5;
x *= 4;
System.out.println(h);
12/5/2015 Sacramento State - CSc 10A 100
Compound Multiply Example
Multiply x by 4
20
12/5/2015 Sacramento State - CSc 10A 101
Compound Multiply Example Output
Incrementing or decrementing a variable by
1 is incredibly common
So, C offers another, even shorter, notation
for incrementing/decrementing a variable
It doesn't require a value, just the variable
name and the operator
12/5/2015 Sacramento State - CSc 10A 102
Increment / Decrement Operators
18
Operator Name
++ Increment the variable by 1
-- Decrement the variable by 1
12/5/2015 Sacramento State - CSc 10A 103
Increment / Decrement Operators
x += 1;
x++;
12/5/2015 Sacramento State - CSc 10A 104
Wow, that is shortcut notation!
The same
Logical
Operators
Creating Powerful Logic
Logical operators in Java are
very odd looking
They are very symbolic – and
are not as intuitive as "and",
"or" and "not"
Don't worry... everyone gets
confused by these
In time, they will look natural
12/5/2015 Sacramento State - CSc 10A 106
Logical Operators in Java
Operator Name Rules
&& AndTrue only if both operands are True
If either is False, the result is False
|| OrTrue if either operand is True
False if both operands are False
! NotTrue if the operand is False
False if the operand is True
12/5/2015 Sacramento State - CSc 10A 107
Logical Operators
12/5/2015 Sacramento State - CSc 10A 108
Java Basic Precedence Levels
7 - !
6 * /
5 + -
4 == != > >= < <=
2 &&
1 ||
Highest
Lowest
19
12/5/2015 Sacramento State - CSc 10A 109
Calculate The Result
! (1 < 4) && 5 > 4 || ! (1 > 4)
! True && 5 > 4 || ! False
False && True || True
False || True
! False && 5 > 4 || ! True
If Statements
Allowing C to Make Decisions
This statement ...
• executes statements if the
expression is true
• can also contain a false branch
Uses blocks of statements
Found in virtually every
programming language
12/5/2015 Sacramento State - CSc 10A 111
If Statement
if (Condition) {
Statements
}
12/5/2015 Sacramento State - CSc 10A 112
Basic Syntax
Either True or False
Multiple
statements
age = 22;
if (age >= 21) {
System.out.println("Kegger!");
}
12/5/2015 Sacramento State - CSc 10A 113
Example
Kegger!
12/5/2015 Sacramento State - CSc 10A 114
Example Output
20
if ( Condition ) {
Statements
} else {
Statements
}
12/5/2015 Sacramento State - CSc 10A 115
If Statement Syntax
Processed if the
Condition is false
int age = 20
if (age >= 21) {
System.out.println("Kegger!");
} else {
System.out.println("Milk!");
}
12/5/2015 Sacramento State - CSc 10A 116
Else Example
Milk!
12/5/2015 Sacramento State - CSc 10A 117
Else Example Output
Loops
Doing the same thing again and again
… and again
while(condition) {
Statements
}
12/5/2015 Sacramento State - CSc 10A 119
While Statement Syntax
int x = 0;
while(x <= 5) {
System.out.println(x);
x++;
}
12/5/2015 Sacramento State - CSc 10A 120
While Loop Example
21
0
1
2
3
4
5
12/5/2015 Sacramento State - CSc 10A 121
While Loop Example Output
for (initial ; condition ; step) {
Statements
}
12/5/2015 Sacramento State - CSc 10A 122
For Statement Syntax
executed first
executed after each
block
for(x = 1; x <= 5; x++) {
System.out.println(x);
}
12/5/2015 Sacramento State - CSc 10A 123
Simple Loop Example
1
2
3
4
5
12/5/2015 Sacramento State - CSc 10A 124
Simple Loop Example Output
Running Your
Program
It's showtime
Compiler
• the computer actually can't understand code
• so, this software translates it into the
processor's instructions
Interpreter
• rather than translating the code, an application
runs its own instructs to do the same thing
• Javascript, for example, is interpreted
12/5/2015 Sacramento State - CSc 10A 126
How Programs are Executed
22
12/5/2015 Sacramento State - CSc 10A 127
Program Compilation
Compiler100010011110
010100010111
111010001000
110000011110
010101000100
000011100010
int year;
year = 1974;
x = y + z;
Sometimes, the compiler will tell you the program has errors
Don't worry, even super-nerds get these
Common ones:
• syntax error
• non-defined error
• warnings
12/5/2015 Sacramento State - CSc 10A 128
What? It didn't compile?
Something you wrote doesn't
follow the syntax rules of the
language
How do I fix it?
• look to see which symbol you
forgot to type
• in Java, it is common to forget
the semicolon
12/5/2015 Sacramento State - CSc 10A 129
Syntax Error
You tried to call a function
that doesn't exist
How do I fix it?
• Java is case sensitive, make
sure you didn't use caps
• you might have forgot a letter
12/5/2015 Sacramento State - CSc 10A 130
Not Defined Error
Not really an error, but the
compiler thinks you are being
naughty
How do I fix it?
• understand why you are being
warned, there is a good reason
• its best to have warning-free
programs
12/5/2015 Sacramento State - CSc 10A 131
Warnings