2

I want to use Persian language as my string to print, it's alright when writing the program but it changes when running it.
What can I do to set it right?

The sample code:

public static void main(String[] args)
    {
        System.out.print("سلام");
    }

The result in windows command prompt is only question marks(????????) and in notepad++ it is like Lسلام

Persian is a middle east language like Arabic.

Veve
  • 6,643
  • 5
  • 39
  • 58
farshad
  • 764
  • 10
  • 25
  • What is the default encoding of the editor you are using? – Tim Biegeleisen Apr 08 '16 at 10:28
  • Depeding on the Encoding of your soruce file (which should be UTF-8) your code is fine. The windows command prompt won't display UTF-8 unless you configure it to do so: https://stackoverflow.com/questions/388490/unicode-characters-in-windows-command-line-how – hinneLinks Apr 08 '16 at 10:35
  • I'm using notepad++ , not sure how should I find out the default encoding of it. – farshad Apr 08 '16 at 23:55

1 Answers1

2

You need UTF-8 encoding to support Persian (which uses a slight variant of the Arabic script). In Java, UTF-8 data can be represented as byte array. So one way of achieving what you want is to create a String from a byte array corresponding to the UTF-8 representation of سلام:

try {
    String str = new String("سلام".getBytes(), "UTF-8");
    System.out.println(str);
}
catch (Exception e) {
    System.out.println("Something went wrong.");
}

If you've never seen a String being created from a byte array before, then have a look at the Javadoc.

Caviat: This answer will only work if your editor is also using UTF-8 encoding. This is required so that when the Persian salam string is converted to a byte array, the encoding is correct.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I got this error when using encoding: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown. when I used throws Exception it was printed wrong again. – farshad Apr 08 '16 at 10:19
  • Wrap the creation of the `String` in a `try-catch` block. – Tim Biegeleisen Apr 08 '16 at 10:21
  • With try/catch code I get :can not find symbol UnsupportedEncodingException error. – farshad Apr 08 '16 at 12:11