Difference Between Kotlin & Java

Kotlin

fun main() {
    val scanner = Scanner(System.`in`)
    print("Enter a number: ")
    val number = scanner.nextInt()
    val factorial = calculateFactorial(number)
    println("Factorial of $number is $factorial")
}

fun calculateFactorial(n: Int): Long {
    return if (n == 0) 1 else n * calculateFactorial(n - 1)
}

Java

public class FactorialJava {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        long factorial = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is " + factorial);
    }

    public static long calculateFactorial(int n) {
        return (n == 0) ? 1 : n * calculateFactorial(n - 1);
    }
}

In this example, you can see some differences between Kotlin and Java:

  1. Syntax: Kotlin code tends to be more concise than Java. For instance, in Kotlin, you don’t need semicolons at the end of each line, and the main function is defined using the fun keyword.
  2. Null Safety: Kotlin’s null safety features are not explicitly demonstrated in this program, but they help prevent null pointer exceptions by design, which is not the case in Java.
  3. Type Inference: Kotlin can often infer variable types, so you don’t have to explicitly specify types as in Java (int, long, etc.).
  4. String Concatenation: Kotlin allows string interpolation with the $ sign, making it more convenient to embed variables within strings.
  5. Function Declaration: Kotlin uses the fun keyword to define functions, while Java uses public static in this case.
  6. Ternary Operator: Kotlin doesn’t have a ternary operator like Java’s ? :. Instead, it uses if as an expression, as seen in the calculateFactorial function.

This is just an example of the differences between Kotlin and Java. Kotlin is designed to be more concise and expressive while maintaining interoperability with Java, making it a compelling choice for many developers.

Leave a comment