Comparing Java String / Char charAt ()

I have seen various comparisons that you can make using the charAt() method.

However, I cannot understand some of them.

 String str = "asdf"; str.charAt(0) == '-'; // What does it mean when it equal to '-'? char c = '3'; if (c < '9') // How are char variables compared with the `<` operator? 

Any help would be appreciated.

+7
java comparison char charat
source share
5 answers

// What does it mean when it is equal to '-'?

Each letter and symbol are symbols. You can look at the first character of the string and check the match.

In this case, you will receive the first character and see if it is a minus symbol. This minus sign (char) 45 cm. Below

// How are char variables compared to the < operator?

In Java, all characters are actually 16-bit unsigned numbers. Each character has a number based on it unicode. for example, '9' is a character (char) 57 This comparison is true for any character smaller than the code for 9 , for example. space.

enter image description here

The first character of your string is 'a' , which is (char) 97 , so (char) 97 < (char) 57 is false.

+13
source share
 String str = "asdf"; String output = " "; if(str.charAt(0) == '-'){ // What does it mean when it equal to '-'? output= "- exists in the first index of the String"; } else { output="- doesn't exists in the first index of the String"; } System.out.println(output); 

It checks if char exists at index 0, this is a comparison.

As for if (c < '9') , the values โ€‹โ€‹of ascii c and 9 are compared. I don't know why you would check if the ascii equivalent of c is less than the ascii equivalent of '9' though.

If you want to get the ascii value of any char, you can:

 char character = 'c'; int ascii = character; System.out.println(ascii); 
+1
source share

str.charAt(0) == '-'; returns boolean, in this case false .

if (c < '9') compares the value of ascii '3' with the value of ascii '9' and returns boolean again.

0
source share
 str.charAt(0) == '-' 

This operator returns true if the character at point 0 is '-' and false otherwise.

 if (c < '9') 

This compares the value of ascii c with the value of ascii '9' in this case 99 and 57, respectively.

0
source share

Symbols are a primitive type in Java, which means that it is not a complex object. As a result, every time you make a comparison between chars , you directly compare their values.

Java characters are defined according to the original Unicode specification, which gives each character a 16-bit value. These are the values โ€‹โ€‹that Java compares when you compare something like c>'3' or str.charAt(0) == '-' .

0
source share

All Articles