Saturday, August 5, 2017

Java SE 8 Foundation Summary

Java SE 8 Foundations Summary

Important

This is a personal summary for Java SE8 Foundations Examination (Exam Number: 1Z0-811). To be success, my personal advice is: be the compiler, read and write a lot of code. Focus on learning objectives wording: Describe, Compile, Identify (read code), Use (write code), Develop, Compare (write and check difference), Handle (exception only), Traverse (array elements).

What is Java

  • Describe the features of Java

There are 6 primary features of java:

  1. Simple: Automatic garbage collection (automatic memory management), use reference instead of pointers, NO operator overloading
  2. Object Oriented: Contrary to procedural programming (sequence programing), OOP allow the interactions of objects. From OOP, consider the following:
    • Modularity: Objects source code can be maintained independently from other source code.
    • Information Hiding: Objects access control allow to show only interaction and hide real code implementation.
    • Code re-use:
    • Plug and debugging ease: Because of object independecy, introduction of new functionalities is easy. If some code is corrupted, or doesn´t work properly, just deleted.
  3. Distributed: RMI, URL and COBRA support distributed network technology.
  4. Multi-Thread: Several task can run concurrently.
  5. Secure: Applets can write to computer, Java tech controls for java code, no memory manipulation (no pointers.
  6. Platform independent program: Program once, use everywhere (Same Java Compiler).
  • Describe the Real world applications of Java

To understand the applications, identify the products or Java Solutions Technology per Group. Java only use one language for all their products. According to the platform, Java offers a solution:

  1. Java SE: Used to develop computer and web (Applets) applications. An Applet is an application launch on a web browser.
    • Java EE: used to develop and distributed large applications (servers and client side). It extends Java SE according to specific needs.
    • Java FX:
  2. Java ME:Applications for constraint consumer devices.
  3. Java Card: Used for identification, security, transaction and mobile SIM.

Java Basics

  • Describe the Java Development Kit (JDK) and the Java Runtime Environment (JRE)

Describe JDK:The Java Development Kit is the software (SDK) that allow programmers to create, compile and excecute Java technology on a particular program.

Describe JRE:To create a Java File we need a IDE. To compile a file we need the IDE or Dev-Kit which include javac command. Now, JRE provides the command java that allow to execute java applications. The Java Runtime Environment (JRE) is a set of software tools for development of Java applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting libraries. JRE is part of the Java Development Kit (JDK), but can be downloaded separately.

  • Describe the components of OOP:
  1. Inheritance:Pass knowledge down. It allows the structure and methods to pass downthe hierarchy. It offers the ability to reuse existing code (objects).
  2. Polymorphism:Objects can take many forms. Same method implemented in different ways.
  3. Encapsulation:It enforce modularity (self contained modules called clases).
  • Describe the components of a basic Java program:
  1. package section
  2. import library section
  3. Java code is organized in classes. Each class can define variables and methods. Class variables and methods are defined inside brackets.
  4. main method is the place where classes variables and methods are used.
  • Compile and execute a program:

To compile from terminal use javac (it creates a binary file with .class extension) instruction found in dev-kit. It is importantn to specify the complete address of the file that contains main code section. If no main section found, than file will not compile. To execute the file and see the result, use java instruction found in JRE. In this case change the "/" for points, and do not use .java ends.

Basic Java Elements

  • Identify the convention followed in a Java program
  1. Packages
    The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981. Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
  2. Classes
    Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
  3. Interfaces
    Interface names should be capitalized like class names.
  4. Methods
    Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
  5. Variables
    Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
  6. Constants
    Should be declared in upper case( static final type CAPITAL = 12)
  • Use Java reserved words

Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.

abstract, continue, for, new, switch, assert***, default, goto*, package, synchronized,boolean, do, if, private, this, break, double, implements, protected, throw, byte, else, import, public, throws, case, enum****, instanceof, return, transient, catch, extends, int short, try, char, final, interface, static, void, class, finally, long, strictfp**, volatile, const*, float, native, super, while,

  • Use single-line and multi-line comments in Java programs

Single line comment is like this:

// Line comment
Multiline comments (JavaDocs) is like these:
/* this is a line comment */
/** This is a JavaDoc comment or multiline comment */
  • Import other Java packages to make them accessible in your code

Just use the keyword import and the corresponding package.

  • Describe the java.lang package.

Provides classes that are fundamental to the design of the Java programming language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time. Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode. The Void class is a non-instantiable class that holds a reference to a Class object representing the type void. The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String, StringBuffer, and StringBuilder similarly provide commonly used operations on character strings. Classes ClassLoader, Process, ProcessBuilder, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies. Class Throwable encompasses objects that may be thrown by the throw statement. Subclasses of Throwable represent errors and exceptions.

Working with Java Data Types

  • Declare and initialize variables including a variable using final

This section says Declare. I belive it is important to identify also default values of each primitive data types. Also identify that local variables will not be initialized.

Data type Default value Size (bytes)
Byte, short, int 0 8,16,32
Long 0L 64
float 0.0F 32
double 0.0 64
char \u0000 16
boolean false 1
String (any object) null Add primitive data type

Identify that declaration and assignment are two different things. Declaration examples include:


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        // Declaration
        byte val1;
        short val2;
        int val3;
        long val4;
        float val5;
        double val6;
        char val7;
        boolean val8;
        String val9;
        Blogger_java vol10;
    }    
}

Assignment requires previous variable declaration


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        // Declaration
        byte val1 = 5;
        short val2 = 12;
        int val3 = 2000;
        long val4 = 1234L;
        float val5 = 12.34F;
        double val6 = 12.34;
        char val7 = 'A';
        boolean val8 = true;
        String val9 = "Hola mundo";
        Blogger_java vol10 = new Blogger_java();
    }    
}
  • Cast a value from one data type to another including automatic and manual promotion

Type promotion rules:

  1. All byte and short values are promoted to int.
  2. If one operand is a long, the whole expression is promoted to long.
  3. If one operand is a float, the entire expression is promoted to float.
  4. If any of the operands is double, the result is double.

Widening conversion rule: from lower byte storage to higher byte storage.

  1. From a byte to a short, an int, a long, a float, or a double
  2. From a short to an int, a long, a float, or a double
  3. From a char to an int, a long, a float, or a double
  4. From an int to a long, a float, or a double
  5. From a long to a float or a double
  6. From a float to a double

Here are some code example:


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Widening rule */
        byte a = 12;
        short b = a; // Promoted to short
        int c = b;  // Promoted to int
        //byte d = c;  // Error, 8 byte to store 32 byte element
        long d = c;  // Promoted. 64 bytes to store 32 byte element
        float e = 12.56F;
        double f = e; // Promoted. 64 byte to store 32 byte element
        
        /* Promotion rule */
        int g = b+c;  // b is promoted to int
        int g_with_cast = (int)b + c;  // First transform b to int and operate
        double h = d + e; // right section promoted to float. finaly promoted to double.
        double h_with_cast = (double)d + (double)e; // casting up is ok
        
        int i = (int)d + (int)e; // casting down (lose precision)
    }    
}
  • Declare and initialize a String variable

Declaration and assignment can be made in one line or split in two lines. String is NOT a Primitive data type , it is an Object.


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Declare a String Object + Assign (two lines)*/
        String var1;
        var1 = "Hola";
        /*Declare a String Object + Assign (one lines)*/
        String var2 = "Mundo";
    }    
}

Observe that there is no import keyword. Then we can conclude that String object is declared in java.lang

There are 3 important rules to remember when dealing with String definition (OCA SE 8 Programer I -Jeanne Boyarsky Scott Selikoff-):

  1. String val1 = 2+3+"5"; // 55 (evaluate from left to right)
  2. String val2 = 3+"4"+5+6; // 3456
  3. String val3 = 3+6; // compilation error

Working with Java Operator

  • Use basic arithmetic operators to manipulate data including +, -, *, /, and %

package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Declare tree variables and initialice two of them */
        int var1 = 12;
        int var2 = 5;
        int result;
        /* Addition */
        result = var1 + var2;
        /* Substraction */
        result = var1 - var2;
        /* Multiplication */
        result = var1 * var2;
        /* Division (result is double) */
        double result_d = var1 / var2;
        /* Modulo */
        result = var1 % var2; /* equal to: 2*/
    }    
}

Special care to output result. Arithmetic operators works like in a calculator. If reader is not familiar with Modulus operator (%), check these exercises:


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Exercise 1*/
        int var1 = 7;
        int var2 = 8;
        int result = var1 % var2;
        System.out.println(result);
        /* Exercise 2 */
        var1 = 10;
        var2 = 2;
        result = var1 % var2;
        System.out.println(result);
        /* Exercise 3*/
        var1 = 9;
        var2 = 2;
        result = var1 % var2;
        System.out.println(result);
        /* Exercise 4*/
        var1 = 73;
        var2 = 26;
        result = var1 % var2;
        System.out.println(result);
    }    
}
  • Use the increment and decrement operators

These belong to unary Java operators (see manual). Imagine that var=3. Preincrement ++var will FIRST increase the value and next perform the operation. Postincrement var++ will FIRST perform the operation and next increase var. Here are some examples. Take a piece of paper write the answers and compare your result with the output that java generate (write this code and compile from Terminal (Mac, Linux) or cmd (Windows)).


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Exercise 1*/
        int var1 = 7;
        int var2 = 8;
        
        System.out.println(var1++ + var2++);
        System.out.println("var1: " + var1);
        System.out.println("var2: " + var2);
        
        /* Exercise 2*/
        int var3 = 2;
        int var4 = 5;
        ++var3;
        
        System.out.println(var4 - var3++);
        System.out.println("var3: " + var3);
        System.out.println("var4: " + ++var4);
        
        /* Exercise 3*/
        double var5 = 17.4;
        double var6 = 8.3;
        --var5;
        var6--;
        
        System.out.println(var5++ + var6);
        System.out.println("var5: " + var5);
        System.out.println("var6: " + var6);
    }    
}
  • Use relational operators including ==, !=, >, >=, <, and <=

Relational operator are used to compare two expressions (primitive data type values). If you want to compare two String objects use equal() String method. For user defined objects, it is recommended to write equal method. The output of relational operators is a boolean expression. Some exercises here:


package blogger_java;

public class Blogger_java {
    public int value;
    public Blogger_java(int x){value = x;}
    public boolean equal(Blogger_java x){
        return (this.value == x.value);
    }
        
    public static void main(String[] args) {
        
        int var1 = 7;
        int var2 = 8;
        
        System.out.println("Exercise 1: " + (var1 == var2) );
        System.out.println("Exercise 2: " + (var1 > var2) );
        System.out.println("Exercise 3: " + (var1 != var2) );
        System.out.println("Exercise 4: " + (var1 >= var2) );
        System.out.println("Exercise 5: " + (var1 <= var2) );
        System.out.println("Exercise 6: " + (var1 < var2) );
        
        String var3 = "Hola mundo";
        String var4 = "Hola mundo";
        
        System.out.println("Ejercise 7: " + (var3==var4));
        System.out.println("Exercise 8: " + (var3!=var4));
        System.out.println("Exercise 9: " + (var3.equals(var4)) );
        
        Blogger_java var5 = new Blogger_java(12);
        Blogger_java var6 = new Blogger_java(12);
        
        System.out.println("Ejercise 10: " + (var5==var6));
        System.out.println("Ejercise 11: " + (var5.equal(var6)));
    }    
}
  • Use arithmetic assignment operators

It combines equality with arithmetic operations. Just remember that: The operation is performed first and next the assignment. The following web page has excellent examples: Java Tutorial

  • Use conditional operators including &&, ||, and ?
  1. Logical and (&&) operator. If only one of the expressions evaluated is false the whole expression will be false.
  2. Logical or (||) operator. If only one of the expressions evaluated is true the whole expression will be true.
  3. Conditional logical ? : operator (ternary operator) is used as a short cut if - else operation.

package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        boolean cond = (7 > 9);
        boolean cond1 = ("Hola"=="hola"); /* equal String function is better */
        boolean cond2 = (12.8 <= 123);
        
        boolean result1 = (cond && cond1 && cond2);
        System.out.println(result1);
        boolean result2 = (cond || cond1 || cond2);
        System.out.println(result2);
        
        String msg = (cond) ? "Yes" : "NO";
        System.out.println(msg);
        }    
}
  • Describe the operator precedence and use of parenthesis

This web has a table explaining the subject and some exercises. Be the compiler and identify the solution..

Working with the String Class

  • Develop code that uses methods from the String class

Be the compiler. Try to identify output message for each exercise.


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Exercise 1 */
        String var = "Hello";
        String var1 = " World";
        
        var.concat(var1);
        var.charAt(3);
        System.out.println("Message 1. var value is: " + var);
        
        /* Exercise 2 */
        String var2 = var1.concat(var);
        System.out.println("Message 2. var2 value is: " + var2);
        
        /* Exercise 3 */
        String var3 = var2.trim();
        System.out.println("Message 3. var3 value is: " + var3);
        
        /* Exercise 4 (number output ¿ interpretation ?)*/
        String var4 = (var1 + var2);
        System.out.println("Message 4. comparison value is: " + var4.compareTo("hello world"));
        System.out.println("Message 5. comparison value is: " + var4.compareToIgnoreCase("HELLO WORLD"));
        
        /* Exercise 5 */
        String var5 = "My name is Mauricio";
        System.out.println("Message 6. char value is: " + var5.charAt(3));
        
        /* Exercise 6 (extend string to endindex -1)*/
        String var6 = var5.substring(3, 7);
        System.out.println("Message 7. substring value is: " + var6);
        
        /* Exercise 7 */
        String var7 = "I'm learning Java SE8";
        System.out.println("Message 8. String length: " + var7.length());
        
        /* Exercise 8 (match id format: ###-##-X)*/
        String var8 = "019-32-F";
        System.out.println("Message 9. String match id format ? : " + var8.matches("[0-9]{3}-[0-9]{2}-[A-Z]{1}"));
        System.out.println("Message 10. String match id format ? : " + var8.matches("[0-9]{4}-[0-9]{1}-[A-Z]{1}"));
        
        /* Exercise 9 */
        String var9[] = var8.split("-");
        System.out.println("Message 11.");
        for(String x: var9){
            System.out.println(x);
        }
        
        /* Exercise 10 */
        String var10 = var2;
        char var11[] = var10.toCharArray();
        System.out.println("Message 12.");
        for(char x: var11){
            System.out.println(x);
        }
        
        /* Exercise 11 */
        String var12 = "BYE java";
        System.out.println("Message 13. " + var12.toLowerCase());
        System.out.println("Message 14. " +var12.toUpperCase());
        
    }
}

String is an object that has a lot of methods. It is important to identify when a String object is defined.

  • Format Strings using escape sequences including %d, %n, and %s

Read table in this page for more information: format specifier. Be the compiler and try to solve the following problems.


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        /* Exercise 1 (Hexadecimal number representation)*/
        System.out.printf("12.34 hexadecimal representation is: %a \n",12.34);
        
        /* Exercise 2 */
        Integer value = null;
        System.out.printf("Is there any value: %b \n", value);
        
        /* Exercise 3 */
        int value1 = 12345;
        System.out.printf("value1 is: %d \n", value1);
        
        /* Exercise 4 */
        double value2 = 3.14E12;
        System.out.printf("value2 is: \n", value2);
        System.out.printf("value2 is: %e \n", value2);
        System.out.printf("value2 is: %f \n", value2);
        System.out.printf("value2 is: %g \n", value2);
        
        /* Exercise 5 */
        int value3 = 98;
        System.out.printf("value3 in octal: %o \n",value3);
        
        /* Exercise 6 */
        int value4 = value3;
        System.out.printf("value4 is: %x", value4);
        
    }
}

Working with the Random and Math Classes

  • Use the Random class

Random class can't be found in java.lang. Therefore we need to import the library java.util.Random


package blogger_java;

import java.util.Random;

public class Blogger_java {
        
    public static void main(String[] args) {
        Random rnd = new Random();
        /* Exercise 1 () number distribution: U(0,1) */
        System.out.println("U[0,1] number: " + rnd.nextDouble());
        
        Random rnd1 = new Random(123987);
        /* Exercise 2 change seed and get number*/
        System.out.println("U[0,1] number: " + rnd1.nextDouble());
        
        /* Exercise 3 int between [0,10]. Which will give cero result*/
        int rnd2 = (int)(10*rnd.nextDouble())+1;
        int rnd3 = rnd.nextInt(10);
        System.out.println("rnd2 value is: " + rnd2);
        System.out.println("rnd3 value is: " + rnd3);
        
        /* Exercise 4 N[2,1]*/
        double rnd4 = 2 + rnd.nextGaussian();
        System.out.println("N(2,1): " + rnd4);
        
        /* Exercise 5 random boolean*/
        System.out.println("random boolean: " + rnd.nextBoolean());
    }
}
  • Use the Math class

Math class is incorporated in java.lang, therefore no import is need it. It includes: abs, trigonometric functions, min/max, power, random, floor, ceil, etc. Some use are:


package blogger_java;

import java.util.Random;

public class Blogger_java {
        
    public static void main(String[] args) {
        Random rnd = new Random();
        
        /* Exercise 1 (abs)*/
        double value1 = (rnd.nextGaussian()*rnd.nextInt(100));
        System.out.println("abs(value1): " + Math.abs(value1));
        
        /* Exercise 2 (ceil)*/
        System.out.println("ceil(value1): " + Math.ceil(value1));
        
        /* Exercise 3 (floor)*/
        System.out.println("floor(value1): " + Math.floor(value1));
        
        /* Exercise 4 nextup + floor*/
        System.out.println("value1 + 1: " + Math.nextUp(Math.floor(value1)));
        
        /* Exercise 5 nextdown + ceil*/
        System.out.println("value1 - 1: " + Math.nextDown(Math.ceil(value1)));
        
        /* Exercise 5 power*/
        System.out.println("2^4: " + Math.pow(2,4));
        
        /* Exercise 6 min*/
        System.out.println("Min(12,3): " + Math.min(12,3));
        
        /* Exercise 7 max*/
        System.out.println("Max(12,3): " + Math.max(12,3));
        
        /* Exercise 8 scalb*/
        System.out.println("3*2^4: " + Math.scalb(3, 4));
    }
}

Using Decision Statements

  • Use the decision making statement (if-then and if-then-else)

With if - then, if condition is false, no output is generated. With if - then - else, if condition is false, else brackets code is generated.


package blogger_java;

public class Blogger_java {
        
    public static void main(String[] args) {
        
        double value1 = 12;
        double value2 = Math.PI;
        
        /* Exercise 1 */
        
        if(value1 > value2){
            System.out.println("value1 > value2: yes !!");
        }
        
        /* Exercise 2 */
        if(value1 == value2){
            System.out.println("value1 and value2 are equal !!");
        }else{
            System.out.println("value1 and value2 are different !!");
        }
        
        /* Exercise 3 nested if (What is printed)*/
        boolean value3 = false;
        boolean value4 = true;
        if(value3){
            System.out.print(1);
            if(value4){
                System.out.print(2);
            }else{
                System.out.print(3);
            }
        }else{
            System.out.print(4);
        }
        
        /* Exercise 4 */
        boolean value5 = !value3;
        System.out.println("");
        if(value5){
            System.out.print(1);
            if(value4){
                System.out.print(2);
            }else{
                System.out.print(3);
            }
        }else{
            System.out.print(4);
        }
    }
}
  • Use the switch statement

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types) and the String class. Switch asses equality only.

Be the compiler and guess the message output.


package blogger_java;

public class Blogger_java {
    
    enum sex{male,female, gay, lesbian};
    
    public static void main(String[] args) {
        
        
        /* Exercise 1 */
        int cars_number = 3;
        assert(cars_number > 0):"Error: Negative number";
        switch(cars_number){
            case 1:
                System.out.println("Ummm only one car !!");
                break;
            case 2:
                System.out.println("This person has a good job !!");
                break;
            case 3:
                System.out.println("This family is huge !!");
                break;
            case 4:
                System.out.println("WTF !!");
                break;
            default:
                System.out.println("Probably live in Dubai !!");
                break;
        }
        
        
        /* Exercise 2 (String) */
        String account = "Credit";
        switch(account){
            case "Company":
                System.out.println("Company account");
                break;
            case "Credit":
                System.out.println("Credit account");
                break;
            case "Rich Person":
                System.out.println("Rich person account");
                break;
            default:
                System.out.println("Saving account");
        }
        /* Exercise 3 (enum)*/
        sex person = sex.female;
        switch(person){
            case female:
                System.out.println("Female person");
                
            case gay:
                System.out.println("Gay person");
                break;
            default:
                System.out.println("Male person");
                break;
        
        }
        /* Exercise 4 */
        int month = 11;
        switch(month){
            case 12:
            case 1:
            case 2:
                System.out.println("Winter in Spain");
                break;
            case 3:
            case 4:
            case 5:
                System.out.println("Spring in Spain");
                break;
            case 6:
            case 7:
            case 8:
                System.out.println("Summer in Spain");
                break;
            case 9:
            case 10:
            case 11:
                System.out.println("Autumn in Spain");
                break;
            default:
                System.out.println("Incorrect season");
                break;
        }
       
    }
}
  • Compare how == differs between primitives and objects
  1. For primitives types == works fine.
  2. With String it is recommended to use equals(String o) method instead of ==.
  3. With object, == does not work. For comparison, implement equal(Object o) method.
  • Compare two String objects by using the compareTo and equals methods
  1. compareTo makes a Lexicographical comparison. Output is an integer value. If both Strings are equal, result must be cero.
  2. equals makes a char by char comparison. It gives a boolean result.

Using Looping Statements

  • Describe looping statements

A loop statement is executed until the condition evaluated returns: false. See oracle documentation for each loop statement.

  • Use a for loop including an enhanced for loop

Both can be used to write and read Arrays. For cero size ArrayList, enhance loop can't be used. For non-cero size ArrayList both for loops can be used to write.


package blogger_java;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;

public class Blogger_java {
    
    public static void main(String[] args) {
        Random rnd = new Random();
        double[] rand_values = new double[100];
        double[] rand_values1 = new double[100];
        ArrayList rand_values2 = new ArrayList<>();
        
        /* Write Array */
        for(int i = 0; i < rand_values.length; i++){
            rand_values[i]=rnd.nextDouble();
        }
        
        for(double x: rand_values1){
            x = rnd.nextDouble();
        }
        
        /* Write ArrayList cero size */
        for(int i = 0; i < 100; i++){
            rand_values2.add(rnd.nextGaussian());
        }
        
        /* Write ArrayList non-cero size */
        for(int i = 0; i < 100; i++){
            i += rnd.nextGaussian();
        }
        
        /* Read Array with standard for loop */
        for (int i = 0; i < rand_values.length; i++) {
            System.out.println(i);
        }
        
        /* Read ArrayList with enhance for loop */
        for(double x: rand_values2){
            System.out.println("x");
        }
    }
}
  • Use a while loop
  • Use a do- while loop

For previous two items see: Oracle Doc

  • Compare and contrast the for, while, and do-while loops

The main difference between for loop, while loop, and do while loop:
While loop checks for the condition first. so it may not even enter into the loop, if the condition is false. It also works with an existing variable.
do while loop, execute the statements in the loop first before checks for the condition. At least one iteration takes places, even if the condition is false. It also works with an existing variable.
for loop is similar to while loop except that initialization statement, usually the counter variable initialization a statement that will be executed after each and every iteration in the loop, usually counter variable increment or decrement

  • Develop code that uses break and continue statements

In the part of the documentation reader can find description of the two items. Other examples are:

  1. Account Balance (label break)

Account start at 1030€. Each withdrawal reduce balance in 100 and stop when account balance is not enough. In that moment request print account balance. Identify where to use break and not modify code behavior.


package blogger_java;

public class Blogger_java {
    
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        int Balance = 1030;
        boolean withdrawal = true;
        start:
            while(withdrawal){
                evaluate:
                if(Balance > 100){
                    Balance -= 100;
                    System.out.println("Retiro 100 €");
                }else{
                   withdrawal = false;
                }
            };
        System.out.println("Account balance: " + Balance);
    }
}
  1. Perforated bottle

A bottle has 3 litters of water in a container where pressure change constantly. There is a whole in the bottle and water flow randomly from the bottle. Water outflow is characterize with the formula: abs(N(3,1)) cm^3, and inflow with the formula: abs(N(0,1)) cm^3. When bottle reach 1 litter (or closer), equilibrium is reach and no outflow /inflow occurs anymore.


package blogger_java;

import static java.lang.Math.abs;
import java.util.Random;

public class Blogger_java {
    
    public static void main(String[] args) {
        double water_start = 3*1000;
        double water_in, water_out, balance;
        boolean ends = true;
        Random rnd = new Random();
        water_level:
        while(ends){
            variables:
            water_out = abs(rnd.nextGaussian())+3;
            water_in = abs(rnd.nextGaussian());
            balance = water_in - water_out;
            reduce_water:
                if(water_start > 1000){
                    water_start +=balance;
                }else{
                    break;
                }
            System.out.println("Water level is: " + water_start);
        }
        System.out.println("final water level is: " + water_start);
    }
}

¿Why there is no need to use label break here?: Because break terminates the innermost switch, for, while, do-while statement. There is only one, then label here is redundant.

  1. Lottery Number

A lottery winer must match two numbers: Lucky number (from 0 to 5) and Fraction number (from 0 to 10). Both numbers are set randomly. ¿ Is the following code correct ?


package blogger_java;

import java.util.Random;

public class Blogger_java {
    
    public static void main(String[] args) {
        Random rnd = new Random();
        boolean lucky_num = true;
        boolean fraction_num = true;
        int lucky_number = 3;
        int fraction_number = 7;
        int game=0;
        start:
        while(lucky_num){
            game++;
            int result_lucky_number = rnd.nextInt(5);
            if(result_lucky_number == lucky_number){
                fraction_search:
                while(fraction_num){
                    game++;
                    int result_fraction_number = rnd.nextInt(10);
                    if(result_fraction_number == fraction_number){
                        System.out.println("We have a winer in " + game + " games.");
                        break start;
                    }else{
                        System.out.println("Lucky found, but fraction not found.");
                        continue;
                    }
                }
            }else{
                System.out.println("Lucky number not found");
            }
                    
        }
        
    }
}

Incorrect code due to: Double game count and Lucky number search only once. Erase second game++ and change continue to continue start (recommended changes makes second while redundant).

Debugging and Exception Handling

  • Identify syntax and logic errors
  • Use exception handling
  • Handle common exceptions thrown
  • Use try and catch blocks

For previous 4 items see Oracle documentation.

