-
Notifications
You must be signed in to change notification settings - Fork 68
/
chapter03-jshell_vs_java.jsh
62 lines (49 loc) · 1.92 KB
/
chapter03-jshell_vs_java.jsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// To starts, run jshell --enable-preview which is a program able to interpret Java syntax
// then cut and paste the following lines to see how it works
// To exit jshell type /exit
// # Jshell vs Java
// We are using jshell, jshell has mostly the same behavior as Java
// but because it's interactive it can do more
// ## Re-defining records or variables
// you can define a record or a variable several times, jshell will use the most recent one
record Point(int x, int y) { }
var p = new Point(2, 3);
record Point(int x, int y) {
int distanceInX(int anotherX) {
return Math.abs(x - anotherX);
}
}
var p = new Point(2, 3);
System.out.println(p.distanceInX(0));
// and you can also directly write a method outside a record,
// it will act as a static method
void hello() {
System.out.println("hello !");
}
hello();
// ## Special commands
// There are a bunch of special commands that starts with '/'
// you can use /help if you want to know more
// By example, you have also a list of the packages automatically imported
/import
// and you can import new package dynamically
import java.util.zip.*
// note that unlike import in Python or #include in C, Java import doesn't load any code,
// it says that is you search a name of a type, here are the packages to search.
// If a type appear in more than one package, an error will be reported and you will
// have to import the type explicitly (without any *)
// by example, to import a List of the package java.util
import java.util.List;
// # Entry Point
// With jshell, the code is executed from top to bottom
// In Java, when executing `java Hello`, the launcher looks for a static method
// named `main` that
// - must be visible from the outside (`public`)
// - takes an array of String (`String[]`) and
// - returns no value (`void`)
record Hello() {
public static void main(String[] args) {
System.out.println("Hello !");
}
}
// unlike in C, the first argument is `args[0]`.