How to Set Java String to Null


In Java programming, "null" is a special keyword reserved to refer to a variable that, while assigned a variable name, does not actually refer to data in memory. All variables, including strings, have a value of null in the time between their creation and when they are assigned a value. A value of null can also be assigned by typing: "String s = null." However, in the case of strings, there are a few caveats.

  • Open "Netbeans" or any other Java Integrated Development Environment.

  • Click "File" and "New class." Name it "StringNullLesson."

  • Type "psvm" to create a main method.

  • Add the following code to your main method:

    String t = null;

    try {


    System.out.println(t + " is not null.");

    } catch (NullPointerException e) {

    System.out.println("t is null.");


    This creates a string and explicitly assigns a value of null. It attempts to access the first character of the string and print it. The whole thing is surrounded by a "Try-catch" statement that should be thrown when Java realizes that you are trying to do something with a null value.

  • Click "Run." You should see an error message saying "t is null."

  • Remove the line "t.charAt(0);" from your code. Click "run" again. This time, you will see the contradictory message "null is not null." Normally, when you attempt to do anything with null, the compiler objects and throws an error immediately. But, whenever Java sees you trying to treat null as if it were a string, it will go along with it, creating a new string containing the word "null." A moment's thought should make it obvious why this is: if Java crashed every time it tried to print a value of "null," then writing an error log file for your application would be almost impossible: the error log itself would crash every time a null pointer was detected. Java assumes that if you are trying to print "null," then you are trying to report the error, and it doesn't get in the way.

  • Add the following code to check for a null String properly:

    if (t == null) throw new NullPointerException();


Promoted By Zergnet


You May Also Like

  • Access 2007: The VBA Set String Variable to Null

    Visual Basic for Applications (VBA) is a programming language used for Microsoft Access. You set a string variable to null to clear...

  • Get and Set Method in Java

    Java is an object-oriented programming (OOP) language. Object-oriented code is organized using a construct called a "class," which serves as a blueprint...

  • What Is a Null Pointer Exception?

    Every Java programmer eventually writes a program that produces the "NullPointerExceptions" error message. It is particularly cryptic to those who are beginning...

Related Searches

Is DIY in your DNA? Become part of our maker community.
Submit Your Work!