Java string variable null

Should Java String method (local) variables be initialized to null or «»?

What is the best practice for initializing a String method (local) variable to avoid the «Variable might not have been initialized» error in Java? String s=null; or String s=»»; Does it make a difference? If so, which one is better and why? I’ve read conflicting answers on the web. Thanks!

Thanks for all your answers. Here’s more info. I designed a web service method that returns a String. Based on certain conditions, that String is assigned a value, but not always. Should I return null or «» when that happens?

6 Answers 6

Yes, it makes a difference. One is a reference to an empty string, one is a null reference. They’re not the same.

Which is better? It depends whether you want a null value or a reference to an empty string. they behave differently, so pick the one which behaves the way you want it to.

I rarely need to assign a «dummy» value to a variable though — usually just initializing the variable at the point of declaration with the real value I want is fine. If you can give us more context, we may be able to help you structure your code better so this isn’t a problem for you.

Would you be able to provide a situation where each of them would be advantageous? I gleaned from the other answers initializing with «» helps avoiding NPE, but also can result in uncaught bugs.

Читайте также:  Убрать ведущие нули python

Best practice is to make as many fields final as possible or use default values to avoid clients instantiating bad or incomplete objects. If it makes sense for the field to be an empty string by default (i.e. it will not risk logic errors) then by all means do it that way. Otherwise, at least null will throw an exception when a client invokes a method on an object that hasn’t been properly instantiated.

So in general, try to force client code to create complete objects during construction. If you don’t know what the string should be at construction time, then have them pass it in as a parameter. If the string is just used for internal logic, it may be better as a local variable or parameter — and in that case I generally prefer null to «» because == null is more explicit than isEmpty().

It all depends on what you want your program to do. Sometimes it can be useful to see whether a string has been set already or not at which null would be best. Other times you want to prevent NullPointers which makes «» better.

Источник

How do I set a String to null in java?

The code String name = null; is simply setting my variable name to the string «null» so I can’t figure out how to make my program wait for input. The compiler won’t allow me to declare the variable without initializing it.

You could set it as String name = «»; or move your string to the place you are getting the input. If you share your code here it will be easier to help.

The code String name = null; is simply setting my variable name to the string «null» it doesn’t. It sets it to null . Unless you mean it prints as the string «null», which is a different thing altogether.

@22niel you set the variable to null, then you print it and it prints null. What were you expecting instead?

2 Answers 2

String s = "Hello World!"; s = null; 

The String still exists in memory because this does not delete it. However the garbage collector will clear the object from memory as there is no variable referencing it.
For all practical purposes s = null; deletes the String.

Before posting here on basic Java Questions, study the Java Tutorials provided by Oracle free of cost.

See the tutorial page on string literals. To quote:

There’s also a special null literal that can be used as a value for any reference type. null may be assigned to any variable, except variables of primitive types. There’s little you can do with a null value beyond testing for its presence. Therefore, null is often used in programs as a marker to indicate that some object is unavailable.

👉 So null is not a piece of text with four characters. The keyword null means “no object at all”, no String , nothing at all, an empty reference.

To test if an object reference variable is null (contains no reference), you have a few choices:

  • Objects.isNull( myVar ) and Objects.nonNull( myVar )
  • null == myVar and null != myVar
  • myVar == null and myVar != null

I recommend you avoid the last. It is much too easy to make the mistake of using a single EQUALS SIGN. The code myVar = null executes, clearing any existing reference from that variable while also returning true . So the compiler will not catch your typo for you. In contrast, the compiler will catch the mistake of null = myVar because null cannot receive an assignment.

Источник

null = «» for a string

@Gabe, Sybase treats null and an empty string as null. IBM DB2/UDB treats them as distinct values. Not certain if MS SQL does. I personally know of no programming language outside of various SQL implementations that do treat them as the same.

Nathan: MS SQL (before v7) treats the empty string as a single space. I’m pretty sure that’s how Sybase works too.

8 Answers 8

The empty string and null are different. The empty string is a string with no characters, null is not having a string at all.

You can call methods on an empty string but if you try to call a method on null you will get an exception.

