简体   繁体   中英

What is java equivalent of null assigned to var in javascript?

In my JS file I have

var previousChar = null;

now I manually ported the code in Java but I am getting error that character can not be assigned null.

Also is using '\\0' is equal or not?

Here is the code in js-

previousChar=null;
nextChar=null;

var str='abc';
previousChar='a';
nextChar='c';

In Java it should be like this, but it gives error

previousChar = null;

You can simply declare the variable as char without assigning it to null value:

char previous;
char next;
String str;

and then:

str = "abc";
previous = 'a';
next = 'c';

this will work.

The error you had was due to the fact that primitive types are handled in a different way than "real" objects are. They cannot be set to null and that means that you can't do something like:

Long longObject = null;
long longPrimitive = longObject;

this would throw a NullPointerException;

You cannot assign null to a char variable because char is a primitive type.

What you have to do is to check the code you're porting on if there are some checks on previousChar or nextChar .

If there are no checks (nothing like if (previousChar === null) ), you may probably leave previousChar and nextChar uninitialized in Java.

But most probably there are some checks, otherwise variables would not have been initialized with null . In this case you'll need to port that logic to java as well. Either use some value as a replacement for null (for instance 0 ), or use additional boolean variables. Finally, you can use the Character wrapper type instead of char , but that's overhead.

both static and instance members of reference type not explicitly initialized are set to null by Java.you must have assign some values to your var variable rather null.

   char previous;
    previous="pre"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM