forked from cirosantilli/java-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
4608 lines (3430 loc) · 145 KB
/
Main.java
File metadata and controls
4608 lines (3430 loc) · 145 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Main Java 7 cheat.
TODO: this is being split up into multiple files to make things more searchable.
Will include every test that does not take too long or produce too much output.
Assertions will be used wherever possible, and values will only be printed if
they cannot be deterministically checked.
# Preprocessor
Java has no preprocessor like in C.
Unlike C, there is no non-messy way of doing the following:
- get current line number
- get current function name
# Conditional compile according to Java version / OS
- Create an interface with a builder for implementations
- Detect OS / Java version with `System.getProperty`
http://stackoverflow.com/questions/4526113/java-conditional-compilation-how-to-prevent-code-chunks-to-be-compiled
*/
/*
# import
In Java, import is just a shorthand generator: after importing `a.b.C` you can use just C.
But you can use classes without importing as long as you pass the full path
a.b.C c = new a.b.C();
Becaues of this, every import argument must have a `.`,
otherwise it is an immediate compile error.
TODO search path?
It is not possible to import a class without package:
# import nested classes
The outer class names acts like a package.
To use the shorthand form `Inner`, you need to import as:
import Outer.Inner;
even when in the current package.
# import static
`import static` imports a static method into the current namespace.
E.g., after:
import static Math.max;
you can then use just:
max(0, 1);
instead of:
Math.max(0, 1);
It only works for static methods, for which the syntax `max()` makes sense:
non-static methods need to know which object they belong to.
# package
# Domain name convention
It is a common convention to match package names with domain names to avoid conflicts.
E.g., if you own `xyz.com`, then you could name your classes as `com/xyz/Class.java` of `com/xyz/app0/Class.java`.
Perfect bijection is of course impossible, because many domain names cannot be package names.
What to do in some of those cases:
http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html
Basically:
- replace hyphens with underscores
- prefix reserved package names like `int` and `java`
and domain names that start with numbers like `123.com` with an underscore
# Reserved package names
`java` and `java.lang` are reserved, and raise `SecurityException` at runtime.
TODO what are all reserved package names?
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
/*
# Top level classes
There can be only one public top-level class per Java file
and it *must* have the same name as the file.
The only things that can come outside of top-level classes in Java are:
- package declaration
- import statement
Having multiple top-level classes is highly discouraged and almost never seen in practice:
http://stackoverflow.com/questions/2336692/java-multiple-class-declarations-in-one-file
*/
// ERROR: cannot be public because does not match the file name.
//public class Main2 {}
// ERROR: Top level classes cannot have neither protected, private or static modifiers.
//private class Main2 {}
// OK.
class Main2 {}
public class Main {
// General purpose fields
public static int publicStaticInt;
// Field modifiers
class TransientField {
public transient int ti;
public int i;
}
// Class
public static class Empty {}
/*
Minimalistic integer wrapper.
*/
public static class MyInt {
public int i;
public MyInt(int i) {
this.i = i;
}
}
public static class TwoInts implements Serializable {
public int i;
public int j;
public TwoInts(int i, int j) {
this.i = i;
this.j = j;
}
public boolean equals(TwoInts other) {
return this.i == other.i && this.j == other.j;
}
}
// TODO break this huge test class up.
public static class Class0 {
// member
private int i = 0;
protected int member;
public Class0 class0;
// static
static int staticI = 0;
//ERROR: already defined
// int staticI = 0;
private final int finalMember;
private final int finalMemberConstructor = 0;
static private final int final_static_member = 0;
// ERROR: static final not initialized.:
//static private final int final_static_member_uinit;
public Class0() {
finalMember = 0;
}
public Class0(Class0 other) {
this.class0 = other;
this.finalMember = 0;
}
// Constructor
public Class0(int i) {
this.i = i;
member = i;
finalMember = i;
// ERROR: already initialized.
//finalMemberConstructor = 1;
this.staticI = 0;
}
public int method() {
// ERROR: cannot set final members outside constructor
//finalMember = 0;
return member;
}
public void setI(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
}
public static class OverrideEquals {
public int i;
public OverrideEquals(int i) {
this.i = i;
}
@Override
public boolean equals(Object other) {
// TODO how to do it? OverrideEquals other does not override base.
//return this.i == other.i;
return true;
}
}
public static class Finalize {
public String s;
public Finalize(String s) {
this.s = s;
}
@Override
public void finalize() {
System.out.println("finalize " + s);
}
}
public static class StaticInitializer {
static HashMap<Integer,Integer> map;
static {
map = new HashMap<>();
// It would not be possibel to do this without the static initializer.
map.put(1, -1);
System.out.println("StaticInitializer");
}
}
static class StaticField {
static final int i = 1;
// ERROR: already defined
//int i = 2;
int getI() {
// No need to prefix it with anything.
return i;
}
}
static class ExceptionInInitializerErrorTest {
static {
if (true)
throw null;
}
}
static class ExceptionInInitializerErrorFieldTest {
static int i = f();
static int f() {
if (true)
throw null;
return 0;
}
}
// Field hiding
static class FieldHideBase {
final int i = 1;
int getI() {
return i;
}
}
static class FieldHideFail extends FieldHideBase {
final int i = 2;
}
static class FieldHide extends FieldHideBase {
final int i = 2;
int getI() {
return i;
}
}
// Interface
interface EmptyInterface {}
interface EmptyInterfaceDerived extends EmptyInterface{}
interface EmptyGenericInterface<T> {}
interface EmptyGenericInterfaceDerived<T> extends EmptyGenericInterface<T> {}
interface InterfacePrivateMethod {
//private void method();
}
// Annotation
@interface EmptyAnnotation {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {
public int i();
public String s();
}
@Retention(RetentionPolicy.SOURCE)
@interface RetentionSource {}
@Retention(RetentionPolicy.RUNTIME)
@interface RetentionRuntime {}
@Retention(RetentionPolicy.CLASS)
@interface RetentionClass {}
// Enum
public enum SimpleEnum {
A,
B,
C
}
//public enum EnumPublicConstructor {
//;
//public EnumPublicConstructor() {}
//}
public enum EnumPrivateConstructor {
// TODO why is this required, but not for an enum with default constructor?
;
private EnumPrivateConstructor() {}
}
public enum EnumImplicitPrivateConstructor {
// Constructor is implicitly private.
EnumImplicitPrivateConstructor() {}
}
public enum EnumConstructor {
A(0),
B(1),
C()
// THIS semicolon is required.
;
private int i;
EnumConstructor() { this.i = -1; }
EnumConstructor(int i) { this.i = i; }
public int getI() { return this.i; }
}
// Method
static void returnVoidImplicit() {}
static class IntWrapper {
private int i;
public IntWrapper(int i) {
this.i = i;
}
public void increment() {
this.i++;
}
public int intValue() {
return this.i;
}
}
static void intWrapperByRef(IntWrapper i) {
i.increment();
}
static void intArrayByRef(int[] is) {
is[0]++;
}
static void intClass0ByRefFail(Integer i) {
// Only assigns the local `i` to a new object,
// but does not change the original `i`.
i = new Integer(i.intValue() + 1);
}
static int varargMethod(int... is) {
// Vargars passes an array to the string.
assert is.getClass() == int[].class;
return is[0] + is[1];
}
// Override TODO
//static class OverrideStatic {
//public static int method() { return 0; }
//}
//static class OverrideStaticDerived extends OverrideStatic {
//public static String method() { return null; }
//}
// Overload
static int overloadMethod(int i) {
return i;
}
static int overloadMethod(float f) {
return (int)f;
}
// ERROR: Cannot differentiate by return value.
//static float overloadMethod(int f) {
//return (float)f;
//}
static int identity(int i) {
return i;
}
static void unreachableAfterReturn() {
return;
// ERROR
//assert true;
}
static int notAStatement() {
return 0;
}
// Annotation
//public @interface MyAnnotation {
//}
//MyAnnotation (doSomething="What to do")
//public void mymethod() {
//}
public static class AnnotationOverrideBase {
public int method() {
return 0;
}
}
public static class AnnotationOverride extends AnnotationOverrideBase {
@Override
public int method() {
return 1;
}
// ERROR: does not override anything.
//@Override
public int method2() {
return 1;
}
}
public static class AnnotationDeprecated {
@Deprecated
public static int method() {
return 0;
}
}
/*
# main
The `main` function of the class is what is run if you run:
javac Main.java
java Main.class
This works since you must have exactly one class per file.
The only valid signatures are:
public static void main(String [])
public static void main(String...)
TODO can args be null?
- http://stackoverflow.com/questions/9605532/args-guaranteed-to-be-non-null
- http://stackoverflow.com/questions/3868878/java-check-if-command-line-arguments-are-null
*/
public static void main(String[] args) throws Throwable {
/*
# Variable scope
Brackets are different than in C++.
- like in C++, they prevent inner definitions from going outside
- unlike in C++, they do *not* prevent outer definitions from going inside.
*/
{
int i = 0;
{
// ERROR: unlike C++, i already defined!
//int i = 1;
// ERROR: cannot find symbol i
//i = 1;
int i2 = 0;
}
// ERROR: cannot find symbol i2
//i2 = 1;
}
/*
# Identifiers
*/
{
/*
# Valid identifier characters
http://stackoverflow.com/questions/11774099/legal-identifiers-in-java
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
The valid characters are defined by those for which:
Character.isJavaIdentifierStart(int)
is `true`. http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#isJavaIdentifierPart%28int%29
It is not clear to me if the API description there is precise or not,
it just mentions generic character sets like "combining mark" and non-spacing mark.
Actual JVM restrictions are much less strict: any byte sequence that does not contain
`; [ / < > :` is valid: http://stackoverflow.com/questions/26791204/why-does-the-jvm-allow-us-to-name-a-function-starting-with-a-digit-in-bytecode
*/
{
/*
# Dollar in identifiers
# $
The only weird character mentioned explicitly by the JLS is `$`.
Sounds like... JavaScript and mercenary money makers.
However the JLS 7 3.8 says:
> The $ character should be used only in mechanically generated source code or,
> rarely, to access pre-existing names on legacy systems
and it is easy to cause name conflicts if you do that.
So never ever use it.
*/
{
int $ = 0;
assert $ == 0;
}
}
{
int i = 0, j = 1;
assert i == 0;
assert j == 1;
}
/*
# Maximum identifier length
http://stackoverflow.com/questions/695951/max-name-length-of-variable-or-method-in-java
None basically.
*/
}
/*
# Primitive types
JLS7 4.
A limited number of types that are not objects.
They make coding in Java harder, but are important for performance:
- byte: 8 bit
- short: 16 bit
- int: 32 bit
- long: 64 bit
- float: 32 bit
- double 64 bit
- boolean
- char: Unicode
All the types have bytecode instructions that differentiate between them,
except for boolean.
`boolean` only matters to disambiguate method signatures,
where it has the identifier `Z`.
Types are also classified as:
# IntegralType
byte, short, int, long, char.
All 2's complement.
# FloatingPointType
float, double.
IEEE 754.
# NumericType
Either Integral and Floating point types.
*/
{
/*
# Definite assignment
Unlike C and C++, many types are initialized automatically
and deterministically to simple "falseish" values like `null`, `0` and `false`.
This type of compiler behavior is called:
http://en.wikipedia.org/wiki/Definite_assignment_analysis
It is mathematically not possible to do it "perfectly" TODO what does that mean exactly?
but Java has complex and generally good heuristics that do it,
that take up an entire chapter of the JSL:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html
The JSL specifies recusivelly and precisely what happens to unassigned values
through every possible statment of the language.
*/
{
// Using an uninitialized local variable is a compile-time error:
// int i;
// assert i == 0;
// Same for static final fields: TODO example
// Non-static fields on the other hand are default initialized.
// TODO why different from local variables and final fields
// http://stackoverflow.com/questions/268814/uninitialized-variables-and-members-in-java
assert publicStaticInt == 0;
// Branching statments: variables are only considered initialized
// if they get set on all possible branches.
}
/*
# int
*/
{
// # int literals
{
// Underscores can be used anywhere inside integers
// to clarify them.
assert 1_2 == 12;
assert 1__2 == 12;
// If they are to be used, the sanest notation is to split
// decimals by 3 characters, and hex by 4.
assert 1_234 == 1234;
assert 0x1234_abcd == 0x1234abcd;
// Binary literals exist.
assert 0b11 == 3;
}
// 32-bit 2's complement guaranteed.
{
assert 0xFFFF_FFFF == -1;
assert Integer.SIZE == 32;
assert Integer.MAX_VALUE == 0x7FFF_FFFF;
// ERROR: integer number too large, unlike some of the more "dynamic languages"
// like Python that do conversion automatically. In Java, you need an explicit BigInteger.
//assert 0xFFFF_FFFF_F;
}
}
/*
# char
http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2
Unicode character, guaranteed 16-bit.
*/
{
assert 0x100 == ((int)'Ā');
// Backslash escapes can be used.
assert 0xFFFF == ((int)'\uFFFF');
/*
4 byte UTF-16 characters need 2 chars.
\ u literals can only go up to FFFF.
You need two \ u escapes for the 4 byte characters.
Some string methods consider 4-byte characters, and others not. See `charAt`.
*/
String s = "\uFFFF\uFFFF";
}
/*
# byte literals
Do not exist: http://stackoverflow.com/questions/5193883/how-do-you-specify-a-byte-literal-in-java
Downcast `int`.
*/
/*
# double literals
# float literals
*/
{
// Without suffix, `D` for double is assumed.
// The `D` suffix does not exist in ANSI C,
// but it does as a GNU extension.
assert Double.class.isInstance(1.2);
assert Double.class.isInstance(1.2d);
assert Double.class.isInstance(1.2D);
// To make floats, use `f`:
assert Float.class.isInstance(1.2f);
assert Float.class.isInstance(1.2F);
// Unlike for C, you can add floating literal suffixes to otherwise integer literals
// without the dot.
//
// This allows you to write floating literals
// that are equal to integers faster: one character `D` instead of two `.0`.
//
// But of course, both of those don't work for hexadecimal,
// where they could be ambiguous with the number itself.
assert Float.class.isInstance(1f);
assert Double.class.isInstance(1d);
assert Integer.class.isInstance(0x1d);
}
/*
# Casting convertion
JLS7 5.5
# Typecast
The term is not used on the JLS, "casting conversion" is used instead.
*/
{
// float to int truncates.
// Other functions can be done with Math
{
assert ((int)1.9) == 1;
// ERROR: incompatible types.
//int i = 1.9;
int i = (int)1.9;
}
/*
Object typecasts
*/
{
/*
# Widening reference conversion
JLS7 5.1.5
Done implicitly already.
# Upcast
Informal term for widening type conversion. Not found on the JLS.
*/
{
class Base {}
class Derived extends Base {}
{ Base b = new Derived(); }
{ Base b = (Base) new Derived(); }
}
/*
# Narrowing reference conversion
JLS7 5.1.6
# Downcast
Informal term for narrowing reference conversion. Not found on the JLS.
*/
{
class Base {}
class Derived extends Base {}
// What can be done.
{
Base b = new Derived();
Derived d = (Derived)b;
}
/*
# ClassCastException
*/
{
boolean fail = false;
try {
Derived d = (Derived) new Base();
} catch (ClassCastException e) {
fail = true;
}
assert fail;
}
// ERROR: Incompatible types.
//{ Derived d = new Base(); }
// ERROR: Incompatible types.
//{ Derived d = (Derived) new String(); }
}
}
}
}
/*
# Operators
*/
{
/*
# Shift operators
# >>>
# Signed shift operator
Much like C, except that:
- negative LHS shift operations have defined values
- `>>` is a keep-sign shift, and `>>>` is a put 0 shift
*/
{
assert (-2 >> 1) == -1;
assert (0x80_00_00_00 >> 1) == 0xC0_00_00_00;
assert (0x80_00_00_00 >>> 1) == 0x40_00_00_00;
}
/*
# Comma operator
Does not exist in Java: <http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.27>
*/
/*
# Unary plus
What is it good for, since there is no operator orelvoad:
http://stackoverflow.com/questions/2624410/what-is-the-purpose-of-javas-unary-plus-operator
*/
/*
# Compound operators
*/
{
/*
`a += b` is not exactly the same as `a = a + b`,
but rather `a = (typeof a)(a + b)`.
http://stackoverflow.com/questions/8710619/java-operator
*/
{
int i = 1;
long j = 2;
i += j;
// ERROR: possible loss of precision.
//i = i + j;
}
}
/*
# Increment operator
# ++
*/
{
/*
Unlike in C the following are defined:
all side effects of the evaluated expression happen before the assignment.
*/
{
{
int i = 0;
i = i++;
assert i == 0;
}
// Because a = b++ equals
//
// tmp = b;
// b = b + 1;
// a = tmp;
//
// So:
//
// tmp = i;
// i = i + 1;
// i = tmp;
{
int i = 0;
i = ++i;
assert i == 1;
}
}
}
/*
# Bitwise operators
*/
{
/*