Introduction to Java
Jim White
Java Developer
Working with, modifying variables
Operators: built-in symbols for various tasks
Arithmetic operators
public class Main {
public static void main(String[] args) {
// Assign calculation to variable a
int a = 5 + 6;
// Print the value of a
System.out.println(a);
}
}
11
// Adding doubles double x = 5.5; double y = 4; double xPlusY = x + y; // Value is 9.5
// String concatenation String message = "Hello"; String messageForJim = message + " Jim"; // Value is "Hello Jim"
++
to raise value by 1int age = 30;
// Using increment to add 1
age++; // Value is now 31
// Subtract double productPrice = 99.9; productPrice = productPrice - 10; // Value is now 89.9
// Decrement value int productLaunch = 99; productLaunch--; // Values is now 98
int price = 100; int quantity = 1; // Multiply two integers int orderRevenue = newPrice * quantity; // Value is 100, int
double newPrice = 94.9; int quantity = 1; // Multiply with double double newOrderRevenue = newPrice * quantity; // Value is 94.9, double
class IntDivision {
public static void main (String[] args){
int numOrders = 100;
int days = 30;
// Output is 3,
// because both numbers are integers
System.out.println(numOrders/days);
}
}
3
class DoubleDivision {
public static void main (String[] args){
int numOrders = 100;
int days = 30;
// Either assing to double
double avgOrders = numOrders / days;
System.out.println(avgOrders);
// Or use a double in the division
System.out.println(numOrders/30.0);
...
3.3333333333333335
3.3333333333333335
class IntDivision {
public static void main (String[] args){
int numOrders = 100;
int days = 30;
// Output is 3,
// because both numbers are integers
System.out.println(numOrders / days);
}
}
3
class DoubleDivision {
public static void main (String[] args){
int numOrders = 100;
int days = 30;
// Either assing to double
double avgOrders = numOrders / days;
System.out.println(avgOrders);
// Or use a double in the division
System.out.println(numOrders / 30.0);
}
}
3.3333333333333335
Operation | Operator | Example |
---|---|---|
Addition | + |
5 + 1.5 |
Subtraction | - |
3.6 - 2 |
Multiplication | * |
0.3 * 2 |
Division | / |
59 / 4 |
int
s returns an int
, unless assigned to double
double
returns a double
Introduction to Java