public static void main(String[] args)
0 Exception in thread "main" java.lang.NullPointerException at Program.main(Program.java:12)

No, an empty string is not null.

They are most definitely not the same. Your String variable acts as a reference to an object in memory, and if it’s set to null, it’s not pointing to anything. If it’s set to the empty-string value, it’s pointing to that.

In my own coding, I generally set a String to «» instead of to null unless I have a special need for null. There are some libraries like Apache Commons that include helper classes like StringUtils that will collapse a check for null, the empty string, and even just whitespace into one call: StringUtils.isBlank(), StringUtils.isNotBlank(), etc. Pretty handy. Or you can write your own helper methods to do similar pretty easily.

Good luck as you progress in Java!

That method has only been available since Java 6 and, unlike the StringUtils methods, is not null safe.

Источник

Should I set the initial java String values from null to «»?

This makes the initial values of field1 and field2 equal to null. Would it be better to have all my String class fields as follows?

Then, if I’m consistent with class definition I’d avoid a lot of null pointer problems. What are the problems with this approach?

An error can be found when an unexpected «» string is used just as usefully as a raised exception. With the advantage your web app does not crash and embarrass you.

11 Answers 11

That way lies madness (usually). If you’re running into a lot of null pointer problems, that’s because you’re trying to use them before actually populating them. Those null pointer problems are loud obnoxious warning sirens telling you where that use is, allowing you to then go in and fix the problem. If you just initially set them to empty, then you’ll be risking using them instead of what you were actually expecting there.

+1, but one caveat: if you’re populating your objects from a database, and that database happens to be Oracle, then an empty string is treated as null. However, explicitly initializing to «» isn’t going to help you in that case.

Absolutely not. An empty string and a null string are entirely different things and you should not confuse them.

  • «null» means «I haven’t initialized this variable, or it has no value»
  • «empty string» means «I know what the value is, it’s empty».

As Yuliy already mentioned, if you’re seeing a lot of null pointer exceptions, it’s because you are expecting things to have values when they don’t, or you’re being sloppy about initializing things before you use them. In either case, you should take the time to program properly — make sure things that should have values have those values, and make sure that if you’re accessing the values of things that might not have value, that you take that into account.

Источник

How to handle null string in java

I am .net programmer and completely new in java. I am facing problem in handling null string in java. I am assigning value from string array to string variable completeddate. I tried all this but that didn’t work.

String COMPLETEDATE; COMPLETEDATE = country[23]; if(country[23] == null && country[23].length() == 0) < // . >if (COMPLETEDATE.equals("null")) < // . >if(COMPLETEDATE== null) < // . >if(COMPLETEDATE == null || COMPLETEDATE.equals("null")) < // . >

country[23] == null && country[23].length() == 0 — that’s a sure-fire way to get a NullPointerException if I’ve ever seen one.

@JarrodRoberson: It doesn’t feel like this is a string comparison issue; this is an «object vs null» comparison issue.

In Java you are not allowed to call methods on a null object. So, if obj==null then obj.anyMethod() produces NPE .

From the looks of your last edit, you completely and drastically changed the scope of the question. If you have another question to ask, create a new question to avoid potentially invalidating existing answers.

4 Answers 4

For starters. the safest way to compare a String against a potentially null value is to put the guaranteed not-null String first, and call .equals on that:

if("constantString".equals(COMPLETEDDATE)) < // logic >

But in general, your approach isn’t correct.

The first one, as I commented, will always generate a NullPointerException is it’s evaluated past country[23] == null . If it’s null , it doesn’t have a .length property. You probably meant to call country[23] != null instead.

The second approach only compares it against the literal string «null» , which may or may not be true given the scope of your program. Also, if COMPLETEDDATE itself is null, it will fail — in that case, you would rectify it as I described above.

Your third approach is correct in the sense that it’s the only thing checking against null . Typically though, you would want to do some logic if the object you wanted wasn’t null .

Your fourth approach is correct by accident; if COMPLETEDDATE is actually null , the OR will short-circuit. It could also be true if COMPLETEDDATE was equal to the literal «null» .

Источник

Оцените статью