7

I have seen various comparisons that you can do with the charAt() method.

However, I can't really understand a few of them.

String str = "asdf";
str.charAt(0) == '-'; // What does it mean when it's equal to '-'?


char c = '3';
if (c < '9') // How are char variables compared with the `<` operator?

Any help would be appreciated.

476rick
  • 2,412
  • 2
  • 25
  • 46
Kcits
  • 430
  • 1
  • 3
  • 12

5 Answers5

13

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

Every letter and symbol is a character. You can look at the first character of a String and check for a match.

In this case you get the first character and see if it's the minus character. This minus sign is (char) 45 see below

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

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

enter image description here

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

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
  • This is the basis for character encoding. https://en.wikipedia.org/wiki/Character_encoding The above referenced definition is using ASCII character encoding. – Andrew Oct 17 '16 at 20:35
1
String str = "asdf";
String output = " ";
if(str.charAt(0) == '-'){
  // What does it mean when it's 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 that char exists in index 0, it is a comparison.

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

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

char character = 'c';
int ascii = character;
System.out.println(ascii);
almost a beginner
  • 1,494
  • 1
  • 15
  • 37
0

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

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

Tilak Maddy
  • 3,027
  • 2
  • 26
  • 44
0
str.charAt(0) == '-'

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

if (c < '9')

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

Nyakiba
  • 814
  • 8
  • 18
0

Characters are a primitive type in Java, which means it is not a complex object. As a consequence, every time you're making a comparison between chars, you are directly comparing 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 is comparing when you are comparing something like c>'3' or str.charAt(0) == '-'.

Roc Aràjol
  • 190
  • 9