Oracle Certification Associate 1Z0-808

From My Limbic Wiki

Links

Installation

Windows

<source lang="Shell"> C:\Program Files\Java </source>

  • Java Se Development Kit 8
    • Java FX SDK
    • Private JRE - Java Runtime Edition
    • Java Mission Control Tools

Can also be installed:

    • Development Tools
    • Source Code
    • Public JRE

Linux

<source lang="Shell"> sudo apt-get install oracle-java8-installer cd /usr/lib/jvm/java-8-oracle

  1. Java version

java -v

  1. Java Compiler

javac -version </source>

Basics

Main Method

<source lang="Java"> public static void main(string[] args){} // valid public static void main(string... args){} // valid </source>

Main Method is a static method and is not associated with any instance of a class. It is called only one time at program start.

<source lang="Java"> public class TestClass {

   public static void main(String[] args) {
        TestClass c = new TestClass("Hello World");
        System.out.println("ça marche-tu ? "+args.toString());
   }

} </source>

Comments

<source lang="Java"> // Single Line Comment

/* Multi Line Comment

  • /

/**

* Java Doc Comment
* @param
* @return 
*/

</source>

Import Conflicts

<source lang="Java"> import java.util.*; import java.sql.*;

// ==> in code = COMPILATION error Date date; </source>

Static Imports

It is not a good idea to do static imports a lot in a projet because it makes difficult to understand where the methods / constants come from

  • Static imports are for importing static members
  • Classic imports are for importing classes

it can be used for methods and constants for example <source lang="Java"> import static java.lang,Math.*;

// Instead of typing Math.min(1,2); we can just type min(1,2) // Because of the static import </source>

Primitives

It is not a good practice to use "l" instead of "L" while declaring long numbers because "l" looks like a "1" number so it can be confusing

Since Java 7 we can use "_" to makes number easier to read.

  • Can be anywhere except: beginning of literal, end of literal and right before or right after the decimal point.
  • Error: Illegal Underscore ==> the code does not compile
KeyWord Size Examples Smallest Data-Type
boolean - true
Numbers without decimal points
byte 8-bits 1
short 16-bits 12 comment
int 32-bits 100 Default all numbers in Java
long 64 bits 12 Requires "L" letter to avoid compilation error, even when stored in long variable
float 32-bits 123.45 Requires letter "f" following the numbers
double 64-bits 123.45

Default all primitives or all that similar types.

Can use "d" / "D" letter to specify

Can convert a Float to Double

char 16-bits 'a'

Octal Numbers

Octal Numbers are numbers from 0 to 7. They can be used in java as

<source lang="Java"> // Valid int octalNumber = 07;

// Invalid - Number is too large, Compilation Error ! int octalNumber = 08; // it is not an octal number

// Valid - BUT coding standards prohibit use of octal literals, as they may be easily confused with decimal literals int octalNumber = 010 // 8 in decimal;

// Valid int declaration int octalNumber = 022; // 18 in decimal

// Valid int declaration int octalNumber = 8;

System.out.println(octalNumber); // print it's int value // Integer to octal String Integer.toOctalString();

</source>

Hexadecimal

Hexadecimals are numbers from 0 to 9 and letters from A to F <source lang="Java"> // Valid int firstHexNumber = 0xF; // 15 in decimal int secondHexNumber = 0x1E; // 30 in decimal

// Print the decimal value System.out.println(firstHexNumber); // print the Hexadecimal value: Integer.toHexString(firstHexNumber);

// p indicates hexadecimal floating point number double hexPi = 0x1.91eb851eb851fp1

int amount = 0xE; // 0x is prefix for hexadecimal </source>

Binary

<source lang="Java"> // Valid int firstBinary = 0xF; // 15 in decimal int secondBinary= 0x1E; // 30 in decimal

// Print the decimal value System.out.println(firstBinary); // print the Binary value: Integer.toBinaryString(firstBinary);

int amount = 0b101; // 0b is the prefix for Binary </source>

Scientific Notation

<source lang="Java"> // Both are valid and compile double scientificNotation = 5.000125E3 // in double 5000.125 double scientificNotation = 5.000125E03 // in double 5000.125 </source>

Chars

<source lang="Java"> char ch = 'a'; char ch1 = '1'; // it is still a char char uniChar = '\u03A9'; // upper case greek omega character char romanNumber= '\u216C'; // roman 50 number </source>

Booleans

<source lang="Java"> boolean booleanTrue = true; System.out.println(booleanTrue); // the ouput is "true"; </source>

Variables

Declaring and initializing

Allowed Characters in variables names: letter digit, dollar sign, underscore.

Declare and or initialize multiple variables on the same line is OK but not a good practice

  • with coma speration: If some are declared only and other initialized, it will compile !
  • with semi colomn separation, but on the same line

<source lang="Java"> int myVariable; // Declaration

// compilation error - Variable might not have been initialized System.out.println(myVariable);

myVariable = 10; // Initialization

//int i3; i4; // does not compile - they are not the same statement

// Java is case sensitive, but it can make the code really hard to understand char char; // does not compile char Char; // compile - not a good practice char cHar; // compile - not a good practice

int _myString = "It is valid identifier"; // It is valid

// Illegal examples

double 3Dpoint; // Variable name cannot start with number double my@Street; // @ is not a letter digit, dollar sign or underscore </source>

About Initialization

<source lang="Java"> public class DefaultInitialization{

   static boolean myBoolean;
   static byte myByte;
   static short myShort;
   static int myInt;
   static long myLong;
   static float myFloat;
   static double myDouble;
   static char myChar;
   public static void main(String[] args){
       int localInt;

// System.out.println("localInt= " + localInt); // compilation error - Variable might not have been initialized

       System.out.println("myBoolean= " + myBoolean); // false
       System.out.println("myByte= " + myByte); // 0
       System.out.println("myShort= " + myShort); // 0
       System.out.println("myInt= " + myInt); // 0
       System.out.println("myLong= " + myLong); // 0
       System.out.println("myFloat= " + myFloat); // 0.0
       System.out.println("myDouble= " + myDouble); // 0.0
       System.out.println("myChar= " + myChar); // 
   }

}

</source>

Scope

<source lang="Java"> public class VariableScope {

   static int globalInt = 5; // global variable
   public static void main(String[] args) {
       int localInt = 10; // local variable
       {
           int microInt = 10; // local variable - can be only accessed in this curcly brackets block
           {
               {
                   // int microInt = 20; // will not compile because is defined in the parent block and in the same scope
               }
           }
       }
       System.out.println(microInt); // compilation error
       int microInt = 30; // can be defined, because it has a different scope
   }

} </source>

Class

Any error in this order will be followed by a compilation error.

  1. Package Declaration
  2. Import Statements
  3. Class Declaration
  4. Field Declarations
  5. Method Declarations

Null

A Null object will print "null" with a sout. But if we try to use the value to do anything, it will return <source lang="Java"> Java.lang.NullPointerException // then a stacktrace </source>

Wrapper Types

Boxing: converting primitive to wrapper int --> Integer

Unboxing: converting wrapper to primitive Integer --> int <source lang="Java"> Integer myInteger = new Integer(10); // Unnecessary boxing Integer myInteger = 20; // as primitive Integer myInteger = Integer.valueOf(10); // Unnecessary boxing Integer myInteger = Integer.parseInt("3"); // parsed from string Integer myInteger = null; int myInteger = null; // does not compile

printSum(1, 5); // autoboxing

private static void printSum(Integer first, Integer second){

   System.out.println(first+second);

} </source>

Java Benefits

  • Object
    • Allows Functional Programming
  • Encapsulation
    • Support Access Modifiers to prodect data from an intended access and modifications
  • Plateform Independant
  • Robust
    • Memory Leaks
    • Manage Memory
    • Garbage Collector
    • Elimiates Pointers
  • Simple
  • Secure

Exam Questions

Traps

  • Says "local" or "global" variable
  • Constructor or Static void main ?
  • Curly Brackets
  • Binary, Hexadecimal, Decimal ?

Operators

