Is null a non-declared variable? - java

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

Related

How to reference an empty variable of any type in java

Let's suppose that we have these variables:
Integer nbr;
String str;
ApiClass someInstance;
Date date;
I want to state that nbr is empty, str is empty, someInstance is empty, date is empty(not assigned to any value), without using myVar = null; because oviously this is a bad habit.
is there any way to test if a java variable is not assigned to anything without assigning to each one nullvalue.
Have a look at Optional:
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
EDIT: Please consider reading the references in the comments. You should not just replace all the null-checks with "isPresent"-checks!
Especially Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! (thanks, #ModusTollens)
Another way around null-Checks is the Null-Object-Pattern. But I feel Optional better suits your requirement.
To make sure all fields have been set before the object is "allowed to be used", you could also go with the builder pattern or a little simpler with an immutable object.
Note: I am deliberately not going into if using nulls is an anti-pattern or not. I am just answering the question.
If you are talking about local variables, this is not possible and a compile error. You cannot access a local variable before it has been assigned a value.
For static or instance fields of a reference type there is no difference between not initializing them and initializing them with null. The initial value is always null, not some distinct "not set" value. Similar for primitive fields, they will be initialized to 0 resp. false, if you don't do it yourself.

Is null an instance of anything? [duplicate]

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

Java check to see if a variable has been initialized

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.

JAVA class null value

I would like to ask if there is anyways in java to ensure that a class can never be instantiated as null. But i want to do this inside the class. For example
class A
{
I can never be null
}
class B
{
A a = null ; << No you cant. Does not compute :P
}
Thanks in advance.
This is not, generally speaking, possible. When you declare:
A a = null;
A a2 = new A();
Both a and a2 are references, not actual objects. Think of a reference as a pointer, but one that does not support C-style pointer arithmetic.
A a = null;
sets up a reference (a pointer) that can point to an object of type A, but is currently initialized to null. It's not possible to have class A ensure that there are never any null references to things of type A.
No.
No. You cannot do that. What is your use case, maybe we can suggest an alternative.
We often talk about a null object but that is totally misleading. An object is an object and only a variable can hold the value null (instead of a reference to an object).
Something like a null object simply doesn't exist in Java.
If we do a
A a = new A();
we create a new instance of A and store a reference (a pointer) to this instance at the variable. The variables value is now some sort of address of the location of this new object. If the instantiation fails (an exception is thrown) then no assignement will be made and the variable keeps its old value. Which may be null - but again, this just tells us that the variable doesn't hold a reference to any object.

java basics about String

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...

Categories

Resources