package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
// result is now 3
int result = 1 + 2;
System.out.println(result);
// result is now 2
result = result - 1;
System.out.println(result);
// result is now 4
result = result * 2;
System.out.println(result);
// result is now 2
result = result / 2;
System.out.println(result);
// result is now 10
result = result + 8;
// result is now 3
result = result % 7;
System.out.println(result);
}
}
Output
3
2
4
2
3
Example 2 การรวมข้อความ หรือ Concat String
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
Output
This is a concatenated string.
Example 3 การ เพิ่ม ลด ค่า
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
// result is now 1
int result = +1;
System.out.println(result);
// result is now 0
result--;
System.out.println(result);
// result is now 1
result++;
System.out.println(result);
// result is now -1
result = -result;
System.out.println(result);
boolean success = false;
// false
System.out.println(success);
// true
System.out.println(!success);
}
}
Output
1
0
1
-1
false
true
Example 4 การ เพิ่ม ลด ค่า ในตัวแปร
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}
Output
value1 is 1 AND value2 is 2
value1 is 1 OR value2 is 1
Example 7 การใช้และเปรียบเทียบค่า Boolean
package com.java.myapp;
public class MyClass {
public static void main(String[] args) {
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}