Arrays and ArrayLists

  • Use a one-dimensional array
  1. Array: Simple fixed sized arrays that we create in Java (index start at cero).
  2. ArrayList: Dynamic sized arrays in Java that implement List interface. It is template initializer with an object (don't confuse with primitives). ArrayList is a class that can be found in: java.util (index start at cero).

package blogger_java;

import java.util.ArrayList;

public class Blogger_java {
    
    enum sex{male,female, gay, lesbian};
    
    public static void main(String[] args) {
        
        /* Example (Array vs ArrayList)*/
        int[] x = new int[3];
        x[0] = 1;
        x[1] = 2;
        x[2] = 3;
        for (int i = 0; i < x.length; i++) {
            System.out.println("Array element: " + x[i]);
        }
        
        ArrayList y = new ArrayList<>();
        y.add(1);
        y.add(2);
        y.add(3);
        
        for(int val: y){
            System.out.println("ArrayList element: "+val);
        }
    }
}
  • Create and manipulate an ArrayList

An important element of Array and ArrayList is: index start at cero. Class methods consider this, then don´t forget it.


package blogger_java;

import java.util.ArrayList;
import java.lang.Math;

public class Blogger_java {
    
    public static void main(String[] args) {
        
        /* Example (manipulate ArrayList)*/
        
        ArrayList y = new ArrayList<>();
        y.add(1.0);
        y.add(2.0);
        y.add(3.0);
        System.out.println("ArrayList size: " + y.size());
        
        for(double val: y){
            System.out.println("ArrayList element: "+val);
        }
        
        y.remove(2); /* removes third element */
        y.clear(); /* clear all array elements */
        
        for(int i = 0; i < 100; i++){
            y.add(Math.random());
        }
        
        System.out.println("New ArrayList size: " + y.size());
        
        y.set(99, Double.NaN);
        System.out.println("ArrayList[100]: " + y.get(99));
    }
}
  • Traverse the elements of an ArrayList by using iterators and loops including the enhanced for loop

Expose different forms to traverse ArrayList elements.


package blogger_java;

import java.util.ArrayList;
import java.lang.Math;
import java.util.Iterator;

public class Blogger_java {
    
    public static void main(String[] args) {
        
        /* Example (Traverse ArrayList)*/
        
        ArrayList values = new ArrayList<>();
        for(int i = 0; i< 10; i++){ /* Set the ArrayList */
            values.add(Math.random());
        }
        
        /* Traverse with iterators */
        System.out.println("Iterator");
        Iterator it = values.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        
        /* do while loop */
        System.out.println("\n do while loop ");
        it = values.iterator(); // re-start iterator
        do{
            System.out.println(it.next()); 
        }while(it.hasNext());
        
        /* while loop */
        System.out.println("\n while loop ");
        it = values.iterator(); // re-start iterator
        while(it.hasNext()){
            System.out.println(it.next());
        }
        
        /* for loop*/
        System.out.println("\n for loop ");
        for(int i = 0; i < values.size(); i++){
            System.out.println(values.get(i));
        }
        
        /* enhance for loop */
        System.out.println("\n enhance for loop ");
        for(double i: values){
            System.out.println(i);
        };
        
        /* functional operator */
        System.out.println("\n functional operator ");
        values.forEach((i) -> {
            System.out.println(i);
        });    
    }
}
  • Compare an array and an ArrayList

Difference can be found in this web .

Classes and Constructors

  • Create a new class including a main method

Java program can only have one main method. If program has more than one class, only one must implement main. Use access_type class classname {.....} to create a class. Inside the brackets deine main method with the signature: public static void main(String[] args) { ... }.

If class is compiled from Terminal (Mac and Linux) or Command Line Interface (Windows), use javac to compile and java to execute. If user define more parameters inside java on terminal, these will be stored in args array. Consider the following example

I compile the file from Terminal (Mac user):

Mauricios-MacBook-Pro:src mauriciobedoya$ javac blogger_java/Blogger_java.java

Mauricios-MacBook-Pro:src mauriciobedoya$ java blogger_java.Blogger_java Hola Mundo hello world

Last four words will be printed. They are added to arg String array as additional arguments passed.

  • Use the private modifier

See the table and recommendations found in Oracle.

  • Describe the relationship between an object and its members

This is best described in Oracle documentation.

  • Describe the difference between a class variable, an instance variable, and a local variable

This blog describe (with examples) the difference. Oracle documentation also gives some insight.

  • Develop code that creates an object's default constructor and modifies the object's fields

Instance variables are unique for each object. Under the existence of instance variables, theses must be initialized by the constructor when object is created (new keyword implemented). In the following code, variables size and color where defined for Jean class, and NetBeans create /assign them automatically with the constructor (insert code help).

To modify object instance variables, use Setters. NetBeans insert them automatically (insert code help).


package blogger_java;

public class Jean {
    private int size;
    private String color;

    public Jean(int size, String color) {
        this.size = size;
        this.color = color;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void setColor(String color) {
        this.color = color;
    }
    
}
  • Use constructors with and without parameters

If constructor doen't has parameters, there is no need to define it explicitly in the class. Constructor parameters must be used to initialize class instance variables. Remember that constructor are never inherited.

  • Develop code that overloads constructors

Constructor overload consider the existence of more than one constructor (different signature).


package blogger_java;

public class Jean {
    private int size;
    private String color;
    
    /* If not specified this Jean is created */
    public Jean(){
        this.size = 32;
        this.color = "Blue";
    }

    public Jean(int size, String color) {
        this.size = size;
        this.color = color;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public void setColor(String color) {
        this.color = color;
    }
    
}

More information related to Constructor in Oracle documentation

Java Methods

  • Describe and create a method
  • Create and use accessor and mutator methods
  • Create overloaded methods

Overload methods is simple the same method with different signature (parameter list /output type).

  • Describe a static method and demonstrate its use within a program

Check Oracle documentation to understand these questions..

No comments:

Post a Comment

Earn free bitcoin