What can relational operators compare?


Can they only compare floats and integers?


Relational operators can compare any two objects so long as they are the same type.


"A" < "B"  =>  true

The relationship here is they are both strings, and ‘A’ is before ‘B’ in the alphabet. The computer doesn’t know this, per se, but has an ordinal table to which it can refer. The lower a letter is in the alphabet, the lower will be its ordinal, or character code.

This is useful for sorting strings.

'aaa' < 'aba' < 'abb' < 'abc'


false < true  => true

false is equated to 0, and true is equated to 1 in the above. (In Python, False casts to 0, and True casts to 1.)

In some computer systems, false is 0, but true is -1, so this needs to be investigated as pertains to Java.

0b00000000  =>  false
0b11111111  =>  true

In binary, the highest order bit is the sign bit. 1 is negative, 0 is positive. Definitely investigate how this all relates to Java.


Note that in Java, you can’t actually use the <, > operator to compare Strings and other datatypes, only with floats, integers, and characters (they’re integer values under the hood; you can cast them to integers) - at least as of java 8

In other languages like C# and python you can overload the operators ( e.g. +, -, <, == )


Thank you for correcting me, and glad you did. char, not String.


Would this be a way to compare strings (it’s in Python because I just started the Java lessons today)?
Also-- this is unrelated-- should I try to become very proficient in one language (Python) before trying out the others?

lv = {}
for x,y in zip(' ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(27)):
	lv[x] = y
def compare_words(one,two):
	for onechar,twochar in zip(one,two):
		if lv[onechar] > lv[twochar]:
			return True
		elif lv[onechar] < lv[twochar]:
			return False
while True:
	print 'Two words will be compared in the format "first word > second word".'
	string1 = raw_input('Choose the first word: ').upper()
	string2 = raw_input('Choose the second word: ').upper()
	print compare_words(string1,string2)


Not to be rude, but in Python we can make direct comparisons of strings so there is no logic other than,

if str_a > str_b:

It would be True if str_a comes after str_b in alphabetical (ordinal, actually) sort.

>>> 'aaa' < 'aab' < 'aba' < 'abb' < 'abc' < 'acc'


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.