We help IT Professionals succeed at work.

adding a null terminator to a java string

dpalyca755
dpalyca755 asked
on
I am using a java program to send an xml string to socket being processed by a C program.
When reading the string it is looking for a \n to know the string is complete.
Is the simplest way to do this to add the \n to my java string?
String A = "<test>hello</test>";
String B = (StringA + "\n");
Comment
Watch Question

Awarded 2011
Awarded 2011
Commented:
If it is looking for "\n" then this is indeed the best way to add it
String B = StringA + "\n";
Awarded 2011
Awarded 2011

Commented:
End of line can be different on different systems
you can add end of line specific to the system on which you are writing the string in this way:
String B = StringA + System.getProperty("line.separator");

However what it is that your server part is waiting for is another question
CPColinSenior Java Architect

Commented:
If you add "\n" you'll be adding a newline character, not a null character. A null character would be something like '\0'
Awarded 2011
Awarded 2011

Commented:
But probably your server will rather be looking for end of line then for null termination
CERTIFIED EXPERT
Top Expert 2016

Commented:
You'll find that the System line separator almost certainly does end with \n anyway, in which case you can save yourself and the system the bother of appending \n by using a PrintWriter. Just as a precaution, you can place the following at the head of your app entry point:

        String sep = System.getProperty("line.separator");

        if (!sep.endsWith("\n")) {
            throw new RuntimeException(
                "System line separator not suitable for network app");
        }

Open in new window

CERTIFIED EXPERT
Top Expert 2016

Commented:
If it is looking for "\n" then this is indeed the best way to add it
String B = StringA + "\n";

Of all ways to implement it, that's not the best. Quite possibly it's the worst