user2385057
user2385057

Reputation: 537

Null assignment behavior java

my date format changes according to certain conditions, in order to have global access I initialize them and then assign a value according to condition.

But looking at De-bugger these values are not being re-assigned, they remain null as per initialization.

I am new to java what is the assignment behavior that is causing this ?

Here's code:

SimpleDateFormat df     = null;
        SimpleDateFormat df2    = null;
        SimpleDateFormat date_c = null;
        SimpleDateFormat t      = null;
        SimpleDateFormat t2     = null;
        SimpleDateFormat df5    = null;
        SimpleDateFormat df3    = null;

        if ( make == "NCR")
        {
        df     = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        df2    = new SimpleDateFormat("yyyyMMddHHmmss");
        date_c = new SimpleDateFormat("yyyyMMdd");
        t      = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        t2     = new SimpleDateFormat("yyyyMMddHHmmss");
        df5    = new SimpleDateFormat("yyyyMMddHHmmss");
        df3    = new SimpleDateFormat("yyyyMMddHHmmss");
        }

        else if ( make == "WINCORE")
        {
            df     = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            df2    = new SimpleDateFormat("yyyyMMddHHmmssS");
            date_c = new SimpleDateFormat("yyyyMMdd");
            t      = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            t2     = new SimpleDateFormat("yyyyMMddHHmmssS");
            df5    = new SimpleDateFormat("yyyyMMddHHmmssS");
            df3    = new SimpleDateFormat("yyyyMMddHHmmssS");
        }

Upvotes: 0

Views: 164

Answers (2)

darijan
darijan

Reputation: 9775

When comparing strings in java, you do not use ==, you use equals()

if ("NCR".equals(make))
 ...
else if ("WINCORE".equals(make))

Also, put the string literal first, in case that make is null, so you don't get a NullPointerException.

Upvotes: 2

Rorick
Rorick

Reputation: 8953

Because neither of two conditions fulfils. You use == for String comparison, and this is most likely an error. == compares objects identity and strings are objects. For value-based comparsion you should use equals. Putting literal to the left gives you a null-safe comparison (it is a common Java idiom): "NCR".equals(make). But you can also use make.equals("NCR") if make is not null or you want NullPointerException for null make.

Compare the following:

assert "NCR" == "NCR" : "String literals are interned, so they have the same identity";
assert "NCR" != new String("NCR") : "String with the same value but not the same identity"; 
assert "NCR".equals(new String("NCR")) : "But they are equal";

Upvotes: 3

Related Questions