Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Variable setting

Tags:

java

Is there any difference among case1, case2 and case3 ? Is there any advantage or disadvantage related to performance?

public class Test {

private String name;

    public void action (){

        name = doSome(); // case 1
        setName(doSome()); // case2
        this.name =doSome(); // case3

    }


    public String doSome(){
            return "Hello";
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }


    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}
like image 707
Manmohan Avatar asked Apr 08 '13 06:04

Manmohan


People also ask

Why do we set JAVA_HOME variable?

JAVA_HOME is an operating system (OS) environment variable which can optionally be set after either the Java Development Kit (JDK) or the Java Runtime Environment (JRE) is installed. The JAVA_HOME environment variable points to the file system location where the JDK or JRE was installed.

What are the 3 types of variables in Java?

There are three types of variables in Java: Local, Instance, and Static.


2 Answers

I guess, in case 2, we are putting one extra method on the stack i.e setName.But from performance point of view, the gain is almost negligible.So According to me, in this example, we should think from code maintaince and readablity point of view than performance.

like image 186
Jaydeep Rajput Avatar answered Oct 15 '22 03:10

Jaydeep Rajput


Use the debug and breakpoints on Eclipse to see how many steps each case takes. The less the better.

Case 1 took 1 step

Case 2 took 2 steps

Case 3 = same as Case 1

Case 1 is the same as Case 3 the this keyword just refers to the current class.

like image 26
Joban Dhillon Avatar answered Oct 15 '22 01:10

Joban Dhillon