Operator Symbols and Examples
Post-unary operators expression++, expression--
Pre-unary operators ++expression, --expression
Other unary operators +, -, !
Multiplications/Divisions/Modulus *, /, %
Addition/Substraction +, -
Shift operators >>, >>>
Relational operators <, >, <=, >=, instanceof
Equal to / not equal to ==,!=
Logical operators &, ^, |
Short-circuit logical operator &&, ||
Ternary operators booleanExpression ? expression1 : expression2
Assignement operators =, +=, -=, *=, /=, %=, &=, ^=, !=, <<=, >>=, >>>=

Numeric Promotion and Casting

Converting a smaller type into a bigger primitive type Rules

  • When 2 values have a different data types, Java will auto promote one of the values to the larger datatype
  • When one of the values is integral and the other is floating-point, Java will auto promote the integral (byte, short, int, long) value to the floating-point (float, double) value's data type
  • Small data types (byte, short, int, char), are the first promoted to int any time they are used with binary arithmetic operator, even when neither of the operand is int
  • After all promotion has finished and the operands are the same data type (e.g all double), the result value will have the same data type as its promoted operants

<source lang="Java"> int x = 5; double y = 10.55;

double result = x + y; // VALID, no compilation error System.out.println("x + y= " + (x+y)); // 15.55 - int x is auto promoted to double

// "f" is REQUIRED float z = 3.35; // Does not compile, Default is Double in 64 bits so it will not be auto converted to float.

short x = 14; // auto-promoted to integer short y = 6; // auto-promoted to integer System.out.println(x/y); // Output of type int // short z = x * y; // does not compile - because of java auto promotion from short to integer on each site // short z = (short) x * (short) y; // does not compile - because when multiplying two shorts, java auto-promote the result to int short z = (short) x * y; // so we need to convert the result - integer - to short; </source>

Unary Operators

<source lang="Java"> ++x; // the operator is before it is applied first and the value returned is the new value x++; // the operator is placed after the operand referred as both increment operator and both decrement operator then the original value of expression is returned with operator applied after the value is returned.

int wrong = !5; // does not compile boolean wrongBoolean = -true; // does not compile boolean wrongBoolean = !0; // does not compile - 0 and false are not related in any way, and ! cannot be aplied to integers

int myInt = 5; // myInt = myInt+1; // int otherInt = myInt; int otherInt = ++myInt; // update the reference myInt and then assign its value to otherInt System.out.println("myInt= " + myInt + " otherInt= " + otherInt); // myInt= 6 otherInt= 6

int myInt = 5; // int otherInt = myInt; // myInt = myInt+1; int otherInt = myInt++; // assign myInt value to otherInt and then update its reference System.out.println("myInt= " + myInt + " otherInt= " + otherInt); // myInt= 6 otherInt= 5

int count = 0; System.out.println(count); // 0 System.out.println(++count); // 1 System.out.println(count); // 1 System.out.println(count--); // 1 System.out.println(count); // 0 </source>

Exam Questions

<source lang="Java"> // Exam Question int e = 3; int f = ++e * 5 / e-- + --e; System.out.println(e); // 2 System.out.println(f); // 7

int g = 6; int h = 2; int i = ++h + --g * 3 + 2 * g++ - h--  % --g; // 3 + 5 * 3 + 2 * 5 - 2  % 5; // 3 + 15 + 10 - 3; // 25 System.out.println(i); System.out.println(3%5); // 3 System.out.println(9%5); // 4 </source>

Assignment Operators

<source lang="Java"> int x = (int) 1.0; // output 1 short y = (short) 19812345; // output 20473 int z = (int) 9f; // output 9 // long t = (long) 32165498731654897; // Integer number too large long u = 32165498731654897L; // output 32165498731654897 </source>

Overflow and Underflow

  • Overflow: when a number is too large to fit its data type
    • Java automatically wraps a round to the next lowest value and starts counting from the lowest rate
  • Underflow: when a number is too small to fit its data type;
    • Java automatically wraps a round to the next largest value and starts counting from the largest rate

Sample with shorts

<source lang="Java"> short y = (short) 32_800; // OverFlow with number: 32_800 // The largest number in short is: 32_767 // Then java goes to the negative, the number becomes: -32_767 // Then java continue to count // Result: -32_736

