|
@@ -0,0 +1,698 @@
|
|
1
|
+
|
|
2
|
+COMMENTING
|
|
3
|
+// Single-line comments start with //
|
|
4
|
+
|
|
5
|
+/*
|
|
6
|
+Multi-line comments look like this.
|
|
7
|
+*/
|
|
8
|
+
|
|
9
|
+/**
|
|
10
|
+ * JavaDoc comments look like this. Used to describe the Class or various
|
|
11
|
+ * attributes of a Class.
|
|
12
|
+ * Main attributes:
|
|
13
|
+ *
|
|
14
|
+ * @author Name (and contact information such as email) of author(s).
|
|
15
|
+ * @version Current version of the program.
|
|
16
|
+ * @since When this part of the program was first added.
|
|
17
|
+ * @param For describing the different parameters for a method.
|
|
18
|
+ * @return For describing what the method returns.
|
|
19
|
+ * @deprecated For showing the code is outdated or shouldn't be used.
|
|
20
|
+ * @see Links to another part of documentation.
|
|
21
|
+*/
|
|
22
|
+
|
|
23
|
+IMPORTING THING INTO YOUR PROGRAM
|
|
24
|
+ // Import ArrayList class inside of the java.util package
|
|
25
|
+ import java.util.ArrayList;
|
|
26
|
+ // Import all classes inside of java.security package
|
|
27
|
+ import java.security.*;
|
|
28
|
+
|
|
29
|
+*** if you know that something your using exists already somewhere else in your
|
|
30
|
+program OR in a package that has already been imported you can have IntelliJ
|
|
31
|
+auto-import it for you! Simple click on the thing that needs to be imported
|
|
32
|
+and then hold OPTION and hit ENTER.
|
|
33
|
+
|
|
34
|
+TYPES (CORE JAVA CHAPTER 3.3 pages 47 to 52)
|
|
35
|
+-There are many types of data in Java, most are classes and have built in methods
|
|
36
|
+that can be used on things of that type, these are known as "reference" types.
|
|
37
|
+Want to know what you can do? Check the api of that class.
|
|
38
|
+
|
|
39
|
+-There are 8 "primitive" types of data that are not classes and have not built
|
|
40
|
+in methods. They are: boolean(true/false), character, byte, short, integer(int),
|
|
41
|
+long, float, doable.
|
|
42
|
+
|
|
43
|
+DECLARING VARIABLES (CORE JAVA CHAPTER 3.4 pages 53 to 54)
|
|
44
|
+ // Initialize a variable using <type> <name> = <val>
|
|
45
|
+ int barInt = 1;
|
|
46
|
+ // Initialize multiple variables of same type with same
|
|
47
|
+ // value <type> <name1>, <name2>, <name3>
|
|
48
|
+ // <name1> = <name2> = <name3> = <val>
|
|
49
|
+ int barInt1, barInt2, barInt3;
|
|
50
|
+ barInt1 = barInt2 = barInt3 = 1;
|
|
51
|
+
|
|
52
|
+VARIABLES TYPES
|
|
53
|
+
|
|
54
|
+ // Byte - 8-bit signed two's complement integer
|
|
55
|
+ // (-128 <= byte <= 127)
|
|
56
|
+ byte fooByte = 100;
|
|
57
|
+
|
|
58
|
+ // If you would like to interpret a byte as an unsigned integer
|
|
59
|
+ // then this simple operation can help
|
|
60
|
+ int unsignedIntLessThan256 = 0xff & fooByte;
|
|
61
|
+ // this contrasts a cast which can be negative.
|
|
62
|
+ int signedInt = (int) fooByte;
|
|
63
|
+
|
|
64
|
+ // Short - 16-bit signed two's complement integer
|
|
65
|
+ // (-32,768 <= short <= 32,767)
|
|
66
|
+ short fooShort = 10000;
|
|
67
|
+
|
|
68
|
+ // Integer - 32-bit signed two's complement integer
|
|
69
|
+ // (-2,147,483,648 <= int <= 2,147,483,647)
|
|
70
|
+ int bazInt = 1;
|
|
71
|
+
|
|
72
|
+ // Long - 64-bit signed two's complement integer
|
|
73
|
+ // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
|
|
74
|
+ long fooLong = 100000L;
|
|
75
|
+ // L is used to denote that this variable value is of type Long;
|
|
76
|
+ // anything without is treated as integer by default.
|
|
77
|
+
|
|
78
|
+ // Note: byte, short, int and long are signed. They can have positive and negative values.
|
|
79
|
+ // There are no unsigned variants.
|
|
80
|
+ // char, however, is 16-bit unsigned.
|
|
81
|
+
|
|
82
|
+ // Float - Single-precision 32-bit IEEE 754 Floating Point
|
|
83
|
+ // 2^-149 <= float <= (2-2^-23) * 2^127
|
|
84
|
+ float fooFloat = 234.5f;
|
|
85
|
+ // f or F is used to denote that this variable value is of type float;
|
|
86
|
+ // otherwise it is treated as double.
|
|
87
|
+
|
|
88
|
+ // Double - Double-precision 64-bit IEEE 754 Floating Point
|
|
89
|
+ // 2^-1074 <= x <= (2-2^-52) * 2^1023
|
|
90
|
+ double fooDouble = 123.4;
|
|
91
|
+
|
|
92
|
+ // Boolean - true & false
|
|
93
|
+ boolean fooBoolean = true;
|
|
94
|
+ boolean barBoolean = false;
|
|
95
|
+
|
|
96
|
+ // Char - A single 16-bit Unicode character
|
|
97
|
+ char fooChar = 'A';
|
|
98
|
+
|
|
99
|
+ // final variables can't be reassigned,
|
|
100
|
+ final int HOURS_I_WORK_PER_WEEK = 9001;
|
|
101
|
+ // but they can be initialized later.
|
|
102
|
+ final double E;
|
|
103
|
+ E = 2.71828;
|
|
104
|
+
|
|
105
|
+ // Other data types worth checking out
|
|
106
|
+ // ArrayLists - Like arrays except more functionality is offered, and
|
|
107
|
+ // the size is mutable.
|
|
108
|
+ // LinkedLists - Implementation of doubly-linked list. All of the
|
|
109
|
+ // operations perform as could be expected for a
|
|
110
|
+ // doubly-linked list.
|
|
111
|
+ // Maps - A mapping of key Objects to value Objects. Map is
|
|
112
|
+ // an interface and therefore cannot be instantiated.
|
|
113
|
+ // The type of keys and values contained in a Map must
|
|
114
|
+ // be specified upon instantiation of the implementing
|
|
115
|
+ // class. Each key may map to only one corresponding value,
|
|
116
|
+ // and each key may appear only once (no duplicates).
|
|
117
|
+ // HashMaps - This class uses a hashtable to implement the Map
|
|
118
|
+ // interface. This allows the execution time of basic
|
|
119
|
+ // operations, such as get and insert element, to remain
|
|
120
|
+ // constant-amortized even for large sets.
|
|
121
|
+ // TreeMap - A Map that is sorted by its keys. Each modification
|
|
122
|
+ // maintains the sorting defined by either a Comparator
|
|
123
|
+ // supplied at instantiation, or comparisons of each Object
|
|
124
|
+ // if they implement the Comparable interface.
|
|
125
|
+ // Failure of keys to implement Comparable combined with failure to
|
|
126
|
+ // supply a Comparator will throw ClassCastExceptions.
|
|
127
|
+ // Insertion and removal operations take O(log(n)) time
|
|
128
|
+ // so avoid using this data structure unless you are taking
|
|
129
|
+ // advantage of the sorting.
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+OPERATORS (CORE JAVA CHAPTER 3.5 pages 56 to 65)
|
|
133
|
+
|
|
134
|
+ System.out.println("\n->Operators");
|
|
135
|
+
|
|
136
|
+ int i1 = 1, i2 = 2; // Shorthand for multiple declarations
|
|
137
|
+
|
|
138
|
+ // Arithmetic is straightforward
|
|
139
|
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
|
|
140
|
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
|
|
141
|
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
|
|
142
|
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int)
|
|
143
|
+ System.out.println("1/2.0 = " + (i1 / (double)i2)); // => 0.5
|
|
144
|
+
|
|
145
|
+ // Modulo
|
|
146
|
+ System.out.println("11%3 = "+(11 % 3)); // => 2
|
|
147
|
+
|
|
148
|
+ // Comparison operators
|
|
149
|
+ System.out.println("3 == 2? " + (3 == 2)); // => false
|
|
150
|
+ System.out.println("3 != 2? " + (3 != 2)); // => true
|
|
151
|
+ System.out.println("3 > 2? " + (3 > 2)); // => true
|
|
152
|
+ System.out.println("3 < 2? " + (3 < 2)); // => false
|
|
153
|
+ System.out.println("2 <= 2? " + (2 <= 2)); // => true
|
|
154
|
+ System.out.println("2 >= 2? " + (2 >= 2)); // => true
|
|
155
|
+
|
|
156
|
+ // Boolean operators
|
|
157
|
+ System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
|
|
158
|
+ System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
|
|
159
|
+ System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
|
|
160
|
+
|
|
161
|
+ // Bitwise operators!
|
|
162
|
+ /*
|
|
163
|
+ ~ Unary bitwise complement
|
|
164
|
+ << Signed left shift
|
|
165
|
+ >> Signed/Arithmetic right shift
|
|
166
|
+ >>> Unsigned/Logical right shift
|
|
167
|
+ & Bitwise AND
|
|
168
|
+ ^ Bitwise exclusive OR
|
|
169
|
+ | Bitwise inclusive OR
|
|
170
|
+ */
|
|
171
|
+
|
|
172
|
+ // Increment operators
|
|
173
|
+ int i = 0;
|
|
174
|
+ System.out.println("\n->Inc/Dec-rementation");
|
|
175
|
+ // The ++ and -- operators increment and decrement by 1 respectively.
|
|
176
|
+ // If they are placed before the variable, they increment then return;
|
|
177
|
+ // after the variable they return then increment.
|
|
178
|
+ System.out.println(i++); // i = 1, prints 0 (post-increment)
|
|
179
|
+ System.out.println(++i); // i = 2, prints 2 (pre-increment)
|
|
180
|
+ System.out.println(i--); // i = 1, prints 2 (post-decrement)
|
|
181
|
+ System.out.println(--i); // i = 0, prints 0 (pre-decrement)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+ENUMS (CORE JAVA CHAPTER 3.5.9 page 65)
|
|
185
|
+
|
|
186
|
+// An enum type is a special data type that enables for a variable to be a set
|
|
187
|
+// of predefined constants. The variable must be equal to one of the values
|
|
188
|
+// that have been predefined for it. Because they are constants, the names of
|
|
189
|
+// an enum type's fields are in uppercase letters. In the Java programming
|
|
190
|
+// language, you define an enum type by using the enum keyword. For example,
|
|
191
|
+// you would specify a days-of-the-week enum type as:
|
|
192
|
+public enum Day {
|
|
193
|
+ SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
|
|
194
|
+ THURSDAY, FRIDAY, SATURDAY
|
|
195
|
+}
|
|
196
|
+
|
|
197
|
+// We can use our enum Day like that:
|
|
198
|
+public class EnumTest {
|
|
199
|
+ // Variable Enum
|
|
200
|
+ Day day;
|
|
201
|
+
|
|
202
|
+ public EnumTest(Day day) {
|
|
203
|
+ this.day = day;
|
|
204
|
+ }
|
|
205
|
+
|
|
206
|
+ public void tellItLikeItIs() {
|
|
207
|
+ switch (day) {
|
|
208
|
+ case MONDAY:
|
|
209
|
+ System.out.println("Mondays are bad.");
|
|
210
|
+ break;
|
|
211
|
+ case FRIDAY:
|
|
212
|
+ System.out.println("Fridays are better.");
|
|
213
|
+ break;
|
|
214
|
+ case SATURDAY:
|
|
215
|
+ case SUNDAY:
|
|
216
|
+ System.out.println("Weekends are best.");
|
|
217
|
+ break;
|
|
218
|
+ default:
|
|
219
|
+ System.out.println("Midweek days are so-so.");
|
|
220
|
+ break;
|
|
221
|
+ }
|
|
222
|
+ }
|
|
223
|
+
|
|
224
|
+ public static void main(String[] args) {
|
|
225
|
+ EnumTest firstDay = new EnumTest(Day.MONDAY);
|
|
226
|
+ firstDay.tellItLikeItIs(); // => Mondays are bad.
|
|
227
|
+ EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
|
|
228
|
+ thirdDay.tellItLikeItIs(); // => Midweek days are so-so.
|
|
229
|
+ }
|
|
230
|
+}
|
|
231
|
+
|
|
232
|
+// Enum types are much more powerful than we show above.
|
|
233
|
+// The enum body can include methods and other fields.
|
|
234
|
+// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+STRINGS (CORE JAVA CHAPTER 3.6 pages 65 to 77)
|
|
239
|
+
|
|
240
|
+// Strings
|
|
241
|
+String fooString = "My String Is Here!";
|
|
242
|
+
|
|
243
|
+// \n is an escaped character that starts a new line
|
|
244
|
+String barString = "Printing on a new line?\nNo Problem!";
|
|
245
|
+// \t is an escaped character that adds a tab character
|
|
246
|
+String bazString = "Do you want to add a tab?\tNo Problem!";
|
|
247
|
+System.out.println(fooString);
|
|
248
|
+System.out.println(barString);
|
|
249
|
+System.out.println(bazString);
|
|
250
|
+
|
|
251
|
+// String Building
|
|
252
|
+// #1 - with plus operator
|
|
253
|
+// That's the basic way to do it (optimized under the hood)
|
|
254
|
+String plusConcatenated = "Strings can " + "be concatenated " + "via + operator.";
|
|
255
|
+System.out.println(plusConcatenated);
|
|
256
|
+// Output: Strings can be concatenated via + operator.
|
|
257
|
+
|
|
258
|
+// #2 - with StringBuilder
|
|
259
|
+// This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together
|
|
260
|
+// when toString() is called.
|
|
261
|
+// Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer.
|
|
262
|
+StringBuilder builderConcatenated = new StringBuilder();
|
|
263
|
+builderConcatenated.append("You ");
|
|
264
|
+builderConcatenated.append("can use ");
|
|
265
|
+builderConcatenated.append("the StringBuilder class.");
|
|
266
|
+System.out.println(builderConcatenated.toString()); // only now is the string built
|
|
267
|
+// Output: You can use the StringBuilder class.
|
|
268
|
+
|
|
269
|
+// StringBuilder is efficient when the fully constructed String is not required until the end of some processing.
|
|
270
|
+StringBuilder stringBuilder = new StringBuilder();
|
|
271
|
+String inefficientString = "";
|
|
272
|
+for (int i = 0 ; i < 10; i++) {
|
|
273
|
+ stringBuilder.append(i).append(" ");
|
|
274
|
+ inefficientString += i + " ";
|
|
275
|
+}
|
|
276
|
+System.out.println(inefficientString);
|
|
277
|
+System.out.println(stringBuilder.toString());
|
|
278
|
+// inefficientString requires a lot more work to produce, as it generates a String on every loop iteration.
|
|
279
|
+// Simple concatenation with + is compiled to a StringBuilder and toString()
|
|
280
|
+// Avoid string concatenation in loops.
|
|
281
|
+
|
|
282
|
+// #3 - with String formatter
|
|
283
|
+// Another alternative way to create strings. Fast and readable.
|
|
284
|
+String.format("%s may prefer %s.", "Or you", "String.format()");
|
|
285
|
+// Output: Or you may prefer String.format().
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+BIG NUMBERS (CORE JAVA CHAPTER 3.9 page 108)
|
|
289
|
+
|
|
290
|
+// BigInteger - Immutable arbitrary-precision integers
|
|
291
|
+//
|
|
292
|
+// BigInteger is a data type that allows programmers to manipulate
|
|
293
|
+// integers longer than 64-bits. Integers are stored as an array of
|
|
294
|
+// of bytes and are manipulated using functions built into BigInteger
|
|
295
|
+//
|
|
296
|
+// BigInteger can be initialized using an array of bytes or a string.
|
|
297
|
+BigInteger fooBigInteger = new BigInteger(fooByteArray);
|
|
298
|
+
|
|
299
|
+// BigDecimal - Immutable, arbitrary-precision signed decimal number
|
|
300
|
+//
|
|
301
|
+// A BigDecimal takes two parts: an arbitrary precision integer
|
|
302
|
+// unscaled value and a 32-bit integer scale
|
|
303
|
+//
|
|
304
|
+// BigDecimal allows the programmer complete control over decimal
|
|
305
|
+// rounding. It is recommended to use BigDecimal with currency values
|
|
306
|
+// and where exact decimal precision is required.
|
|
307
|
+//
|
|
308
|
+// BigDecimal can be initialized with an int, long, double or String
|
|
309
|
+// or by initializing the unscaled value (BigInteger) and scale (int).
|
|
310
|
+BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt);
|
|
311
|
+
|
|
312
|
+// Be wary of the constructor that takes a float or double as
|
|
313
|
+// the inaccuracy of the float/double will be copied in BigDecimal.
|
|
314
|
+// Prefer the String constructor when you need an exact value.
|
|
315
|
+BigDecimal tenCents = new BigDecimal("0.1");
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+ARRAYS (CORE JAVA CHAPTER 3.10 pages 111 to 124)
|
|
320
|
+// The array size must be decided upon instantiation
|
|
321
|
+// The following formats work for declaring an array
|
|
322
|
+// <datatype>[] <var name> = new <datatype>[<array size>];
|
|
323
|
+// <datatype> <var name>[] = new <datatype>[<array size>];
|
|
324
|
+int[] intArray = new int[10];
|
|
325
|
+String[] stringArray = new String[1];
|
|
326
|
+boolean boolArray[] = new boolean[100];
|
|
327
|
+
|
|
328
|
+// Another way to declare & initialize an array
|
|
329
|
+int[] y = {9000, 1000, 1337};
|
|
330
|
+String names[] = {"Bob", "John", "Fred", "Juan Pedro"};
|
|
331
|
+boolean bools[] = {true, false, false};
|
|
332
|
+
|
|
333
|
+// Indexing an array - Accessing an element
|
|
334
|
+System.out.println("intArray @ 0: " + intArray[0]);
|
|
335
|
+
|
|
336
|
+// Arrays are zero-indexed and mutable.
|
|
337
|
+intArray[1] = 1;
|
|
338
|
+System.out.println("intArray @ 1: " + intArray[1]); // => 1
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+CONTROL FLOW (CORE JAVA CHAPTER 3.8 pages 89 to 106)
|
|
343
|
+
|
|
344
|
+// If statements are c-like
|
|
345
|
+ int j = 10;
|
|
346
|
+ if (j == 10) {
|
|
347
|
+ System.out.println("I get printed");
|
|
348
|
+ } else if (j > 10) {
|
|
349
|
+ System.out.println("I don't");
|
|
350
|
+ } else {
|
|
351
|
+ System.out.println("I also don't");
|
|
352
|
+ }
|
|
353
|
+
|
|
354
|
+ // While loop
|
|
355
|
+ int fooWhile = 0;
|
|
356
|
+ while(fooWhile < 100) {
|
|
357
|
+ System.out.println(fooWhile);
|
|
358
|
+ // Increment the counter
|
|
359
|
+ // Iterated 100 times, fooWhile 0,1,2...99
|
|
360
|
+ fooWhile++;
|
|
361
|
+ }
|
|
362
|
+ System.out.println("fooWhile Value: " + fooWhile);
|
|
363
|
+
|
|
364
|
+ // Do While Loop
|
|
365
|
+ int fooDoWhile = 0;
|
|
366
|
+ do {
|
|
367
|
+ System.out.println(fooDoWhile);
|
|
368
|
+ // Increment the counter
|
|
369
|
+ // Iterated 99 times, fooDoWhile 0->99
|
|
370
|
+ fooDoWhile++;
|
|
371
|
+ } while(fooDoWhile < 100);
|
|
372
|
+ System.out.println("fooDoWhile Value: " + fooDoWhile);
|
|
373
|
+
|
|
374
|
+ // For Loop
|
|
375
|
+ // for loop structure => for(<start_statement>; <conditional>; <step>)
|
|
376
|
+ for (int fooFor = 0; fooFor < 10; fooFor++) {
|
|
377
|
+ System.out.println(fooFor);
|
|
378
|
+ // Iterated 10 times, fooFor 0->9
|
|
379
|
+ }
|
|
380
|
+ System.out.println("fooFor Value: " + fooFor);
|
|
381
|
+
|
|
382
|
+ // Nested For Loop Exit with Label
|
|
383
|
+ outer:
|
|
384
|
+ for (int i = 0; i < 10; i++) {
|
|
385
|
+ for (int j = 0; j < 10; j++) {
|
|
386
|
+ if (i == 5 && j ==5) {
|
|
387
|
+ break outer;
|
|
388
|
+ // breaks out of outer loop instead of only the inner one
|
|
389
|
+ }
|
|
390
|
+ }
|
|
391
|
+ }
|
|
392
|
+
|
|
393
|
+ // For Each Loop
|
|
394
|
+ // The for loop is also able to iterate over arrays as well as objects
|
|
395
|
+ // that implement the Iterable interface.
|
|
396
|
+ int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9};
|
|
397
|
+ // for each loop structure => for (<object> : <iterable>)
|
|
398
|
+ // reads as: for each element in the iterable
|
|
399
|
+ // note: the object type must match the element type of the iterable.
|
|
400
|
+ for (int bar : fooList) {
|
|
401
|
+ System.out.println(bar);
|
|
402
|
+ //Iterates 9 times and prints 1-9 on new lines
|
|
403
|
+ }
|
|
404
|
+
|
|
405
|
+ // Switch Case
|
|
406
|
+ // A switch works with the byte, short, char, and int data types.
|
|
407
|
+ // It also works with enumerated types (discussed in Enum Types), the
|
|
408
|
+ // String class, and a few special classes that wrap primitive types:
|
|
409
|
+ // Character, Byte, Short, and Integer.
|
|
410
|
+ // Starting in Java 7 and above, we can also use the String type.
|
|
411
|
+ // Note: Do remember that, not adding "break" at end any particular case ends up in
|
|
412
|
+ // executing the very next case(given it satisfies the condition provided) as well.
|
|
413
|
+ int month = 3;
|
|
414
|
+ String monthString;
|
|
415
|
+ switch (month) {
|
|
416
|
+ case 1: monthString = "January";
|
|
417
|
+ break;
|
|
418
|
+ case 2: monthString = "February";
|
|
419
|
+ break;
|
|
420
|
+ case 3: monthString = "March";
|
|
421
|
+ break;
|
|
422
|
+ default: monthString = "Some other month";
|
|
423
|
+ break;
|
|
424
|
+ }
|
|
425
|
+ System.out.println("Switch Case Result: " + monthString);
|
|
426
|
+
|
|
427
|
+ // Conditional Shorthand (TERNARY STATEMENTS)
|
|
428
|
+ // You can use the '?' operator for quick assignments or logic forks.
|
|
429
|
+ // Reads as "If (statement) is true, use <first value>, otherwise, use
|
|
430
|
+ // <second value>"
|
|
431
|
+ int foo = 5;
|
|
432
|
+ String bar = (foo < 10) ? "A" : "B";
|
|
433
|
+ System.out.println("bar : " + bar); // Prints "bar : A", because the
|
|
434
|
+ // statement is true.
|
|
435
|
+ // Or simply
|
|
436
|
+ System.out.println("bar : " + (foo < 10 ? "A" : "B"));
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+CLASSES (CORE JAVA 4.3 pages 145 to 157)
|
|
441
|
+
|
|
442
|
+ // Class Declaration Syntax:
|
|
443
|
+ // <public/private/protected> class <class name> {
|
|
444
|
+ // // data fields, constructors, functions all inside.
|
|
445
|
+ // // functions are called as methods in Java.
|
|
446
|
+ // }
|
|
447
|
+
|
|
448
|
+ class Bicycle {
|
|
449
|
+
|
|
450
|
+ // Bicycle's Fields/Variables
|
|
451
|
+ public int cadence; // Public: Can be accessed from anywhere
|
|
452
|
+ private int speed; // Private: Only accessible from within the class
|
|
453
|
+ protected int gear; // Protected: Accessible from the class and subclasses
|
|
454
|
+ String name; // default: Only accessible from within this package
|
|
455
|
+ static String className; // Static class variable
|
|
456
|
+
|
|
457
|
+ // Static block
|
|
458
|
+ // Java has no implementation of static constructors, but
|
|
459
|
+ // has a static block that can be used to initialize class variables
|
|
460
|
+ // (static variables).
|
|
461
|
+ // This block will be called when the class is loaded.
|
|
462
|
+ static {
|
|
463
|
+ className = "Bicycle";
|
|
464
|
+ }
|
|
465
|
+
|
|
466
|
+ // Constructors are a way of creating classes
|
|
467
|
+ // This is a constructor
|
|
468
|
+ public Bicycle() {
|
|
469
|
+ // You can also call another constructor:
|
|
470
|
+ // this(1, 50, 5, "Bontrager");
|
|
471
|
+ gear = 1;
|
|
472
|
+ cadence = 50;
|
|
473
|
+ speed = 5;
|
|
474
|
+ name = "Bontrager";
|
|
475
|
+ }
|
|
476
|
+ // This is a constructor that takes arguments
|
|
477
|
+ public Bicycle(int startCadence, int startSpeed, int startGear,
|
|
478
|
+ String name) {
|
|
479
|
+ this.gear = startGear;
|
|
480
|
+ this.cadence = startCadence;
|
|
481
|
+ this.speed = startSpeed;
|
|
482
|
+ this.name = name;
|
|
483
|
+ }
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+INHERITANCE (CORE JAVA CHAPTER 5.1 pages 204 to 227)
|
|
487
|
+
|
|
488
|
+// PennyFarthing is a subclass of Bicycle
|
|
489
|
+class PennyFarthing extends Bicycle {
|
|
490
|
+ // (Penny Farthings are those bicycles with the big front wheel.
|
|
491
|
+ // They have no gears.)
|
|
492
|
+
|
|
493
|
+ public PennyFarthing(int startCadence, int startSpeed) {
|
|
494
|
+ // Call the parent constructor with super
|
|
495
|
+ super(startCadence, startSpeed, 0, "PennyFarthing");
|
|
496
|
+ }
|
|
497
|
+
|
|
498
|
+ // You should mark a method you're overriding with an @annotation.
|
|
499
|
+ // To learn more about what annotations are and their purpose check this
|
|
500
|
+ // out: http://docs.oracle.com/javase/tutorial/java/annotations/
|
|
501
|
+ @Override
|
|
502
|
+ public void setGear(int gear) {
|
|
503
|
+ this.gear = 0;
|
|
504
|
+ }
|
|
505
|
+}
|
|
506
|
+
|
|
507
|
+// Object casting
|
|
508
|
+// Since the PennyFarthing class is extending the Bicycle class, we can say
|
|
509
|
+// a PennyFarthing is a Bicycle and write :
|
|
510
|
+// Bicycle bicycle = new PennyFarthing();
|
|
511
|
+// This is called object casting where an object is taken for another one. There
|
|
512
|
+// are lots of details and deals with some more intermediate concepts here:
|
|
513
|
+// https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
|
|
514
|
+
|
|
515
|
+// Interfaces
|
|
516
|
+// Interface declaration syntax
|
|
517
|
+// <access-level> interface <interface-name> extends <super-interfaces> {
|
|
518
|
+// // Constants
|
|
519
|
+// // Method declarations
|
|
520
|
+// }
|
|
521
|
+
|
|
522
|
+// Example - Food:
|
|
523
|
+public interface Edible {
|
|
524
|
+ public void eat(); // Any class that implements this interface, must
|
|
525
|
+ // implement this method.
|
|
526
|
+}
|
|
527
|
+
|
|
528
|
+public interface Digestible {
|
|
529
|
+ public void digest();
|
|
530
|
+ // Since Java 8, interfaces can have default method.
|
|
531
|
+ public default void defaultMethod() {
|
|
532
|
+ System.out.println("Hi from default method ...");
|
|
533
|
+ }
|
|
534
|
+}
|
|
535
|
+
|
|
536
|
+// We can now create a class that implements both of these interfaces.
|
|
537
|
+public class Fruit implements Edible, Digestible {
|
|
538
|
+ @Override
|
|
539
|
+ public void eat() {
|
|
540
|
+ // ...
|
|
541
|
+ }
|
|
542
|
+
|
|
543
|
+ @Override
|
|
544
|
+ public void digest() {
|
|
545
|
+ // ...
|
|
546
|
+ }
|
|
547
|
+}
|
|
548
|
+
|
|
549
|
+// In Java, you can extend only one class, but you can implement many
|
|
550
|
+// interfaces. For example:
|
|
551
|
+public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
|
552
|
+ InterfaceTwo {
|
|
553
|
+ @Override
|
|
554
|
+ public void InterfaceOneMethod() {
|
|
555
|
+ }
|
|
556
|
+
|
|
557
|
+ @Override
|
|
558
|
+ public void InterfaceTwoMethod() {
|
|
559
|
+ }
|
|
560
|
+
|
|
561
|
+}
|
|
562
|
+
|
|
563
|
+// Abstract Classes
|
|
564
|
+
|
|
565
|
+// Abstract Class declaration syntax
|
|
566
|
+// <access-level> abstract class <abstract-class-name> extends
|
|
567
|
+// <super-abstract-classes> {
|
|
568
|
+// // Constants and variables
|
|
569
|
+// // Method declarations
|
|
570
|
+// }
|
|
571
|
+
|
|
572
|
+// Abstract Classes cannot be instantiated.
|
|
573
|
+// Abstract classes may define abstract methods.
|
|
574
|
+// Abstract methods have no body and are marked abstract
|
|
575
|
+// Non-abstract child classes must @Override all abstract methods
|
|
576
|
+// from their super-classes.
|
|
577
|
+// Abstract classes can be useful when combining repetitive logic
|
|
578
|
+// with customised behavior, but as Abstract classes require
|
|
579
|
+// inheritance, they violate "Composition over inheritance"
|
|
580
|
+// so consider other approaches using composition.
|
|
581
|
+// https://en.wikipedia.org/wiki/Composition_over_inheritance
|
|
582
|
+
|
|
583
|
+public abstract class Animal
|
|
584
|
+{
|
|
585
|
+ private int age;
|
|
586
|
+
|
|
587
|
+ public abstract void makeSound();
|
|
588
|
+
|
|
589
|
+ // Method can have a body
|
|
590
|
+ public void eat()
|
|
591
|
+ {
|
|
592
|
+ System.out.println("I am an animal and I am Eating.");
|
|
593
|
+ // Note: We can access private variable here.
|
|
594
|
+ age = 30;
|
|
595
|
+ }
|
|
596
|
+
|
|
597
|
+ public void printAge()
|
|
598
|
+ {
|
|
599
|
+ System.out.println(age);
|
|
600
|
+ }
|
|
601
|
+
|
|
602
|
+ // Abstract classes can have main method.
|
|
603
|
+ public static void main(String[] args)
|
|
604
|
+ {
|
|
605
|
+ System.out.println("I am abstract");
|
|
606
|
+ }
|
|
607
|
+}
|
|
608
|
+
|
|
609
|
+class Dog extends Animal
|
|
610
|
+{
|
|
611
|
+ // Note still have to override the abstract methods in the
|
|
612
|
+ // abstract class.
|
|
613
|
+ @Override
|
|
614
|
+ public void makeSound()
|
|
615
|
+ {
|
|
616
|
+ System.out.println("Bark");
|
|
617
|
+ // age = 30; ==> ERROR! age is private to Animal
|
|
618
|
+ }
|
|
619
|
+
|
|
620
|
+ // NOTE: You will get an error if you used the
|
|
621
|
+ // @Override annotation here, since java doesn't allow
|
|
622
|
+ // overriding of static methods.
|
|
623
|
+ // What is happening here is called METHOD HIDING.
|
|
624
|
+ // Check out this SO post: http://stackoverflow.com/questions/16313649/
|
|
625
|
+ public static void main(String[] args)
|
|
626
|
+ {
|
|
627
|
+ Dog pluto = new Dog();
|
|
628
|
+ pluto.makeSound();
|
|
629
|
+ pluto.eat();
|
|
630
|
+ pluto.printAge();
|
|
631
|
+ }
|
|
632
|
+}
|
|
633
|
+
|
|
634
|
+FINAL CLASSES/METHODS (CORE JAVA CHAPTER 5.1.7 page 217)
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+// Final Classes
|
|
638
|
+
|
|
639
|
+// Final Class declaration syntax
|
|
640
|
+// <access-level> final <final-class-name> {
|
|
641
|
+// // Constants and variables
|
|
642
|
+// // Method declarations
|
|
643
|
+// }
|
|
644
|
+
|
|
645
|
+// Final classes are classes that cannot be inherited from and are therefore a
|
|
646
|
+// final child. In a way, final classes are the opposite of abstract classes
|
|
647
|
+// because abstract classes must be extended, but final classes cannot be
|
|
648
|
+// extended.
|
|
649
|
+public final class SaberToothedCat extends Animal
|
|
650
|
+{
|
|
651
|
+ // Note still have to override the abstract methods in the
|
|
652
|
+ // abstract class.
|
|
653
|
+ @Override
|
|
654
|
+ public void makeSound()
|
|
655
|
+ {
|
|
656
|
+ System.out.println("Roar");
|
|
657
|
+ }
|
|
658
|
+}
|
|
659
|
+
|
|
660
|
+// Final Methods
|
|
661
|
+public abstract class Mammal()
|
|
662
|
+{
|
|
663
|
+ // Final Method Syntax:
|
|
664
|
+ // <access modifier> final <return type> <function name>(<args>)
|
|
665
|
+
|
|
666
|
+ // Final methods, like, final classes cannot be overridden by a child
|
|
667
|
+ // class, and are therefore the final implementation of the method.
|
|
668
|
+ public final boolean isWarmBlooded()
|
|
669
|
+ {
|
|
670
|
+ return true;
|
|
671
|
+ }
|
|
672
|
+}
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+CATCHING EXCEPTIONS (CORE JAVA CHAPTER 7.2 pages 367 to 377)
|
|
677
|
+ // Try-with-resources (Java 7+)
|
|
678
|
+ // Try-catch-finally statements work as expected in Java but in Java 7+
|
|
679
|
+ // the try-with-resources statement is also available. Try-with-resources
|
|
680
|
+ // simplifies try-catch-finally statements by closing resources
|
|
681
|
+ // automatically.
|
|
682
|
+
|
|
683
|
+ // In order to use a try-with-resources, include an instance of a class
|
|
684
|
+ // in the try statement. The class must implement java.lang.AutoCloseable.
|
|
685
|
+ try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
|
|
686
|
+ // You can attempt to do something that could throw an exception.
|
|
687
|
+ System.out.println(br.readLine());
|
|
688
|
+ // In Java 7, the resource will always be closed, even if it throws
|
|
689
|
+ // an Exception.
|
|
690
|
+ } catch (Exception ex) {
|
|
691
|
+ //The resource will be closed before the catch statement executes.
|
|
692
|
+ System.out.println("readLine() failed.");
|
|
693
|
+ }
|
|
694
|
+ // No need for a finally statement in this case, the BufferedReader is
|
|
695
|
+ // already closed. This can be used to avoid certain edge cases where
|
|
696
|
+ // a finally statement might not be called.
|
|
697
|
+ // To learn more:
|
|
698
|
+ // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
|