/* ExpressionExample.java Examples of basic expressions in Java */ package pkg119_02_variables.variableEx; public class ExpressionExample { public static void main(String[] args) { int x = 2; int y = 5; // evaluating expression // plug in variable values // order of operations // * / % left to right // + - left to right int z = 12 + 3 * y / 15 - x % 2; // 12 + 3 * 5 / 15 - 2 % 2 // 12 + 15 / 15 - 2 % 2 // 12 + 1 - 2 % 2 // 12 + 1 - 0 // 13 - 0 // 13 // result goes in z System.out.println(z); // precedence can be changed with parentheses x = (x + 7) * 3; // (2 + 7) * 3 // 9 * 3 // 27 // result goes in x System.out.println(x); // increment and decrement x++; // same as x = x + 1 y--; // same as y = y -1 System.out.println(x); System.out.println(y); // more shortcuts x += 5; // same as x = x + 5 y -= 5; z *= 2; x %= 2; // string concatenation String str = "hello"; String str2 = " world"; // + to stick strings together String hw = str + str2; System.out.println(hw); // can do right inside println System.out.println(str + str2); // no problem with str on both sides str = str + str2; System.out.println(str); // shortcut str += "!"; System.out.println(str); // + for addition and concatenation int num = 12; String out = num + " is the answer"; // 12 + " is the answer" // "12" + " is the answer" -- int becomes String // "12 is the answer" System.out.println(out); // double quotes make a String literal // doesn't matter if string has name of variable in it // String literals do not get turned into variables! out = "num" + " is the answer"; // "num is the answer" System.out.println(out); System.out.println(num + 1 + "is too big"); // num + 1 + "is too big" // 12 + 1 + "is too big" // 13 + "is too big" // "13" + "is too big" // "13is too big" -- if I don't put in space, no space System.out.println("just silly:" + num + 1); // "just silly:" + num + 1 // "just silly:" + 12 + 1 // "just silly:" + "12" + 1 // "just silly:12" + 1 // "just silly:12" + "1" // "just silly:121" } }