CS62 - Spring 2020 - Class 1
Example code in this lecture
SimpleFunctions
ClassBasics
Lecture notes
introduction
- what intro class?
- why are you taking this course?
- what do you hope to get out of this course?
goals of the class
- teach you how to program in Java
- teach (force you?) to become an independent programmer
- advanced programming
- more practice
- Java has some additional features that allow us to investigate some programming paradigms in more detail
- more tools
- object oriented programming
- data structures
- which ones have you seen/heard of?
- way for storing and accessing data
- basic performance analysis and design
- after this class, you'll be ready to take many of the upper division CS classes
course web page:
https://cs.pomona.edu/classes/cs62/
administrative
- textbook
- grade breakdown
- basic schedule
- Class T/Th
- Wednesday labs
- Required to attend for the full three hours
- Start with a lab exercise, possibly with a small deliverable at the end
- Often, start the assignment for that week
- Assignments will be due on Tuesday
- Thursday quizzes (starting next week)
TODO before lab tomorrow
- create a github account if you don't have one (go to github.com)
- accept piazza invitation (all communications will be through that)
- read through course webpage
Your first Java
- take a look at the first five functions in
SimpleFunctions code
- what do they do?
- what are some of the similarities with python you notice (there are lots!)?
- what are some of the differences from python you notice (there are lots!)?
some high-level syntactic differences
- all statements in Java are terminated with a semi-colon. This (not an end of line) indicates to java that the statement is done
- Java uses curly braces and parenthesis to identify blocks of code (not indentation, like python)
- For example, the following are *all* equivalent to the add function
int add(int num1,
int num2
){return num1+num2;
}
int add(int num1, int num2){return num1+num2;}
int
add
(
int num1,
int num2
)
{
return
num1
+
num2
;
}
- Java doesn't care!
- We will follow certain conventions to make the code more readable, though!
- Curly braces, {}, denote a block of code
- parentheses, (), denote parameters or arguments
- variable and function name conventions
- like python, all functions and variable names will start with a lowercase letter
- unlike python, for multi-word variables and functions the convention for Java is to use "camel-casing", i.e. capitalize the first letter of each new word
- For example:
firstAndLastSame NOT first_and_last_same
sumUpTo NOT sum_up_to
- comments: java has two different types of comments
- single line comments: //, everything following this to the end of the line is a comment and is ignored
- multi-line comments: /* */
- Everything between /* and */ is a comment and is ignored
- by convention, we will often put a * on each line in the comments to indicate that this is still part of the comment, but it is NOT required
- this can be very useful during testing (or other situations) when you want to temporarily comment out a large section of code
statically typed vs. dynamically typed languages
- What is a type?
- the type of an object define the types of operations you can perform on that object
- in strongly-typed languages anything that represents a value has a type (e.g. objects)
- in dynamically-typed languages each object is checked on the fly when the program is done to make sure
- For example, is there any problem with the following python statements:
x = 10
y = "banana"
x/y
- Yes! You can't divide a number by a string
- When would python recognize that this was an error?
- Not until you run the program and it gets to that particular line
- it would check to see what type x was
- and check to see what type y was
- and only then realize that you can't calculate x/y
- in statically-type languages the type of objects can be determined *without* running the code
- often when this means is that the programmer is required to declare the types of things in the languages
- For example, the above statements would be written in Java as follows:
int x = 10
String y = "banana"
x/y
- When we declare variables we *have* to specify their type
- Because of this, Java can easily figure out before running that x/y will cause an error
- why statically typed?
- static typing allows errors to be caught much earlier and, often, automatically
typed variables
- every variable and parameter must have a type
- what are some of the types Java might have?
- int (integers)
- long (integers with more capacity, more on this later)
- float (decimal numbers)
- double (decimal numbers with greater precision, more on this later)
- boolean
- String (strings)
- many more we'll get to later
- to declare a new variable, you first specify the type then the name then assign to it
<type> <name> = <value>;
- Java will enforce that for the lifetime of the variable, it can only be assigned to something of that type (there are actually a few caveats to this, but more later)
- For example:
int x = 10
x = "banana"
- Java will complain!
- when you declare parameters in addition to giving them a name, you also have to specify their type!
- Java checks these when a function is called
- For example:
add(10, "banana")
- would result in an error, even before the function is called
- notice this avoids a lot of issues/errors that could come up either by accident or maliciously
type methods
- in addition to having to specify the types of all variables and parameters, you also need to specify the type of value that a function returns
- add returns an int
- firstAndLastSame returns a boolean
- what is void?
- void is used when a function doesn't return a value
Strings
- Strings are not a built-in data type, like they are in python (and other languages)
- because of this, there is no special functionality for indexing using []
for loops
- for loops in Java are a bit more general than for loops in python
- for loops consist of three parts:
1) a beginning statement that is only run once (initialization)
2) the condition or test to see if the loop should keep going (condition)
3) a statement that is run after each loop iteration (increment)
- all three parts are enclosed in parentheses
- each of the parts is separated by a semi-colon
- the main body of the for loop is denoted by braces
- like other blocks of code, we will indent to make it more readable
- When the program is running and it encounters a for loop:
- first, the initialization statement is run
- this is only done once for a for loop!
- often this is a variable declaration, but anything could go here
- if a variable is declared, the scope of that variable is just the for loop block
- next, the condition is checked. If it's false, the loop finishes immediately.
- if the condition is true, the statements in the for loop block are executed
- after each iteration, the increment condition is run once
- the condition is then checked again and the process is repeated
- really just syntactic sugar for a while loop
printing
- not as nice as in python :(
- A couple of different ways to right now:
- print something and then end the line:
System.out.println(...)
- print something, but DON'T end the line:
System.out.print(...)
- Java is pretty smart about converting things to strings
- all built-in data types (ints, float, double, etc.) get converted in a straightforward way
- most other types of objects also do the right thing
++
- Java has a few extra short-hands that are not in Pyhon
- ++ is equivalent to += 1, for example:
i++;
does the same thing as
i += 1
or
i = i + 1
- -- also is available
What do the two mystery methods do in
SimpleFunctions code
?
- e.g., what will the following return?
- mystery(10)
- mystery2(10)
- mystery(10)
- 0 + 3 + 6 + 9 = 18
- mystery2(10)
- same thing!
- 0 + 3 + 6 + 9 = 18
- add up the powers of 3 up to, but not including, num
- which is faster?
- mystery only does an iteration for the numbers that we want
classes
- A class is a template for an object
- a class defines:
- the types of things you can do to/with an object of that class (i.e. methods)
- how you can create new objects
- what data we need to keep track of for an object
- Let's say we want to come up with a template (i.e. class) for balls
- What questions might we ask about a ball? What types of things might we do to a ball?
- how big is it?
- what is it filled with?
- what's it's color?
- where is it?
- move it?
- throw it?
- ...
- What information might we need to keep track of about a ball?
- size
- color
- what it's filled with
- location
- all this information defines the category of ball
- we can instantiate the class (i.e. create a new ball object) by setting all of the attributes
- each ball we create will have it's own individual attributes
- changing the attributes of one ball (e.g. the location) will NOT affect the other balls
- The class then describes all the things we can do with a particular instance of a ball (any ball!):
- throw it
- ask about it's color
- ...
designing a class in Java
- three key things when designing a class:
- what are the methods we want the object to have?
- what types of things do we want the object to do?
- what types of questions might we want to ask about the object?
- what data do we need to keep track of *per* object?
- what differentiates one object of the class from another?
- what information do we need to make or create a new object of that class?
let's design a card class to represent a playing card
- what methods do we want the object to have?
- what suit?
- what number?
- maybe:
- face-up/face-down?
- change suit/number?
- location?
- what data do we need to keep track of per card?
- number
- suit
- maybe: location, face-up/face-down
- what information do we need to know to create a new card?
- number
- suit
writing a class in Java
- first, we tell Java that we're declaring a new class
public class ClassName{
}
- this goes in a file that has the same name as the class with the extension .java
- by convention, class names are capitalized
- for all of the data that we want to store, we create "instance variables"
- these are just variables declared inside of the class
- they are available to methods declared inside the class
- for each bit of functionality we want, we write methods
- the "constructor" of an object is a method that has the same name as the class and NO return type
- it's used to create (or construct) a new object
look at the BasicCard class in the
ClassBasics code
- two instance variables: number and suit
- each card object will have its own copy of these variables
- 4 methods (including the constructor)
- all are very simple!
- BasicCard is the constructor and is called when we're creating a new card
- it takes two parameters
- all it does is store these two parameters away
- getSuit and getNumber
- just give data back
- cheat()
- doesn't take any parameters or give anything back
- alters the state of the card
creating a new object
- now that we have defined out class, we can create a new object that is an instance of that class
- creating a new class also creates a new type
BasicCard card = new BasicCard(10, "hearts")
- BasicCard is the type
- card is the name of the variable
- this first part is just like what we've been doing all along
- = (assignment)
- new: keyword that tells Java to create a new object
- BasicCard(...) is the call to the constructor
- Java creates a new object
- that object has its own copies of the instance variables
- the constructor code is then called
main
- ALL Java programs have to start in a "main" method
- the syntax for the main method is:
public static void main(String[] args){
...
}
- To run a program, you click on the green arrow button
- Eclipse will look for a main method in the currently open class
- and the program will start executing there
look at the main method in the BasicCard class in the
ClassBasics code
- constructs two different card objects
- prints out the number and suit for the two cards
- calls the cheat method on card1
- then prints out the number and suit for the two cards again
- when you run the code:
- you see each of the cards gets their own copies of the instance variables
- each object has it's own state
- the cheat method changes the state of card1, but card2 is unaffected