Preferable way to initialize object [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Should I initialize variable within constructor or outside constructor
For example I have a field int x.
Does Java prefer the field to be initialized when it's declared
int x = 0;
or rather in the constructor?
public foo() {
x = 0;
}
Which is more preferred from a designing perspective?

Both are good, as long as you know what will happen.
The order in which they will be initialized is this:
Class members (like: public int x = 0;)
Constructors (like: this.x = 0;)
However, initializing integers to zero is a no-op. Java does this automatically.
A little demo to demonstrate an error of ignoring the order of initialization:
class Foo
{
public String str;
public String strTwo = "Here is str: " + str;
public Foo()
{
str = "Java";
System.out.println(strTwo);
}
}
This will print Here is str: null.

Instance variables of primitive types are initialized implicitly whereas reference variable are assigned with null values.
So if you want to assign like ::
int x=0;
it will be x=0 for all objects.
But in case of constructors you can initialize them with different value in different constructor, though its not a good practice to initialize with different values in different constructor.

Does Java prefer the field to be initialized when it's declared or rather in the constructor?
If you are initializing with default value, it'll be redundant to initialize either in constructor or at declaration time.
However, if you want to initialize with a value different from default value, constructor should be used over delaration.
Which is more preferred from a designing perspective?
From design point of view, No difference at all. It is implementaiton detail.

My preference is to initialize default values outside constructor like
int x=0;
So that if you have multiple constructors and lot of instance variables, you won't forgot to initialize. In-case if I require specific value to variable, then I will re-initialize in constructor.

From what I recall, the bytecode produced by the compiler in both instances is pretty much identical, and it is really just a matter of preference and coding style. Personally, I tend to prefer to initialize variables in the constructor - In some cases you will have to initialize variables in a constructor anyway (Such as when passing in arguments to a constructor), and it means you need only look in one place to understand what is going on, rather than 2.
(On a side note - in your example there is no need to do "int x = 0" since defining "int x;" will automatically have it set to 0.)

public foo() {
x = 0;
}
this will be good. if u use this int x =0 it will be for all objects. but the constructor notation is for objects which are created by that particular constructors.

Related

Making a new Object in java [duplicate]

This question already has answers here:
Should I instantiate instance variables on declaration or in the constructor?
(15 answers)
Closed 9 years ago.
When I use Java based on my C++ knowledge, I love to initialize variable using the following way.
public class ME {
private int i;
public ME() {
this.i = 100;
}
}
After some time, I change the habit to
public class ME {
private int i = 100;
public ME() {
}
}
I came across others source code, some are using 1st convention, others are using 2nd convention.
May I know which convention do you all recommend, and why?
I find the second style (declaration + initialization in one go) superior. Reasons:
It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).
Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.
I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.
As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.
class String
{
char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
String()
{
this.arr=new char[0];
}
String(char[] arr)
{
this.arr=arr;
}
}
So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.
FYI other option's for initialization without using a constructor :
class Foo
{
int i;
static int k;
//instance initializer block
{
//run's every time a new object is created
i=20;
}
//static initializer block
static{
//run's only one time when the class is loaded
k=18;
}
}
The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.
Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
Both the options can be correct depending on your situation.
A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.
It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
One thing, regardless of how you initialize the field, use of the final qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
Wikipedia
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
I would say, it depends on the default. For example
public Bar
{
ArrayList<Foo> foos;
}
I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.
You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

Why can't we initialize local variable before declaring it unlike static variable?

