80
COMP-202 Unit 1: Introduction Part C CONTENTS: More on methods and variables Computer Memory Binary

Unit 1: Introduction - McGill University School of ... · Unit 1: Introduction Part C CONTENTS: More on methods and variables ... COMP-202 - Introduction 16 Returning a value Methods

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

COMP-202Unit 1: Introduction

Part C

CONTENTS:More on methods and variablesComputer MemoryBinary

Announcements• Tutorial 2 starts Thursday. See WebCT for more

information•

• Main topics include: variables, methods, type-checking, and expressions

Assignment 1• Assignment 1 will be released on Wednesday. It

will be due January 21st•

• Worth 4%•

• The assignment will ask you to work with variables, expressions, and methods

• More information to come....

Dan's Office Hours

• McConnell Engineering Room 306•

• Wednesday : 11:30-1:30• Friday : 11:30-12:30• (might be a bit late if class runs

over)•

• Email Dan if these times do not work and we can make alternate arrangements

Next few lectures• Monday: Introduction to methods and

variables and more on Java structure • Today: Finish Monday + How memory in

a computer works • Friday : More on variables, expressions,

and types • Monday the 17th: basics of String

operations

Last Class

• Java structure• Using methods in your

program• Having methods give output• Storing things in your

program

Question : Java Structure

• What is the relationship between classes, methods, and statements in Java?

COMP-202 - Introduction 8

Structure of Java

File: “C.java”

Class C

Method a

Method b

A “class” can contain as many “methods” as you want.

In order to run your class, you need a main method

This structure is dictated by the designers of the Java language.

A “method” contains many statements or commandsA “statement” is a command or instruction

statement1

statement3statement4

statement2

Question : Java Structure

• What method must a Java class have in order to be run as a program?

• Why is this required?

Question : Method

• How can we know what kind of thing a method outputs?

• How can we know the specific value that a method outputs?

Question : Variables

• What are the two things we need to do to declare a variable in Java?

• What do we have to do to assign a variable?

Today

• More on Methods and Variables:

• Storing the output of a method in a variable

• Giving input to a method• Memory: How computers

store things

Goals for today

• Know how to store results in variables• Write a method that takes input from another method• Be able to call a method with various input• Know a bit about how memory works on a computer• Be able to device an “encoding scheme” to store

things in memory.

COMP-202 - Introduction 14

Method Structure public static outputType MethodName(input) {

}

-A Java method is a list of statements that has been given a name

-Methods always go inside of classes-They consist of a “header” and “body”-The header includes the name of the method as well as

its return (output) type and input arguments-Everything between the { and } is the method body

COMP-202 - Introduction 15

Methods• When you call a method, the computer will “jump”

from the place it was before to the method.•

• When it finishes the method, it will “jump” back.•

• When you run a Java program, the main method is called by your computer.

COMP-202 - Introduction 16

Returning a value

Methods can also give output. If you want the method to give an output, you write what you want it to output instead of the word void before the name of your method. For example

public static Flamingo GetPinkAnimal()--if you want the method to output flamingos

public static Pizza Dominos()--if you want it to output pizza

COMP-202 - Introduction 17

Outputting a valueIf you make your method output

something instead of void, you must write what it should output using a “return” statement. We often call this “returning a value”

/*The following function ReturnsANumber*/public static int ReturnANumber() {

return 0;}This means the method outputs 0.

COMP-202 - Introduction 18

Getting the outputIf you know a method has output, you can

use it by calling the method

public class GetANumber {public static void main(String[] args) {

System.out.println(ReturnANumber()); }

public static int ReturnANumber() {return 0;

}}

COMP-202 - Introduction 19

Declaring a variableTo declare a variable in Java, you first write the type you

want to store. Then you write the name you want to identify it with

type name;

This says to the Java compiler: “I want you to make space to store a type. In the future when I use name in a computation, I want that to refer to this space you created”

COMP-202 - Introduction 20

Setting the value of a variableTo store a value in a variable, after you declare it, use

the equal sign.

name = value;

Note: The = does not me “equals” in Java. It means “set name to be the value value”

COMP-202 - Introduction 21

What if you don't declare xIf you write

x = 5;

without declaring x, you will get a compiler error.

The error will complain that it does not recognize x.

COMP-202 - Introduction 22

Some basic types

int : stores an integer numberString : stores letters. For example “Hello

World”double : stores real numbers (fractions)long : stores a long integer (up to 9

quintillion!)float : like double, can store numbersboolean : stores either true or falsechar : stores one character

COMP-202 - Introduction 23

Mismatching types: Compiler error

int x;x = “Hello”What are the types of “Hello” and x

COMP-202 - Introduction 24

Declaration and initialization

It is also possible to declare a variable at the same time as you set it's value. For example,

