@inponomarev
Ivan Ponomarev, Synthesized.io/MIPT
Hello, World!
New Maven Project
New package
New class
psvm — sout
Manifest (runnable jar)
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
_ (underscore)
null true false
(Java 9)
open module requires transitive exports
opens to uses provides with
(Java 10)
var
(Java 14)
yield record
(Java 15)
sealed non-sealed permits
/**
* This is the first sample program in Core Java Chapter 3
* @version 1.01 1997-03-22
* @author Gary Cornell
*/
public class FirstSample
{
public static void main(String[] args)
{
/*multiline
comment*/
System
.out //single-line comment
.println("We will not use 'Hello, World!'");
}
}
Value
Primitive
byte
, short
, int
, long
char
float
, double
,
boolean
Reference
Arrays
Objects
null
, damn it!
Type | Storage | Range |
| 1 byte | –128 to 127 |
| 2 bytes | –32,768 to 32,767 |
| 4 bytes | –2,147,483,648 to 2,147,483, 647 |
| 8 bytes | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Long 100L
Underscores 1_000_000
Hexadecimal 0xCAFEBABE
Binary 0b0101
Octal 010
Type | Storage | Range |
| 4 bytes | Approximately ±3.40282347E+38F (6–7 significant decimal digits) |
| 8 bytes | Approximately ±1.79769313486231570E+308 (15 significant decimal digits) |
2.998e8
1.0
(1.
)
3.14F
0x1.0p-3
(0.125, 2 to the power of minus three)
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Double.NaN
System.out.println(2.0 - 1.1)
outputs 0.8999999999999999
NEVER USE DOUBLE FOR COUNTING MONEY!
System.out.println(2.0 / 0.0)
outputs 'Infinity` (but 2 / 0 is 'divizion by zero')
System.out.println(0.0 / 0.0)
outputs 'NaN`
Comparison with infinity and NaN
does not work, we need to use Double.isNaN
, Double.isInfinite
.
strictfp
double x = 9.997F; //float to double converted implicitly
int nx = (int) x; //9
nx = (int) Math.round(x); //10
char
type16 bit
code unit in the UTF-16 encoding
Not always a whole character (although almost always)!
Be careful with Unicode, use 'String'
char
literals'ы'
'\u03C0'
(Greek π)
'\''
(escaped single quote)
Unicode escape trap: // Look inside c:\users
String s = "Hello, world!";
//Before Java 13
String txt =
"Some\n" +
" Nested\n" +
" Text\n" +
" Is\n" +
"Here\n";
Some
Nested
Text
Is
Here
String txt = """
Some
Nested
Text
Is
Here
""";
//The maximum number of spaces ahead has been removed:
Some
Nested
Text
Is
Here
Escape sequence | Name | Unicode Value |
| Backspace | \u0008 |
| Tab | \u0009 |
| Linefeed | \u000a |
| Carriage return | \u000d |
| Double quote | \u0022 |
| Single quote | \u0027 |
| Backslash | \u005c |
| intentional whitespace (Java 13+) | |
| line continuation (Java 13+) |
boolean
typetrue
and false
Unlike C and many other languages, integers are not automatically cast to boolean
Avoids if (x = 0) {…
errors
// declaration
double salary;
int vacationDays;
long earthPopulation;
boolean done;
// not very welcomed
int i, j;
// technically possible, but . . .
int суммаНДФЛ;
int vacationDays;
System.out.println(vacationDays); //COMPILATION ERROR
// variable not initialized
Possible initialization methods:
int vacationDays;
vacationDays = 12;
int vacationDays = 12;
final
keyword (constants)final
is used in two cases:
prohibits changing the value
prevents overriding of methods/classes
final int a;
...
a = 42; // initialization
...
a = 43; // compilation error:
// variable a might already have been initialized
Place of definition: class, method, block
In Java, there is nothing outside classes ("global" variables)!
int n;
. . .
{
int k;
int n; // Error--can't redefine n in inner block
. . .
} // k is only defined up to here
var i = 1; // i is of int type
//BEFORE JAVA 10
URL codefx = new URL("http://codefx.org");
URLConnection connection = codefx.openConnection();
Reader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
//AFTER JAVA 10
var codefx = new URL("http://codefx.org");
var connection = codefx.openConnection();
var reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
Arithmetic: +
, -
,*
, /
, %
Division works as integer if both arguments are integer
Unary +
and -
.
|
| |
|
| |
|
| |
|
| |
|
| |
|
| the highest (sign) bit is retained |
|
| the highest (sign) bit is filled with zero |
5 >> 32 == ?
5 >> 32 == 5
only 5 low-order bits of the second operand (0..31) are used for int
,
only 6 low-order bits of the second operand (0..63) are used for long
&
, |
, ^
, ~
<
<=
>
>=
instanceof
==
!=
Without short circuiting: '&', '|', '^', '!' (exclamation instead of a tilde)
With short-circuiting '&&', '|| `.
x != 0 && 1 / x > x + y // no division by 0
int x;
System.out.println(x = 42); //prints 42
Example of use:
while ((n = readValue()) != null)
... //do something with n
a++
, ++a
a--
, --a
+=
, -=
, *=
, /=
, %=
, &=
, |=
, ^=
, <<=
, >>=
, >>>=
WARNING: These operations may appear to be atomic. But they are not.
x < y ? x : y
Operators | Associativity |
| Left to right |
| Right to left |
| Left to right |
| Left to right |
| Left to right |
| Left to right |
| Left to right |
Operators | Associativity |
| Left to right |
| Left to right |
| Left to right |
| Left to right |
| Left to right |
//Conjunction operator has higher priority than disjunction, that's why
a || b && c
// is equivalent to
a || (b && c)
Operators | Associativity |
| Right to left |
| Right to left |
//Since += associates right to left, the expression
a += b += c
//means
a += (b += c)
//That is, the value of b += c
// (which is the value of b after the addition)
//is added to a.
There isn’t one!
You can list multiple statements separated by commas in for(…)
and try(…)
blocks
if
statement
| ![]() |
if
+ block
| ![]() |
if
+ block + else
| ![]() |
else
is grouped with the nearest if
| ![]() |
else if
chains
| ![]() |
switch
Same nonsense as in C/C++:
| ![]() |
switch
-case
peculiarities:Do not forget about break`s (Checkstyle-like utilities will remind you), or else all the code to the end of `switch
will be executed, like in C language!
You can use switch
with integers, char
-s, String
-s (Java 7+) and enum
-s.
JDK 12 & 13 — Preview Feature
JDK 14 — Standard Feature
int numLetters = switch(day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case SATURDAY -> 8;
default -> 9;
}
Expression | Statement |
|
|
Expression | Statement (Good Old C-style Switch) |
|
|
You can build an array of any type.
The length of the array can be determined in the runtime, but cannot be changed after creation.
The array is allocated on the heap and is passed by reference.
Arrays verify the data type (ArrayStoreException
) and boundaries ('ArrayIndexOutOfBoundsException') in the run time.
Harsh Truth of Life: Chances are you won’t use arrays in modern code.
Two options:
int[] a
'int a[]' — don’t do that
Initialization:
int[] a = new int[100];
int[] a = {1, 3, 5};
anonymous array: foo(new int[] {2, 4, 6});
int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12; // now smallPrimes[5] is also 12
luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);
//now luckyNumbers is a separate array
//and it became twice as long
String[] a = new String[1];
// Compiles. after all, a string is an object,
// and so why not think of an array of strings as an array of objects?
Object[] b = a;
// runtime ArrayStoreException
b[0] = 5;
(All this is terribly incompatible with generics and Collections API that try to catch type errors at compile time, but more on that later.)
There are none really, but use can build arrays of arrays.
| ![]() |
| ![]() |
while
loop: same as in C
| ![]() |
final boolean flag = false;
. . .
while (flag) {
. . . //won't compile, unreachable code
}
do while
: loop with postcondition
| ![]() |
Harsh Truth of Life: do-while
is needed very rarely.
for
loopsAgain, everything is the same as in C (in fact, the abbreviation of the while
loop):
for (int i = 1; i <= 10; i++)
System.out.println(i);
And even though there is no "comma" operator, you can do this (but you don’t need to):
for (int i = 1; i <= 10; i++, j++)
System.out.println(i);
for (int i = 1; i <= 10; i++)
{
. . .
}
// i no longer defined here
int i;
for (i = 1; i <= 10; i++)
{
. . .
}
// i is still defined here
break
and continue
To interrupt the entire cycle:
while (years <= 100) {
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
if (balance >= goal) break;
years++;
}
Move on to the next cycle:
Scanner in = new Scanner(System.in);
while (sum < goal) {
System.out.print("Enter a number: ");
n = in.nextInt();
if (n < 0) continue;
sum += n; not executed if n < 0
}
goto
, but there are labels for break
and continue
!Scanner in = new Scanner(System.in);
int n;
// label is here!
read_data: while (. . .) {
. . .
for (. . .) {
System.out.print("Enter a number >= 0: ");
n = in.nextInt();
if (n < 0)
break read_data;
// break out of read_data loop
. . .
}
}
if (n < 0) {
// deal with bad situation
} else {
// carry out normal processing
}