double x = 3.14;
IO.println(x);
IO.println((int)x);
Type Casting Danger: Different Amounts
You can also run into trouble when the data type you are casting from has less available space then the type you are casting to
For example int has 32 bits to work with where as short only has 16 bits
Thus, if you have a really big int it won’t all fit into a short and you will get data loss
We will talk about this more later but try this example now anyway:
int x = 2_147_483_647; // Max Int
IO.println(x);
IO.println((short)x);
Java Rules For Integer vs Floating Point Math
An operator’s operands (arguments) must have same type
The result will have the same type as the arguments
Some times Java can ensure this property implicitly
When 1 type can represent the other without loss
For all operators if either operand is a double then the result with be a double
Thus, when performing division if you want floating-point division cast 1 or both operands to double
If you want integer division then both arguments must have type int
Relational Operators
Java has all the standard relational operators:
Name
Symbol
Equal
==
Not Equal
!=
Less Than
<
Greater Than
>
Less Than Equal
<=
Greater Than Equal
>=
Boolean Operators
Java has all the standard boolean operators:
Name
Symbol
And
&&
Or
||
Not
!
Python vs Java: Boolean Operators
Python capitalizes booleans (True and False) whereas Java does not (true and false)
Python
if True and False or not True:
print("hello")
Java
if (true && false || !true) {
IO.println("hello");
}
Combining Operators With Assignment
Every operator which has two operands has an assignment shortcut
For example:
// Variable declarations omitted
x += y // x = x + y
x *= y // x = x * y
x /= y // x = x / y
x %= y // x = x % y
q &&= p // q = q && p
Increment and Decrement
Incrementing and decrementing by 1 is so common that each received a special operator ++ and -- respectively
For example:
int x = 0;
x++; // x = x + 1
x--; // x = x - 1
Python vs Java: Randomness
Recall, that all randomness in computers is actually pseudo randomness
Meaning it really is just a sequence of numbers which appears random but if you know which number started the sequence you know the whole sequence
This first number is referred to as the seed
# Set seed to 123
random.seed(123)
# Generate a number between [1,10]
x = random.randint(1, 10)
# Print it
print(x)
// Create Random object and set seed to 123
Random random = new Random(123);
// Generate a number between [1,10]
int x = random.nextInt(1, 11);
// Print it
IO.println(x);