Test Class
Test Class
java
1 import java.time.LocalDate;
15
16 public class TestClass implements SomeInterface{
17
18 public static void main (String[] args) {
19 TestClass testClass = new TestClass();
20
21 // mainSwitch(args);
22 // main// Implemementer.getInstance().someStuff2();
23 StringBuilder sb = new StringBuilder("Hello ");
24 setStringBuilderNull(sb);
25 System.out.println(sb);
26 }
27
28
29 /* TODO LAMBDAS
30 // Variáveis de instancia interface
31 // Variáveis de instancia subclasse
32 // Métodos estáticos interface
33 // Métoodos estáticos subclasse
34 * Metodo abstracto pode ser override ?
35 */
36
37
38
39 static void setStringBuilderNull(StringBuilder sb) {
40 sb.append("World");
41 sb = null; // ----> It does not affect the outer instance variable
42 }
43
44
45
46
47 /*
48
49 LocalDateTime ld = LocalDateTime.of(2015, Month.OCTOBER, 31, 10, 0);
50 ZonedDateTime date = ZonedDateTime.of(ld, ZoneId.of("US/Eastern"));
51
52 date=date.plus(Duration.ofDays(1));System.out.println(date);
53 date=ZonedDateTime.of(ld,ZoneId.of("US/Eastern"));
54 date=date.plus(Period.ofDays(1));System.out.println(date);
55
56
57 Important thing to remember here is that Period is used to manipulate
dates
58 in terms of days, months, and years, while Duration is used to
manipulate dates in terms of hours,
59 minutes, and seconds. Therefore, Period doesn't mess with the time
component of the date while
60 Duration may change the time component if the date is close to the DST
Page 1
TestClass.java
boundary.
61
62 Durations and periods differ in their treatment of daylight savings
time when added to ZonedDateTime.
63 A Duration will add an exact number of seconds, thus a duration of one
day is always exactly 24 hours.
64 By contrast, a Period will add a conceptual day, trying to maintain the
local time.
65
66 For example, consider adding a period of one day and a duration of one
day to 18:00 on the evening before
67 a daylight savings gap. The Period will add the conceptual day and
result in a ZonedDateTime at 18:00 the
68 following day. By contrast, the Duration will add exactly 24 hours,
resulting in a ZonedDateTime at 19:00
69 the following day (assuming a one hour DST gap).
70
71 */
72
73
74 String global = "111";
75
76 public int parse(String arg) {
77 String global = arg; // -----> Allowed, hides the main instance
78 int value = 0;
79 try {
80
81 value = Integer.parseInt(global);
82 } catch (Exception e) {
83 System.out.println(e.getClass());
84 }
85 System.out.print(global + " " + value + " ");
86 return value;
87 }
88
89
90
91
92 // you can't instantiate a Short object with an int argument
93
94
95 // probe(Integer) will be bound to probe(Integer) (exact match). If
that is not available,
96 // it will be bound to probe(long), and then with probe(int...) in that
order of preference.
97 // probe(long) is preferred over probe(int...
98
99
100
101 // Variavel pode ser redefinida
Page 2
TestClass.java
Page 3
TestClass.java
Page 4
TestClass.java
198 */
199
200 // --------------------------------------------------------------------
201 // Exceptions ->, the most specific method depending upon the argument
is called
202
203 // The concept is : variables are hidden and methods are overridden.
!!!!
204
205 /*
206
207 1. Boolean class has two constructors - Boolean(String) and
Boolean(boolean) The String constructor allocates
208 a Boolean object representing the value true if the string argument is
not null and is equal, ignoring case,
209 to the string "true". Otherwise, allocate a Boolean object
representing the value false.
210 Examples: new Boolean("True") produces a Boolean object that
represents true. new Boolean("yes") produces a
211 Boolean object that represents false. The boolean constructor is self
explanatory.
212
213 2. Boolean class has two static helper methods for creating booleans -
parseBoolean and valueOf.
214 Boolean.parseBoolean(String ) method returns a primitive boolean and
not a Boolean object (Note - Same is with
215 the case with other parseXXX methods such as Integer.parseInt - they
return primitives and not objects).
216 The boolean returned represents the value true if the string argument
is not null and is equal, ignoring case,
217 to the string "true". Boolean.valueOf(String ) and its overloaded
Boolean.valueOf(boolean ) version, on the
218 other hand, work similarly but return a reference to either
Boolean.TRUE or Boolean.FALSE wrapper objects.
219 Observe that they dont create a new Boolean object but just return the
static constants TRUE or FALSE defined in
220 Boolean class.
221
222 3. When you use the equality operator ( == ) with booleans, if exactly
one of the operands is a Boolean wrapper,
223 it is first unboxed into a boolean primitive and then the two are
compared (JLS 15.21.2). If both are Boolean wrappers,
224 then their references are compared just like in the case of other
objects. Thus, new Boolean("true") == new Boolean("true")
225 is false, but new Boolean("true") == Boolean.parseBoolean("true") is
true.
226
227 *
228 */
229
Page 5
TestClass.java
230
231 /*
232 Remember these rules for primitive types:
233 1. Anything bigger than an int can NEVER be assigned to an int or
anything
234 smaller than int ( byte, char, or short) without explicit cast.
235 2. CONSTANT values up to int can be assigned (without cast) to
variables of lesser size
236 ( for example, short to byte) if the value is representable by the
variable.
237 ( that is, if it fits into the size of the variable).
238 3. operands of mathematical operators are ALWAYS promoted to AT LEAST
int. (i.e. for byte *
239 byte both bytes will be first promoted to int.) and the return value
will be AT LEAST int.
240 4. Compound assignment operators ( +=, *= etc) have strange ways so
read this carefully:
241 A compound assignment expression of the form E1 op= E2 is equivalent to
E1 = (T)((E1) op (E2)),
242 where T is the type of E1, except that E1 is evaluated only once. Note
that the implied cast
243 to type T may be either an identity conversion or a narrowing primitive
conversion.
244 For example, the following code is correct: short x = 3; x += 4.6;
and results in x having the
245 value 7 because it is equivalent to: short x = 3; x = (short)(x +
4.6);
246
247 */
248 // ---------------------------------------------------
249
250 // LocalDateTime.parse -> doesnt throw ParseException and must receive
251 // string in the format 2015-01-01T17:13:5
252
253
254
255
256 // ---------------------------------------------------
257
258 /*
259 Main must deal with Exception
260 public static void main (String[] args) throws Exception {
261
262 }
263
264 static void thrower() throws Exception {
265
266 }
267
268 */
Page 6
TestClass.java
269
270
271
272 // ------------------------------------------------------------
273 // ArrayList does implement RandomAccess.
274
275 // ------------------------------------------------------------
276
277 /*
278
279
280 class A{
281 public A() {} // A1
282 public A(String s) { this(); System.out.println("A :"+s); } // A2
283 }
284
285 class B extends A{ //No argument will be added by the JVM
286 public int B(String s) { System.out.println("B :"+s); return 0; } // B1
287 }
288 class C extends B{
289 private C(){ super(); } // C1
290 public C(String s){ this(); System.out.println("C :"+s); } // C2
291 public C(int i){} // C3
292 }
293
294
295
296
297 */
298 // -------------------------------------------------------------
299
300 /*
301 public static void mainStringImmutable() {
302 String s1 = new String("java");
303 StringBuilder s2 = new StringBuilder("java");
304 replaceString(s1); // S1 doesnt change, its immutable
305 replaceStringBuilder(s2);
306 System.out.println(s1 + s2);
307 }
308 static void replaceString(String s) {
309 s = s.replace('j', 'l');
310 }
311 static void replaceStringBuilder(StringBuilder s) {
312 s.append("c");
313 }
314 }*/
315 // -------------------------------------------------------------
316
317 /*static void mainNullConcatenate() {
318 System.out.println(null + true); // null cannot be concatenated
Page 7
TestClass.java
Page 8
TestClass.java
has no package)
365
366 // -------------------------------------------------------
367
368
369
370 public static void mainAssignPriority(){
371
372
373
374 int i = 4;
375 int ia[][][] = new int[i][i = 3][i];
376 System.out.println( ia.length + ", " + ia[0].length+", "+ ia[0]
[0].length);
377 }
378
379 static void parse() {
380 LocalDate d1 = LocalDate.parse("2015-02-05",
DateTimeFormatter.ISO_DATE);
381 LocalDate d2 = LocalDate.of(2015, 2, 5);
382 LocalDate d3 = LocalDate.now();
383 System.out.println(d1);
384 System.out.println(d2);
385 System.out.println(d3);
386 }
387
388 // -------------------------------------------------------------
389
390 // You can apply a label to any code block or a block level statement
(such as a for statement) but not to declarations.
391 // For example: loopX : int i = 10;
392
393 // -------------------------------------------------------------
394
395 // java.lang.Number is not final, it can be extended
396
397 // -------------------------------------------------------------
398
399 // The getClass method always returns the Class object for the actual
object on which the method is
400 // called irrespective of the type of the reference
401
402 // -------------------------------------------------------------
403
404 // Exception of unreachable code, it is allowed:
405 // if (false) { x=3; }
406
407 // --------------------------------------------------------------
408
409
Page 9
TestClass.java
Page 10
TestClass.java
Page 11
TestClass.java
503 interface T3 extends T1, T2{ public void m1(); public void m1(int
x); }
504
505
506
507
508
509 // ------------------------------------------------------
510
511 class Super { }
512 class Sub extends Super { }
513
514 /*public static void mainSuper(){
515 Super s1 = new Super(); //1
516 Sub s2 = new Sub(); //2
517 s1 = s2; //3
518 // s2 = s1; sub class cannot be assigned superclass
519 }
520 */
521
522
523 // ------------------------------------
524 // Package import does not use static keyword.
525
526
527 // --------------------------------------------------
528 // s1.subList(1, 1) -> will return an empty sub list. (from index
inclusive to index exclusive)
529
530
531 // ---------------------------------------
532 // When executed it will throw an error because the main should return
void
533 /*class TestClassError{
534 public static long main(String[] args){
535 System.out.println("Hello");
536 return 10L;
537 }
538 }
539 */
540
541 // -------------------------------------
542 // Which variable (or static method) will be used depends on the class
that the variable is declared of.
543 // Which instance method will be used depends on the actual class of
the object that is referenced by the variable.
544 class TestClassExtends {
545 // static void main(String args[]) {
546 // A o1 = new C();
547 // B o2 = (B) o1;
Page 12
TestClass.java
Page 13
TestClass.java
596
597 //
---------------------------------------------------------------------------
------
598
599
600 // Covariant returns are allowed since Java 1.5, which means that an
overriding method can change the return type
601 // to a subclass of the return type declared in the overridden method.
602 // But remember than covarient returns does not apply to primitives.
603
604
605 void executeSub() {
606 System.out.println(new Sub2().someMethod());
607 System.out.println(new Sub3().someMethod());
608 }
609
610 class Base2 {
611
612 Object someMethod() {
613 return "Base";
614 }
615 }
616
617 class Sub2 extends Base2 {
618
619 String someMethod() {
620 return "Base1";
621 }
622 }
623
624 class Base3 {
625
626 int someMethod() {
627 return 1;
628 }
629 }
630
631 class Sub3 extends Base3 {
632
633 int someMethod() { //cannot change return type on primitives
634 return 12;
635 }
636 }
637
638
639
640
641
642
Page 14
TestClass.java
643 // -------------------------------------------------------
644
645
646 static void mainStringConcat() {
647
648 String abc = "";
649 abc.concat("abc"); // abc is not altered
650 abc.concat("def"); // abc is not altered
651 System.out.print(abc);
652 }
653
654 // ---------------------------------------------------
655
656
657 // 1. Literal strings within the same class in the same package
represent references to the same String object.
658 // 2. Literal strings within different classes in the same package
represent references to the same String object.
659 // 3. Literal strings within different classes in different packages
likewise represent references to the same String object.
660 // 4. Strings computed by constant expressions are computed at compile
time and then treated as if they were literals.
661 // 5. Strings computed at run time are newly created and therefore are
distinct. (So line 4 prints false.)
662 // 6. The result of explicitly interning a computed string is the same
string as any pre-existing literal string with
663 // the same contents. (So line 5 prints true.)
664
665 // ---------------------------------------------------
666
667 public static void mainNonLoop(){
668 int i;
669 int j;
670 for (i = 0, j = 0; j < i; ++j, i++){
671 System.out.println(i + " " + j); // Will never be executed
672 }
673 System.out.println("End");
674 }
675
676 public static void mainConcatenateNull() {
677 String newStr = null;
678 newStr += "teste";
679 System.out.println(newStr); // nullteste
680 }
681
682
683 public static void mainStack(){
684 Stack s1 = new Stack ();
685 Stack s2 = new Stack ();
686 processStacks (s1,s2);
Page 15
TestClass.java
Page 16
TestClass.java
object with some changes to the original, you can use the instance method
726 // named with(...). For example, LocalDate sunday =
ld.with(java.time.temporal.TemporalAdjusters.next(DayOfWeek.SUNDAY));
727 // 4. Formatting of date objects into String and parsing of Strings
into date objects is done by java.time.format.DateTimeFormatter class.
728 // This class provides public static references to readymade
DateTimeFormatter objects through the fields named ISO_DATE,
ISO_LOCAL_DATE,
729 // ISO_LOCAL_DATE_TIME, etc.
730 // For example - LocalDate d1 = LocalDate.parse("2015-01-01",
DateTimeFormatter.ISO_LOCAL_DATE);
731 // The parameter type and return type of the methods of
DateTimeFormatter class is the base interface TemporalAccessor instead of
concrete classes
732 // such as LocalDate or LocalDateTime. So you shouldn't directly cast
the returned values to concrete classes like this -
733 // LocalDate d2 = (LocalDate)
DateTimeFormatter.ISO_LOCAL_DATE.parse("2015-01-01"); //will compile but
may or may not throw a ClassCastException at runtime.
734 // You should do like this - LocalDate d2 =
LocalDate.from(DateTimeFormatter.ISO_LOCAL_DATE.parse("2015-01-01"));
735 // 5. Besides dates, java.time package also provides Period and
Duration classes. Period is used for quantity or amount of time in terms of
years,
736 // months and days, while Duration is used for quantity or amount of
time in terms of hour, minute, and seconds.
737 // Durations and periods differ in their treatment of daylight savings
time when added to ZonedDateTime. A Duration will add an exact number of
738 // seconds, thus a duration of one day is always exactly 24 hours. By
contrast, a Period will add a conceptual day, trying to maintain the local
time.
739 // -----------------------------------------
740
741 static void testBitwiseOperator() {
742 // Applied to numeric or booleans
743 int a = 12;
744 long b = 12l;
745
746 System.out.println(a&b);
747 System.out.println(a|b);
748 System.out.println(a^b);
749 System.out.println(~a);
750 }
751
752 // -----------------------------------------
753
754
755 public static void testStringBuilder() {
756
757 StringBuilder b1 = new StringBuilder("snorkler");
Page 17
TestClass.java
Page 18
TestClass.java
-12
800 System.out.println(LocalTime.of(14, 12)); // 14:12
801 System.out.println(LocalDateTime.of(LocalDate.of(2018, Month.APRIL,
12),LocalTime.of(14, 12)));
802
803 //ZonedDateTime b; //with timezone information
804 }
805
806
807 // java.time Package: This is the base package of new Java Date Time
API.
808 // All the commonly used classes such as LocalDate, LocalTime,
LocalDateTime, Instant, Period, Duration are part of this package.
809 // All of these classes are immutable and thread safe.
810
811 // java.time.format Package: This package contains classes used for
formatting
812 // and parsing date time objects such as
java.time.format.DateTimeFormatter.
813
814
815
816 // -----------------------------------------
817
818 static void testCharIntegerConversion() {
819 Integer i = new Integer(2);
820 //char c = i; Integer cannot be converted to char
821 char c1 = 12;
822 }
823
824
825
826 // -----------------------------------------
827
828
829 class Base{
830 int i=10;
831 void testMethod() {
832 System.out.println("Base method1");
833 }
834
835
836
837 }
838 /* class Sub extends Base{
839 int i=20; //This i hides Base's i.
840 void testMethod() {
841 System.out.println("Base method2");
842 }
843
Page 19
TestClass.java
844 }
845
846 public void mainHideVariable() {
847
848 Sub s = new Sub();
849 System.out.println(s.i); // 20
850 System.out.println(((Base)s).i); //the base value, the same applies
to static methods
851 // Instance methods have different behaviour
852 s.testMethod(); // the sub method because is a instance method
853 ((Base)s).testMethod(); // the sub method because is a instance
method
854 }*/
855
856
857
858
859 // -----------------------------------------
860
861 class InterfaceImplementer implements TestInterface{
862
863 void test(){
864 System.out.println(someIntValue); // can be acessed statically
865 //someIntValue = 16; // but the value cannot be altered (is
final)
866 }
867 }
868
869 interface TestInterface {
870 int someIntValue = 12;
871 // private int somePrivate = 12; // private fields cannot be
defined in an interface
872 // protected int someProtected = 12; // protected fields cannot be
defined in an interface
873
874 }
875
876 // -----------------------------------------
877
878 static void autoboxing() {
879 int k = 0;
880 // Both are valid
881 k = new Integer(12) + new Integer(12);
882 System.out.println(k);
883 k = new Integer(12) + 12;
884 System.out.println(k);
885 }
886
887
888 public static void mainPrimitiveConversion () {
Page 20
TestClass.java
889 // Byte->Short->Integer->Long
890 int i = 12;
891 byte b = 12;
892 short s = 12;
893 long l = 121212;
894
895 i = b;
896 //b = i; // Doesnt compile, byte smaller than int
897 //s = i; //Doesnt compile, short smaller than int
898
899
900 // to compile explicit cast is needed.
901 i = (int)l; //if long value is larger than max MAX_INT_VALUE int
will have unknown value
902
903 long l1 = 112121111111000112l;
904 double d = 121212;
905
906 d = l1;
907
908 System.out.println(d);
909
910 System.out.println(Byte.MIN_VALUE +" to "+ Byte.MAX_VALUE);
// -128 to 127
911 System.out.println(Short.MIN_VALUE +" to "+ Short.MAX_VALUE);
// -32768 to 32767
912 System.out.println(Integer.MIN_VALUE +" to "+ Integer.MAX_VALUE);
// -2147483648 to 2147483647
913 System.out.println(Long.MIN_VALUE +" to "+ Long.MAX_VALUE);
// -9223372036854775808 to 9223372036854775807
914 System.out.println(Double.MIN_VALUE +" to "+ Double.MAX_VALUE); //
4.9E-324 to 1.7976931348623157E308
915
916 }
917
918
919 public static void mainStringComparison () {
920
921 String s1 = "S1";
922 String s2 = "S1";
923 String s3 = new String("S1");
924
925 System.out.println(s1 == s2); // True
926 System.out.println(s1.equals(s2)); // True
927 System.out.println(s1 == s3); // False
928 }
929
930
931 // Test usage of switch with char and int
932 // A switch can evaluate char, byte, short, int, enum and String.
Page 21
TestClass.java
Page 22