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.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With