Transcript week5

APCS-A: Java
Assignments & Syntax
October 3, 2005
week5
1
Checkpoint
• 80 point Quiz #3
• Car Homework
 Any questions?
 Visual check of everybody’s assignment
week5
2
Making Mistakes
•
•
•
•
What happens if you forget a semi-colon?
Forget parenthesis?
Forget opening or closing brackets?
Don’t use the “right” capitalization?
• Programming languages are very picky!
 Why do you think that is?
week5
3
Syntax
• Syntax is…
 The rules governing the structure of a language
 The rules that the compiler understands
 Defines meaning of the various symbols used in a
language
• Alice didn’t let you make syntax mistakes
 It only allowed you to drag-and-drop code statements
that were syntactically correct
• Java isn’t like this
 If you get the syntax wrong, the compiler won’t know
what you are trying to do
week5
• So it won’t do anything (it gives you an error)
4
System.out
• System.out represents an output device or
file, which by default is the monitor screen
• The print and println methods take one
parameter
 The string of characters to be printed
• println - prints the information sent, then
moves to the beginning of the next line
• print - does not advance to the next line
week5
5
Concatenation
• Joining together or appending one string to
the end of another
• String literals cannot extend across
multiple lines in your program
 You must use the plus sign to concatenate two
string literals together
System.out.println(“This is a bad program
because it extends across multiple lines
without concatenating the strings together.
This will not compile.”);
week5
System.out.println(“This is a good program”
+ “ because it uses the + sign to extend”
+ “ the program across multiple lines.”);
6
Variables
• A variable is a name for a location in memory
•
that stores data
When you declare a variable, you tell the
compiler to reserve a certain size piece of
memory to store data in (based on the type of
data)
 We will talk more about the types of data tomorrow
• Example:
 String name;
 int number;
week5
7
Variables
• Variables need a data type and a identifier.
• Think of a variable as a cup. A container. It
holds something.
 The data type tells Java the size of the container.
 The identifier is there so you know which container is
yours.
name
week5
number
8
Assignments
• When you declare a variable, you just set aside
•
the memory - but that space is “blank”
To actually place something in the variable, you
need to assign a value to it:
 name = “Nicole”;
 number = 123;
“Nicole”
name
week5
number
9
Assignment Statements
• More examples:
 String anotherName = “Philip”;
 int num = 5 + 4*23;
• In Java, here are the basic rules:
 On the left side is always the variable name, the “container” in
which we are going to store data
 On the right side could be a single piece of data, or an expression
that has to be evaluated
• The single piece of data, or the result of whatever is evaluated is
then “assigned” to the variable (ie - placed into the memory location)
 You always end each statement with a semi-colon
week5
10
A program example
public class Example {
String name;
int number; //make the containers
public void doAssignment(){
name = “Nicole”;
number = 123;
printStuff();
}
private void printStuff(){
System.out.println(“The name in this program is: “ + name);
System.out.println(“The number is” + number);
}
}week5
11
Additional assignments
• If we reassign a value to a variable, the new value is
written to memory.. What happens to the old value?
int myVar = 123;
myVar = 34343435345;
• If we just reference (use) a variable, the value is not
changed
System.out.print( “myVar is: “ + myVar);
// after this call, myVar still has 34343435345 stored in it
week5
12
Strongly Typed
• Java doesn’t let us store the wrong kind of data in our
variables
 Unlike Alice, it doesn’t stop you from trying to assign the wrong
kind of data
 The compiler will cause an error if you try to use the wrong kind
of data for a variable.
• If we declare a variable of type String:
String s;
• Then we can’t put an integer into that String
s = 1232;
//Compile error: incompatible types - found int but expected java.lang.String
week5
13
Constants
• Sometimes we want to store a piece of data that will never change
 For example, we may want to say that a table at lunch can hold no more
than 12 people. If we just use the number 12 in our program, people
looking at our code may not know where it came from
• So we give it a name like MAX_PEOPLE to help explain what the
piece of data is doing in a program
• Also, lets say that we suddenly get new lunch tables that have a
maximum of 15 people…
 We only have to change the data in one place, instead of trying to find all
the places that the number 12 was used in our program
• Constants are not variables (the value can never change)
 they hold one value for the durations of the program
