pag. 76-85

Variables

 
/**
 * The variables passed as method's parameters has to match the type.
 * For example, if we pass a string as math.sum() param we get compile error.
 */

package com.minte9.basics.variables;

public class Variables {
    public static void main(String[] args) {
    
        Math math = new Math();
        int sum = math.sum(1,2); 
        // math.sum(1, "2");  // ❌ compile error

        System.out.println("sum(1,2) = " + sum);  // sum(1,2) = 3
    }
}

class Math {
    public int sum(int n1, int n2) {
        return n1 + n2;
    }
}

// Output: Sum(1,2) = 3

Default values

 
/**
 * Class instance variables always have default value.
 * Local variable does not have a default value, they must initialized.
 * 
 * Local variables must be initialized before use.
 * Null is allowed anywhere.
 */
package com.minte9.basics.variables;

public class DefaultValues {
    public static void main(String[] args) {
        new Values().showValues();
    }
}

class MyObj {}

class Values {
    int a;  // 0
    float b;  // 0.0
    boolean c;  // false
    MyObj v;  // null

    public void showValues() {
        String local_variable = "a";  // no default value

        System.out.println("int a = " + a);
        System.out.println("float b = " + b);
        System.out.println("boolean c = " + c);
        System.out.println("object v = " + v);
        System.out.println("String local_var = " + local_variable);

        /**
            int a = 0
            float b = 0.0
            boolean c = false
            object v = null
            String local_var = a
         */
    }
}

Pass by value

 
/**
 * Variables in Java are passed by value (copy), not by reference
 * 
 * In this example, first variable x = 7 bits are copied (00000111).
 * Then this copy goes in z variable (z = x)
 * Then after variable z changes (z = 0), x is not changed.
 */

package com.minte9.basics.variables;

public class PassedByValue {
    public static void main(String[] args) {

        int x = 7; // 00000111
        int z = x; // x bits are copied in z

        System.out.println("First: x == z " + (x == z));

        z = 0;  // x is not changed
        
        System.out.println("Second: x != z " + (x != z));

        
    }
}

/**
    First: x == z true
    Second: x != z true
*/

Setter

 
/**
 * Setter and getter JavaBeans specifications:
 * 
 * The setter method for foo must be called setFoo()
 * The gettter method for xIndex must be called getxIndex()
 */

package com.minte9.basics.variables;

public class Setter {           
    public static void main(String[] args) {
        
        Dog dog = new Dog();  
        dog.setName("Rex");
        
        System.out.println(dog.getName()); // Rex
    }
}

class Dog {
    private String name;

    public void setName(String x) {
        name = x;
    }
    public String getName() {
        return name;
    }
}




References: