Java vs Kotlin

Amir Ansari
9 min readNov 3, 2020

Lets start this topic with Similarities

•statically typed

•free and open-source

•convert code to ByteCode

•Interoperable

•object-oriented programming languages

1. Statically typed

Both Java and Kotlin are statically typed language, it means type checking is done at compile time. (There are dynamically types languages as well some examples are PHP, Python, JavaScript)

It can be understood with below example..

2. Free and open-source

Both are free and open-source (free to use and open for contribution)

3. ByteCode

Both convert code to ByteCode executable by JVM

4. Interoperable

•Both are interoperable, which means Java files and Kotlin files can co-exist in one project or jar.

5. OOPS support

Both are object-oriented programming languages

(So they support basic concepts of OOPS)

Polymorphism, Inheritance, Encapsulation, Abstraction.

Now Let’s discuss the Basic Differences

1. Intro & Release
•Java was developed by Sun Microsystems (now the property of Oracle) in 1995.

•It supports almost all types of machines, and OS X be it Android, Windows or Linux.

•Kotlin was introduced by JetBrains in 2011, open-sourced in 2012, officially supported in Google I/O (annual event of Google developers) in 2017.

•Google claimed that 70% of the top 1,000 Android apps are written in Kotlin now.

•Some apps are under construction in Kotlin from Java, for instance, The Google Home app isn’t completely written in Kotlin yet,

•but as of June, 2020 about 30% of the code base was rewritten in Kotlin from the legacy Java code.

•Other popular Kotlin apps examples from Google include Maps, Play, Drive.

•There are plenty of android apps by other companies written in Kotlin now.

•In nutshell, Android development is now backed by “Kotlin-first” policy. It is similar to IOS apps development which shifted from Objective-C to Swift.

2. Version
•As on November 2020, Kotlin version is v1.4.0

•while Java 15 has now released, but java 8 (aka 1.8) is still most popular.

3. Speed
•Java does beat Kotlin by 12–15% for clean builds. That means, Kotlin compiles a little slower than Java for full builds

•However, for partial builds with incremental compilation enabled i.e. only building with small changes, Kotlin compiles as fast or slightly faster than Java.

4. Lines of code
•Code written in Kotlin is much smaller compared to Java.

There is nearly 30–40% less code in Kotlin. So Apps have potential to lose 1/3rd weight.

•Java is detailed while Kotlin is concise and modern.

5. Market share
•Kotlin developers are 1/5th of Java developers as per surveys.

•7.8% Kotlin developers against more than 40% developers using Java, but also these surveys suggest that Kotlin is more loved than Java and expanding fast.

•References -

https://www.statista.com/statistics/793628/worldwide-developer-survey-most-used-languages/

https://insights.stackoverflow.com/survey/2020#most-popular-technologies

https://insights.stackoverflow.com/survey/2020#most-loved-dreaded-and-wanted

6. Null Safety
•Kotlin is safe against NullPointerException. This type of error is the largest cause of app crashes on Google Play.

•Java lets developers assign a null value to any variable.

•Unlike Java, all types are non-nullable in Kotlin by default. Assigning or returning a null will give compile time error.

•In order to assign a null value to a variable in Kotlin, it is required to explicitly mark that variable as nullable.

val number: Int? = null //Nullable type

val name: String = null //Error because not possible to assign a null value

Nullable types are used with safe call operator.

name?.getLength()

So even name becomes null, whole expression is equivalent to null without NullPointerException

7. Hybrid apps

•Kotlin can be used to write native code of Android and IOS apps

•Kotlin Multiplatform Mobile (KMM) works on both Android and iOS.

•Java is not used for IOS app development till now.

Now Let’s see STYLE Differences

  1. Main function

•In Java, the “main” method should be inside a class. It is declared as static method.

•In Kotlin, to make a function static, one way is to put it directly under a package. So it can be standalone function without a class.

•Arguments of main method, can be omitted in Kotlin, if our program does not need to accept command-line arguments

fun main(args : Array<String>) {

println(“hello”)

}

•In Java, if we don’t include arguments to main function (even if we don’t use), it gives us error.

Error: Main method not found in class

2. Default behaviour

•Unlike Java, by default, classes are final in Kotlin, so need to mark a class with the open keyword to let it be extended.

•Also method() must be explicitly marked as open to be overridable.

class A { … } in Java is equal to open class A { … } in Kotlin.

final class B { … } in Java is equal to class B { …} in Kotlin.

•In Kotlin, everything without access modifiers is public by default. We can explicitly say public in the definition, but it is not necessary.

public class A { … } and class A { … }

are same in Kotlin.

There are four visibility modifiers in Kotlin: private, protected, public and internal.

Internal is visible everywhere in the same module.

•Java has default keyword.

•A default keyword is an access modifier. If you didn’t assign any access modifier to variables, methods, constructors and, classes, by default, it is considered as default access modifier.

•Default is equivalent to Package-public, means visible within same package

•Default methods enable new functionality to be added to the interfaces.

interface AnInterface {

public default void myMethod() {

System.out.println(“D”);

}

} /Allowed

•Kotlin does not have default keyword

3. Data types and Arrays

•Mutable and Immutable types in Kotlin are known as var and val

//Compiler can understand the type of the variable by looking at the values

var website = “hello”

var website: String = “hello” //both same

//It is mandatory to specify the type if declaration first and initialization later

var website: String

website = “hello“

•Underscores in numeric literals allowed

val creditCardNumber = 1234_5678_9012_3456L

Smaller types are not comparable

val a: Int = 10; val b: Long = 10L

print(a == b) // Error, cannot compare in kotlin but true in Java

•Primitive data type name in Kotlin start with Caps, ex. Boolean, Int while in Java it starts with small letter ex. char, double

•Wrapper class ex. Integer, is available in both

