Download slides - Angus Forbes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS 5JA Introduction to Java
Last class...
We gave a definition of high-level vs. low-level. We talked about what
object-oriented means.
We gave a broad overview of about how software is a set of precise
instructions and also a way to model aspects or features of a problem or a
system.
Hopefully by now we have all installed the JDK and can compile and
execute our code!
Today we are going to start diving into how we give instructions to the
computer. In particular, we will look at how we can define and manipulate
data using variables.
At the end of class we will look at a small program together.
CS 5JA Introduction to Java
The turn-in webpage...
But first...
You can find the link to the Turn-in website from the homework.
CS 5JA Introduction to Java
What is a variable?
A variable is an address or an index to some place in the computers
memory which holds data.
It's called a variable because it can be changed.
Each variable has a name and a type.
The variable is always referred to by its name.
CS 5JA Introduction to Java
An example of a variable...
int myNumber;
You are declaring the variable named "myNumber" of type int (integer).
That is, a whole number.
You can then assign a specific integer to your variable. It's like having a
bucket, and adding a label to it. Then you put something inside it.
myNumber = 9;
What this is saying is: Put the integer 9 into the bucket labeled
“myNumber".
CS 5JA Introduction to Java
Assigning data to a variable
But it's a very fragile bucket. And if you put anything else into it besides a
whole number, it will break, and your program will not run. For instance :
myNumber = 9.5; //Error!
This doesn’t work because we are trying to put a decimal number into a
bucket of type integer. The bucket labeled “myNumber” is expecting an
integer. Nothing else will fit into that bucket.
Even though the bucket is labeled “myNumber”, the name has no actual
meaning.
For example if you make a bucket of type int but call it
“myDecimalNumber”, it still can only accept integer numbers!
CS 5JA Introduction to Java
Assigning data to a variable
Putting data into a bucket is called variable assignment. You assign data to
a variable by using the = sign. For all practical purposes, the label on the
bucket equals the data inside the bucket.
myNumber = 123;
When you see the equals sign in a statement like this, it helps to say out
loud to yourself: I am putting the number 123 into the integer variable
called “myNumber”.
What does this do?
int myNumber;
myNumber = 123;
myNumber = 321;
CS 5JA Introduction to Java
Assigning data to a variable
If you assign new data to a variable, you destroy the data that was already
in there. In the above example, the first line creates an integer bucket. The
second line puts the number 123 into the bucket. The third line puts the
number 321 into the bucket and completely destroys whatever was in there
before.
You can think of it like this: When you first create the variable, there is a
little blackboard in the bucket. When you assign data to the variable, you
are taking out the blackboard, erasing whatever is on it, and writing the
new data on the blackboard, then putting it back in the bucket.
You can also create the variable and assign data to it at the same time:
int myNumber = 1001; //both creates and assigns
CS 5JA Introduction to Java
Operations
Certain activities are so fundamental that they are built right into the
language and have their own symbols. These symbols are called
operators. Here are some mathematical operators: +, -, *, /, %, ++, = that
work on data in integer buckets (variables of type int).
For example, if we want to add two numbers together we can use the
addition operator.
int x = 5;
int y = 6;
int z = x + y; //Now what is in the z bucket?
CS 5JA Introduction to Java
Operations on variables
int x = 5;
int y = 6;
int z = x + y;
Now z contains the number 11.
In the third line we did is the following: took a number out of the integer
bucket x, took another number out of the integer bucket y and then gave
them to the CPU and told it to add those two numbers together. Then we
took that number and put it inside of the bucket z.
Try this:
int x = 5;
int y = 6 + x;
int z = x * y; //What number is assigned to z?
CS 5JA Introduction to Java
Operations on variables
int x = 5;
int y = 6 + x;
int z = x * y; //What number is assigned to z?
After the second line, y contains the number 11, and x still contains the
number 5. So at the third line we take the number 5 out of x and 11 out y
and tell the CPU to multiply them together. We put the result into z. Since 5
times 11 equals 55, z now contains the number 55.
CS 5JA Introduction to Java
Types of variables
You can make buckets of any type you want! There are some data types
that are so common that we refer to them as primitive types. These are the
8 primitive types:
Whole numbers
int (32-bit), short (16-bit), long (64-bit), char (16-bit, positive only),
byte (8-bit)
Decimal numbers
double (32-bit), float (64-bit)
Logical
boolean (1-bit, true or false)
(http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html)
CS 5JA Introduction to Java
What is a bit?
A bit is a the smallest possible piece of information. It is either ON or OFF,
a 1 or a 0. You can build larger pieces of information from a series of bits.
For example, you can build a binary number from a series of bits. if you
have two bits then there are 4 possible permutations, so you can
represents 4 numbers with 2 bits, the numbers 0, 1, 2, and 3.
00 = the number 0
01 = the number 1
10 = the number 2
11 = the number 3
CS 5JA Introduction to Java
Binary numbers
The first column from the end tells you if you should add a 1 to your
number.
The next column to the left tells you if you should add a 2 to your number.
So if the binary number is “01”: The first column is OFF, so we do not add a
1. But the second column is ON, so we do add a 2. Thus the binary
number “01” equals the number 2
Each successive column tells you if you should add 2^n to your number.
For example if you have a number that is 4-bits long then the first column
is 2^0 or 1, the second is 2^1 or 2, the third is 2^2 or 4, the fourth is 2^3 or
8, etc. With a 4-bit number you count from 0 up to 1+2+4+8 or 15 for a total
of 2^4 or 16 numbers.
(You’ll notice that first = 0, second = 1, etc. This is very common in
programming. We start counting at 0 instead of 1. Usually.)
CS 5JA Introduction to Java
What number is this?
How many bits does this number have?
What is the highest number we can represent with this many bits?
8
4
2
1
ON
ON
OFF
ON
CS 5JA Introduction to Java
Binary numbers
If an int is represented with 32 bits, then what is the maximum number a
variable of type int can point to?
2^32 = 4,294,967,296 numbers, and since we include zero, we can count
from 0 through 4,294,967,295.
However, one bit is used to determine whether it is negative or positive
number, so we can actually represent -2,147,483,648 through
+2,147,483,647.
So what happens here? int myNumber = 2,147,483,648; //???
If you are curious read Appendix E in the book. Also:
http://en.wikipedia.org/wiki/Binary_numeral_system
http://en.wikipedia.org/wiki/Two's_complement
CS 5JA Introduction to Java
Examples of other primitive variables
double myDecimal = 1043.13299843;
boolean myTruthValue = true;
char myLetter = ‘J’;
What happens if you do this?
double myNumber = 10; //automatic translation to 10.0
int myNumber = 10.5; //Possible loss of precision!
int myLetter = ‘b’; //Huh?
CS 5JA Introduction to Java
Other non-primitive variables
You can also have variables for more complicated types that you either use
from the java library or that you build yourself. Any type that is not primitive
is capitalized.
You make a new variable for your type just by writing:
String myString;
And you put new data into your bucket with the new keyword:
myString = new String(“I am a string!”);
Or, as before, you can make the bucket and put the data object into it at
the same time.
String myWords = new String(“This is a string of
letters...”);
CS 5JA Introduction to Java
The Scanner object
The java library has tons of types already made for you. A very useful thing
that you will probably want to do is let people type in something from the
terminal window.
How do you get something you type into your program? You use the built
in Scanner object. The Scanner waits for you to type something in, then
when you press return it lets you examine what was typed in. Let’s make a
bucket that holds a Scanner:
Scanner myScanner;
You now have a variable named myScanner which is able to hold a
Scanner.
Let’s make a Scanner and put it in our bucket:
myScanner = new Scanner(System.in);
CS 5JA Introduction to Java
The Scanner object
The Scanner is not just a simple data type. It is an object. Last week we
talked about how objects are models. The Scanner object models a
machine which scans and processes a line of text in a book. Or which
scans a barcode and processes the symbols it reads.
The line below creates a Scanner machine which reads input from the
System (which by default is the keyboard) and then puts it in the bucket
labelled myScanner.
Scanner myScanner = new Scanner(System.in);
You can then use this machine to scan a line of text.
CS 5JA Introduction to Java
The Scanner object
Let’s say we want to read a number from the line of text that a user types
in.
We can pass an instruction to the Scanner machine by invoking one of the
Scanner’s methods.
Methods are how you interact with the objects you create.
Here is how we instruct the our Scanner to read a number from a line of
text:
myScanner.nextInt();
CS 5JA Introduction to Java
The Scanner object
This method processes the text and returns the integer it found. We can
make a bucket for this number just as we did before:
int userNumber;
userNumber = myScanner.nextInt();
In English:
Make an integer bucket called userNumber.
Take the Scanner out of the bucket called myScanner.
Tell the Scanner to wait for the user to enter text AND to then to scan for
the first number in that text.
Put that number into the userNumber bucket.
We now have a variable that we can do something with! Hooray!
CS 5JA Introduction to Java
Javadocs
A simple program which uses a Scanner to add two numbers together is
on page 47 of your text book.
If you are curious you can look at the Javadocs and find out every method
that exists. The Javadocs for a particular object contain all the methods
you can use to pass instructions to that object. For instance, below is the
link for the Scanner object:
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
And this is the link for all of the objects in the Java library:
http://java.sun.com/javase/6/docs/api/
CS 5JA Introduction to Java
A look ahead...
In the future, we will make our own custom objects.
Once we do that, we can make a bucket to hold that object, and write
functions to manipulate them.
For example we might create these objects:
BowlingBall myBlackBowlingBall = new
BowlingBall(Color.BLACK);
Or
Alien mySpaceAlien = new Alien(“Zorgon”);
And then instruct them somehow:
myBlackBowlingBall.drop();
mySpaceAlien.fireWeaponAtNearestEnemy();
CS 5JA Introduction to Java
Let’s look at a program...
CS 5JA Introduction to Java
On Tuesday...
Last class we talked about a few different things:
We talked about variables, how to create them and how to assign data to
them. We also talked about how to create a variable and assign data to it
at the same time.
We talked about different mathematical operators you could use with
variables of type int. We talked about the 8 different primitive data types,
and about how you can use other built-in non-primitive data types (or
objects), or import them from the Java library, or create custom ones.
We looked closely at the Scanner object from the java.util library and
looked at program that uses the Scanner object to add two numbers
together.
We also took a brief tangent and looked at bits and binary numbers.
CS 5JA Introduction to Java
Today...
We are going to talk about variables just a little bit more and also talk more
about operators, including the order of operations for mathematical
operators. Also we will introduce equality and relational operators.
We will look at a short program that makes use of the concepts we’ve
introduced so far.
And we have a new homework assignment. The assignment will ask you to
write a few short programs of your own.
That is, by the end of the homework you will be actual programmers!
Note: Your TAs are there to help... Feel free to go to any TAs office hours.
They will also arrange to meet you at other times if they are too busy to
help you. Ask “stupid” questions during discussion sections– If you don’t
understand something then I guarantee that you are not alone.
CS 5JA Introduction to Java
Pop Quiz!
Convert these three numbers from binary into decimal and write down how many
bits are used to represent each number :
a. 1010
b. 11001010
c. 0000000000000001
Here is a short snippet from a program:
int a = 15;
int b = a / 3;
int c = b * a;
What are the values of a, b, and c after these three lines are executed?
What is the value of x after the following line has been executed?
int x = 15.9;
Name the 8 primitive data types in Java. Which one is only 1-bit in size?
CS 5JA Introduction to Java
Variables, another view...
Another way to think of variables is as data that occupies a space in memory.
You can think of the memory available to your program as a big empty field of 1s
and 0s. When you make a variable you are building a fence around an area in that
field.
If you use a primitive, then the size is always the same. If it’s a byte then you have
a plot of land that is 8 bits big (representing the number -128 through 127). There is
a fence around it with a sign that has the name of the variable.
byte myByte = 65;
1010101000011001
0100111001101000
1010010000011010
0011110011010011
fence around “myByte” farm
other data
CS 5JA Introduction to Java
Variables, another view...
This is also one reason why we had that error when we tried to put a
decimal into an int bucket.
The default decimal data type is a double. And a double needs to be
represented with a farm with 64 plots of land, or bits. So when we try to put
a 64 bits into an space in memory that only room for 32, the java compiler
complains and will not run.
However, the opposite works just fine. You can put an int into a double
without any errors, because there is enough room for it.
Changing one data type into another data type is called casting. We’ll
encounter this again later...
CS 5JA Introduction to Java
Order of Operations
What else can we do with integers?
There are a number of fundamental mathematical operators. You can use
them to build equations out of numbers of variables that have data types of
whole or decimal numbers.
*, /, %, +, - stand for multiplication, division, modulo, plus and minus,
respectively.
Just as in a mathematical equation, you evaluate multiplication and
division before subtraction and addition. If you want to force a different
order, you simply put them in parentheses. You can not use brackets as
you would in an equation. Rather you use a as many parentheses as
necessary.
CS 5JA Introduction to Java
Order of Operations
For example, if you are making a variable to store the results of the
following equation: int result = 5 + 7 * 4 - 6 / 3;
you first multiply 6 and 4, then divide 2 by 3, then perform the addition,
then the subtraction. So,
after first operation : 5 + 28 – 6 / 3
after second operation : 5 + 28 – 2
after third operation : 33 – 2
after fourth operation : 31
Thus, the variable result contains the integer 31.
To make things clearer you can also write your equations with paretheses:
int result = 5 + (7 * 4) – (6 / 3); //also = 31
CS 5JA Introduction to Java
Order of Operations
What does this do?
int result = ((((6 + 5) * 4) + 3) * 2);
As opposed to this?
int result = 6 + 5 * 4 + 3 * 2;
Or this?
int result = 6 + (5 * (4 + (3 * 2)));
CS 5JA Introduction to Java
Order of Operations
What does this do?
int result = 7 / 4; //???
What does this do?
int result = 5 % 3; //???
The modulo operator tells you the remainder. So for example 11 / 3 = 3,
and 11 % 3 = 2 because the division of 11 by 3 has a remainder of 2.
If you want to represent decimals you use the double data type for your
variables.
CS 5JA Introduction to Java
Increment and decrement operator
Just for fun, there’s another operator which doesn’t work on numbers
themselves, but that works instead on variables that contain numbers:
int value = 5;
value++; //increments the number in value by 1
value--; //decrements the number in value by 1
Another common thing to do is to use a variable in a particular operation
and then assign the result back into the variable:
int value = 5;
value = value + 5; //now value = 10
You can also write this second line as:
value += 5; //adds 5 to whatever number was in value
CS 5JA Introduction to Java
Increment operator
remember what happens here?
int myNumber1 = 2,147,483,648; //Error!
but...
int myNumber2 = 2,147,483,647; //upper bound of int
myNumber2++; //???
CS 5JA Introduction to Java
A bit more about the String object
We talked about Strings briefly when we mentioned that Java has some
built in non-primitive data types. We also make use of Strings whenever
we use the System.out.println command. The println instruction (or
method) requires that you pass in a String.
You can create this String explicitly:
String text = new String(“Hello World!”);
Or explicitly, but using a short cut:
String text = “Text created with a short cut...”;
Or implicitly, on the fly as we invoke the method:
System.out.println(“Text created on the fly!”);
Just as we can use a number without assigning it to a variable, we can use
a String without assigning it as well. Whenever Java sees a quote, it
assumes a String will follow.
CS 5JA Introduction to Java
The + operator for the String object
The plus sign for data type String means “append” instead of “add”.
So when you see code that looks like this:
String text1 = “The word String refers to ”;
String text2 = “a ‘string’ of letters...”;
String text3 = text1 + text2;
System.out.println(text3);
So now this is what gets printed on the command line:
The word String refers to a ‘string’ of letters...
CS 5JA Introduction to Java
The + operator for the String object
The append operator is smart enough to turn primitive data types into text
as well.
int numMonkeys = 99;
System.out.println(“There are ” + numMonkeys + “
monkeys jumping on the bed.”);
prints the following on the command window:
There are 99 monkeys jumping on the bed.
CS 5JA Introduction to Java
The if statement
There is an important set of syntax in Java referred to as “Control
Statements”. They tell the program to ignore or repeat certain parts of the
code. The if statement is kind of a bump in the rode. If you hit the bump
you go up in the air, and then come back to the ground. If you don’t hit the
bump, you just stay on the road.
boolean isBumpInRoad = true;
if (isBumpInRoad == true)
{
System.out.println(“Wheeee!”);
}
System.out.println(“on the road...”);
If the boolean variable isBumpInRoad is false, then we never say
“Wheeee!”.
CS 5JA Introduction to Java
equals & equals equals??
If there is a single equals, it is the assignment operator. We have been
using it since last class for when we put data into a variable.
In this line we are making a bucket of type boolean and putting the value
true into it:
boolean isBumpInRoad = true;
But in this line we are checking to see if our variable named
isBumpInRoad contains the value true. In other words: is the data in
isBumpInRoad equal to the boolean data true? The == operator is the
equality operator:
if (isBumpInRoad == true)
CS 5JA Introduction to Java
equals equals
Just to be slightly more confusing...
If the statement after the if keyword evaluates to true, then we execute the code
between the squiggly brackets. Otherwise, we skip them.
boolean isBumpInRoad = true;
if (isBumpInRoad == true) //yes this statement is true
{
//so yes execute this code!!!
}
However, if isBumpInRoad is false, then we skip that code:
boolean isBumpInRoad = false;
if (isBumpInRoad == true) //no! this statement is NOT true
{
//so we do NOT execute this code!!!
}
CS 5JA Introduction to Java
One more time...
If there is a single equals, it is the assignment operator:
int number = 5;
If there is double equals, it is the equality operator:
if (number == 5) //yes this is true
{
System.out.println(“your number is indeed equal to 5.”);
}
But, if we set number to be something else:
int number = 6;
if (number == 5) //no, this is NOT true, so skip...
{
System.out.println(“your number is indeed equal to 5.”);
}
CS 5JA Introduction to Java
The conditional
The section inside the parentheses after the if keyword is called the
conditional. We evaluate the conditional and if it is true, then we execute
the code inside the squiggly brackets. If it is false, then we skip it.
Look at these code snippets and evaluate the conditional:
int number = 15;
if (number == 15) {};
char letter = ‘A’;
if (letter == ‘A’) {};
if (true) {};
if (false) {};
CS 5JA Introduction to Java
Other comparison operators
(Important note! These comparison operators only work with primitive data
types!!! We will explore this later...)
There are also other operators that are used to compare pieces of data.
The “not equals” operator, or inequality operator.
int number = 97;
if (number != 15) {}; //what does this evaluate to?
int number = 97;
if (number != 97) {}; //and this?
CS 5JA Introduction to Java
Other comparison operators
The relational operators (greater than, less than, greater than or equal to,
less than or equal to)
int number1 = 97;
int number2 = 98;
if (number1 > number2) {}; //evaluates to?
int number = 5;
if (number <= 5) {}; //and this?
int number = 17;
if (16 >= number) {}; //and this?
CS 5JA Introduction to Java
For Next Week
You have some real homework... Let’s look at it...
We will start thinking about larger programs which are made of more than
one file.
We will start making (simple) custom objects with custom sets of
instructions.
We will learn about all of the control statements available to us.
We will look at the logical operators.
In two weeks... We will start doing some simple 2D graphics