3

I want to know what it's the correct way to do that things in Java. My test code:

public class InitializeTest {
    int i;
    int b;
    int x;
    String frase;

    public static void main (String args[]) {
        InitializeTest IT = new InitializeTest();
        System.out.println(IT.i=IT.getI());
        System.out.println(IT.b=IT.getB());
        System.out.println(IT.x=IT.getX());         
            }

    public int getI(){
        return 3;}
    public int getB(){
        return 5;}
    public int getX(){
        return 8;}
}

Should i initialize the variables i, b and x or not? What changes if not? I read about this but it's not clear for me, can anyone give me a clear answer?

I read about that here Do I really have to give an initial value to all my variables? , but don't know if is the same for Java.

Community
  • 1
  • 1
DavidM
  • 570
  • 4
  • 21
  • Why do you have getters returning hard-coded numbers? Also System.out.println(IT.i=IT.getI()); <-- this is confusing and not good practice. This code appears to be flawed from the ground up I'm afraid. – Jeff Watkins May 15 '13 at 15:06
  • int variables are by default initialized with 0. see this link http://stackoverflow.com/questions/2437603/why-does-using-a-default-valued-java-integer-result-in-a-nullpointerexception – M Sach May 15 '13 at 15:11

2 Answers2

7

Java class field primitives are initialized to default values and objects to null. So numeric types are initialized to 0.

Accessing an uninitialized local variable will give you a compiler error.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html See the section "Default Values"

Simon
  • 6,293
  • 2
  • 28
  • 34
  • Thanks, that's one of the things I wanted to know! – DavidM May 15 '13 at 15:07
  • 5
    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. So this answer is NOT always true. – hamid May 15 '13 at 15:10
4

int variables are by default initialized with 0. see this link Why does using a default-valued Java Integer result in a NullPointerException?

Should i initialize the variables i, b and x or not? What changes if not?

so answer is no. Not required

But if yes if you want that your primitive variable by default should return the value other default provided by JVM, then you should go ahead

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314