Download slides

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

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

Document related concepts
no text concepts found
Transcript
CIT 590
Intro to Programming
Java lecture 4
Agenda
• Types
• Collections – Arrays, ArrayLists, HashMaps
• Variable scoping
• Access modifiers – public, private, protected and what is
the default?
• Objects interacting with other objects
Types
Primitive data types
If you want to store just a single value, the following types
are used
int, double, boolean, char
int x;
x = 3;
double y;
y = 3.5;
Strings
Strings are basic enough that Java uses syntax that
reminds you of primitive data types
String s = “alphabetagamma”;
s = s + “456”;
s now has the value alphabetagamma456.
Objects
• Almost all of Java programming is done in an object
oriented way.
• To create instances of objects the syntax is
Classname variablename =
new Classname(constructor arguments)
• Every java program will have a class and therefore will
create one or more objects.
Java class
public class Thing {
// instance variables
int property1;
String property2;
//constructor
public Thing (int property1, String property2) {
this.property1 = property1;
this.property2 = property2;
}
//other methods
method1
method2
public static void main(String[] args) {
Thing t = new Thing(3, “ab”);
t.method1(appropriate arguments);
t.method2(appropriate arguments);
}
Reminder of method syntax
Return type name(Argument data type1 argumentName1,
Argument data type 2 argumentName2)
{
return something with the correct return type
}
int function(double num, String s) {
int x = 7;
return x;
}
Returning from a method in Java
If a function returns nothing the return type is void. In those
cases you are allowed to write return; but nothing else is
allowed.
For functions that return something, Java is strict about its
returns.
Every path through a method must return.
Every path through a method must return the same data type.
Every path through a method must return something whose data
type is the same as that committed to in the method definition.
Strings
Actually Strings are objects.
String s = “Hurrah for the red and the blue”;
s.substring(0,6) gives you Hurrah
s.charAt(2) gives you the char ‘r’
The plus operator
• + means addition for integers and concatenation for
strings
• int x = 3; int y = 4;
System.out.println(x + y + “ = “ + x + y);
This will give you “7 = 34”
Remember to evaluate left to right and keep track of what
datatype you are dealing with.
Arrays
• String[] - an array of strings;
• int[] – an array of ints
int[] numbers = new int[10];
Array of 10 numbers
• Indexing is the same as python
for (int i = 0 ; i < numbers.length; i++) {
// do stuff with numbers[i]
}
Arraylists
• Think of Arraylists in exactly the same way as lists in Python.
• You will have to import java.util.ArrayList; Most people just
import java.util.* at the start of their programs.
• The key difference is the way you initialize one of them
• ArrayList<Integer> numberList =
new ArrayList<Integer>();
• ArrayList<String> stringList =
new ArrayList<String>();
• ArrayListExperiments.java
• http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
13
Hashmaps
• The equivalent of python dictionaries.
• With both ArrayLists and Hashmaps, the syntax only allows for class
datatypes
ArrayList<String> is ok
ArrayList<int> is not ok.
Instead you have to write ArrayList<Integer>
Similarly if you have a dictionary in Python that maps string keys to
integer values the way to declare that in Java is
HashMap<String, Integer> and not HashMap<String, int>
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
toString() method of a class
• Same as the __str__ method in Python
• Return a string. DO NOT PRINT a string
public String toString() {
String returnString = “”;
//modify returnString over here in some way
return returnString;
}
• example Card.java
Unit testing with objects
• assertEquals does not work ‘out of the box’ when it comes
to objects
• For HW9, it is totally OK to use the toString() method or
knowledge of the internals of the objects to compare two
objects
assertEquals(object1.toString(), object2.toString());
Totally OK for HW9
16
Methods may have local variables
• A method may have local (method) variables
• Formal parameters are a kind of local variable
• int add(int m, int n) {
int sum = m + n;
return sum;
}
• m, n, and sum are all local variables
• The scope of m, n, and sum is the method
• These variables can only be used in the method, nowhere else
• The names can be re-used elsewhere, for other variables
17
Blocks (Compound statements)
• Inside a method or constructor, whenever you use braces,
you are creating a block, or compound statement:
int absoluteValue(int n) {
if (n < 0) {
return -n;
}
else return n;
}
• The scope of a variable is the block in which it is defined.
18
Nested scopes
1 int fibonacci(int limit) {
2
int first = 1;
3
int second = 1;
4
while (first < 1000) {
5
System.out.print(first + " ");
6
int next = first + second;
7
first = second;
8
second = next;
9
}
10
System.out.println( );
11 }
19
Declarations in a method
• The scope of formal parameters is the entire method
• The scope of a variable in a block starts where you
define it and extends to the end of the block
if (x > y) {
int larger = x;
}
else {
int larger = y;
}
return larger;
Scoped to the if block
Scoped to the else block
Illegal 
20
The for loop
• The for loop is a special case
• You can declare variables in the for statement
• The scope of those variables is the entire for loop
• This is true even if the loop is not a block
void multiplicationTable() {
int i;
for (i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++)
System.out.print(" " + i * j);
System.out.println();
}
}
Access modifiers
Do not worry about the subclass column right now.
World means a different class, different package.
Access modifiers
• The best practice is to have the instance variables be private.
• The best practice is to have most methods be public
• Because we often do want to access and potentially modify the
instance variables, a very common set of methods are getters and
setters
Assume we have a class with a private instance variable called counter.
public int getCounter() { return counter; }
public void setCounter(int counter) {
this.counter = counter;
}
23
null
• If you declare a variable to have a given object type, for
example,
• Person john;
• String name;
• ...and if you have not yet assigned a value to it, for example,
with
• john = new Person();
String name = “John Smith";
• ...then the value of the variable is null
• null is a legal value, but there isn’t much you can do with it
• It’s an error to refer to its instance variables, because it has none
• It’s an error to send a message to it, because it has no methods
• The error you will see is NullPointerException