int x = 5;String y = “Hello”;

COMP-202 - Introduction 25

Using variables later

Once you have set a variable, you can use it in later computations:

What do you think the following does?

int x = 5;int y = x + 3;System.out.println(y);

COMP-202 - Introduction 26

Storing the output of a method

You can also use variables to store the output of a method

Suppose you have a method named ReturnAnInteger that returns (or outputs) an int.

COMP-202 - Introduction 27

Storing the outputWhat would the following code do?

int x = ReturnAnInteger();System.out.println(x);

COMP-202 - Introduction 28

Storing the outputWhat would the following code do?

int x = ReturnAnInteger();System.out.println(x);

The first line does a lot of things. First it calls the method ReturnAnInteger() . It then stores the output from ReturnAnInteger() into the variable x. Because ReturnAnInteger() outputs or returns an int, we make x an int.

The second line, takes the stored value and prints it to the screen.

COMP-202 - Introduction 29

Storing the outputWhat about the following?

String x = ReturnAnInteger();System.out.println(x);

COMP-202 - Introduction 30

Storing the output

The type of your variable MUST match the return type of the method. Otherwise you will have the same problem with mismatched types

(There are a few exceptions that are okay, for example if you try to put an int into a double)

COMP-202 - Introduction 31

Giving Input to MethodsMethods can also have input

Everything between the ()'s in the method is input to the method.

public static int X-Squared(int x) {return x*x;

}

COMP-202 - Introduction 32

Giving Input to Methodspublic static int X-Squared(int x) {

x*x;}

This method takes as input one value. This value must be an int.

We often refer to the input a method takes as the method's arguments

What do you think this method does?

COMP-202 - Introduction 33

Calling a method with arguments

The previous method takes as input one int and outputs one int.

Because it takes as input an int, you must “give” or “pass” it an int as input. Thus to call it, you should write

System.out.println(X-Squared(3));

COMP-202 - Introduction 34

Calling a method with arguments

Inside the method you called, the variable on the method header line will be assigned the value of the argument you gave.

e.g. If you call the method X-Squared(3)

Then inside the method, the value of the variable x will be 3

COMP-202 - Introduction 35

Calling a method with arguments

What if you called it by writing

X-Squared();

(without any input)?

COMP-202 - Introduction 36

What will the following snippet output?

public class Mystery {.....//some other stuff here

int x = 2;int y = X-Squared(x);System.out.println(y);

}

COMP-202 - Introduction 37

What will the following snippet output?

public class Mystery {.....//some other stuff here

int x = 2;int y = X-Squared(x+2);System.out.println(y);

}

COMP-202 - Introduction 38

What will the following snippet output?

public class Mystery {.....//some other stuff here

int x = 2;int y = X-Squared(x+2);System.out.println(y+2);

}

COMP-202 - Introduction 39

Methods with more than one argument

Methods can also have more than one argument as input. For example

public static int Add(int x, int y) {return ?????

}

What could we write instead of ????? if we wanted the method to output the addition of x and y?

COMP-202 - Introduction 40

Methods with more than one argument

Methods can also have more than one argument as input. For example

public static int Add(int x, int y) {return x+y;

}

What could we write instead of ????? if we wanted the method to output the addition of x and y?

COMP-202 - Introduction 41

Exercises• 1)Make sure you can compile HelloWorld.java• 2)Take the program from the slides with the method

PrintMoreStuff() in it. Make sure you can compile it• 3)Try to change the method PrintMoreStuff so that it

takes as a method an int and prints the value of the int instead of always printing the same thing.

• 4)Call this method 5 times from your main() method. Make sure one time is with the value stored in a variable

• 5)Now change PrintMoreStuff() so that it takes two ints as input and prints the sum of the 2 values

COMP-202 - Introduction 42

Exercises• Write a program that does the following:•

• 1)Creates two doubles and stores two different values in them

• 2)Write a method Multiply() that takes as input 2 doubles and returns the product of the two numbers. (Note: to multiply in Java, use * )

• 3)Call this method twice. The first time call it directly in a println() statement. The second time, store the value in a third variable and then the value of the variable to the screen

• 4)Once you have completed this and believe it works, try changing the entire program so that it works on 2 ints instead of 2 doubles.

Part 2: How a Computer Works

COMP-202 - Introduction 44

Note:•Make sure you are studying from the “printable” form of these notes. They contain important important information that was mentioned in class, but was not written on the lecture notes

COMP-202 - Introduction 45

Hardware and Software•A computer system consists of both hardware components and software••Hardware consists of the physical, tangible parts of a computer–•Software: Programs and data that they use•A computer requires both hardware and software

COMP-202 - Introduction 46

An (old) Personal ComputerMonitor /screen(output)

