1

Which one of these cases is the proper way of using variables with methods?

The first case:

private static String var1;
public static void main(String[] args) {
    var1 = "Hello";
    method1();
}

private static void method1(){
    System.out.println(var1);
}

However, in this case I quote from Oracle: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

If I understood this properly, it is a bad programming practice to make operations with non initialized variables. Does this include assigning a non default value? Are they saying that String test="abcd" is better thanString test; test = "abcd" ?

The second case:

public static void main(String[] args) {
    String var1 = "Hello";
    method1(var1);
}

private static void method1(String chain){
    System.out.println(chain);
}

Which of these 2 cases would use more hardware?

Janis Baiza
  • 951
  • 6
  • 15
Alpha2k
  • 2,212
  • 7
  • 38
  • 65
  • 1
    "Are they saying that `String test="abcd"` is better than `String test; test = "abcd"`?" - Yes, that's *exactly* what they're saying. – JonK Apr 27 '15 at 07:48
  • 2
    The quote you have given and your main question is not seems related – Baby Apr 27 '15 at 07:50
  • 1
    Actually, @JonK, that's not what they are saying. At least not in this particular quote. What they are saying is that it's bad practice to do something like (a field) `int i;` and then in the code do `i++` and rely on the fact that `i` is 0. It would be better to declare `i` as `int i=0` or to put a value in it. This is unconnected to the question whether an initializer is better than a separate declaration and assignment statement. – RealSkeptic Apr 27 '15 at 07:50
  • possible duplicate of [Declaring variables inside or outside of a loop](http://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop) – azurefrog Apr 27 '15 at 07:52
  • Your question isn't about loops per se, but the general principle of declaring variables with as small a scope as possible still holds. – azurefrog Apr 27 '15 at 07:52
  • It's odd given that the method is in the same class as `main` but the ultimate solution doesn't involve `System.out.println(...)` in a method. – ChiefTwoPencils Apr 27 '15 at 07:55
  • @ChiefTwoPencils its just an example, it could be extended to more classes outside of main class. – Alpha2k Apr 27 '15 at 07:56

2 Answers2

3

First, to expand on my comment: the quotation you brought warns you against relying on the default values of fields.

When you define a field, for example:

private int diff;

It will have the value zero. You could write code in one of your methods that does something like:

result = 5 + diff;

And since diff is zero, this will work. But it's bad practice. If you want to rely on the fact that diff is zero, you should declare it as

private int diff = 0;

Or otherwise initialize it before starting to use it.


This is unrelated to your actual two question. So, which of those two cases would use more hardware?

private static String var1;

This allocates enough bytes in heap memory for a String reference when the class is loaded. This is part of the heap dedicated to class variables (since the variable is static).

var1 = "Hello";

This allocates memory to the "Hello" (this allocation is done early because this is a literal, but it's nevertheless allocated), and assigns (copies) the reference to the variable var1.

So:

  • 1 reference location in memory allocated.
  • 1 string object allocated. ("Hello")
  • 1 assignment of that string.
  • 1 copy of that reference to the stack for the println method.

In the second method, you are using local variables and method parameters. Local variables and parameters are allocated during the execution of the code, on the stack. When a method is called, enough space is allocated for all the parameters and local variables it will use.

  • 1 stack location for reference allocated in main to var1
  • 1 string object allocated to "Hello"
  • 1 assignment of that string to var1
  • 1 stack location for reference allocated in method1 for chain.
  • 1 assignment to a reference - passing the value of var1 to chain in the method call.
  • 1 copy of that reference to the stack for the println method.

So, without going into how many bytes and how many CPU cycles are spent exactly in these operations, it is clear that the second method takes a bit more hardware than the first.

Does that matter? No, not really. Optimization (saving up resources) should be done only when you actually experience slowness or memory bloat in your application. It is much more important to design the class properly. And to that end, I believe the consensus would be that the second case, with the local variables and parameter passing, is superior to the first case, with its static variable.

Why? It's a long and opinion-prone discussion, but, for example, using class and even instance variable is much like using global variables. You can change them outside of the method that uses them, which means if you change the implementation you might change values your methods are relying on. It's likely to be harder to read and understand, and harder to debug. It's best to keep instance variables to represent true "state" of an object, and class variables (static) should be used as little as possible.

Clean design generally trumps hardware considerations.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
2

If you are asking why

String  var1 = "Hello" 

is better than

String var1;
var1 = "hello"

Then it is because.

  1. It is better to initialize a variable as it can prevent possible NullPointerExceptions and bugs down the code. If you do not initialize a variable most languages assign a default value. (Always better to deal with a known devil than an unknown).

  2. In some cases it helps the compiler to precompile the code.

From a purist point of view String var = null; should be considered better than String var; as it increases readability of the code. Also better to write one line of code instead of two for same functionality.

Regarding your query about performance, the difference should be very negligible.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Raj
  • 1,945
  • 20
  • 40