You are on page 1of 3

java & Kotlin Coding Syntax

Here are a few code snippets to demonstrate some of the syntax differences between Java and
Kotlin:

Defining a class
Java
java
Copy code
public class Person {
private String name;
private int age;

public Person(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}
}
Kotlin
kotlin
Copy code
class Person(val name: String, val age: Int)
Null safety
Java
java
Copy code
String name = null;
if (name != null) {
int length = name.length();
} else {
// handle null case
}
Kotlin
kotlin
Copy code
val name: String? = null
val length = name?.length ?: 0
Extension functions
Java
java
Copy code
public class StringUtils {
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
}

boolean isBlank = StringUtils.isBlank(" ");


Kotlin
kotlin
Copy code
fun String.isBlank() = trim().isEmpty()

val isBlank = " ".isBlank()


These code snippets illustrate some of the differences between Java and Kotlin in terms of syntax
and language features. However, it's important to note that the choice between Java and Kotlin
depends on more than just syntax and language features, and developers should consider factors
such as performance, ecosystem, and community support when choosing a language for their
projects.

You might also like