Logo
Kotlin Basics
Kotlin BasicsOperators

Operators

Introduction to various operators in Kotlin for arithmetic, comparison, and logical operations, and how to use them effectively in your code.

Operators are special symbols or keywords that are used to perform operations on operands. Kotlin provides a rich set of operators for various kinds of operations including arithmetic, comparison, and logical operations. Understanding these operators is crucial for writing concise and efficient code.

Arithmetic Operators

These operators are used for mathematical calculations.

Addition (+)

Adds two numbers together.

val sum = 5 + 3  // Result: 8

Subtraction (-)

Subtracts the right operand from the left.

val difference = 10 - 4  // Result: 6

Multiplication (*)

Multiplies two numbers.

val product = 5 * 2  // Result: 10

Division (/)

Divides the left operand by the right.

val quotient = 10 / 2  // Result: 5

Modulus (%)

Finds the remainder of division.

val remainder = 10 % 3  // Result: 1

Comparison Operators

These operators are used to compare two values.

Equal To (==)

Checks if two values are equal.

val isEqual = (5 == 5)  // Result: true

Not Equal To (!=)

Checks if two values are not equal.

val isNotEqual = (5 != 3)  // Result: true

Greater Than (>)

Checks if the left operand is greater than the right.

val isGreater = (10 > 5)  // Result: true

Less Than (<)

Checks if the left operand is less than the right.

val isLess = (5 < 10)  // Result: true

Logical Operators

These operators are used for logical operations, typically with boolean values.

Logical AND (&&)

Returns true if both conditions are true.

val andResult = (5 > 3 && 10 > 5)  // Result: true

Logical OR (||)

Returns true if at least one condition is true.

val orResult = (5 < 3 || 10 > 5)  // Result: true

Logical NOT (!)

Inverts the value of a boolean.

val notResult = !(5 == 3)  // Result: true

Summary and Best Practices

  • Use arithmetic operators for mathematical calculations.
  • Use comparison operators to compare values and make decisions.
  • Use logical operators to combine multiple conditions.
  • Always be cautious with the order of operations and consider using parentheses for clarity.

Understanding and effectively using operators in Kotlin allows you to write more concise and readable code. This is especially useful in complex calculations and conditional statements in Android Native development.

Book a conversation with us for personalize training today!

Was this helpful?
Logo