farshad
farshad

Reputation: 792

Using other languages rather than English for java strings (Persian as an example)

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.

Upvotes: 2

Views: 2486

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521279

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.

Upvotes: 2

Related Questions