Preparing Java 7 Certifications

3,887 views

Published on

My personal note book to prepare java 7 certication

Published in: Education, Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,887
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
230
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Preparing Java 7 Certifications

  1. 1. Oracle Certificate Associate Java 7 My Personal Note This PPT is NOT a Java 7 course is a set of concepts to MEMORIZE to take the OCA7 Prerequisites: java expert
  2. 2. Bibliography 1.OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA 2.Manuale di Java 7 C. De Sio Cesari HOEPLI 3.Oracle certified associate java se 7 programmer study guide Richard Reese PACKT
  3. 3. OOP basic OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
  4. 4. (Default) Constructor • A default constructor is the one that has no arguments and is provided automatically for all classes. This constructor will initialize all instance variables to default values. • However, if the developer provides a constructor, the compiler's default constructoris no longer added. • The developer will need to explicitly add a default constructor. • It is a good practice to always have a default, no-argument constructor.
  5. 5. Legal vs Illegal • Legal class MyClass … public void MyClass(String name){ } • Having a method with the same name of a constructor, but it is NOT a constrcutor • Legal class MyClass … { name=... } //init block • • Legal class MyClass … public MyClass(String name){ this(name,”another sring”) } public MyClass(String name, String surname){ ... • Calling a constructor within another constructor
  6. 6. Classes • Compile error • abstract final class .. • class public .. • Visibility precendence • public > protected > default > private • Classes modifier (inner excluded) • public and default
  7. 7. Interfaces • An interface is similar to an abstract class. • It is declared using the interface keyword and consists of only: – abstract methods and – final variables. • Note: final keyword is illegal on interface
  8. 8. OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA Methods • The signature of a method consists of: – The name of the method – The number of arguments – The types of the arguments – The order of the arguments • Notice that: – the definition of a signature does not include the return type. – pacakge scoped cannot be visible by any class outside the (also inheriting) private void setAge(int age) { age = age; } This code would not have the intended consequences of modifying the age instance variable. The parameters will have "precedence" over the instance variables. Private void myMethod(int … x) { } Calling myMethod without parameter yMethod()) we pass an empty array.
  9. 9. Widening • Precedence – Widening – Boxing – Varargs
  10. 10. Variables • Variables can be classified into the following three categories: – Instance variables – Static variables – Local variables • Identifiers are case-sensitive and can only be composed of: – Letters, numbers, the underscore (_) and the dollar sign ($) – Identifiers may only begin with a letter, the underscore or a dollar sign • Examples of valid variable names include: – NumberWheels, OwnerName, Mileage, _byline, NumberCylinders, $newValue, _engineOn
  11. 11. Numbers • Number of digits Recommended data type – Less than 10 Integer or BigDecimal – Less than 19 Long or BigDecimal – Greater than 19 BigDecimal • When using BigDecimal, it is important to note the following: – Use the constructor with the String argument as it does a better job at placing the decimal point – BigDecimal is immutable – The ROUND_HALF_EVEN rounding mode introduces the least bias OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
  12. 12. Floating point (exp) float num1 = 0.0f; 1.System.out.println(num1 / 0.0f); 2.System.out.println(Math.sqrt(-4)); 3.System.out.println(Double.NaN + Double.NaN); 4.System.out.println(Float.NaN + 2); 5.System.out.println((int) Double.NaN); 6.System.out.println(Float.NEGATIVE_INFINITY); 7.System.out.println(Double.NEGATIVE_INFINITY); 8.System.out.println(Float.POSITIVE_INFINITY); 9.System.out.println(Double.POSITIVE_INFINITY); 10.System.out.println(Float.POSITIVE_INFINITY+2); 11.System.out.println(1.0 / 0.0); 12.System.out.println((1.0 / 0.0) - (1.0 / 0.0)); 13.System.out.println(23.0f / 0.0f); 14.System.out.println((int)(1.0 / 0.0)); 15.System.out.println(Float.NEGATIVE_INFINITY == Double.NEGATIVE_INFINITY); 1.NaN 2.NaN 3.NaN 4.NaN 5.0 6.-Infinity 7.-Infinity 8.Infinity 9.Infinity 10.Infinity 11.Infinity 12.NaN 13.Infinity 14.2147483647 15.True ● Strictfp abide the IEEE standard ● Strictfp abide the IEEE standard
  13. 13. Boxing and Unboxing and equals• Autoboxing is the automatic conversion of primitive data types into their corresponding wrapper classes. This is performed as needed so as to eliminate the need to perform trivial, explicit conversion between primitive data types and their corresponding wrapper classes. • Unboxing refers to the automatic conversion of a wrapper object to its equivalent primitive data type. In effect, primitive data types are treated as if they are objects in most situations. OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
  14. 14. Literals • Literal constants are simple numbers, characters, and strings that represent a quantity. There are three basic types: – Numeric – Character – Strings • Java 7Java 7 added the ability to uses underscore characters (_) in numeric literals. NOTE • consecutive underscores are treated as one and also ignored • underscores cannot be placed: – At the beginning or end of a number – Adjacent to a decimal point – Prior to the D, F, or L suffix ● Numeric literals that contain a decimal point are by default double constants. ● Numeric constants can also be prefixed with a 0x to indicate the number is a hexadecimal number (base 16). ● Numbers that begin with a 0 re octal numbers (base 8). ● Numeric literals that contain a decimal point are by default double constants. ● Numeric constants can also be prefixed with a 0x to indicate the number is a hexadecimal number (base 16). ● Numbers that begin with a 0 are octal numbers (base 8).
  15. 15. Remember String pool True return • String a=”hello”; String b=”hello”; a==b; “hel”+”lo” ==b; “hello” ==a; “hello”.replace('l','l')==a • False return • String a=”hello”; String b=new String(”hello”); “hel”.concat(“lo”) ==a; “hel”+”lo” ==b; “hello” ==b;“heLLo”.replace('L','l')==a
  16. 16. Character Escapes • a alert • b backspace • f form feed • n new line • r carriage return • t horizontal tab • v vertical tab • backslash • ? question mark • ' single quote • " double quote • ooo octal number • xhh hexadecimal number • Character: This deals with the manipulation of character data • Charset: This defines a mapping between Unicode characters and a • sequence of bytes • CharSequence: In this, an interface is implemented by the String, • StringBuffer and StringBuilder classes defining common methods • StringTokenizer: This is used for tokenizing text • StreamTokenizer: This is used for tokenizing text • Collator: This is used to support operations on locale specific strings • The String, StringBuffer, and StringBuilder classes Mutable Synchronized String no no StringBuilder yes no StringBuffer yes no
  17. 17. Operators TIPS • Total += 2; // Increments total by 2 • Total =+ 2; // Valid but simply assigns a 2 to total! TIPS • Total += 2; // Increments total by 2 • Total =+ 2; // Valid but simply assigns a 2 to total! OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
  18. 18. String equals (intern) String firstLiteral = "Albacore Tuna"; String secondLiteral = "Albacore Tuna"; String firstObject = new String("Albacore Tuna"); if(firstLiteral == secondLiteral) { //RETURN TRUE .. If !(firstLiteral == firstObject) { //RETURN TRUE ... • String make an intern constant equaks fo every instance
  19. 19. OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA Operators • “=>” is not legal • “5 < x < 15” is not legal • Do not confuse the bitwise operators, &, ^, and | with the corresponding logical operators && and ||. The bitwise operators perform similar operations as the logical operators, but do it on a bit-by-bit basis. • “=>” is not legal • “5 < x < 15” is not legal • Do not confuse the bitwise operators, &, ^, and | with the corresponding logical operators && and ||. The bitwise operators perform similar operations as the logical operators, but do it on a bit-by-bit basis.
  20. 20. Mistakes if (1>2 && 2>1 | true) { System.out.println("1"); } else { System.out.println("2"); } • Th results is 2 since the “|” operator is evaluated before the && • (1>2 && 2>1 | true) • Is (1>2 && (2>1 | true))
  21. 21. If short circuit 1.If (a == b && c==d) 2.If (a == b || c==d) • Java will evaluate only the first expression if 1. a!=b 2. a==b 1. To avoid short circuit use the bitwise operator • Sometimes the short circuit could be avoided (eg. When you evaluate a method and you expect the method will be called)
  22. 22. If mistakes • if (limit > 100) – if (stateCode == 45) • limit = limit+10; • else – limit = limit-10; • if (isLegalAge) – System.out.println("Of legal age"); • else – System.out.println("Not of legal age"); – System.out.println("Also not of legal age"); • In the example the last print is executed owever • In the example else is referred to the second if
  23. 23. Switch tips • switch (x) { • case 4: • case 5: • cost = weight * 0.23f; • break; • case 6: • cost = weight * 0.23f; • break; • default: • cost = weight * 0.25f; • } – – • switch (zone) { • case "East": • cost = weight * 1.09; • break; – case "NorthCentral": • cost = weight * 1.1; • break; • default: • cost = weight * 1.2; • } • It works only on Java 7 • It raise exception when zone is null. Consult java.util.Objects• integer data types include byte, char, short, and int. Any of these data types can be used with an integer switch statement. The data type long is not allowed.
  24. 24. arrays • array of objects uses a reference variable • array are intialized to default primitive value or null if object • For each loop works • for(int j : numbers) { – ...; • } • Bidimensional array (they are arrays of arrays) • int coords[][] = new int[ROWS][COLS]; or • coords = new int[ROWS][]; • coords[0] =new int[COLS]; • To compare arrays –Arrays.equals(arr1,arr2) –Arrays.deepEquals(arr1,arr2) //for object simce use equals object method • System.arraycopy method –Performs a shallow copy • Arrays.copyOf method –Performs a deep copy of the entire array • Arrays.copyOfRange method –Performs a deep copy of part of an array • clone method –Performs a shallow copy
  25. 25. Legal vs Illegal • Legal • int[] a, b[]; //b is a 2D array • int[] a[]; //2D array • Illegal int[] z = new int[]; • Illegal • int[] a = new int[2] {1.0,2.0} • int[] a = {1.0,2.0} • int[] a = new int[] {1.0,2.0}
  26. 26. Arrays class • int arr1[] = new int[5]; • Arrays.fill(arr1,5); // fill the integer array with the number 5 • Arrays.toString(arr1)); //return array data • Arrays.deepToString(arr2); / / return also the array of aray data Arrays.asList • The asList method takes its array argument and returns a java.util.List object representing the array. If either the array or the list is modified, their corresponding elements are modified. Arrays.asList • The asList method takes its array argument and returns a java.util.List object representing the array. If either the array or the list is modified, their corresponding elements are modified.
  27. 27. Iterator of ArrayList ListIterator • next: This method returns the next element • previous: This method returns the previous element • hasNext: This method returns true if there are additional elements that follow the current one • hasPrevious: This method returns true if there are additional elements that precede the current one • nextIndex: This method returns the index of the next element to be returned by the next method • previousIndex: This method returns the index of the previous element to be returned by the previous method • add: This method inserts an element into the list (optional) • remove: This method removes the element from the list (optional) • set: This method replaces an element in the list (optional) Iterator • next: This method returns the next element • hasNext: This method returns true if there are additional elements • remove: This method removes the element from the list – (UnsupportedOperationException exception should be thrown) Other colllection elements • Set : HashSet, TreeSet • List: ArrayList, LinkedList • Map: HashMap, TreeMap The ArrayList class is not synchronized. When an iterator is obtained for a ArrayList object, it is susceptible to possible simultaneous overwrites with loss of data if modified in a concurrent fashion. When multiple threads access the same object, it is possible that they may all write to the object at the same time, that is, concurrently. The ArrayList class is not synchronized. When an iterator is obtained for a ArrayList object, it is susceptible to possible simultaneous overwrites with loss of data if modified in a concurrent fashion. When multiple threads access the same object, it is possible that they may all write to the object at the same time, that is, concurrently. To sort array list Collections.sort(ar r); To sort array list Collections.sort(ar r);
  28. 28. for • For loop • for (<initial-expression>;<terminal-expression>;<end-loop operation>) • could be rewritten as – <initial-expression> – for (;;) { • if ! <terminal-expression> break • .. • <end-loop operation> – } – • Legal: for(;;) ; • Legal: for (int i=0, j=0; i<10; i++, j++) {}
  29. 29. For each • for (<dataType variable>:<collection/array>){} • On a list – May not be able to remove elements from a list as you traverse it (in the case of the ArrayList, we can remove an element) – We cannot modify (add) the list from within the for-each statement. – Inability to modify the current position in a list – Not possible to iterate over multiple collections • If the array/collection is null, you will get a null pointer exception.
  30. 30. While, do while, breal and continue • while (<boolean- expression>) <statements>; • do <statement> while (<boolean- expression>); • continue transfer the control to the end of the loop • break stop the loop • break mylabel : labels can be used to break us out of more than one loop
  31. 31. Remember • Compile error • while(true); • Infinite loop • for(;true;) • Warning • if(true){}
  32. 32. Legal vs Illegal • Legal • while((i = 1)! =2) {} • do System.out.print ln(i++); while (i < 5) • Illegal • while(i = 1) {} • while(i ) {} • do System.out.println(i++); System.out.println(); while (i < 5)
  33. 33. Immutable Object To create an immutable object: • Make the class final which means that it cannot be extended (covered in the Using the final keyword with classes section in Chapter 7, Inheritance and Polymorphism) • Keep the fields of the class private and ideally final • Do not provide any methods that modify the state of the object, that is do not provide setter or similar methods • Do not allow mutable field objects to be changed
  34. 34. Inheritance • Overload vs Override – The same method name with different signature vs the same method with same signature • Abstract – An abstract class cannot be instantiated. – An abstract callss can contain non abstract method • Final – Fianal class cannot be overriden • Upcasting is possible. – (DerivedClass) new BaseClass(); //error!
  35. 35. Exception Try { } catch(Exception1 | Exception2 e) { } finally { } • A checked exception requires the client to catch the exception or pass it up the call hierarchy. • The catch block's parameter (e) is implicitly final. • The order of catched exception is followed by jvm • Multiple catch exception is a new Java 7 feature • he finally block will always• execute regardless of the existence or non-existence of exceptions. However, if a try or catch block invokes the System.exit method, the program immediately terminates and the finally block does not execute. • A checked exception requires the client to catch the exception or pass it up the call hierarchy. • The catch block's parameter (e) is implicitly final. • The order of catched exception is followed by jvm • Multiple catch exception is a new Java 7 feature • he finally block will always• execute regardless of the existence or non-existence of exceptions. However, if a try or catch block invokes the System.exit method, the program immediately terminates and the finally block does not execute. • Throwable – Error – Exception • RuntmeException (unchecked) • <Custom>Exception (checked)
  36. 36. Try with resource try (<resources>) { } catch (Exception1 | Exception2 ex) { } • Any resources used with the try-with- resources block must implement the interface java.lang.AutoCloseable.
  37. 37. Mistakes • i/0 • Return AritmeticException (DivisionByZero doesn't exist) String s; s+=””; • Return NullPointerException • 1.0/0.0 return Infinity • Exception doesn't override Error
  38. 38. Java packages Class Note Class Note String Immutable and final java.lang.Objects Java 7 utility class System final Paths Java 7 IO utility Numeric abstract StringBuilder Remember Java doc Integer, Float, .. final ArrayList Remeber Java Doc
  39. 39. Compile or not Compile (sheet reference)
  40. 40. Compile or not Compile (sheet reefernce)
  41. 41. Compile or not compile (sheet refrence)
  42. 42. Giacomo Veneri, Mcs, PhD http://jugsi.blogspot.it OCID: OC1280222

×