Speakers(output)

Keyboard (input)Mouse(input)

•Case;•contains:•CPU•Memory•Disk drives•...

COMP-202 - Introduction 47

Central Processing Unit (CPU)•The "operation/action" part of the computer's brain–Basically controls the information / data in a computer•Perform instructions–Arithmetic operations–Logic operations–Decisions•The instructions it understands are much simpler and fine-grained than those we have seen in previous examples

COMP-202 - Introduction 48

Memory•Memory holds the data–Think of a filing cabinet•Main memory: Most of it is called RAM, which stands for Random-Access Memory–Data has to be loaded into RAM for programs to use it

COMP-202 - Introduction 49

taking notes; packing a box

remembering what Dan said 2 minutesago

remembering your name

COMP-202 - Introduction 50

taking notes; packing a box(CPU)

remembering what Dan said 2 minutesago (RAM)

remembering your name (secondarystorage)

COMP-202 - Introduction 51

How do we store things?• Computer memory is electronic. It's just a bunch of

wires!•

• All it can recognize is “on” (current goes through) and “off” (no current goes through)

• Using many of these on/off “switches” together, we can encode many things.

• For example, we can store whether it is morning or afternoon using the following “encoding:”

• “if the 1st switch is on, then it must be PM. If the 1st switch is off, then it must be AM”

COMP-202 - Introduction 52

Storing whether it is afternoon or morning

• Pick one electrical switch in memory.• Whenever it is “on” it is AM• Whenever it is “off” it is PM•

• A computer stores billions or trillions of these “switches” By combining many of these, we can control many things.

• Note: This is just an example. Your computer probably stores this in an entirely different way.

COMP-202 - Introduction 53

Encoding the day of the week

• How could we encode the day of the week?•

• If we just use 1 switch, there will not be enough room to store the information.

• How many “switches” will we need?

COMP-202 - Introduction 54

Storage is Exponential

• In general, if there are n possible values to store, we can encode it using

• log2(n) “switches”•

• Of course, there is no such thing as a fraction of a switch, so we will always have to round up.

• Put another way, if we have n switches, we can store 2n values

COMP-202 - Introduction 55

Bits = Switch

• 1 “bit” is the same thing as a “switch”• It has one or two values “on” or “off”• For simplicity of notation, we will often just refer to

these as 1 (on) and 0 (off)•

• If you like, you could call them “true/false,” “yes/no,” “oui/non,” or “cats/dogs”

COMP-202 - Introduction 56

Byte = 8 bits

• A byte is simply 8 bits•

• Question: How many possible values can we store in a byte?

COMP-202 - Introduction 57

Other Memory Units

• A kilobyte is 210 bytes (1024 bytes)• A megabyte is 210 kilobytes (1024 bytes)• Strangely, a gigabyte is just 1,000,000,000 bytes•

COMP-202 - Introduction 58

Practice Exercises

1) How many bits does it take to encode the day of the month?

2) How could you encode the letters of the alphabet?3) How could you encode a 3 letter word?4) How would you encode a sentence?

COMP-202 - Introduction 59

Main Memory Organization

92789279928092819282928392849285

address cell

Main memory is divided into many memory locations (or cells)

Each memory cell has a numeric address which uniquely identifies it

Each cell contains a data value (for example, 22)

COMP-202 - Introduction 60

Binary Numbers• Binary is simply an encoding for storing a number as a series

of “on/off” switches or ones and zeroes.•

• Suppose we know that we want to store the numbers 0-7. Similarly to how we encoded days of the week, we can encode the numbers 0-7 as a sequence of on/off switches

• 000 (off/off/off) ---> 0• 001 (off/off/on) ---> 1• 010 (off/on/off) ----> 2• 011 (off/on/on) -----> 3• 100 (on/ off/off)----> 4• 101 (on/off/on)---> 5• 110 (on/on/off) ----> 6• 111 (on/on/on )------> 7•

COMP-202 - Introduction 61

Binary Numbers• There is nothing particularly special about this specific

encoding, but it is more mathematically convenient to use this encoding.

• You can see it is similar to counting in “normal” decimal numbers.

• First we start from 0• Then we increase the right most column as high as it goes• When it gets to its max (1 in binary), we reset it to 0 and

“carry” the digit to the next column•

COMP-202 - Introduction 62

What is each column's value• In base 10, we have ones, tens, hundreds, thousands, etc as

the columns.•

• That is, if I have the number 521, I would say it is “5 one hundreds, 2 tens, and 1 one”

• What are they in base-2? •

COMP-202 - Introduction 63

What is each columns value• In base 2, the columns are worth•

• 1,2,4,8,16,32, etc.....•

• The pattern is that in base 10, they are worth•

