Unit-IV; Professional Sales Representative (PSR).pptx
Preparing Java 7 Certifications
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. 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. OOP basic
OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
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. 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. Classes
• Compile error
• abstract final class ..
• class public ..
• Visibility precendence
• public > protected >
default > private
• Classes modifier
(inner excluded)
• public and default
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. 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.
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. 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
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. 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).
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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
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. 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. 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. 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. 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.
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