TurkuBasicOOPinJava / Week 1: Types, condition clauses and loops /4. Match expressions and results AND DATATYPE
KaiquanMah's picture
Rename Week 1: Types, condition clauses and loops/4. Match expressions and results to Week 1: Types, condition clauses and loops/4. Match expressions and results AND DATATYPE
431c880 verified
raw
history blame
2.8 kB
Java's basic types
Type Saved information Number range
byte integer 1 byte
short integer 2 bytes
char character One Unicode-system character
int integer 4 bytes
long integer 8 bytes
float floating point number (i.e decimal number) 4 bytes
double floating point number 8 bytes
eg
public class Example {
public static void main(String[] args) {
String name = "Mike Madeup";
int age = 23;
double height = 171.25;
}
}
eg
// boolean (IN LOWERCASE) - true, false
public class Example {
public static void main(String[] args) {
boolean True = true;
boolean False = false;
boolean first_larger = 10 > 3;
System.out.println(first_larger);
}
}
Output:
true
eg
public class Example {
public static void main(String[] args) {
int first = 23;
int second = 10;
int multiply = first * second;
int sum = first + second;
int largeNum = (first + second) * 100;
System.out.println(multiply);
System.out.println(sum);
System.out.println(largeNum);
}
}
Output:
230
33
3300
eg
//If there are several different types involved in an expression, the type of the result is determined by the "largest" type, for example:
public class Example {
public static void main(String[] args) {
int integer = 10;
double float = 5.0;
System.out.println(integer * 2);
System.out.println(float * 2);
System.out.println(integer * 2.0);
System.out.println(integer + integer);
System.out.println(integer + float);
}
}
Output:
20
10.0
20.0 // int * float -> float
20
15.0 //int + float -> float
eg
//division
public class Example {
public static void main(String[] args) {
System.out.println(5 / 2);
System.out.println(5 / 2.0);
System.out.println(5.0 / 2);
System.out.println(5.0 / 2.0);
}
}
Output:
2 // int/int -> int
2.5 // int/float -> float
2.5 // float/int -> float
2.5 // float/float -> float
eg
public class Example {
public static void main(String[] args) {
int divided = 10;
int divisor = 4;
// This returns and integer...
System.out.println(divided / divisor);
// Result is wrong here too...
double divide = divided / divisor;
System.out.println(divide);
//...but this works:
System.out.println(divided * 1.0 / divisor);
}
}
Output:
2 // int/int -> int (rounded down)
2.0 // int/int -> int (rounded down) -> then convert to double
2.5 // 'new' double/int -> double
eg
2 * (3 - 1) 4
6/4 1
2 * 3.0 + 1 7.0
2.0 * (3.0 - 1.0) 4.0
2 * 3 + 1 7
2 * (3 + 1) 8
2 * (3.0 + 1) 8.0
6/(2*2.0) 1.5