Introduction
1. What is Kotlin?
Kotlin is a modern programming language mainly used for Android app development.
It is simple, safe, and works with Java.
Simple Kotlin Program
fun main() {
println("Hello Kotlin")
}Output
Hello KotlinExplanation
| Code | Meaning |
|---|---|
fun | Used to create a function |
main() | Starting point of a Kotlin program |
println() | Prints output on the screen |
2. Kotlin Features
Kotlin has many useful features.
| Feature | Simple Meaning |
|---|---|
| Concise code | Less code compared to Java |
| Null safety | Helps avoid null pointer crash |
| Type inference | Kotlin detects data type automatically |
| Java interoperability | Kotlin can use Java code |
| Data classes | Easy way to create model classes |
| Extension functions | Add new functions to existing classes |
| Coroutines | Used for background tasks |
| Smart cast | Kotlin automatically converts checked types |
Example: Kotlin is Concise
Java Code
String name = "Mahesh";
System.out.println(name);Kotlin Code
val name = "Mahesh"
println(name)Simple meaning:
Kotlin does the same work with fewer lines and cleaner syntax.
3. Kotlin vs Java
| Point | Java | Kotlin |
|---|---|---|
| Code length | More code | Less code |
| Null safety | Manual handling | Built-in null safety |
| Semicolon | Usually used | Not required |
| Variables | final, normal variable | val, var |
| Data class | Need constructor, getter, setter | One line |
| Android support | Supported | Preferred |
| Functional features | Limited | Strong support |
| Coroutines | Not built-in | Easy support |
Example: Model Class
Java
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}Kotlin
data class User(
val name: String,
val age: Int
)Simple meaning:
Kotlin removes boilerplate code like constructor, getter, and setter.