If you can't read please download the document
Upload
giacomo-veneri
View
3.824
Download
1
Embed Size (px)
Citation preview
Oracle Certificate AssociateJava 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
Bibliography
OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
Manuale di Java 7 C. De Sio Cesari HOEPLI
Oracle certified associate java se 7 programmer study guide Richard Reese PACKT
OOP basic
OCA Java SE 7 Programmer I Certification Guide PREPARE FOR THE 1Z0-803 EXAM MALA GUPTA
(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.
Legal vs Illegal
Legalclass MyClass public void MyClass(String name){}
Having a method with the same name of a constructor, but it is NOT a constrcutor
Legalclass MyClass
{name=...
} //init block
Legalclass MyClass public MyClass(String name){this(name,another sring)}
public MyClass(String name, String surname){...
Calling a constructor within another constructor
Classes
Compile error
abstract final class ..
class public ..
Visibility precendence
public > protected > default > private
Classes modifier (inner excluded)
public and default
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
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 theinstance variables.
Private void myMethod(int x) {
}
Calling myMethod without parameter (myMethod()) we pass an empty array.
Widening
PrecedenceWidening
Boxing
Varargs
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
Numbers
Number of digits Recommended data typeLess 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
Floating point (exp)
float num1 = 0.0f;
System.out.println(num1 / 0.0f);
System.out.println(Math.sqrt(-4));
System.out.println(Double.NaN + Double.NaN);
System.out.println(Float.NaN + 2);
System.out.println((int) Double.NaN);
System.out.println(Float.NEGATIVE_INFINITY);
System.out.println(Double.NEGATIVE_INFINITY);
System.out.println(Float.POSITIVE_INFINITY);
System.out.println(Double.POSITIVE_INFINITY);
System.out.println(Float.POSITIVE_INFINITY+2);
System.out.println(1.0 / 0.0);
System.out.println((1.0 / 0.0) - (1.0 / 0.0));
System.out.println(23.0f / 0.0f);
System.out.println((int)(1.0 / 0.0));
System.out.println(Float.NEGATIVE_INFINITY == Double.NEGATIVE_INFINITY);
NaN
NaN
NaN
NaN
0
-Infinity
-Infinity
Infinity
Infinity
Infinity
Infinity
NaN
Infinity
2147483647
True
Strictfp abide the IEEE standard
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
Literals
Literal constants are simple numbers, characters, and strings that represent aquantity. There are three basic types:Numeric
Character
Strings
Java 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 are octal numbers (base 8).
Remember String pool
True returnString 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
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
MutableSynchronized
Stringnono
StringBuilderyesno
StringBufferyesno
Operators
TIPSTotal += 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
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
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.
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))
If short circuit
If (a == b && c==d)
If (a == b || c==d)
Java will evaluate only the first expression if
a!=b
a==b
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)
If mistakes
if (limit > 100)if (stateCode == 45)limit = limit+10;
elselimit = limit-10;
if (isLegalAge)System.out.println("Of legal age");
elseSystem.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
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.
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 arraysArrays.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
Legal vs Illegal
Legal
int[] a, b[]; //b is a 2D array
int[] a[]; //2D array
Illegalint[] 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}
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.
Iterator of ArrayList
ListIteratornext: 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)
Iteratornext: 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 elementsSet : 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.
To sort array listCollections.sort(arr);
for
For loop
for (;;)
could be rewritten as
for (;;) {if ! break
..
}
Legal: for(;;) ;
Legal: for (int i=0, j=0; i