Вы находитесь на странице: 1из 22

TestClass.

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

102 class X{ Long val = 10l; }


103 class Y extends X{ Y val = null; }
104
105
106 // --------------------------------------
107 /*
108 interface I {
109 static int a =1;
110 int b =2;
111 int c =5;
112
113 public default void someStuff() { // by default are public, cannot
have other value
114 System.out.println("Some stuff");
115 }
116
117 void someStuff2();
118
119 }
120
121 static class Implemementer implements I {
122 static I getInstance() {
123 return new Implemementer();
124 }
125 static int a =3;
126 int b =4;
127
128 // Can be overwrittem
129 // public void someStuff() {
130 // System.out.println("Some Implementer");
131 // }
132
133 public void someStuff2() {
134 System.out.println(a); // 3
135 System.out.println(b); // 4
136 System.out.println(I.a); // 1
137 System.out.println(I.b); // 2
138 System.out.println(c); // 5
139 }
140
141 }
142
143
144 // ---------------------------------------------------
145
146 static void testLocalDates() {
147 LocalDate ld = LocalDate.of(2018, 1, 1);
148 System.out.println(ld); // 2018-01-01
149 LocalDateTime lt = LocalDateTime.of(2018, 1, 1, 1, 1,1,1); // 2018-
01-01T01:01:01.000000001

Page 3
TestClass.java

150 LocalDateTime lt2 = LocalDateTime.of(2018, 1, 1,1,1); // 2018-01-


01T01:01
151
152 // Formatters
153 System.out.println(ld.format(DateTimeFormatter.ofPattern("yyyy")));
// 2008
154
155 // Modifiers
156 ld = ld.plus(Period.ofDays(1)); // Add 1 day
157 ld = ld.plus(1,ChronoUnit.DAYS); // Add 1 day
158
159 // Parsers
160 System.out.println(LocalDate.parse("2018-01-01")); // VALID
161 //System.out.println(LocalDate.parse("2018/01/01")); // INVALID
162
163 }
164
165
166
167
168
169
170
171 // -------------------------------------------------------
172
173 // INITIALIZATION ORDER
174 // 1- Static block (order or appearance)
175 // 2- Intance initialization
176 // 3- Construtor
177
178 // -------------------------------------------------------
179
180 static void testCasts() {
181
182 byte b = 1;
183 short s = 1;
184 int i = 1;
185 long l = 1;
186 //b =(short) b*b; //Invalid (doesnt fit)
187 }
188
189
190
191 // --------------------------------------------------------------------
192
193 /*List list = new ArrayList();
194 list.add("val1");
195 list.add(2, "val2"); // Index out of bounds exception
196 list.add(1, "val3"); //3 Elements are moved down
197 System.out.println(list);

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

319 System.out.println(true + null); // null cannot be concatenated


320 System.out.println(null + null); //null cannot be concatenated
321 }*/
322
323 // -------------------------------------------------------------
324
325 /*
326 Compilation error, local variables must be initialized if used,
327 otherwise a compilation error occurs in line 5
328
329 static double percent; // 1
330 int offset = 10, base = 50; // 2
331
332 public static double calc(double value) {
333 int coupon, offset, base; // 3
334 if (percent < 10) { // 4
335 coupon = 15;
336 offset = 20;
337 base = 10;
338 }
339 return coupon * offset * base * value / 100; // 5
340 }
341 */
342
343 // -------------------------------------------------------------
344
345 static void mainConcatenation() {
346 System.out.println(12+12+"1" + 2 + 3); // 24123
347 System.out.println("2" + 5+ 3); // 253
348 }
349
350 // ------------------------------------------------------------------
351
352 // First, static statements/blocks are called IN THE ORDER they are
defined. (Hence, a and c will be printed.)
353 // Next, instance initializer statements/blocks are called IN THE ORDER
they are defined. Finally, the constructor is called.
354
355
356 //
357 // Java does not allow variables to have the same name as keywords (if,
for, else, while, class etc.) and
358 // literals (true, false, and, null) but there is no restriction on
naming variables after the names of classes.
359
360
361 // -------------------------------------------------------
362
363
364 // The package with no name is also default imported (in case the class

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

