Java check to see if a variable has been initialized - java

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.

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.

Default Primitive Values in Java - Memory Allocation?

I have scoured the Internet and have not found satisfying answers to my question. In a localized instance, if I have the code:
public static void main (String args[])
{
int x;
System.out.println(x);
}
...it will not compile, because the Java compiler will warn me that x should be initialized. I understand that.
My question is, will Java actually set aside 4 bytes of memory for the integer x? And if so, does it wipe out that block of memory? Does it define it as NULL (I don't think so because NULL and an int are incompatible types)? Or does the memory address of int x still retain the value last stored in memory, or does x just simply have "no value?"
I know that the above works in C, and that in C, it would just print out whatever is in that memory block. I want to know how Java handles this.
===EDIT===
Okay, okay. For some reason, my basic knowledge of programming had entirely exited my mind, as when a program does not compile, the question of memory allocation is irrelevant, as pointed out by both of the members who posted the answers. (Cue facepalm)
So what if I had the code:
public static void main (String args[])
{
int x;
}
How is the integer x resolved in memory then?
It's not a warning; it's a compiler error. That code won't compile, so no bytecode is generated. The question of whether memory is set aside is irrelevant, because there is no program to run.
However, if the x variable is not local, then Java will assign a default value of 0.
Section 4.12.5 of the JLS states:
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (§4.3), the default value is null.
Each method parameter (§8.4.1) is initialized to the corresponding argument value provided by the invoker of the method (§15.12).
Each constructor parameter (§8.8.1) is initialized to the corresponding argument value provided by a class instance creation expression (§15.9) or explicit constructor invocation (§8.8.7).
An exception parameter (§14.20) is initialized to the thrown object representing the exception (§11.3, §14.18).
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 using the rules for definite assignment (§16 (Definite Assignment)).
Given that your questions are:
[W]ill Java actually set aside 4 bytes of memory for the integer x?
And if so, does it wipe out that block of memory?
The answer you seek is in JLS 4.12.3.8:
A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment (§16 (Definite Assignment)) prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or for statement is complete.
So the answers are:
Maybe. The value will be stored somewhere.
Yes. No uninitialized values are allowed by the JLS.
Nothing happens to the local variable until it is assigned. It is impossible to use the value until it has been assigned, however, so you can never use an uninitialized value. At the point of initialization, some sort of storage location must be used (obviously). However, nothing about the JLS requires the JVM to allocate memory.
Whether memory is allocated would be determined at runtime based on the execution context, whether the value needed to be pushed onto a stack frame to make a method call, whether an unused CPU register was available, etc. A naive JVM implementation might just always allocate memory, but that would be slow, and as such I would expect most real-world JVMs to try something more optimized.

Using objects/variables initialized inside a loop?

I declare my objects outside of an if statement, but initialize them inside of it. Later I try and use them but it won't allow it because they haven't been initialized. The if statements are structured so that they all will execute before the objects are used, and hence the objects will be initialized guaranteed, but java doesn't allow that. Any way around this?
If you know that all paths will ultimately initialize them, but the compiler doesn't, you can initialize them to null or 0 or false (as ajb helpfully reminds) -- or some other special initial value you define -- when declaring them. They then have a concrete initial value.
If the variable is still null (or whatever it's initial value was) by the time you use it (evidenced perhaps by an NPE in the case of an object) then you know something went wrong; you can also self-document your assumptions with asserts later.
You should post your code so we can give you better advice; the compiler is relatively smart about path analysis, although it can't, of course, handle cases that rely on external input or assumed preconditions and invariants. Still, it's always possible that you've overlooked something (perhaps an exception or unexpected condition leads to a path where the value is uninitialized - which is fine, you just have to make sure it's initialized).
The only way an object's initialization is guaranteed after a conditional expression is if there exists a branch that is always executed, such as an else statement, or default in switch statements.
To decompose that, take this example code:
String word;
String name = "Peter";
if("Peter".equals(name)) {
word = "The Bird";
}
System.out.println(word);
This will fail since the compiler identifies a branch in which word is not initialized.
If you add an else clause, then the compiler will believe that word is initialized.
String word;
String name = "Peter";
if("Peter".equals(name)) {
word = "The Bird";
} else {
word = "Nope";
}
System.out.println(word);
Java requires that a variable be initialized along all possible paths to the point of use before its value can be referenced. Eg, if you have
int x;
if (a == b) {
x = 5;
}
if (c == d) {
x = 6;
}
int y = x;
In the above case the compiler cannot know that either the first or second if statement will be true, and so it's not certain that x gets assigned a value along all paths leading to the assignment to y. So the compiler will disallow this (and, if the compiler didn't reject this, the "verifier" inside the JVM would).
The solution is to assign a value to the variable (maybe zero or -1 in this case, null for an object reference) so that it's known to have a value along all paths.
But note that you probably should not just assign a dummy value to every variable you declare, since very often the compiler message that no value is assigned can indicate a real live code bug where you've accidentally omitted assigning a value to the variable along some path.
initialize them to null
Object myAwesomesauceVariableOfAwesome = null;
if(myUnbelievablyWildBoolean){
myAwesomesauceVariableOfAwesome = getAwesomesauce();
}
doSomethingCompletelyMindBlowingWithAwesomesauce(myAwesomesauceVariableOfAwesome);

Handling uninitialized Strings in Java

Here's part of a small program I'm doing as a homework assignment:
public Exam maxGrade() {
Node p = firstNode;
int max = 0;
String name;
while (p!=null) {
if (p.info.getGrade()>max) {
max = p.info.getGrade();
name = p.info.getName();
}
p = p.next;
}
if (name==null)
return null;
else
return searchByName(name);
}
So when I go ahead and compile, the compiler outputs this message:
Student.java:127: error: variable name might not have been initialized
if (name==null)
The problem is easily solved by substituting the fourth line with:
String name = null;
Now, I can see some logic in this. But I'd really like to grasp the workings behind the problem.
I mean, it seems reasonable that the compiler checks whether a variable is initialized if it sees you're doing something with it in your code, but I don't think I'm doing anything that NEEDS the variable to be initialized.
According to sources like this when I simply declare my String (or any other Object) variable "name", it already points to null. Then why is it considered an anomaly to simply check if that value is null? Will the compiler consider an error anything that I do to my uninitialized variable other than assignments?
Fields of object type are initialized to null by default. Array members are also initialized to null by default.
Local variables are not - they must be initialized explicitly.
This is a good thing. Uninitialized variables are frequently an indication of error.
From "Initial Values of Variables" in chapter 4 of the Java Language Specification:
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 using the rules for definite assignment (§16).
The compiler requires that you initialize the Object to be null if you're making any assumption as to its value. This is simply a (very useful) precaution.
Addendum:The compiler cant check the semantics of your program. Even if you know that a variable is initilized before its first usage the compiler cant.
consider the following function:
public boolean mod2(int i){
if(i % 2 == 0){
return true;
}
if(i % 2 != 0){
return false;
}
}
We all know that this method would always return true or false. The compiler instead cant ensure that there will always be a return value because he has to know that there will only those two results. So the compiler will report an error about a missing return statement.

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