Syntax error Difference between Java and Kotlin in Android with Examples

Difference between Java and Kotlin in Android with Examples



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.

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

Kotlin:
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. Key Java Kotlin
1 Exceptions Java uses checked exceptions for exception handling. Kotlin has no checked exception. It throws compile-time errors.
2 Null Handling Java has not enforced null check thus null pointer exception arises when code is not handling null. Kotlin enforces the null check at compile time.
3 Non-Private Fields Java constructs have non-private fields. Kotlin does not allow non-private fields in its constructs.
4 Arrays Java arrays are covariant. Kotlin arrays are invariant.
5 Ternary Operator Java has a ternary operator. Kotlin does not support a ternary operator.


Updated on: 2020-04-16T05:57:32+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements