Arithmetic operators#
| Operator | Meaning | 17 op 5 |
|---|---|---|
+ |
add (also joins strings) | 22 |
- |
subtract | 12 |
* |
multiply | 85 |
/ |
divide (integer division for ints) | 3 |
% |
remainder | 2 |
3 2 3.4 -2 0.30000000000000004 Sum: 175 Sum: 22
"Sum: " + a + b gives Sum: 175, not Sum: 22 - once the left side is a String, + joins text. Use brackets around arithmetic inside print statements.
0.1 + 0.2 is not exactly 0.3 because decimals are stored in binary. For money in real applications, use long paise or java.math.BigDecimal.
Relational and logical operators#
Relational operators (==, !=, >, <, >=, <=) return a boolean. Logical operators combine booleans: && (and), || (or), ! (not). && and || short-circuit.
Eligible for placement: true Scholarship: false Not eligible: false false
Assignment, increment and the ternary operator#
x = 4 i=7 j=5 k=7 Pass
The Math class#
java.lang.Math is available without import:
12.0 1024.0 7.5 42 5.0 4.0 5 3.141592653589793 Hypotenuse: 5.00 Dice is between 1 and 6: true
Reading input with Scanner#
java.util.Scanner reads from the keyboard (System.in). Import it, create one Scanner, and call the method for the type you want:
| Method | Reads |
|---|---|
nextInt() |
an int |
nextDouble() |
a double |
nextLong() |
a long |
next() |
one word |
nextLine() |
the rest of the current line |
nextBoolean() |
true/false |
hasNextInt() |
is there another int to read? |
Name: Marks in 3 subjects: Priya Soni, your average is 85.00
Scanner से input पढ़ने के लिए पहले import java.util.Scanner; लिखें, फिर Scanner sc = new Scanner(System.in); बनाएँ। number के लिए nextInt()/nextDouble(), एक शब्द के लिए next() और पूरी line के लिए nextLine() का उपयोग करें।
After nextInt(), the Enter key (newline) is still waiting in the input. A following nextLine() then returns an empty string! Call an extra sc.nextLine(); to consume it, or read everything with nextLine() and convert using Integer.parseInt(...).
117 -> Siddharth Rathore
Operator precedence (high to low)#
()and postfixx++- unary:
++x,-x,!, casts */%+-<><=>=instanceof==!=&&||?:=+=-=...
Summary#
/between ints truncates;%keeps the sign of the left operand; String+joins left to right.&&and||short-circuit; the ternary?:picks between two values.Mathhassqrt,pow,abs,max,round,random...Scannerreads typed input; watch out for the leftover newline afternextInt().