short y = (short) -32_800; // Underflow with number: -32_800 // The lowest number in short is: -32_767 // Then java goes to the negative, the number becomes: 32_767 // Result: 32_736 </source>

Sample with Bytes

<source lang="Java"> byte positiveByte = 127; //positiveByte = positiveByte + 1 // Compilation error. int and byte = incompatible types. positiveByte++;

byte negativeByte = -128; negativeByte--;

System.out.println(positiveByte); // -128 System.out.println(negativeByte); // 127 </source>

Compound Assignment Operators

<source lang="Java"> int x = 2; int y = 3; // int a+= 5; // does not compile

x *= z; // x = x * z - same as above

// Without explicit cast long a = 10; int b = 4; // b = b * a; // does not compile // b = (int)(b * a); // compile, but too long to write it

b *= a;

// Weird assignment long c = 4; long d = (c=2); // shorter form of c = 2; long d = c; - It is not a good practice and confusing but it can be at the exam System.out.println(c); // 2 System.out.println(d); // 2

long e = 3; long f = 2; long h = 1; long i = e + 3 * (f = 3) - (h -= 2); //long i = 3 + 3 * 3 - -1; //long i = 3 + 9 + 1; System.out.println(i); </source>

Relational Operators

Tricks in exams <source lang="Java"> int d = 12; long e = 15L; double f = 14.5;