week5
14
Constants in Java
• To declare a constant in Java, you use the reserved word
final
• By convention, we use uppercase letters to name
constants so that we can tell them about from regular
variables
final int MAX_PEOPLE = 12;
• The compiler will then prevent anybody from changing
the value once it has been set to the initial value
week5
15
Arithmetic Operators
• What if we want to have a counter variable?
 Something that starts at 0 and then counts up, one-byone depending on what else we may be doing in a
program
• int x = 0;
• So we could do:
• x = x + 1;
 So what would x equal? How does this all work?
• We do this a lot in programming, so there’s
shortcut for this (called the increment operator)
 x++;
week5
// is the same as x = x+1;
16
Other Arithmetic Operators
• Minus
 x = x -1;
• Multiplication
 x = x * 5;
• Division:
 x = x/2;
• What do you think will happen if we try to divide by zero?
• You have the special operator for increment, do
you think there are any similar operators for
these functions?
week5
17
APCS-A: Java
Data Types
October 4, 2005
week5
18
Checkpoint
• Car Homework
 Any questions?
 Visual check of everybody’s assignment
week5
19
Lab Today… but
• First there are a couple more things to
cover…
• There’s another mathematical operator…




week5
The Modulo operator
Modulo - what the heck is that???
%%%%%%%%%%%%%%
Oops -- just one: %
20
Modulo
• The modulo operator ( % ) returns the
remainder from dividing one integer by
another integer
week5
21
Elements of a Method
• Signature of the method




public void makePixel(int x, int y)
Public/private/protected is optional
The return type
The name of the method
• Good programming practice: Make it descriptive
 Parameter declarations (if any)
 ==> Signature tells the user and the compiler more about what to expect
from the method
• Body
• Comment
 Good Programming Practice: Place comments before methods that
describe what the method does
week5
22
Lab
• Build a simple calculator
• Learn how Java deals with ints…
 This will lead us into our discussion of data
types tomorrow. Wahoo :)
week5
23
APCS-A: Java
Data Types
October 5, 2005
week5
24
Today
• Cover some details from yesterday’s lab
• Some additional information about
variables and methods
 Return statements
 Scope
 Programming practices
• Data Types
week5
25
Lab Redux
• What is the difference between ‘String’ and ‘string’?
• What is the difference between ‘System’ and ‘system’?
• Any other questions from lab yesterday?
 What did we get when we divided 5/2?
 5%2?
week5
26
Return Statements
• In methods, you can define the “return
type” to be “void” (returns nothing)
• Return type to be any of the built-in data
types we will talk about later today (like int)
• Return type can also be an object type
 Like Dog, Person, or String
• Note: String is actually an object
week5
27
Return Statements
public void add (int x, int y) {
int z = x+y;
System.out.println(“answer is: “ + z);
}
public int add (int x, int y) {
return (x+y);
}
The first function is called with the statement:
add(5, 10);
The second statement can be called in many ways, but we probably
want to do something with the answer returned back (we want to
catch the answer somehow
week5
28
Catching return types
public int add(int x, int y)
•
•
In BlueJ, we could just get the answer back in an
method result window
Or we could use the answer in another part of our
program


In another method
In a statement or some sort (assignment statement, print
statement, etc)
System.out.println(“answer is: “ + add(5,10));
int answer = add(5, 10); //notice I “catch” the value in an int variable
divide(answer, 2);
week5
29
Scope
• Parameters and variables have scope
 This means that they are only valid in the block (between the
curly braces) in which they were defined
• Class scope
 Variables defined at the top of the program (not inside any
constructors or methods) -- these variables can be used
anywhere in the class
• Constructor/Method scope
 parameters passed in to a constructor/method can only be
referred to in that constructor/method
 Variables declared in a method can only be referred to in that
method
• What happens when you refer to a parameter/variable
outside the block it was defined in?
week5
30
Scope
public class ScopeClass {
int x = -1;
String s = “gook ”;
public void scopeFunc1() {
String s = “Gobble-D ”;
System.out.println(s + x);
scopeFunc2(42);
}
public void scopeFunc2(int x) {
System.out.println(s+x);
}
Question #1
Question #2
}
week5
1) What do you get if you make a call to scopeFunc1()?
2) What do you get if you make a call directly to scopeFunc2()?
31
Why does scope matter?
• In the last example, s wasn’t even a particularly good variable
name… so we could have come up with even more descriptive
names and not had the problem of trying to refer to two different
variables with the same name
• But what about in the Car class we defined for homework:
 We could have had an instance variable: String color, which had the
