Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String/Char charAt() Comparison

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.

like image 621
Kcits970 Avatar asked Oct 17 '16 12:10

Kcits970


People also ask

Can you compare a string and a char in Java?

Object Oriented Programming Fundamentals You can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.

Do you use == or .equals for char?

equals() is a method of all Java Objects. But char is not an Object type in Java, it is a primitive type, it does not have any method or properties, so to check equality they can just use the == equals operator.

Can you compare strings char?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

How do you compare characters in a string to a character?

strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.


Video Answer


1 Answers

// 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.

like image 132
Peter Lawrey Avatar answered Sep 20 '22 06:09

Peter Lawrey