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:
- 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
mainfunction is defined using thefunkeyword. - 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.
- Type Inference: Kotlin can often infer variable types, so you don’t have to explicitly specify types as in Java (
int,long, etc.). - String Concatenation: Kotlin allows string interpolation with the
$sign, making it more convenient to embed variables within strings. - Function Declaration: Kotlin uses the
funkeyword to define functions, while Java usespublic staticin this case. - Ternary Operator: Kotlin doesn’t have a ternary operator like Java’s
? :. Instead, it usesifas an expression, as seen in thecalculateFactorialfunction.
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.