410 public static void mainPrecendence() {


411 int i = 0;
412 int[] iA = { 10, 20 };
413 iA[i] = i = 30;
414
415 System.out.println("" + iA[0] + " " + iA[1] + " " + i);
416 }
417
418 // The statement iA[i] = i = 30 ; will be processed as follows:
419 // iA[i] = i = 30; => iA[0] = i = 30 ; => i = 30; iA[0] = i ; =>
iA[0] = 30 ;
420
421 // Here is what JLS says on this:
422 // 1 Evaluate Left-Hand Operand First
423 // 2 Evaluate Operands before Operation
424 // 3 Evaluation Respects Parentheses and Precedence
425 // 4 Argument Lists are Evaluated Left-to-Right
426
427 // For Arrays: First, the dimension expressions are evaluated,
left-to-right. If any of the expression evaluations completes abruptly, the
expressions to the right of it are not evaluated.
428
429
430
431 // -----------------------------------------------------------
432
433 public static void mainChainedEquals() {
434 int i = 0;
435 int[] iA = { 10, 20 };
436 iA[i] = i = 30;
437 System.out.println("" + iA[0] + " " + iA[1] + " " + i);
438 }
439
440
441
442 // --------------------------------------------------
443 class MyException extends Throwable{} class MyException1 extends
MyException{} class MyException2 extends MyException{} class MyException3
extends MyException2{}
444 /*
445 public static void mainExceptions(String[] args) {
446 ExceptionTest et = new ExceptionTest();
447 try {
448 et.myMethod();
449 } catch (MyException me) {
450 System.out.println("MyException thrown");
451 } catch (MyException3 me3) { // WRONG, first declare the sub
exceptions
452 System.out.println("MyException3 thrown");
453 } finally {

Page 10
TestClass.java

454 System.out.println(" Done");


455 }
456 } */
457
458 // ---------------------------------------------------
459
460 /* void mainshowJ() {
461 while (j <= 5) { // Different j from for loop
462 for (int j = 1; j <= 5;) {
463 System.out.print(j + " ");
464 j++;
465 }
466 j++;
467 }
468 }
469 */
470
471 //
472 // An interface can have a static method but the method must have a
body.
473 // A default method must have a body.
474
475 // ------------------------------------------------
476
477 public static void mainFinnally(){
478 int k = 0;
479 try{
480 int i = 5/k;
481 }
482 catch (ArithmeticException e){
483 System.out.println("1");
484 }
485 catch (RuntimeException e){
486 System.out.println("2");
487 return ;
488 }
489 catch (Exception e){
490 System.out.println("3");
491 }
492 finally{
493 System.out.println("4");
494 }
495 System.out.println("5");
496 }
497
498
499 // --------------------------------------
500
501 interface T1{ } interface T2{ int VALUE = 10; void m1(); }
502 // Multiple parent only allowed for Interface

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

548 // System.out.println(o1.m1()); // It will be invoked C1 m1


549 // System.out.println(o2.i); // It will be invoked b m1
550 // }
551 }
552
553 class A { int i = 10;
554
555 int m1() {
556 return i;
557 }
558 }
559
560 class B extends A {
561 int i = 20;
562
563 int m1() {
564 return i;
565 }
566 }
567
568 class C extends B {
569 int i = 30;
570
571 int m1() {
572 return i;
573 }
574 }
575
576 // --------------------------------------------------------
577
578
579 static void mainStringComparison2 () {
580 String str1 = "one";
581 String str2 = "two";
582 System.out.println( str1.equals(str1=str2) ); //first str1 is
evaluated it has value "one"
583 System.out.println(str1);
584 System.out.println(str2);
585 }
586
587
588
589
590 // -----------------------------------------------
591
592
593 // Exceptions that extend RuntimeException
594 // java.lang.SecurityException, java.lang.ClassCastException,
java.lang.NullPointerException, java.lang.IndexOutOfBoundsException
595

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

687 System.out.println (s1 + " "+ s2);


688 }
689 public static void processStacks(Stack x1, Stack x2){
690 x1.push (new Integer ("100")); //assume that the method push adds
the passed object to the stack.
691 x2 = x1; // It doesnt have any effect, the outer reference will
stay the same
692 }
693
694
695 // -----------------------------------------------------------------
696 public static void mainIncremeter() throws Exception{
697 int i = 1, j = 10;
698 do {
699 if (i++ > --j) continue;
700 } while (i < 5);
701 System.out.println("i=" + i + " j=" + j);
702 }
703
704
705 // A char value can ALWAYS be assigned to an int variable, since the
int type is wider than the char type.
706
707 // ------------------------------------------------------
708
709
710 // Questao 61 initial test -----------------------------------------
711 // a protected member is accessible in the subclass only using a
reference whose declared type is of the same subclass (or its subclass.).
712
713
714 // -----------------------------------------
715
716
717 // Here are some points that you should keep in mind about the new
Date/Time classes introduced in Java 8 -
718 // 1. They are in package java.time and they have no relation at all to
the old java.util.Date and java.sql.Date.
719 // 2. java.time.temporal.TemporalAccessor is the base interface that is
implemented by LocalDate, LocalTime, and LocalDateTime concrete classes.
720 // This interface defines read-only access to temporal objects, such as
a date, time, offset or some combination of these, which are
721 // represented by the interface TemporalField.
722 // 3. LocalDate, LocalTime, and LocalDateTime classes do not have any
parent/child relationship among themselves. As their names imply,
723 // LocalDate contains just the date information and no time
information, LocalTime contains only time and no date,
724 // while LocalDateTime contains date as well as time. None of them
contains zone information. For that, you can use ZonedDateTime.
725 // Since you can't modify them once created, if you want to create new

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

758 StringBuilder b2 = new StringBuilder("yoodler");


759
760 //b1.append(b2.substring(2,5).toUpperCase()); // b1 - snorklerODL
b2 yoodler
761 //b2.insert(3, b1.append("a")); //b1 snorklera yoosnorkleradler
762 b1.replace(3, 4, b2.substring(4)).append(b2.append(false)); //
763 System.out.println(b1); // snorlerkleryoodlerfalse
764
765 }
766
767 // -----------------------------------------
768
769 // A break statement with no label attempts to transfer control to the
innermost enclosing switch,
770 // while, do, or for statement; this statement, which is called the
break target, then immediately
771 // completes normally. If no switch, while, do, or for statement
encloses the break statement, a compile-time error occurs.
772
773
774 // -----------------------------------------
775
776 // This would have been true prior to Java 1.5. But from Java 1.5, an
overriding method is allowed
777 // to change the return type to any subclass of the original return
type, also known as covariant
778 // return type. This does not apply to primitives, in which case, the
return type of the overriding
779 // method must match exactly to the return type of the overridden
method.
780 // Questão 47
781
782 // -----------------------------------------
783
784 public static void main_MIN_VALUE() throws Exception{
785 int a = Integer.MIN_VALUE;
786 int b = -a;
787 System.out.println( a+ " "+b);
788 }
789
790 // -----------------------------------------
791 // The main method can declare that it throws checked exceptions
792 // public static void main (String[] args) throws Exception {}
793
794
795 // -----------------------------------------
796
797 static void testLocalDate() {
798 // Local Date
799 System.out.println(LocalDate.of(2018, Month.APRIL, 12)); // 2018-04

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

933 /*public static void mainSwitch () {


934
935
936 boolean b = true; // NOT VALID
937 switch (b) {
938 }
939
940
941 char a = 1;
942 int b = 1;
943 switch (a) {
944 case 1:
945 System.out.println("1");
946 break;
947 case 'A':
948 System.out.println("A");
949 break;
950 case '1':
951 System.out.println("1 char");
952 break;
953 default:
954 System.out.println("3");
955 }
956 }
957
958
959
960 */
961
962 }
963

Page 22

Вам также может понравиться