Why can't i be initialized before declaring it in code 1 but it can be in code 2 :
class Code1 {
void methodOfCode1() {
// System.out.println(i); can't use a local field before it is defined
// i = 10; can't initialize a local field before it is defined
int i;
}
}
class Code2{
static
{
i = 10; //A field can be initialized before it is defined.
}
static int i;
}
The answer is order of execution.
Code executes sequentially, you must define what something is before you use it. Therefore in a method you must declare a variable before you use it.
In Java the compiler initializes your class in multiple passes. It first runs through and declares all of the static members, then it sets the default values for all static members. This all happens before any methods (static or not) are executed.
It's the scope of the variable & the lack of type prior to its use: you have yet to define i. You must define a variable before it can be used:
int i = 0;
System.out.println(i); // works
System.out.println(j); // will not work
byte j;
Here's the Java Language Specification giving you the detail.
During initialise a variable, some amount of memory is allocated based on datatype.
Unless you allocate memory, you can't initialize value.
Because compiler must know where this variable is stored and how many bytes it have to use. If I tell computer var=97 before initializing, it cannot know where this "var" variable is stored. Also if "var" is char , computer needs one byte to store in RAM. However it also can be an integer which is 4 bytes(depends on different systems). Therefore, there would be an ambiguous situation for the system.Compiler does not allow that , reasonably.
Java is strongly-typed, you can't use something that you don't know what it is. For instance, a method is different if it receives a String or if it receives an int, so the compiler must be able to know which is the proper method to be invoked
For instance, this is valid:
public void dealWithIt(int val){
val++
System.out.println(val);
}
public void dealWithIt(String val){
System.out.println(val);
}
The compiler can't assign a value to a variable before know what type of variable it is.
In Java, a variable's type must be declared before it can be used.
For example:
System.out.println(i); // for this statement i is unknown/undefined...
i = 10; // same for above...
EDITED :
First inside class Code1,
you haven't declare variable before use it, which is against of Java Standard API so obviously compiler will complain.
while into class Code2 case,
you have declare 'static' both instance as well as block.
so it does not required any instance to load it.
(review static concept in depth will let you to the correct direction)

Not understanding how my variables are initialized

so I think I'm missing something. I am aware that
If no constructor is supplied java makes one for you.
If there's a constructor defined, default constructor by java is not used.
Constructor is used to initialize variables
Here's some simple code:
class a {
int f; // a variable with no value
int c; // a variable later initialized by the constructor
int b = 5; // this will be second question, a less important one
a(){
c = 1; // Constructor initiatives C, but not F
}
public static void main(String[] args){
a var = new a();
System.out.print(var.f); // Please see my comment below
}
}
Here's what I do not understand. Why is var.f printed? I did not initialize f in the constructor, however, there's no compile error and 0 value is initialed. I don't understand how '0' is initialized to 'f' despite me not having used it in constructor
Regarding b = 5, I understand what this code leads to, however, I do not think I understand what/who does the initialization here, is it new operator or something else? Thanks.
Edit: since the answers so far are not addressing my question
I am aware of the default values. I thought it was the default constructor that assigned them, is it not? If not, what assigns default values?
Java like most of programming languages has default values for uninitialized variables. Every numeric type of variable is initialized to 0-related value.
Boolean is false as default.
Strings and all of the objects have null as their default value.
Check docs for more info: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
int is a primitive data type. By definition, primitives cannot be null as they are not objects and will have a default value if not initialized. See here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If you want to be able to have a variable that is not initialized, you can use the object equivalent of an int java.lang.Integer
Instance variables that are declared but not initialised are given a default value.
References take a default value of null.
Primitives take a default value of zero
In regards to your query on your primitive int variable b, the new operator is not required, the new operator is used when instantiating a reference. When an instantiating a reference an object is created and memory is allocated on the JVM for that object.
Strings are a reference variable, but may be instantiated using the new keyword for example:
String example = new String("abc");
System.out.println(example); // prints abc.
Usually you would just write:
String example = "abc";
In the latter the literal is placed in to the 'string pool'...
You can read more about the string pool here: http://examples.javacodegeeks.com/core-java/lang/string/java-string-pool-example/
If no constructor is supplied java makes one for you.
Correct.
If there's a constructor defined, default constructor by java is not used.
It is not generated.
Constructor is used to initialize variables
Correct.
c = 1; // Constructor initiatives C, but not F
Untrue. Your code initializes c. The generated constructor initializes both.
I did not initialize f in the constructor
No, but Java did.
Java generates the following code for a constructor:
A super call.
Default initialization code for all variables declared without initializers. The default values are false, zero, or null as appropriate to the type.
Calls to all anonymous initializer blocks. (2) and (3) happen in textual order and can therefore be interleaved with each other.
Regarding b = 5, I understand what this code leads to, however, I do not think I understand what/who does the initialization here, is it new operator or something else?
See above.
I am aware of the default values. I thought it was the default constructor that assigned them, is it not?
No.
If not, what assigns default values?
The constructor. Any constructor.

Initialization of class variables in constructor in java

