0% found this document useful (0 votes)
21 views39 pages

2.1 - Tracing Plus Methods

Uploaded by

Md. Obaydullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views39 pages

2.1 - Tracing Plus Methods

Uploaded by

Md. Obaydullah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

XPD124 Programming Fundamentals

Code Tracing

Week 2

6.Tracing Code by Hand


class and object Appendix: Code Tracing Problems
method 7. Methods in Self-contained Programs
control structure
statement
Tasks started last week and this week

1PP Hello World

• Install the JDK and VS Code software


• Take screenshots to show it worked
• Create a small program that displays
several lines of text

2PP Code Tracing and Code


Writing
• Code Tracing, and also create a small
program
Activity: Swap Two Values
Create new box C
C = A so C [3] this is to
START keep 3 intact to save it GOAL
for when we swap and
assign it to B
3 A = B so A [5]
A A 5
B = C so B [3]
B 5 B 3

You can only


• copy values between boxes
• create new labelled boxes
Why code reading is a useful skill
Reading and writing are complementary skills

Can diagnose and


fix errors in existing
program
Can predict
Ability to read code
program behaviour
Can recognise and
avoid errors before
running program
Tracing: essential tools

Paper & pen (or text editor)

Knowledge of the programming


language’s semantics
✓ A mental model of computer memory
(we will use a table holding values)
✓ The effect of assignment statements
✓ The order in which parts of a statement are
executed by the computer
✓ The behaviour of methods that are called
If unsure about the effect of a statement: ask for help,
consult documentation or write a small program to find out
Demonstrations & Activities
Let’s trace some code
• including declaration, assignment & simple expressions

You trace some code


• and we’ll check it together

Implementing an action-oriented method


• making a sequence of actions easily reusable

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

5. System.out.println("b was " + b);


6. c = b / a;
7. b = c + a; //same as saying 2+5
8. System.out.println("b is now " + b);
Demonstrations & Activities: Tracing
Let’s trace some code
• including declaration, assignment & simple expressions

You trace some code


• and we’ll check it together

Implementing an action-oriented method


Implementing a function
You trace some code

Activity: Trace the execution of the following code


by creating a tracing table
Line x y p q Output
1. double x, y; 2 7
3 3
2. int p = 7;
4 42
3. int q = 3;
5 84.0
4. p = (p + q) * (p - q) + 2;
6 40.0
5. x = p * 2; 7 2
6. y = p - 2; 8
7. p = 84 / p; (7+ 3) * (7-3) + 2
10 * 4 + 2
8. 40 + 2
Demonstrations & Activities: Methods
Let’s trace some code
• including declaration, assignment & simple expressions

You trace some code


• and we’ll check it together

Implementing an action-oriented method

Implementing a function
XPD124 Programming Fundamentals

Solving Problems with Computers:


Using ‘Primitive’ Data

class and object 04 Working with Primitive Data


method
control structure
statement
Template for a program

public class ClassName { Program

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

Expression: anything that can be evaluated to


produce a single value
1 + 1
"Hello"
2
Variable declaration
• Planning (pseudocode)
Variables:
type identifier, short description
int myAge, age in years

• Implementation
type name identifier ; Variable Declarations

type name identifier = expression ;

int myAge; //age in years


double pi = 3.14159;
Turtle drawingTool;
Primitive versus object types

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

Why should we care? Gangnam Style


http://www.abc.net.au/news/2014-12-05/gangnam-style-psy-gallops-beyond-youtube-counter/5945606
Characters and Booleans
Characters (see Appendix C) Booleans

• char 16 bits • boolean > 1 bit


any one of ~65,536 value is true or false
Unicode characters
e.g., 'a' or 'Z' or 'Я' or '子'
• single characters only

char letter = 'a’;


String test = “true”;
boolean isFresh = true;
Primitive wrappers

int Integer Also: Byte, Short, Long

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.

• numerals with a decimal point


double • 1. 1.0 2.5 3.14159 etc.

• character in single quotes


char • 'a' 'z' '1'

boolean • true false


A word about Strings
Strings are so common
they have their own Strings contain
literal representation characters

"This is a string literal"

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

Type of expression must


myAge = 18; be compatible with type
pi = 3.14159; of variable
drawingTool = new Turtle();
Constants
365 in a
12 in a
24 in a
final double taxPercentage = 12.5;
A constant is a named value (i.e., a variable)
whose value, once assigned, cannot be changed
during program execution
Constant Declarations
final type name IDENTIFIER = expression ;
final type name IDENTIFIER ; Can only be assigned once after this
XPD124 Programming Fundamentals

Solving Problems with Computers:


Importing and using objects

class and object 05 Using Objects


method
control structure
statement
What if we wanted to model > 1?
public class PersonDatabase {
public static void main(String[] args) {
int age;
char gender;
int height; Only good enough
double weight; for one person
boolean wearsGlasses;

//Lots of code to store values


// and do something with them
}
}
Primitive versus object types

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

ClassName identifier ; Object Declarations

ClassName identifier = new ClassName ( arguments );

The constructor is a special method in the


class that performs initialisation actions on
the new object
Examples
String title;
Turtle fred;
Scanner sc;

title = new String(); //creates a new, empty string


fred = new Turtle();
//Scanner's constructor takes an argument
sc = new Scanner( System.in );

//Or

Turtle arthur = new Turtle();


//arthur is a different Turtle object to fred
A sample complete program
import java.util.Scanner;

public class CreateAnObject {

public static void main(String[] args) {


String word; Declaration
Scanner sc = new Scanner(System.in);
Class names
Declaration and instantiation (creation)
word = sc.next();
System.out.println("The word was " + word);
}

}
importing classes

To use a class defined in some package…


java.util

Scanner

Option 1: Use fully-qualified name Option 2: Import it


in declaration and instantiation
import java.util.Scanner;
...
java.util.Scanner sc; public class WithImport {
sc = new java.util.Scanner(System.in); public static void main(String[] args) {
... Scanner sc;
sc = new Scanner(System.in);
}
}
java.lang package and import wildcards
Contents of java.lang package always available
java.lang
Integer
String
System etc.

Can import everything from a package with *


e.g., import java.util.*;
import KIT101.turtle.*;
(but better practice to import only what you need)
XPD124 Programming Fundamentals

Solving Problems with Computers:


Some commonly used objects
plus one we provide for practice

class and object 05 Using Objects


method
control structure
statement
Some (of many) useful Java classes

From the Java Class Library From this unit


• String of characters (i.e., text) • Turtle graphics
• Scanner for reading user input
• Random number generator
• Math utilities
• System utilities (& text output)

Click the class name to go to that slide


String class
Import Instantiation
• Not required String s = new String("not necessary");
String s2 = "can use a literal";

java.lang

Special features Useful methods


• immutable (cannot be changed) char charAt(int i)
• concatenation (joining) operator + int indexOf(char c)
int compareTo(String s)
• can access character at each
boolean equals(String str)
position, starting from 0 String substring(int startAt,
int endBefore)

see Strings*.java
Scanner class
Import Instantiation
import java.util.Scanner; Scanner sc;
sc = new Scanner(System.in);

System.in is a stream of characters


java.util from ‘standard input’; often the
keyboard

Warnings Useful methods


• nextType methods read next value int nextInt()
of that type up to whitespace double nextDouble()
boolean nextBoolean()
• next() reads next word (up to next
String next()
whitespace)
String nextLine()
• nextLine() reads entire line,
including any whitespace
Random class
Import Instantiation
import java.util.Random; Random rand = new Random();
Random rand2 = new Random(123);

123 is a random seed


java.util

Pseudorandom Useful methods


• Computers do not generate truly int nextInt(int limit)
random numbers but sequences of double nextDouble()
numbers that are sufficiently close void setSeed(long seed)
to random
• Setting the random seed allows the
same sequence to be produced
Turtle class
Import Instantiation
import kit101.turtle.Turtle; Turtle t = new Turtle();

kit101.turtle

Requires that kit101 and turtle folder are


in same folder as your program

Initial state Useful methods


• position (centre of world) void move(double dist)
• direction (facing east) void moveTo(int x, int y)
void turn(double deg)
• pen down? (true)
void penUp()
• pen colour (black) void penDown()
void setColor(java.awt.Color c)
Math class
Import Instantiation
Not required Not possible

java.lang

A utility class Useful methods (lots more)


• Math functions int abs(int num)
• Mathematical constants: double abs(double num)
int max(int n1, int n2)
• π Math.PI
double sin(double angle)
• e Math.E
System class
Import Instantiation
Not required Not possible

java.lang

A utility class; includes Some System.out methods


• static final streams for standard void print(String s)
input, standard output, and void println(String s)
standard error: System.in, void println(int n)
System.out & System.err void println(double d)
void println(boolean b)
• System.out is PrintStream object
void println(char b)

You might also like