[Solved] What is a variable in Java and why should I use it? [closed]


There are two key elements you should know about:

  • Use a variable to store the object and
  • then pass it as a parameter to a method.

Part 1: a variable

After creating an object, you should store it in a variable. Otherwise it just exists in memory and will be garbage collected and thus be gone. Having a variable enables you to access it later and it will prevent it from being garbage collected as long as the variable exists (that’s something about scope, you might want to make yourself familiar with that as well).

Variables have a type (MyClass) and a name and you use the = to assign it.

Here’s the relevant part:

public static void main(String[] args) {
    MyClass object1 = new MyClass();       // <--- note the change
    myMethod();
}

You now have a variable named object1 and you can use it with that name.

Part 2: a parameter

Now that you have a variable, you can “give” it to the method. We also say “pass”. This is done in the parentheses like this:

public static void main(String[] args) {
    MyClass object1 = new MyClass();
    myMethod(object1);
}

At this time, your code will not run, because that method does not know anything about the parameter yet. Depending on the tool, you may see this immediately, e.g. by underlined text in Eclipse:

Eclipse error message]

To tell the method what it gets, you also define the type and a name there:

public static void myMethod(MyClass differentName) {
    // Here's where I want to use my object
}

Inside the method myMethod, note that the name of the variable can be different. This does not matter, the program just gives a different name to the exact same thing. My name is Alfred, but you can call me Al.

Inside myMethod you can use the variable under its new name only. Depending on what you want to do, you can access it by typing its name and a .. You can even pass it to other methods. Depending on the tool, you’ll get suggestions on what you can do with it:

Suggestions in Eclipse

4

solved What is a variable in Java and why should I use it? [closed]