More Types, Methods, Conditionals
More Types, Methods, Conditionals
More Types, Methods, Conditionals
Example:
String a = “a”;
String b = “letter b”;
a = “letter a”;
String c = a + “ and “ + b;
Operators
Symbols that perform simple computations
Assignment: =
Addition: +
Subtraction: -
Multiplication: *
Division: /
Outline
Lecture 1 Review
More types
Methods
Conditionals
Division
Division (“/”) operates differently on
integers and on doubles!
Example:
double a = 5.0/2.0; // a = 2.5
int b = 4/2; // b = 2
int c = 5/2; // c = 2
double d = 5/2; // d = 2.0
Order of Operations
Precedence like math, left to right
Right hand side of = evaluated first
Parenthesis increase precedence
double x = 3 / 2 + 1; // x = 2.0
double y = 3 / (2 + 1); // y = 1.0
Mismatched Types
Java verifies that types always match:
To call a method:
NAME();
class NewLine {
public static void newLine() {
System.out.println("");
}
To call:
NAME(EXPRESSION);
class Square {
public static void printSquare(int x) {
System.out.println(x*x);
}
To call:
NAME(arg1, arg2);
class Multiply {
public static void times (double a, double b) {
System.out.println(a * b);
}
Math.cos(Math.PI / 2)
Math.pow(2, 3)
Math.log(Math.log(x + y))
Outline
Lecture 1 Review
More types
Methods
Conditionals
if statement
if (CONDITION) {
STATEMENTS
}
public static void test(int x) {
if (x > 5) {
System.out.println(x + " is > 5");
}
}
x == y: x equals y
( equality: ==, assignment: = )
Boolean operators
&&: logical AND
||: logical OR
String to int:
int foo = “18”; // ERROR!
int foo = Integer.parseInt (“18”);
Comparison operators
Do NOT call == on doubles! EVER.
a = 6.123233995736766E-17
a == b will return FALSE!
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.