简体   繁体   中英

Using Unicode as Java Variables?

I was wondering if it is possible to use unicode as variable names in java. For example:

public static double δ = 1.001;

Whenever I do something like this in java, I get an error. Is there anyway to make it so that δ can be used as a variable in java?

If not, are there any alternatives I could use?

according to doc it is possible

Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character " ". The convention, however, is to always begin your variable names with a letter, not "$" or " ". Additionally, the dollar sign character, by convention, is never used at all.


**If It is Not Working, compile file with -encoding option(normally without -encoding It should work.This is not a necessary step first check without this) **

-encoding : encoding Set the source file encoding name, such as EUC-JP and UTF-8.. If -encoding is not specified, the platform default converter is used.

 javac -encoding UTF-8 HelloWorld.java 

How to configer Your IDE :

I am using Intellij idea:

add additional command line parameter : -encoding UTF-8

在此处输入图片说明

It's worked !

在此处输入图片说明

It is a legal name. From JLS 3.8 Identifiers - Letters and digits (for identifiers) may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese, Japanese, and Korean. This allows programmers to use identifiers in their programs that are written in their native languages.

You can use unicode itself(not only a character) as a variable like below mentioned screenshot.

在此处输入图片说明

  1. As you can see the Sysout with \ (space character) there is no error.
  2. The below we are create a string variable(P) with unicode and it can even print "Hi" in the console if you run the program by removing last Sysout.
  3. When trying to print unicode chatacter (Q -- \Q) which is not defined giving compilation error.

It looks weird but java supports it as mentioned by Evgeniy Dorofeev.

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