val num:Integer = Integer(10) //valid in Kotlin

val num:Integer = 10 //Not valid

•Arrays are declared as below

Int[] numbers = new int[] {10, 20, 30, 40, 50}

val numbers = intArrayOf(10, 20, 30,40,50)

val numbers = arrayOf(10, 20, 30,40,50)

var numbers = IntArray(5){it*10}

var numbers = Array<Int>(5){it*10}

4. List

List type is non-mutable by default in Kotlin, So add() or remove() does not work simply as Java.

val lst = listOf<Int>(10, 20, 30, 40, 50)

lst.add(60) //Error

val lst2 = mutableListOf<Int>(10, 20, 30, 40, 50) //same as ArrayList<Int>

// val for mutableList?? Yes, because no new assignment, only content altering

lst2.add(60) //OK

lst2 += 70 //also OK

take and drop function operate on Kotlin List

val nums = listOf(0,1,2,3,4,5,6,7)

nums.take(3) // [0,1,2]

nums.drop(3) // [3,4,5,6,7]

5. Loop

Kotlin is versatile in terms of for loops. Java has fixed known structure.

val lst : List<Int> = listOf<Int>(10, 20, 30, 40, 50)

for(item in lst){

println(item)

}

for(item in 0 until lst.size){

println(lst[item])

}

for(item in 0..4){ //range operator

println(lst[item])

}

Lastly we will look for features differences

  1. Constructors
  • Kotlin has two type of constructors.

•The one written with class name is primary constructors and one written inside body of class are secondary constructors.

•There can be one primary constructor and multiple secondary constructors.

The primary constructor cannot contain any code. Initialization code can be placed in init block.

fun main(args: Array<String>) {

val per1 = Person(“amir”) //only primary constructor called

val per2 = Person(“ansari”,20, ‘A’) // if remove ‘A’ , second constructor not called //as no default value for blood_group

}

secondary constructor must extended the first constructor behavior.

class Person (var name: String, var age: Int = 18) {

init{

println(“Student has got a name as $name and age as $age”)

}

var blood_group: Char = ‘O’

constructor(_name: String, age: Int, blood_group: Char) : this(_name, age) {

this.blood_group = blood_group

println(“Student name= $_name and age= $age and blood group=$blood_group”)

}

}

2. Extension functions

•Kotlin allows developers to extend a class with new functionality via extension functions.

•This is great improvement as it allows to do so without extending that class.

•Basically, an extension function is a member function of a class that is defined outside the class.

•They were not available in Java.

fun String.countSpaces(): Int {

return this.count { c -> c == ‘ ‘ }

}

3. Higher-Order Functions

•In Kotlin, a function which can accepts a function or lambda as parameter or can returns a function is called Higher-Order function.

// lambda expression

var lambda = {a: Int , b: Int -> a + b }

// higher order function

fun highfun( lmbd: (Int, Int) -> Unit) { // accepting lambda as parameter, return nothing

var result = lmbd(2,4) // invokes the lambda expression by passing parameters

println(“The sum of two numbers is: $result”)

}

fun main() {

highfun(lambda) //passing lambda as parameter

}

4. Data classes

•Big projects have several classes that are solely meant to hold data.

•A developer had to write a lot of standard but frequent code in Java (aka boilerplate code), Data classes in Kotlin skip that extra efforts.

•Java class for this purpose will have all the getters and setters , Hashcode(), toString() and equals() functions. While Kotlin equivalent is below..

data class Person(var name: String, var surname: String, var id: String)

and that’s all.

5. Static Members

•Once we declare a variable static they will be loaded in to the memory at the compile time i.e. only one copy of them is available. Singletons and statics have very similar behavior.

•static keyword makes that component part of the class, not related to object of the class.

•In OOP, something that is not an object should not exist.

•In Java, everything must be declared inside a class. But not so in Kotlin. components can be declared outside class and that would be automatically static. So we don’t need static keyword.

•In Java, static members are treated very differently than object members. This means that we can’t do things like implementing an interface or putting your class ‘instance’ into a map, or pass it as a parameter to a method that takes Object.

•In Kotlin, rather companion object is used and static is not a keyword.

  • Companion objects allow for above limitations. That’s the advantage.
  • Even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects, and can, for example, implement interfaces.

6. Asynchronous processing

•RxJava, AsyncTask (deprecated now), Handlers, Callbacks there are multiple threading solutions for Async works. In Java

•With all those existing features, Kotlin also has Coroutines, which make it simpler in Kotlin,

Coroutines (aka lightweight threads) they are not separate threads, but multiple coroutines can share single thread.

7. Checked Exceptions

•i.e. IOException, FileNotFoundException

•Present in Java but not supported in Kotlin

  • Reason behind is that, they don’t do anything except containing a comment in catch block

8. Lazy loading

•In Kotlin, ‘lateinit’ and ‘by Lazy’ allow to initialize values before they are actually used

val myUtil by lazy {

MyUtil(parameter1, parameter2)

}

lateinit var myUtil: MyUtil

•The above code is initializing a MyUtil object. But this will only be done upon the first usage of myUtil.

•both have the same concept but are actually very different. one is val (immutable) and the other is var (mutable)

@Inject
lateinit var myUtil: MyUtil

  • lateinit was explicitly introduced in Kotlin for DI variables. It should be used for mutable or externally set values. It is useful if we don’t want to initialize the value but still avoid null check.

•To check whether a lateinit var has already been initialized, use .isInitialized() on the reference to that property:

if (foo::bar.isInitialized) {

println(foo.bar)

}

lateinit var can be initialized from anywhere the object is seen.

Java on the other hand, does not support deferred initialization, So values are initialized even if they are not used.

These are some of the differences between two powerful languages.

Thank you for reading.

--

--