简体   繁体   English

在JavaScript中分配给var的null的Java等效项是什么?

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

In my JS file I have 在我的JS文件中

var previousChar = null;

now I manually ported the code in Java but I am getting error that character can not be assigned null. 现在,我手动将代码移植到Java中,但是却收到无法将字符分配为null的错误。

Also is using '\\0' is equal or not? 还使用'\\ 0'等于还是不?

Here is the code in js- 这是js-中的代码

previousChar=null;
nextChar=null;

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

In Java it should be like this, but it gives error 在Java中应该是这样,但是却给出了错误

previousChar = null;

You can simply declare the variable as char without assigning it to null value: 您可以简单地将变量声明为char,而无需将其分配为null值:

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: 它们不能设置为null,这意味着您不能执行以下操作:

Long longObject = null;
long longPrimitive = longObject;

this would throw a NullPointerException; 这将引发NullPointerException;

You cannot assign null to a char variable because char is a primitive type. 您不能将null分配给char变量,因为char是原始类型。

What you have to do is to check the code you're porting on if there are some checks on previousChar or nextChar . 您需要做的是检查在移植的代码上是否对previousCharnextChar进行了一些检查。

If there are no checks (nothing like if (previousChar === null) ), you may probably leave previousChar and nextChar uninitialized in Java. 如果没有检查(类似于if (previousChar === null) ),则可能在Java中未设置previousCharnextChar

But most probably there are some checks, otherwise variables would not have been initialized with null . 但是最有可能进行一些检查,否则变量将不会使用null初始化。 In this case you'll need to port that logic to java as well. 在这种情况下,您还需要将该逻辑移植到Java。 Either use some value as a replacement for null (for instance 0 ), or use additional boolean variables. 请使用某个值代替null (例如0 ),或使用其他布尔变量。 Finally, you can use the Character wrapper type instead of char , but that's overhead. 最后,您可以使用Character包装器类型而不是char ,但这是开销。

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. Java未将未明确初始化的引用类型的静态成员和实例成员都设置为null。您必须为var变量分配一些值,而不是null。

   char previous;
    previous="pre"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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