Difference between Java and Kotlin in Android with Examples

JavaAndroidObject Oriented ProgrammingProgramming

Kotlin was introduced in Android development considering multiple enhancements in Kotlin w.r.t Java. For example:

  • Less no. of Lines and easier development with the same functionality.

TextView displayText = (TextView) findViewById(R.id.textView);
displayText.setText("Hello World");

textView.setText("Hello World")
  • Compile-time handling of infamous null pointer exception.

var value: String = "abc"

// compilation error
value = null
  • Data class instead of POJO.

data class User(val name: String, val age: Int)

The following are some of the important differences between Java and Kotlin.

Sr. No.KeyJavaKotlin
1ExceptionsJava uses checked exceptions for exception handling.Kotlin has no checked exception. It throws compile-time errors.
2Null HandlingJava has not enforced null check thus null pointer exception arises when code is not handling null.Kotlin enforces the null check at compile time.
3Non-Private FieldsJava constructs have non-private fields.Kotlin does not allow non-private fields in its constructs.
4ArraysJava arrays are covariant.Kotlin arrays are invariant.
5Ternary OperatorJava has a ternary operator.Kotlin does not support a ternary operator.

Published on 16-Apr-2020 09:26:49