Char and Boolean Data Types in Java and Kotlin with Examples
Table of Contents
Introduction
Char and Boolean are fundamental data types used for representing characters and logical values. Both Java and Kotlin support these types with small but important differences in syntax and safety.
1. Char Data Type
The Char data type is used to store a single Unicode character such as letters, digits, or symbols.
- Memory Size: 16 bits
- Represents Unicode characters
- Written using single quotes (
'A')
Char Example Overview
| Feature | Java | Kotlin |
|---|---|---|
| Keyword | char | Char |
| Unicode Support | Yes | Yes |
| Numeric Operations | Allowed | Not Allowed |
Kotlin Example
val letter: Char = 'A'
println(letter)
Java Example
char letter = 'A';
System.out.println(letter);
2. Boolean Data Type
The Boolean data type is used to store true or false values. It is commonly used in conditions, loops, and decision-making logic.
- Possible Values: true or false
- Used in conditional statements
- Essential for control flow
Boolean Example Overview
| Feature | Java | Kotlin |
|---|---|---|
| Keyword | boolean | Boolean |
| Primitive Type | Yes | No (handled internally) |
| Null Safety | No | Yes |
Kotlin Example
val isActive: Boolean = true
if (isActive) {
println("User is active")
}
Java Example
boolean isActive = true;
if (isActive) {
System.out.println("User is active");
}
Java vs Kotlin – Char & Boolean Differences
| Aspect | Java | Kotlin |
|---|---|---|
| Char Arithmetic | Allowed | Not Allowed |
| Boolean Null Safety | No | Yes |
| Primitive Types | Yes | No (optimized internally) |
| Type Safety | Medium | High |
Example Difference
// Kotlin (Not Allowed)
val c: Char = 'A'
val num: Int = c
// Java (Allowed)
char c = 'A';
int num = c;
Interview Questions & Answers
Q1. What is the size of Char data type?
Answer: 16 bits in both Java and Kotlin.
Q2. Can Char be used as a number?
Answer: Yes in Java, but not in Kotlin.
Q3. What values can Boolean hold?
Answer: Only true or false.
Q4. Why is Kotlin Boolean safer?
Answer: Kotlin provides null safety and strict type checking.
Conclusion
Char and Boolean data types play a critical role in representing characters and logical decisions. Kotlin enhances these types by enforcing stronger type safety and preventing unintended conversions.
Comments
Post a Comment