String is not null, but it behaves as if it were

Hi, i’m trying to read a ASCII object (.obj) file and i’m having troubles.
In the file, there are some empty lines with only \r\n (CRLF) line breaks, for example, line 1 and 3 (the 1st line is 0).
When I do things with the line (is a String), the line seems to be empty so, it has to be null (or “”), but is not null.
Here is how to replicate

`void setup() {
size(200, 200);
String[] file = loadStrings(“sample.obj”); // Line 1 contains \r\n (CRLF)

if (file[1] == “\r\n”) { println(“Contains CRLF”); } // Or, not?

printArray(file[1].toCharArray()); // If I print the string as array, it seems like there is not any element, so it has to be null, right?

if (file[1] == null) { println(“Its sure that is null”); } // Well, no

if (file[1] == file[3]) { println(“1 & 3 are equal”); } // Even this is false

// What the hell is this?
}`

The code dose’t print anything, even the printArray().

Here is my .obj file: https://drive.google.com/file/d/1Fu2xcDPLcdZIXM8VFoEiR3Bx-5cZTlTA/view?usp=sharing

Any one can help me?

1 Like

first line would be file[0]

1 Like

You are right, but the first line is not empty, is the line 1 and 3, that are empty
The problem is only by the empty lines so i’m using line 1 (second line).

The Processing statement loadStrings will load an ASCII file into a String array. Some of the array elements maybe empty Strings "" but none of the array elements will be null

So (file[1] == null) will never be true.

Strings are objects so this statement asks if they are the same object and clearly they aren’t because each element in the array is a different object. To compare the characters in these objects use
if (file[1].equals(file[3])) { println(“1 & 3 are equal”); }
or
if (file[1].equalsIgnoreCase(file[3])) { println(“1 & 3 are equal”); }

2 Likes

Thanks for your answer, but (file[1] == "") is false too

You can’t use == with String (as quark mentioned).

Instead use: if ( file[1].equals("") )

3 Likes

Ok, so much thanks for your help, excuse me, I’m still a beginner

In order to avoid a potential null value, it’s much safer to test "" (or any String literal) against a variable when using equals(): :nerd_face:
if ( "".equals(variable) ) {}

Or better yet, use method isEmpty(): :bulb:
if ( variable.isEmpty() ) {}

Or alternatively, method isBlank() can some times be better than vanilla isEmpty():
if ( variable.isBlank() ) {}

Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#isBlank()

3 Likes

I’ll take that into account, thanks :grin: