No Slide Title - Calvin College

Download Report

Transcript No Slide Title - Calvin College

Java Basics
Joel Adams and Jeremy Frens
Calvin College
(1/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Classes
Last time, we saw that classes play a central role in Java.
Pattern:
AccessMode class TypeName {
Declarations
}
where AccessMode is either public or private.
Example:
public class Person {
// declarations of Person attributes
}
Java style: Names of classes begin with a capital letter.
(2/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Java Primitive Types
Java has two kinds of types: primitive vs. reference types.
The four most commonly used primitive types include:
Type
Bits Stores
int
32 integers (…, -3, -2, -1, 0, 1, 2, 3, …)
double
64 real numbers (-3.5, 0.0, 1.67, 3.0e8, …)
char
16 characters ('A', 'a', '?', '!', '1', '2', '+', '-', …)
boolean ?? logical values (false, true)
Java also provides:
(3/20)
byte (8 bit char),
short (16 bit int.),
long (64 bit int.), and
float (32 bit real).
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Variable Declarations
Java requires that all variables be declared using a type.
Pattern:
Type VariableName [ = InitialValue ] ;
Examples: int
myAge = 45;
// sigh!
double
myHeight = 6.0; // feet
char
myGender = 'M'; // male
boolean amMarried = true;
Multiple variables of the same type can be declared together:
int
width = 100,
height = 200,
depth = 300;
(4/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Primitive Numeric Expressions
Primitive type variables can be used in the usual way:
(5/20)
int
i = 3, j = 5;
System.out.println(j+i);
System.out.println(j-i);
System.out.println(j*i);
System.out.println(j/i);
System.out.println(j%i);
//
//
//
//
//
8
2
15
1
2
double
x = 3.0, y = 5.0;
System.out.println(y+x);
System.out.println(y-x);
System.out.println(y*x);
System.out.println(y/x);
//
//
//
//
8.0
2.0
15.0
1.6666667
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Mathematical Methods
Java’s Math class provides assorted constants and methods,
including:
Math.abs(v)
Math.pow(x, y)
Math.sqrt(x)
Math.rint(x)
Math.round(x)
Math.max(x, y)
Math.min(x, y)
Math.exp(x)
Math.log(x)
// the absolute value of v
// x raised to the power y
// the square root of x
// the int closest to x
// the long closest to x
// maximum of x and y
// minimum of x and y
// e raised to the power x
// natural logarithm of x
Note that these are messages sent to a class (Math).
(6/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Assignment Statements
To change the value of a variable, use an assignment…
Pattern:
Variable = Expression ;
where Expression, Variable are each of the same type.
Examples:
energy = mass * Math.pow(C, 2);
circumf = 2.0 * Math.PI * radius;
hypot = Math.sqrt(Math.pow(a, 2) +
Math.pow(b, 2) );
A semicolon must be present at the end of every assignment.
(7/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Short-Cut Arithmetic Operators
Some assignments are used so frequently, Java provides a
short-cut for them:
Instead of Writing:
var = var + 1;
var = var - 1;
var = var + x;
var = var - x;
var = var * x;
var = var / x;
You Can Write:
var++;
or
var--;
or
var += x;
var -= x;
var *= x;
var /= x;
++var;
--var;
Assignments can also be chained together:
w = x = y = z = 1; // init. all to 1
(8/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Boolean Expressions
Boolean expressions are built using the relational operators:
x
x
x
x
x
x
== y
!= y
< y
<= y
> y
>= y
//
//
//
//
//
//
equality (gotcha)
inequality
less-than
less-than-or-equal-to
greater-than
greater-than-or-equal-to
Use the logical operators to combine relational expressions:
0 < x && x < 101
x < 1 || x >
100
!(0 < x && x < 101)
(9/20)
2003 Joel C. Adams. All Rights Reserved.
// AND
// OR
// NOT
Dept of Computer Science
Calvin College
Reference Types
In contrast to int, char, …; a class is a reference type…
Variables of that type (called handles) store addresses.
String is a commonly-used reference type:
String s = null;
// s is a handle
s = "Hi there";
char ch = '!';
// ch is primitive
s = s + ch;
// + appends
s += ch;
// append shortcut
System.out.println(s);
// Hi there!!
char firstChar = s.charAt(0),
// 'H'
lastChar = s.charAt( s.length()-1 );
You can send a message (see API) to an object via its handle.
(10/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Methods
We saw last time that classes usually contain methods…
-- the methods in a class correspond to the messages to which
an object of that class will respond.
Pattern:
AccessMode class TypeName {
AccessMode [Kind]
ReturnType methodName ( ParamDecs ) {
Statements
}
}
Method-names style: each word except the first is capitalized.
(11/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
The main() Method
Each Java program must have a method named main():
public class MyProgram {
public static void main(String [] args) {
...
}
}
A static method is a message sent to a class
(so they’re called class methods):
double result = Math.sqrt(x);
A non-static method is a message sent to an object
(an instance of a class, so they’re called instance methods):
int length = s.length();
(12/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Other Methods
Non-main methods follow the same pattern:
Example:
class Sphere {
public static double volume(double radius) {
return 4.0 * Math.PI
* Math.pow(radius, 3) / 3.0;
}
public static double mass(double radius,
double density){
return density * volume(radius);
}
...
If a method has a non-void return-type, it must
}
use a return statement to return a value.
(13/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Control Structures: if
Java’s if statement provides basic selective execution:
Example: if (s == null || s.equals("")) {
System.err.println("error");
System.exit(1);
} else
System.out.println(s);
If you are selecting a single statement, you need no braces; if
you are selecting multiple statements, you need braces.
Style: Many people just use braces all the time.
(14/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Multibranch if
The Statement following an if’s else can be another if:
Example:
public static char computeGrade(int score) {
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else if (score >= 60) grade = 'D';
else grade = 'F';
return grade;
}
Style: Java doesn’t care (much) about lines or white space…
(15/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Control Structures: switch
Java’s switch statement also provides multibranch execution:
Example:
(16/20)
switch ( score / 10 ) {
case 10: case 9:
grade = 'A'; break;
case 8:
grade = 'B'; break;
case 7:
grade = 'C'; break;
case 6:
grade = 'D'; break;
default:
grade = 'F';
}
2003 Joel C. Adams. All Rights Reserved.
Must be
int-compatible
 break
statements are
needed to
avoid “dropthrough”
behavior…
Dept of Computer Science
Calvin College
Control Structures: loops
Java provides 3 basic loops: while, do, and for.
The while loop is a test-at-the-top loop:
Example: s = myTextField.getText();
while ( invalidValue(s) ) {
statusLine.setText("invalid value");
s = myTextField.getText();
}
Or:
(17/20)
while ( true ) {
s = myTextField.getText();
if ( validValue(s) ) break;
statusLine.setText("invalid value");
}
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Control Structures: do
The do loop is a test-at-the-bottom loop:
Example:
public static void pause(double seconds) {
long startT = System.currentTimeMillis();
if (seconds > 0) {
long currentT = 0,
millisecs = (long)(1000*seconds+0.5);
do {
currentT = System.currentTimeMillis();
} while (currentT - startT <= millisecs);
} else {
System.err.println("seconds is negative");
}
(18/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Control Structures: for
Java’s for loop is an amazingly flexible counting loop:
Examples:
for (int i = 1; i <= 100; i++) {
System.out.println(i); // up by 1s
}
for (double d = 0.5; d >= -0.5; d -= 0.02) {
System.out.println(d); // down by 0.02
}
for (Node n = aList.getFirstNode();
n != null; n = n.getNextNode()) {
System.out.println(n); // traverse a list
}
(19/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College
Summary
Java categorizes types as primitive or reference.
Java expressions consist of:
Applying operators to primitive type values
Sending messages to reference type values (objects).
Static methods are messages to classes.
Non-static methods are messages to objects.
Java provides a rich set of control structures:
If and switch statements for selection;
While, do, and for statements for repetition.
(20/20)
2003 Joel C. Adams. All Rights Reserved.
Dept of Computer Science
Calvin College