car’s color
 We could have had a paint method: public void paint (String
color) {} in which we wanted to reset the Car’s color (the instance
variable) to the new color (passed in with the parameter to the method)
week5
32
How do we solve this
scope problem?
• The beginner’s way -- name your parameters something different
than your class (instance) variables
• In Car class, we could have the instance variable, String color
• In the paint method, we could instead call the parameter String
newColor
• Or, if you love your name… then when the class variable interferes
with the scope of a parameter or method variable, you can use the
advanced programmers’ solution: the this keyword to refer to the
instance variable (which we will talk about later)
 this.color = color;
week5
33
More about variables…
• The burning question: What can I name my variables?
 Almost anything… But not Java reserved words…
 abstract do if package synchronized boolean double
implements private this break else import protected
throw byte extends instanceof public throws case false
int return transient catch final interface short true
char finally long static try class float native
strictfp void const for new super volatile continue
goto null switch while default
• Luckily, BlueJ colors these words a different color so you will know
there is something special about them before you know what they all
mean
week5
34
Naming Practices in
Programming
• Class names start with a capital letter
 public class Dog { }
• Object names start with a lowercase letter
 Dog fido = new Dog();
• Method names and variables start with lowercase, but use capital
letters for subsequent words
 public void changeMyOil() {}
 int myAge;
• Constants use all caps
 MAX_INT_SIZE
week5
35
Primitive Data Types
• What is an int? (Think back to math…)
• What might other primitive data types be?
• What other kinds of information might an object need to
know?
week5
36
Data Types
• A variable's data type determines the values that the variable can
contain and the operations that can be performed on it
• Primitive Data Types are built-in data types (in Java, there are 8 of
them)

week5
boolean, char, byte, short, int, long, float, double
Type
Storage
Min Value
Max Value
boolean
1 bit
0 (false)
1 (true)
byte
8 bits
-128
128
int
32 bits
-2,147,483,648
2,147,483,647
double
64 bits
Approx -1.7E+308 with Approx 1.7E+308 with
15 significant digits
15 significant digits
37
Pre-Defined Data Types
• Pre-defined data types are just objects that Java has provided you that store
information
• What is a String?
 Stores a section of text
 Always in double quotes
• Java has several other data structures to store data in useful ways
 We will be learning many of them this semester and next
week5
38
Converting Data Types
• What do we do if we want to compare an int variable to a double
variable?
 Or do int + double?
 int / double?
• There are three ways that Java deals with this
 Assignment conversion
 Promotion
 Casting
week5
39
Assignment Conversion
• Occurs when one type is assigned to a variable of another type
during which the value is converted to the new type (only widening
conversions can happen this way)
double dollars = 5;
• Here the 5 will get automatically converted to a double (5.0) to be
stored in the variable dollars
week5
40
Promotion
• If we divide a floating point number (float or
double) by an int, then the int will be
promoted to a floating point number before
the division takes place
• When we concatenate a number with a
string, promotion also happen - the number
is converted (promoted) to a string, and
then the strings are joined
week5
41
Casting
• The most general form of conversion in Java
 If a conversion is possible, you can make it happen with casting
• You cast a variable by automatically applying a data type to it
int x = 5;
double dollars = 5.234;
x = (int) dollars; //forces the double to become an int
• This will truncate (not round) the original value
• This can also be used to make sure we get the answer we expect -->
if we want to divide 5/2 and get 2.5, then we want to force the result
to be a double:
double answer = (double) x / y;
OR
double answer = (double) x / (double) y;
week5
42
Tomorrow
• Quiz - we want to make sure that we are
all comfortable with Java and the
beginning Java syntax before moving
further along
• Question: Programming Homework or
Abstract Homework for 4 day weekend?
week5
43
Lab
• Redo/Adjust Calculator
 Use return statements (change your methods to have non-void
return types)
 Change your calculator to support decimals (doubles)
• Add functions to make your calculator “Smarter”
 Write a method that will return the average of 3 numbers
 Write a Fahrenheit to Celsius conversion function
• And a Celsius to Fahrenheit converter
 Write a method that will determine the value of coins in a “jar” and
print the total in dollars and cents. The method will take in 4
integer parameters, representing the numbers of each kind of
coin
week5
44