PROGRAMMING

  minte9
learningjourney




S R Q

Parameters

p76 The variables passed as method's parameters has to match the type.
 
/**
 * The variables passed as method's parameters ...
 * has to match the type
 */

package com.minte9.basics.variables;

public class Parameters {
    public static void main(String[] args) {
    
        Math math = new Math();

        int sum = math.sum(1,2);
        System.out.println(sum); // 3

        //int sum2 = math.sum(3, "1"); // compile error
    }
}

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

Default values

p85 Object instance variables always get a default value.
 
/**
 * Class instance variables always have default value
 * Local variables must be initialized before use
 */
package com.minte9.basics.variables;

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

        Values obj = new Values();  
        obj.showValues();
    }
}

class Values {
    
    int a; // default value 0
    float b;
    boolean c;
    Values v;

    public void showValues() {
        System.out.println(a); // 0
        System.out.println(b); // 0.0
        System.out.println(c); // false
        System.out.println(v); // null

        String a = "a"; // local variable, no default value
        System.out.println(a); // a
    }
}

Pass by Value

p77 Variables in Java are passed by value (a copy), not by reference.
 
/**
 * Variables in Java are passed by copy, 
 * not by reference
 * 
 * x bits are copied / this copy goes in z
 * z changes / x not changed
 */

package com.minte9.basics.variables;
public class PassedByValue {
    public static void main(String[] args) {
        new MyClass();
    }
}

class MyClass {
    int x;

    public MyClass() {
        x = 7; // 00000111
        go(x); // x bits are copied in z
    }

    public void go(int z) {
        System.out.println(x == z); // true

        z = 0; // x doesn't change
        System.out.println(x == z); // false
    }
}

Setter

p79 Setter and getter naming convention are an important Java standard.
 
/**
 * 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;
    }
}

Questions    
Last update: 61 days ago
Loops