2.1 - Tracing Plus Methods
2.1 - Tracing Plus Methods
Code Tracing
Week 2
Implementing a function
• making a calculation easily reusable
Demonstration
Line a b c Output
3 5
1. int a, b, c; 4 10
2. 5 b was 10
6 2
3. a = 5; 7 7
4. b = 10; 8 b is now 7
Implementing a function
XPD124 Programming Fundamentals
variable declarations
public static void main(String[] args) {
variable declarations Telling the computer what placeholders
for data your algorithm requires
statements The actions that your program will perform
}
}
Data has a type
“25” + “2”
What values 25 + 2 “252”
can be true
3.14159
represented 'a'
What –
+
operators can / ||
be applied % &&
Statements and expressions
Statement: a single instruction to the computer
System.out.println("Hello");
myTurtle.penDown();
• Implementation
type name identifier ; Variable Declarations
Class types
Primitive types
(objects)
• data only • data and
• one piece of methods
data (behaviour)
• may hold many
primitives and
other objects
Later in the unit: primitives and objects are stored in different areas of memory
Java primitive number types
Floating point (real)
Integers
numbers
• byte 8 bits • float 32 bits
-128 to 127 7-8 significant digits
• short 16 bits • double 64 bits
-32768 to 32767 15-16 significant digits
mostly mostly
• int 32 bits
use this
use this
-2147483648 to
2147483647
• long 64 bits
-9223372036854775808 to
int num = 10;
9223372036854775807
Also: Float
double Double
primitive class
types types
char Character • ‘wrap’ primitives
when an object
is needed
• have methods
boolean Boolean for working with
primitives
Value literals
Expressions that literally represent a single value
• Numerals with no decimal point
int • 1 2 1024 etc.
It has type
String
int num = 10; String is a class
type, not a
String message = “hello”; primitive
Assignment
Changes the value of a variable by assigning it the
value of an expression
• Planning (pseudocode)
identifier = expression value Read = as becomes
int myAge;
myAge = 25.6; //this is wrong because it is a double trying to be an
int
• Implementation
identifier = expression ; Variable Assignment
Class types
Primitive types
(objects)
• data only • data and
• one piece of methods
data (behaviour)
• may hold many
primitives and
other objects
Creating Objects
A variable either holds a primitive type, or it
holds a reference to, i.e. the address of, an
object
Actual object is created with new keyword
Declares reference only;
its value will be null
//Or
}
importing classes
Scanner
java.lang
see Strings*.java
Scanner class
Import Instantiation
import java.util.Scanner; Scanner sc;
sc = new Scanner(System.in);
kit101.turtle
java.lang
java.lang