System.out.println((d < e + " " + (e > f)); </source>

Equality Operators

Java can compare primitive numbers but not a number and boolean, a string or object and a boolean and so on

<source lang="Java"> int a = 5; int b = 3; boolean c = a == b; // valid boolean d = a != b; // valid // boolean g = true == 0; // does not compile - cannot use it with numbers // boolean g = false != "test"; // does not compile </source>

Object Equality

Range [-128, 127] must be interned(JLS7 5.1.7)

IntegerValueOf.png <source lang="Java"> // 100, is an object in the cache provided by Integer, so it has the same reference Integer inRangeA = 100; Integer inRangeB = 100; System.out.println(inRangeA == inRangeB); // true because == Compare the references

/*

Different Object References / Memory Accessors
  • /

// 200, is not an object in the cache provided by Integer, so it has the same reference Integer inRangeC = 200; Integer inRangeD = 200; System.out.println(inRangeC == inRangeD); // false because == compare the references

int inRangeE = 300; // creates the reference in memory int inRangeF = 300; // 300 exist now in memory, so java just use the reference System.out.println(inRangeE == inRangeF); // false because == compare the references

int inRangeG = 400; int inRangeH = inRangeG; System.out.println(inRangeG == inRangeH); // false because == compare the references

// Unique Number for objects in memory - also Memory Location / Adress System.out.println(System.identityHashCode(inRangeA)); System.out.println(System.identityHashCode(inRangeB)); System.out.println(System.identityHashCode(inRangeC)); System.out.println(System.identityHashCode(inRangeD)); System.out.println(System.identityHashCode(inRangeE)); System.out.println(System.identityHashCode(inRangeF)); System.out.println(System.identityHashCode(inRangeG)); System.out.println(System.identityHashCode(inRangeH)); </source>

Character Arithmetic

<source lang="Java"> char myCharA = 'A'; char myCharNum = '1'; System.out.println(Character.isLetter(myCharA)); // true System.out.println(Character.isDigit(myCharNum)); // true

//Exam Questions char letter = 65; // A in ASCII table int myInt = letter + 3; // 68 char myNewLetter = (char) myInt; // 68 is D in ASCII table

char newChar = (char) (letter + 1); // B System.out.println(newChar == 'B'); // true System.out.println(newChar++ < 'C'); // true - 67 < 68 System.out.println(newChar); // C - 68 </source>

Questions

<source lang="Java"> /*

Valid answers: A-B-D
int can be auto-promoted to long or double
  • /

byte x = 5; byte y = 10; __?__ z = x + y // default result of x + y is int, but it can be auto-promoted

A. int B. long C. boolean D. double E. short // int cannot be promoted to short, because int is larger F. byte </source>

Basic Flow Control

if / else

<source lang="Java"> int x1 = 50, x2 = 75; boolean b = x1 >= x2; // false if(b = true) System.out.println("Success"); // true - it is an assignation b = true, not b == true else System.out.println("Failure"); </source>

ternary operator

<source lang="Java">

y = (x > 5) ? (2 * x) : (4 * x);

//exam trap System.out.println(y < 10 ? 5 : "test"); // valid - int is converted to string to be printed int myInt = y < 10 ? 5 : "test"; // does not compile - Incompatible types

// valid and compile ! System.out.println(x > 2 ? x < 4 ? 10 : 8 : 7); // is equal to System.out.println( (x > 2) ? (x < 4 ? 10 : 8) : 7); </source>

switch

<source lang="Java"> int x = 0; switch(x){

 case 1 :
 case 2 : System.out.println("test"); break;
 case 3 :
 case 'K' : // Character can be cast to an integer
 case "Test" :  // does not compile - String cannot be cast to an integer
 default: System.out.println("nothing"); break;

}

final char a = 'A', d = 'D'; char grade = 'B'; switch(grade){

   case a:
   case 'B': System.out.println("great");
   case 'C': System.out.println("good"); break;
   case d:
   case 'F': System.out.println("notgood");

} // it will print "greatgood" cause there is no "break;" after the "case 'B'" line </source>

while Loop

The problem with while loop is, it is easy to create a loop that will never ends

<source lang="Java"> while (y < 20) // there is no curly brackets

   y++;       // so only the first line after the while statement is executed as while body
   x++;       // theses lines are OUTSIDE the while loop
   y+=10;     // theses lines are OUTSIDE the while loop  

int x = 0; while x < 10 // does not compile - while loop required braces x++; </source>

do-while loop

It is the same as While loop but it garentees the bloc of code will be executed at least once

<source lang="Java"> int x = 10; do x--; while (x > 10);

do{ int y = 1; // does not compile because while loop cannot access to y wich is not declared in the same scope System.out.println(y++ +" "); } while(y <=10);

</source>

for loop

<source lang="Java"> for(;;;){ // compile - infinite or endless for loop

   System.out.println("Hello World !");

}

// compile for(int y =0; z =4; x < 5 && y < 10; x++ , y++){ // this is legal, and compile

}

// compilation error int z = 5; // 1st declaration for(int y =0; z =4; x < 5 && y < 10; x++ , y++){ // d is already defined in the scope

}

// compilation error - incompatible types // it is not possible to use different types of number inside the for loop for(int c =0; long d =4; x < 5 && y < 10; x++ , y++){ // d is already defined in the scope

}

for(int = 0; i < 10 ; ){ // infinite loop

   i = i++; // this is always the "old" value of i wich is incremented, so always the same
   System.out.println("Hello World");

} </source>

Understanding Strings

<source lang="Java"> String hello = "hello"; String world = "world"; // hello + world; // does not compile - it is not a statement // String integerToString = 5; // does not compile </source>

String Immultability

immutable is the opposite of changeable. It is still Garbage Collected

String is immultable, it means when you create a string, there is no way to change it

it is only possible to create another string. <source lang="Java"> String hello = "hello"; hello.toUpperCase(); System.out.println(hello); // prints "hello" in lower case because strings are immutable hello = hello.toUpperCase(); // System.out.println(hello); // prints "HELLO". A new String has been created /*

 variable are references to the String object in memory, so it is possible to change the reference to point to another one
  • /

String s1 = "1"; String s2 = s1.concat("2"); // 12 s2.concat("3"); // s2 is not changing System.out.println(s1); // 1 System.out.println(s2); // 12 s2 = s2.concat("3"); // 123 System.out.println(s2); // 123 </source>

String Pool and String Equality

String.png

<source lang="Java"> String name = "john"; String anotherName = "john"; String john = "jo"+"hn"; String newName = new String("john"); String trimName = " jo".trim() + "hn";

// == operator is checking the Object Reference System.out.println(name == anotherName); // true - same memory reference System.out.println(name == john); // true - same memory reference System.out.println(name == newName); // false - Another memory reference System.out.println(name == trimName ); // false - Another memory reference

// .equals method is checking the value to compare if two object are equals in sense of equivalency System.out.println(name.equals(anotherName)); // true - same memory reference System.out.println(name.equals(john)); // true - same memory reference System.out.println(name.equals(newName)); // true - Another memory reference

System.out.println(System.identityHashCode(name)); System.out.println(System.identityHashCode(anotherName)); System.out.println(System.identityHashCode(john)); System.out.println(System.identityHashCode(newName));

String str1 = "abc"; String str2 = "ab"; String str3 = str1 + "c"; String str4 = "abc" + "c"; System.out.println(str1 == str2); // false System.out.println(str1 == str3 ); // false System.out.println(str1 == str4 ); // true </source>

String methods

indexOf, substring

<source lang="Java"> // Substring String str = "Java is fun"; System.out.println(str.indexOf("fun")); // 8 System.out.println(str.substring(4,4)); // return an empty string // System.out.println(str.substring(4,2)); // out of range // System.out.println(str.substring(4,15)); // index out of range </source>

equalsIgnoreCase

<source lang="Java"> // equalsIgnoreCase method System.out.println("abc".equalsIgnoreCase("ABC")); // true

// startsWith / endsWith String str = "beginning";

System.out.println(str.startsWith("b")); // true System.out.println(str.startsWith(str)); // true System.out.println(str.startsWith("B".toLowerCase())); // true System.out.println(str.endsWith("ng")); // true

// contains System.out.println(str.contains("ginn"));

// replace System.out.println(str.replace("n","A"));

// trim str = " " + str + " "; System.out.println(str); System.out.println(str.trim()); </source>

Method Chaining

<source lang="Java"> String start = "Java"; System.out.println( start.trim().toLowerCase().replace("j","Z")); </source>

String Builder

String and StringBuilder

<source lang="Java"> String s1 =="java"; StringBuilder s2 = new StringBuilder("java"); // StringBuilder s3 = "new String"; // does not compile // if (s1 == s2) // does not compile - java does not allow to compare String and StringBuilder. They are two different classes

   // System.out.println("same memory reference");

if (s1.equals(s2))

   System.out.println("values are equals");

</source>

Concatenation

<source lang="Java"> // concatenation with + String alphabet = ""; for(char letter = 'a'; letter <= 'z' ; letter++){

   alphabet += letter; // every iteration will create a new String Object !

} System.out.println(alphabet);

// append StringBuilder sb = new StringBuilder(); for(char letter = 'a'; letter <= 'z' ; letter++){

   sb.append(letter); // add char to string builder, reuses string builder without creating a string object each time

} System.out.println(sb); </source>

Reference

<source lang="Java"> // reference StringBuilder builder = new StringBuilder("start"); builder.append("-middle"); StringBuilder anotherBuilder = builder.append("-end"); // updates the builder object and gives the reference to the same value at another builder

// Memory reference - Value System.out.println(builder); // start-middle-end System.out.println(anotherBuilder); // start-middle-end System.out.println(builder == anotherBuilder); // true - they have the same memory reference

// Memory Reference StringBuilder a = new StringBuilder("This "); StringBuilder b = a.append("Java "); // both object have the same reference b = b.append("is".append(" so ").append("Cool"); // the value in memory is updated System.out.println(a); // ThisJava is so Cool System.out.println(b); // ThisJava is so Cool </source>

Length & Capacity

<source lang="Java"> // Length & Capacity StringBuilder builder = new StringBuilder(100); // 100 is the capacity System.out.println(builder.length()); // 0 System.out.println(builder.capacity()); // 100 builder.append("text"); System.out.println(builder.length()); // 4 System.out.println(builder.capacity()); // 100 </source>

Insert

<source lang="Java"> // insert - char index position are updated with every insert StringBuilder builder = new StringBuilder("programming"); builder.insert(7,"-"); // offset, str builder.insert(7,2); // offset, i System.out.println(builder); // program2-ming </source>

Delete && deleteCharAt

<source lang="Java"> // delete - char index position are updated with every delete StringBuilder builder = new StringBuilder("programming"); builder.delete(7,8); // from, to builder.deleteCharAt(7); // at //builder.delete(7,6); // indexOutOfBand Exception builder.delete(7,7); // does not change anything System.out.println(builder); // programng </source>

Reverse

<source lang="Java"> StringBuilder builder = new StringBuilder("ABC123"); builder.reverse(); System.out.println(builder); // 321CBA String builderToString = builder.toString(); builderToString = builderToString.toLowerCase(); System.out.println(builderToString); //321cba </source>

Arrays

it is not possible to change the size of an array. "length" property is final, so it is a constant and cannot be changed.

Declaration

<source lang="java"> // size need to be "int" - it cannot be a double type[] varName = new type[size]; // ={0,0,0} empty array declaration, inizialized with 0 type[] varName = new type[]{1,2,3,4,5,6,7,8,9}; // initialized array

int[] myArray = new int[4*5/3]; // valid = 6,6666666667, is rounded to 6 System.out.println(myArray.length); // 6

// other declrations int[] myArray = {1,2,3,4,5,6,7,8,9}; // legal - anonymous array int[] myArray = {}; // legal - empty array. size = 0 int myArray[]; int[] myArray; int[] arrayOne, arrayTwo; // valid - creates two arrays int arrayOne[], arrayTwo; // valid - creates one array and one int - Bad Practice //int[20] amyArray; // does not compile - size need to be at the initialization char[]c = new char[2]; // is valid - even if is missing the space between char[] and "c" </source>

Equality

<source lang="java"> String[] animals = {"parrot","dog","cat"}; String[] myAnimals = animals; String[] otherAnimals = {"parrot","dog","cat"};

// understanding System.out.println(animals); // [i = int[] - [L = String[] ....

// equals System.out.println(animals.equals(myAnimals)); // true System.out.println(animals.equals(otherAnimals)); // false

// == System.out.println(animals == myAnimals); // true System.out.println(animals == otherAnimals); // false

// Arrays Provide an equals method import java.util.Arrays; System.out.println(Arrays.equals(animals,myAnimals)); // true System.out.println(Arrays.equals(animals,otherAnimals)); // true </source>

Using

<source lang="java"> String[] pets = {"parrot","dog","cat"}; System.out.println(pets[3]); // throws ArrayIndexOutOfBounds exception System.out.println(Arrays.toString(pets)); // print array in one line

String[] notInit; System.out.println(Arrays.toString(notInit)); // does not compile - cause the array has not been initialized

// size of an array String[] pets = {"parrot","dog","cat"}; // System.out.println(pets.length()); // does not compile - length is not a method, but a final field System.out.println(pets.length); // </source>

Foreach Loop

<source lang="java"> /*

   for(datatype variableName : collection){
       //body
   }
  • /

</source>

OptionalLabel: Break; Continue;

Reference to a head loop.

Break: stop the loop.

Continue: skip the actual iteration and go the the next iteration.

<source lang="java"> // label myLabel: {

   int[] myArray = {1,2,3,4};

}

String[] animals = {"Dog", "Cat", "Lizard"}; MY_LOOP: for(String animal : animals){

   if(animal.equals("Cat")){
       break MY_LOOP;
   }

} </source> Labelbreakcontinue.png

Sorting

<source lang="java"> import java.util.Arrays; int[] numbers = {965,23,89,87,41,8,5}; String[] strings = {"965","23","89","87","41","8","5"}; String[] alpha = {"W","E","A","E","U","V","C"}; Arrays.sort(numbers); Arrays.sort(strings); Arrays.sort(alpha); System.out.println(Arrays.toString(numbers)); // [5, 8, 23, 41, 87, 89, 965] - Number sort System.out.println(Arrays.toString(strings)); // [23, 41, 5, 8, 87, 89, 965] - Alphabetical sort System.out.println(Arrays.toString(alpha)); // [A, C, E, E, U, V, W] - Alphabetical sort </source>

Binary Search

Binary Search gives unpredictable results if it is used on a array wich is not sorted <source lang="java"> // Binary search return the index of the found number OR // a negative index, which is the index of where it should be int[] numbersSample = {1,3,5,6,7}; System.out.println(Arrays.binarySearch(numbersSample,2)); // -2 : number 2 needs to be inserted before the index 2 System.out.println(Arrays.binarySearch(numbersSample,5)); // 2 : number 5 is found at the index 2 System.out.println(Arrays.binarySearch(numbersSample,7)); // 4 : number 4 is found at the index 7 System.out.println(Arrays.binarySearch(numbersSample,1)); // 0 : number 1 is found at the index 0 System.out.println(Arrays.binarySearch(numbersSample,3)); // 1 : number 3 is found at the index 1 System.out.println(Arrays.binarySearch(numbersSample,6)); // 3 : number 6 is found at the index 3 System.out.println(Arrays.binarySearch(numbersSample,4)); // -3 : 4 needs to be inserted before the index 3 </source>

Variable Arguments

<source lang="java"> public static void main(string[] args){} // valid public static void main(string... args){} // valid </source>

Multidimensionnal Arrays

/ ! \ Java is row major, that means row first

MultidimensionnalArrays.png

<source lang= "java"> String[][] myStringArray = new String[][]{

   {"One","Two"},
   {"Three","Four","Five"},
   {"Six","Seven","Eight","Nine"},
   null

}; System.out.println(Arrays.toString(myStringArray)); // [[Ljava.lang.String;@3ada9e37, [Ljava.lang.String;@5cbc508c, [Ljava.lang.String;@3419866c, null]

int[][][] threeDArray = new int[][][]{

   {{1,2,3},{4,5,6},{7,8,9}},
   {{10,11,12},{13,14,15},{16,17,18}},
   {{19,20,21},{22,23,24},{25,26,27}},

}; System.out.println(Arrays.toString(threeDArray)); //[[[I@63e31ee, [[I@68fb2c38, [[I@567d299b] </source>

Nested Loop

When a loop contains another loop, it is called "nested loop" <source lang= "java"> for (int i = 0 ; i < 5 ; i++){

   for (int j = 0 ; j < 5 ; j++){
      // this is a nested loop
   }

} </source>

Exam Questions

<source lang= "java"> int[][] scores = new int[5][]; Object[][][] cubbies = new Object[3][0][5]; // String beans[] = new beans[6]; // does not compile - it is uses variable name as if it was a type java.util.Date[] dates[] = new java.util.Date[2][]; //int[][] types = new int[]; // does not compile - don't specify any size //int[][] java = new int[][]; // does not compile - don't specify any size /*

 The first size / dimension is always required
*/

</source>

ArrayList

The array list will automatically resize if you try it with more elements that it can currently hold <source lang= "java"> ArrayList<String> list = new ArrayList<String>(); // second type is not necessary ArrayList<String> list = new ArrayList<>(20); // initial capacity of 20 List<String> list = new ArrayList<>(); // using the interface as type // ArrayList<String> list = new List<>(); // does not compile

ArrayList<String> list = new ArrayList<String>(); // second type is not necessary list.add(0,"Romain"); // 0 is the index, "Romain" the value/element


/*

* .equals() method to compare two arraylist returns true ONLYF IF:
   - Elements are equals
   - Elements are in the same order
*/

</source>

Wrappers

<source lang= "java"> // List<double> doubleList = new ArrayList<>(); // does not compile - type argument cannot be a primitive type List<Double> doubleList = new ArrayList<>(); doubleList.add(10.5); // autoboxing double number = doubleList.get(0) // unboxing to primitive

List<Integer> numbers = new ArrayList<>(); numbers.add(null); numbers.add(null); System.out.println(numbers.size()); // 2 int getNullInt = numbers.get(0); // null pointer exception Integer getNullInteger = numbers.get(0); // null pointer exception </source>

ArrayList and Array Conversion

<source lang= "java"> List<String> names = new ArrayList<>(); names.add("Romain"); names.add("John"); names.add("Doeuf");

Object[] namesArray = names.toArray(); // convert a list ton an array;


List<String> petsList = Arrays.asList("cat","dog","parrot"); // returns fixed size array </source>

Exam Tips

  • Accolades mal placées
  • E scientifique remplacé par un F
  • Declare and or initialize multiple variables on the same line is OK but not a good practice
    • with coma speration: If some are declared only and other initialized, it will compile !
    • with semi colomn separation, but on the same line
  • Error is thrown BEFORE an SOUT