we know that...
Instance Variable are initialized in default constructor. For eg.
public class H{
int x;
public static void main(String... args){
System.out.print(new H().x);
}
}
The O/P of above code is 0 because there is a default constructor which is called , and that constructor initialized the x to 0.
Now, my question is, if we run the below code, i.e.
public class H{
int x;
public H(){}
public static void main(String... args){
System.out.print(new H().x);
}
}
The actual O/P is 0 in this case also, but I think there should be compiler error that x is not initialized, because we have override the default constructor and didn't initialize x.I think I have made my question clear..
In Java, instance members are defaulted to the all-bits-off version of their value automatically (ints are 0, object references are null, floats are 0.0, booleans are false, and so on). It's not something the default constructor does, it's done before the constructor runs.
The order is:
Default the instance members to their all-bits-off value. (The optimizer can skip this if it sees #2 below or possibly if it can prove to itself that nothing uses the member prior to an initialization per #3 below.)
Apply any inline initialization of them. For instance:
int a = 42;
Apply instance initialization blocks in source code order.
Call the appropriate constructor.
So for example:
class Example {
int a = 42;
// Instance initializer block:
{
this.a = 67;
}
Example() {
System.out.println(this.a);
}
}
new Example() outputs 67.
Obviously, initializing in both places like that would be poor practice, this is just for illustration.
Non-final fields are initialized by default in java. Only variables inside methods and final fields are not initialized by default.
If you had declared x to be final, then you would be correct. You would have a compile error in the code.
All instance level variables are initialized to their default values irrespective of whether the constructor has been overloaded ( or explicit no-argument constructor has been added). The constructor merely changes the default value(s).
Instance variables have default values associated with them
From The Java™ Tutorials:
Default values
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.
Java is quite neat to programmers (unlike others, C for instance), this means that it initializes fields automatically. An exception is final fields and fields inside a methods (where the compiler will then produce an error).
Hope it helped.

Should I initialize variable within constructor or outside constructor [duplicate]

This question already has answers here:
Should I instantiate instance variables on declaration or in the constructor?
(15 answers)
Closed 9 years ago.
When I use Java based on my C++ knowledge, I love to initialize variable using the following way.
public class ME {
private int i;
public ME() {
this.i = 100;
}
}
After some time, I change the habit to
public class ME {
private int i = 100;
public ME() {
}
}
I came across others source code, some are using 1st convention, others are using 2nd convention.
May I know which convention do you all recommend, and why?
I find the second style (declaration + initialization in one go) superior. Reasons:
It makes it clear at a glance how the variable is initialized. Typically, when reading a program and coming across a variable, you'll first go to its declaration (often automatic in IDEs). With style 2, you see the default value right away. With style 1, you need to look at the constructor as well.
If you have more than one constructor, you don't have to repeat the initializations (and you cannot forget them).
Of course, if the initialization value is different in different constructors (or even calculated in the constructor), you must do it in the constructor.
I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.
As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.
I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.
For example in your second snippet, you can remove the constructor and have a clearer code.
If you initialize in the top or in constructor it doesn't make much difference .But in some case initializing in constructor makes sense.
class String
{
char[] arr/*=char [20]*/; //Here initializing char[] over here will not make sense.
String()
{
this.arr=new char[0];
}
String(char[] arr)
{
this.arr=arr;
}
}
So depending on the situation sometime you will have to initialize in the top and sometimes in a constructor.
FYI other option's for initialization without using a constructor :
class Foo
{
int i;
static int k;
//instance initializer block
{
//run's every time a new object is created
i=20;
}
//static initializer block
static{
//run's only one time when the class is loaded
k=18;
}
}
The only problem I see with the first method is if you are planning to add more constructors. Then you will be repeating code and maintainability would suffer.
I recommend initializing variables in constructors. That's why they exist: to ensure your objects are constructed (initialized) properly.
Either way will work, and it's a matter of style, but I prefer constructors for member initialization.
Both the options can be correct depending on your situation.
A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.
It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.
One thing, regardless of how you initialize the field, use of the final qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
Wikipedia
It can depend on what your are initialising, for example you cannot just use field initialisation if a checked exception is involved. For example, the following:
public class Foo {
FileInputStream fis = new FileInputStream("/tmp"); // throws FileNotFoundException
}
Will cause a compile-time error unless you also include a constructor declaring that checked exception, or extend a superclass which does, e.g.:
public Foo() throws FileNotFoundException {}
I would say, it depends on the default. For example
public Bar
{
ArrayList<Foo> foos;
}
I would make a new ArrayList outside of the constructor, if I always assume foos can not be null. If Bar is a valid object, not caring if foos is null or not, I would put it in the constructor.
You might disagree and say that it's the constructors job to put the object in a valid state. However, if clearly all the constructors should do exactly the same thing(initialize foos), why duplicate that code?

Categories