This question already has answers here:
Difference between local variable initialize null and not initialize?
(6 answers)
Closed 7 years ago.
My code below is compile error.
The local available may not has been initialized
String str;
my_obj.setValue(str);
and fixed by this
String str = null;
my_obj.setValue(str);
So is null instance of anything? What is the difference between null and not initialized.
Why does it work for this way?
My Class
class MyClass {
String str;
}
I have initialized obj not obj.str. but no such a compile error that ways...
MyClass obj = new MyClass();
my_obj.setValue(str);
I already read what all of you recommend before I post this questions. Maybe it duplicated, but I didn't get any idea form those.
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.
Local variables must be initialized before they are accessed.
not initialized means, that you have not created object for that instance. Assigning a value will create a object to use it.
String str ;
Above code represents, that you have just declared it. But, can't use it until, it is assigned with some real value or null.
Reference to the question could be verified on this link
Related
This question already has answers here:
Why are local variables not initialized in Java?
(16 answers)
Closed 6 years ago.
instance and static variables will be initialized with a default values if we don't initialize with our own values but it doesn't happen with local variables.
Why they designed like so ?
The reason we have default values at all is that it's was decided it was too complicated to determine if a variable is initialised before it is used (unless it's final) This is because you could call methods in any order.
For local variable it can determine whether you have used a variable before you gave it a value, so this check prevents you using uninitialised values to avoid errors in your code.
If I declare a class attribute like this:
private static String month;
I don't know if later in the code is right to check like this:
if(month == null){
month = "January";
}
My main question is, is null a non-declared variable?
What is the best approach to this?
Thank you in advance.
null is a built-in special constant that represents an empty object reference, not a variable. When you declare a variable representing an object at the class or at the instance level, its initial value is set to null. When you declare a local variable, you must set its value explicitly - to null or to some object.
Yes it is ok since all instance references are initialized to null.
But be careful, it is only true for instance references. The local ones must ALWAYS be initialized manually.
Best approach is always initialize your variable because if you dont then java will set it to null. Null means not referencing to any object which implies either not initialized or deliberately set as null
a null variable is a reference which doesn't point to an instantiated object. SO you have a reference to a string which is yet to be pointed to a string.
Class member variables are initialised with nulls for object references. Inside a method they aren't, so you'll need to initialise it before you use it in order to make it compile in those situations.
For objects null is the default value. In this case, month is String type, and String is object in Java so the default value for month is null
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
If I instantiate an object and pass it to an function, in this function I assign this object to null.
It seems when return from the function, the object still there.
I just want to know when I assign null, what happens.
You can never assign to an object. All you ever have are primitives and references. A reference is either null or a pointer to an object of suitable class.
Java arguments are passed by value. Your called method got a copy of a reference. It made that reference null. The calling method has its own reference which was unaffected by any assignments to the passed copy. That reference still points to the object.
Arguments to methods in Java are 'pass-by-value', which means you are passing a copy of the object reference into the method. Assigning this reference a value of null will change its value within the method call, but does nothing to the reference outside the method, since its a copy. Illustrated with code:
void doSomething(final String input) {
input = null;
System.out.println("Input is: " + input); // prints null
return;
}
final String name = "Bob";
doSomething(name);
System.out.println("Name is: " + name); // prints 'Bob'
when you instantiate an object and pass it to a function, and inside the function you reassign that to null or whatever, at the calling side it is not reflected as arguments are pass by value (copy of reference in case of objects), at calling side it'll still point to the old object. If you want to restrict reassigning in a method, you can use final keyword in method parameter
When you pass the object reference to a function(Java always call it method),in the method scope,a new reference is created on stack memory,but they point to the same object in heap memory.So if you assign null to the new reference,Only this reference's link to that object is break,It does not affect the prevous one.
I need to use something similar to php's isset function. I know php and java are EXTREMELY different but php is my only basis of previous knowledge on something similar to programming. Is there some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...
if(box.isset()) {
box.removeFromCanvas();
}
So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
int: 0
char: \u0000 or 0
double: 0.0
boolean: false
reference: null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.
To what value is a variable of the String type automatically initialized?
null
Unless it's inside a method (local variable), in which case it's not declared to anything.
Here's a summary of the answers posted by Martin v. Löwis and silky.
We can say the following about the initialization of a String object:
If the String is a local variable, it will not be initialized.
If the String is a class variable, instance variable, or an array component, then it will be initialized to null.
The reasoning is as follows:
As a variable with the type of String is a reference type, according to The Java Language Specification, Third Edition, Section 4.12.5: Initial Values of Variables says the following:
Every variable in a program must have
a value before its value is used
It goes on to say the following about the initialization of reference types:
Each class variable, instance variable, or array component is
initialized with a default value when
it is created (§15.9, §15.10):
[removed information on irrelevant information]
For all reference types (§4.3), the default value is null.
And finally, the follow about local variables:
A local variable (§14.4, §14.14) must
be explicitly given a value before it
is used, by either initialization
(§14.4) or assignment (§15.26), in a
way that can be verified by the
compiler using the rules for definite
assignment (§16).
If the variable is a class variable, instance variable, or array component, it is initialized to null (since the default value for a reference type is null)
If the variable is a local variable, then it must be given a value explicitly (i.e. it has no default value in this case).
A variable of type String is a reference variable. As an instance variable, it gets initialized to null, see the specification for the discussion of other cases.
It's null unless it's local, in which case it is technically uninitialized, but in fact you can't use it, for that reason, so the language is still type-safe. You can't deref a garbage pointer.
null
String str=null means that the str is a object of String class which is not pointing to anything...but when we talk abt memory allocation,memory will be allocated to str as soon as it comes into existence....u can check the amount of memory by using the profiling option in netbeans..
the string value should be NULL in default , no need to initialize it.
string class objects are NULL by default only if they are defined as class level atttributes, otherwise string objects don't have any default value they need to be explicity initialized.
If the variable of type String is within a method, it would not automatically initialise. Otherwise it would be initialised with null as a value.
Any variable that is declared within a class is automatically initialized.
Any variable that is declared within a method must be initialized otherwise it will generate an error.
Strings are initialized to null,ints to 0 and so on..
Check this page for more information...