Comparison Operators
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 22 of 93.
Comparison operators let you compare two values and get a Boolean result, either true or false. These operators are essential for making decisions in your programs.
Here are Kotlin's comparison operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 5 > 3 | true |
< | Less than | 5 < 3 | false |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 3 <= 5 | true |
You can use these with variables and store the results:
fun main() {
val age = 18
val isAdult = age >= 18
println(isAdult) // Prints: true
val score = 85
val isPerfect = score == 100
println(isPerfect) // Prints: false
}Comparison operators work with any numeric types and are the foundation for decision-making logic you'll learn in upcoming lessons.
Challenge
EasyWrite a function checkScores that takes score1, score2, and passingScore and returns a string with three comparison results.
Compare the two scores against each other and against the passing threshold using comparison operators.
Logic:
- Check if
score1is greater thanscore2 - Check if
score1equalsscore2 - Check if
score2is greater than or equal topassingScore
Parameters:
score1(Int): The first scorescore2(Int): The second scorepassingScore(Int): The minimum passing score
Returns: A string with three boolean results separated by spaces. Format: [result1] [result2] [result3]
Example: For inputs 85, 70, and 60, return "true false true" because 85 > 70 is true, 85 == 70 is false, and 70 >= 60 is true.
Try it yourself
fun checkScores(score1: Int, score2: Int, passingScore: Int): String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground