Java Basics

Printing

System.out.println("Hello world");
 
// println for print in new line
// print just keeps printing on the same

Variables

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";

Data types

Choose based on the range you need — saves memory.

  • byte — whole numbers from -128 to 127. Use instead of int when value is guaranteed within that range, to save memory.
  • short — whole numbers from -32 768 to 32 767.
  • int — whole numbers from -2 147 483 648 to 2 147 483 647. Default choice for numeric variables.
  • long — whole numbers from -9.2×10¹⁸ to 9.2×10¹⁸. Used when int isn’t large enough. End the literal with "L".
  • float / double — fractional numbers. Suffix with "f" (float) or "d" (double). float has ~6–7 decimal digits of precision; double has ~16. Prefer double for most calculations.

Casting

  • Widening (automatic): byteshortcharintlongfloatdouble
  • Narrowing (manual): doublefloatlongintcharshortbyte

Arithmetic operators

OperatorNameDescriptionExample
+AdditionAdds two valuesx + y
-SubtractionSubtracts one value from anotherx - y
*MultiplicationMultiplies two valuesx * y
/DivisionDivides one value by anotherx / y
%ModulusReturns the division remainderx % y
++IncrementIncreases value by 1++x
--DecrementDecreases value by 1--x

Assignment operators

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3

Comparison operators

OperatorNameExample
==Equal tox == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Logical operators

OperatorNameDescriptionExample
&&Logical ANDTrue if both statements are truex < 5 && x < 10
||Logical ORTrue if one statement is truex < 5 || x < 4
!Logical NOTReverses the result!(x < 5 && x < 10)

Strings

text.length()
text.toUpperCase()
text.toLowerCase()
text.indexOf("")
text1.concat(text2)

Escape characters

EscapeResultDescription
\''Single quote
\""Double quote
\\\Backslash

String control codes

CodeResult
\nNew line
\rCarriage return
\tTab
\bBackspace
\fForm feed

Math

Math.max(x, y)   // returns highest value
Math.min(x, y)   // returns lowest value
Math.sqrt(x)
Math.abs(x)
Math.random()    // returns a random number between 0.0 (inclusive) and 1.0 (exclusive)
int randomNum = (int)(Math.random() * 101);  // 0 to 100

See next