• 10^0, 10^1, 10^2, 10^3, etc.•

• In base 2, they are worth•

• 2^0, 2^1, 2^2, 2^3, etc.•

• What are they in base 3? base 30?•

COMP-202 - Introduction 64

Program Execution and Hardware

MonitorKeyboard

CPU

MainMemory

READ DISP

LOAD STORE

17 18

17 18

ADD

17→18

COMP-202 - Introduction 65

Hardware Interaction

Monitor

Keyboard

CentralProcessing

Unit(CPU)

MainMemory

HardDrive

CD-RW

COMP-202 - Introduction 66

Program Execution (fetch-execute cycle)

•A program tells the CPU how to manipulate and/or move information•The CPU repeatedly performs the three following operations:–Reads the next instruction in the program–Figures out what the instruction means•add two values?•load some value from memory?•store some value in memory?•compare two numbers?•...–Performs the instruction•This is called the fetch-execute cycle

COMP-202 - Introduction 67

Program Execution (2)•Suppose you want to write a program that reads a number from the keyboard, adds 1 to it, and displays the new value to the screen•This program might consist of the following instructions:–READ a value from the keyboard and store it in memory location x–LOAD the value stored in memory location x into the CPU–ADD 1 to the value stored in the CPU–STORE the value currently in the CPU back into memory location x–DISPLAY the value stored in memory location x to the screen

COMP-202 - Introduction 68

Program Execution and Hardware

MonitorKeyboard

CPU

MainMemory

READ DISP

LOAD STORE

17 18

17 18

ADD

17→18

COMP-202 - Introduction 69

Machine Language•Each instruction that a CPU understands is represented as a different series of bits

• The set of all instructions that a CPU understands directly forms the machine language for that CPU

•Each CPU type understands a different machine language–In other words, for each different model of CPU, a given series of bits could mean a different instruction

• For example, on an x86-compatible CPU (Intel, AMD), the series of bits 10101010 could mean ADD, while on a PowerPC CPU (old Macs, PlayStation 3) it could mean LOAD

COMP-202 - Introduction 70

Machine Language Example•Here are the first 20 bytes of a machine language program that:–asks the user to enter an integer value using the keyboard–reads this value from the keyboard–adds one to this value, and–displays the new value to the screen

01111111 01000101 01001100 01000110 0000000100000001 00000001 00000000 00000000 0000000000000000 00000000 00000000 00000000 0000000000000000 00000010 00000000 00000011 00000000

More the 6500 bytes in total!

COMP-202 - Introduction 71

Do you think it would be fun or easy to write a program in

binary?

COMP-202 - Introduction 72

Machine Language Disadvantages

••What are some of the problems with Machine Languages?

COMP-202 - Introduction 73

High-Level Languages (1)•To make programming more convenient for humans, high-level languages were developed•No CPU understands high-level languages directly–Programs written in these languages must all be translated in machine language before a computer can run them (that's what a compiler is for)•

COMP-202 - Introduction 74

Compilers vs. Interpreters

COMP-202 - Introduction 75

Compilers

CPU 1 CPU 2

Source code(high-level)

Compiler(to CPU 1)

Compiler(to CPU 2)

Binary code(CPU 1)

Binary code(CPU 2)

COMP-202 - Introduction 76

Interpreters (1)•An interpreter is another kind of program. It takes source code and translates it into a target language–However, the target language instructions it produces are executed immediately–No executable file is created

COMP-202 - Introduction 77

Interpreters (2)

CPU 1 CPU 2

Source code(high-level)

Interpreter(for CPU 1)

Interpreter(for CPU 2)

COMP-202 - Introduction 78

Java combines a compiler with an interpreter

• Java compiler (javac, included in JDK 6) takes source and translates it into bytecode

foo.java(Java)

foo.class(bytecode)

javac

foo.class can than be executed using an interpreter, the Java Virtual Machine (JVM)

COMP-202 - Introduction 79

Programming Errors•A program can have three types of errors•Compile-time errors: the compiler finds problems with syntax and other basic issues•Run-time errors: a problem occurs during program execution, and causes the program to terminate abnormally (or crash)–Division by 0•Logical errors: the program runs, but produces incorrect results

• celcius = (5.0 / 9.0) * fahrenheit - 32; // Incorrect equation; should be // (5.0 / 9.0) * (fahrenheit – 32)

COMP-202 - Introduction 80

Development Life Cycle

Runprogram0 errors

Syntaxerrors

Logic andrun-timeerrors

Compileprogram

Write program

•Errors may take a long time to debug!–Important Note: When you compile for the first time and see 150 errors, do not despair. Only the first 1 or 2 errors are relevant. Fix those and compile again. There should be fewer errors (like 50). Repeat until there are no more errors.