0
What is the default value(or garbage value) of String?
15 Respostas
+ 10
java and modern languages are dummies safe, you cannot have undefined behaviors.
The fact that the compiler complains is good! You know you made a mistake and also where you did it! Isn't that awesome?
+ 10
Right @Martin ! thanks for the good clarification!
+ 9
In java variables are objects, you cannot have garbage, they are always initialized (maybe to null).
You cannot have strange values, because the object style is a powerful protection against set, initialize and get operations.
2nd is always a good thing to make the compiler complain if something wrong.. this way you'll find bugs easily. For example.. what is the difference below ?
if ( a == 0 )
if ( 0 == a )
I hope I was more clear and I given something to you.
+ 8
@Napster what's not clear?
+ 4
@Napster
Here is an example I wrote up to explain what I meant. When it's coming from the class level, you get default values even if you don't initialize the variables after declaring them. If you do it on a local level, as per the example above that you said didn't work, then you'll get the error that you received about needing to initialize the variable. That's because local variables don't get default values.
https://code.sololearn.com/cqbhzTHmVQap/#java
class myClass {
// Class level member declared but not initalized. Defaults to null
String myStr;
}
public class Program
{
public static void main(String[] args) {
// TEST THE CLASS LEVEL VARIABLE BY CHECKING FOR NULL VALUE
myClass obj = new myClass();
if(obj.myStr == null) {
System.out.println("See? It's null, which is why this returned true.");
}
}
}
::::: OUTPUT :::::
See? It's null, which is why this returned true.
+ 2
default value of String is null
String s1;
System.out.println(s1);
// null
+ 2
@Napster
When you declare a variable on the local level, it isn't assigned a default value, so in the case of his example there isn't a default value; it is undefined.
However, when you're doing this from a class level, it IS assigned default values. In that case, the default value will be null.
Hope that helps.
+ 2
@Napster
Great! Glad to hear that it's making a bit more sense to you now. Happy to help.
+ 1
@ Jakob Marley...Thanks a lot.Finally I understood it. Ur explanation was very easy to understand.Hope u will continue to help the Sololearners.đđâșđ
+ 1
@Martin Taylor..It worked in my computer.Thank u!!!đđ
+ 1
@AZTECCO What r u trying to say?
+ 1
@AZTECCO I couldn't understand ur answer.It would be very nice of u to explain what u r trying to say
0
@Manorama I tried this in java.It didn't work.It says that s1 isn't initialized.But thanks anywayđđđ