Vishnu Chaturvedi
Vishnu Chaturvedi

Reputation: 69

How to print null without quotes when using String.format

I am working on one program in Java that is using String.format() to print a string. Below scenario is:

StringJava.class

public static String myString = "This is my name : "\%s\""

Suppose in my main class I am using String.format() in such a way that if we pass some value it will return the respective string. For example:

System.out.println(String.format(StringJava.myString, some_value))

It will give me the expected result that is : This is my name "some_value"

But if i try to pass null values like this:

System.out.println(String.format(StringJava.myString, null))

It will give me the result that is: This is my name "null"

But I want my result as: This is my name null

How can I fix this "null" issue?

Upvotes: 1

Views: 1971

Answers (2)

user4910279
user4910279

Reputation:

You should change the constant myString to a method.

public static String myString(String name) {
    return String.format("This is my name : %s", name == null ? null : "\"" + name + "\"");
}

and

 System.out.println(StringJava.myString("Jhon"));
 System.out.println(StringJava.myString(null));

output

This is my name : "Jhon"
This is my name : null

Upvotes: 1

Udith Gunaratna
Udith Gunaratna

Reputation: 2111

Instead of specifying the quotes in the myString itself, write a small utility method to process the value before feeding it to the String.format() method. Within this utility method, you can check for null and treat differently.

public static String myString = "This is my name : %s"

System.out.println(String.format(StringJava.myString, wrapWithQuotes("some_value")));
System.out.println(String.format(StringJava.myString, wrapWithQuotes(null)));

private String wrapWithQuotes(String input) {
    return (input != null) ? '"' + input + '"' : null;
}

Upvotes: 4

Related Questions