Tuesday, January 26, 2021

Java TreeMap Vs HashMap With Examples

1. Overview

In this tutorial, We will learn the core differences between TreeMap and HashMap classes with example programs.

If you are new to java programming, suggest to go through the below topics.

HashMap Examples

TreeMap Examples

In java, All Map implementations are to store the key-value pairs but there are few differences based on the implementations.

Java TreeMap Vs HashMap With Examples


HashMap is extensively used in the day to day development from the collection framework when compared to TreeMap. Both uses internally bucketing concept but when any bucket partition becomes large the it does convert into TreeNode Structure.

2. Similarities between HashMap and TreeMap

The below are the common things in both classes. Let us look into those before understanding the differences.

2.1 HashMap and TreeMap classes implement Map<K,V>, Cloneable, Serializable interfaces and extends AbstractMap<K,V> class.

2.2 Both stores the values based on the keys. Always key and value should be provided.

2.3 Always key should be unique and if we add the same key again then old value will be replaced with the new value.

2.4 These are not synchronized.

2.5 Not thread-safe because if the original Map is modified during the iteration then it cause to throw runtime exception ConcurrentModificationException.

3. HashMap Examples

In the below example, we added few values to HashMap using put() method. Next, printed the all the values of HashMap.

Further tried to print the values using iterator and deleted the key "0333" from the original hashmap.

Removal key from hashmap produces the runtime exception.

package com.javaprogramto.collections.hashmap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExamples {

	public static void main(String[] args) {

		Map<String, String> hashMap = new HashMap<>();

		hashMap.put("0111", "one's");
		hashMap.put("0222", "two's");
		hashMap.put("0333", "three's");
		hashMap.put("0444", "four's");
		hashMap.put("0111", "one's modified");

		System.out.println("HashMap values are - " + hashMap);

		System.out.println("Iterating Hashmap and modifying the values");

		Set<String> keys = hashMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + hashMap.get(key));
			if (key == "0333") {
				hashMap.remove(key);
			}
		}

	}

}


Output:


HashMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating Hashmap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1490)
	at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1513)
	at com.javaprogramto.collections.hashmap.HashMapExamples.main(HashMapExamples.java:29)


4. TreeMap Examples

In the below example, we added few values to TreeMap using put() method. Next, printed the all the values of TreeMap in sorted order.

Further tried to print the values using iterator and deleted the key "0333" from the original treemap.

Removal key from treemap produces the runtime exception.

package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapExamples {

	public static void main(String[] args) {

		Map<String, String> treeMap = new TreeMap<>();

		treeMap.put("0111", "one's");
		treeMap.put("0222", "two's");
		treeMap.put("0333", "three's");
		treeMap.put("0444", "four's");
		treeMap.put("0111", "one's modified");

		System.out.println("treeMap values are - " + treeMap);

		System.out.println("Iterating treeMap and modifying the values");

		Set<String> keys = treeMap.keySet();

		Iterator<String> iterator = keys.iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			System.out.println("key - " + key + ", value - " + treeMap.get(key));
			if (key == "0333") {
				treeMap.remove(key);
			}
		}

	}
}


Output:


treeMap values are - {0111=one's modified, 0222=two's, 0333=three's, 0444=four's}
Iterating treeMap and modifying the values
key - 0111, value - one's modified
key - 0222, value - two's
key - 0333, value - three's
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1208)
	at java.base/java.util.TreeMap$KeyIterator.next(TreeMap.java:1262)
	at com.javaprogramto.collections.treemap.TreeMapExamples.main(TreeMapExamples.java:29)

5. Differences between HashMap and TreeMap

The below are the main differences between these two maps.

5.1 TreeMap implements the NavigableMap interfaces rather than Map interface.

5.2 HashMap is implemented based on the hashtable

     TreeMap is implemented based on Tree Structured based map such as Red Black Tree which is a balanced.

5.3 HashMap allows only one null key and multiple null values.

      TreeMap does not allow null key but allows null values.

5.4 HashMap does not sort the keys where as TreeMap does sort the keys.

5.5 HashMap is faster then TreeMap because hashmap does not sort so it provides easy access to insertion and retrieval with constant time O(1) with put() and get() methods.

5.6 HashMap uses the equals() method for duplicate keys comparison but for TreeMap, keys are compared and sorted based on the compareTo() method. So, key must implement the Comparator or Comparable interface else will get the runtime error.

6. Conclusion

In this article, We've seen the first example programs on HashMap and TreeMap classes and next similarities and differences between HashMap and TreeMap.

GitHub HashMap

GitHub TreeMap

Java 8 Stream map() and filter() methods

Java Arrays.setAll() Examples To Modify Existing Array

1. Overview

In this article, You'll learn how to use JDK 1.8 Arrays.setAll() method to modify the existing values of the array with a unique generator function. Arrays class is part of java.util package.

This method sets all elements of the specified array, using the provided generator function to compute each element.

In the previous article, We've seen how to set the whole array with the same value using Arrays.fill() method?

Java Arrays.setAll() Examples

Saturday, January 23, 2021

Java LocalDate atStartOfDay() Example

1. Overview

In this tutorial, We'll learn how to use LocalDate.atStartOfDay() method in java 8. This is the newly added method in Date Time API in java 8.

atStartOfDay() method does appends the might night date with time part as 00:00 to LocalDate.

This is an overloaded method and available in two versions as below. 

public LocalDateTime atStartOfDay()

public ZonedDateTime atStartOfDay(ZoneId zone)


public LocalDateTime atStartOfDay(): This method appends the mid night to the LocalDate and returns it as LocalDateTime object with time default values as zero's.

public ZonedDateTime atStartOfDay(ZoneId zone): This method takes ZoneId instance for time zone value and converts the LocalDate to ZonedDateTime by adding the time part as zero's.

Let us explore the examples on these two methods with examples.

Java LocalDate atStartOfDay() Example



But, you need to remember one core point is that LocalDate does not store the time part but to convert it to LocalDateTime, we need to add time part. This adding the time part is done with atStartOfDay() method.


2. Java 8 LocalDate.atStartOfDay() - LocalDate to LocalDateTime


Understand the example program using atStartOfDay() method with zero parameters to convert localdate to LocalDateTime object to mid night and adding time units with default values as 0.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * Example for public LocalDateTime atStartOfDay() method in LocalDate class in
 * java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayExamples {

	public static void main(String[] args) {
		// Example 1

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime1 = localDate1.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("localDateTime1 : " + localDateTime1);

		// Example 2

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// converting LocalDate object to LocalDateTime object
		LocalDateTime localDateTime2 = localDate2.atStartOfDay();

		// printing the LocalDate, LocalDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("localDateTime2 : " + localDateTime2);
	}
}

Output:
localDate1 : 2020-12-07
localDateTime1 : 2020-12-07T00:00
localDate2 : 2023-02-02
localDateTime2 : 2023-02-02T00:00

3. Java 8 LocalDate.atStartOfDay(ZoneId z) - LocalDate to ZonedDateTime


Next, example on how to convert LocalDate to ZonedLocalDate in java 8 with atStartOfDay() method that takes ZoneId as argument.

This method also works by adding time units as zero but it converts the date part as per the given timezone id.

In the below example, we have tried with the system timezone, Singapore and EST time zone dates.

package com.javaprogramto.java8.dates.localdate;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Example for public ZonedDateTime atStartOfDay(ZoneId zoneid) method in
 * LocalDate class in java 8.
 * 
 * @author JavaProgramTo.com
 *
 */

public class LocalDateAtStartOfDayZoneIdExamples {

	public static void main(String[] args) {
		// Example 1 - IST

		// creating LocalDate object
		LocalDate localDate1 = LocalDate.now();

		// Getting the default timezone from system.
		ZoneId defaultId = ZoneId.systemDefault();

		// converting LocalDate object to ZonedDateTime object using timezone.
		ZonedDateTime zonedDateTime1 = localDate1.atStartOfDay(defaultId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate1 : " + localDate1);
		System.out.println("zonedDateTime1 : " + zonedDateTime1);

		// Example 2 - EST

		// creating LocalDate object
		LocalDate localDate2 = LocalDate.of(2023, 02, 02);

		// Getting the EST timezone from system.
		ZoneId timezoneESTId = ZoneId.of("US/Eastern");

		// converting LocalDate object to ZonedDateTime object using est zone id;
		ZonedDateTime zonedDateTime2 = localDate2.atStartOfDay(timezoneESTId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate2 : " + localDate2);
		System.out.println("zonedDateTime2 : " + zonedDateTime2);

		// Example 2 - Singapore

		// creating LocalDate object
		LocalDate localDate3 = LocalDate.of(2023, 02, 02);

		// Getting the Asia/Singapore timezone from system.
		ZoneId timezoneSingaporeId = ZoneId.of("Asia/Singapore");

		// converting LocalDate object to ZonedDateTime object using Asia/Singapore zone id;
		ZonedDateTime zonedDateTime3 = localDate3.atStartOfDay(timezoneSingaporeId);

		// printing the LocalDate, ZonedDateTime objects
		System.out.println("localDate3 : " + localDate3);
		System.out.println("zonedDateTime3 : " + zonedDateTime3);
	}
}
Output:
localDate1 : 2020-12-07
zonedDateTime1 : 2020-12-07T00:00+05:30[Asia/Kolkata]
localDate2 : 2023-02-02
zonedDateTime2 : 2023-02-02T00:00-05:00[US/Eastern]
localDate3 : 2023-02-02
zonedDateTime3 : 2023-02-02T00:00+08:00[Asia/Singapore]
From the output, We can see that timezone is added in the returned ZonedDateTime object and time units are 00:00 values.


4. Conclusion


In this article, we've seen how to use LocalDate.atStartOfDay() method with examples to convert LocalDate object to LocalDateTime and ZoneDateTime objects in java 8.


Friday, January 22, 2021

How To Iterate or Traverse TreeMap In Reverse Order in Java?

1. Overview

In this tutorial, We will learn how to traverse and print the values of the TreeMap in the reverse order in java?

By default, TreeMap sorts the objects added to it in ascending order. But, now we want to print the values are in reverse order that means in the descending order. 

In the previous article, we have seen how to traverse TreeMap in natural order in java 8?

This can be done using the following in 3 ways.

1) Collections.reverseOrder()
2) TreeMap.descendingkeySet()
3) TreeMap.descendingMap()

How To Iterate or Traverse TreaMap In Reverse Order in Java?


2. TreeMap Reverse Traverse - Collections.reverseOrder()


First, let us learn the simple and easy one to understand the reversing and accessing the values from TreeMap.

When we create the TreeMap object, we just need to pass the Collections.reverseOrder() to the TreeMap constructor. Collections.reverseOrder() method indicates to TreeMap sort the keys based on the reverse order that is descending order.

The below example is based on the Collections.reverseOrder() method.

package com.javaprogramto.collections.treemap;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReverseTraversalExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with reverse comparator using Collections.reverseOrder()
		Map<String, Integer> studentsCountMap = new TreeMap<>(Collections.reverseOrder());
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method which returns the keys in the reverse order
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:

See how the order of the output is printed in the reverse order.

Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

3. TreeMap Reverse Traverse - Collections. descendingkeySet()


The above method works only when we have control over creating the TreeMap instance otherwise need to follow the new method as below.

There are some scenarios where the TreeMap is created by another api or library that TreeMap object you are getting into your code.

In such cases, TreeMap has another method descendingkeySet() to get the keys in the descending order which is contrary to the natural order.

But, First need to get the keys in descending order and next get the value from map again with get() method.
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapReversedescendingkeySetExample {

	public static void main(String[] args) {
		
		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting all keys as Set object using descendingKeySet()
		Set<String> keysSet = studentsCountMap.descendingKeySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator which retrieves the values in the reverse order.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}
	}
}

Output:
Key - 5nd class, Value - 500
Key - 4nd class, Value - 400
Key - 3nd class, Value - 300
Key - 2nd class, Value - 200
Key - 1nd class, Value - 100

4. TreeMap Reverse Traverse - Collections. descendingMap()


Finally, TreeMap has another useful method to get the Map in descending order with descendingMap().

Next, iterate returned map with java 8 forEach() method to print the key-values

import java.util.Map;
import java.util.TreeMap;

public class TreeMapReversedescendingkeymapExample {

	public static void main(String[] args) {

		// Creating the TreeMap object with default constructor
		TreeMap<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Getting all keys as Set object using descendingKeySet()
		Map<String, Integer> map = studentsCountMap.descendingMap();

		map.forEach((key, value) -> System.out.println("Key - " + key + ", Value - " + value));
	}
}

5. Conclusion


In this article, we have explored the different ways to traverse the TreeMap in the reverse order.


Wednesday, January 20, 2021

How To Iterate TreeMap in older Java and new Java 8? Or How to iterate over each entry in a Java Map?

1. Overview

In this tutorial, We will learn how to iterate the map in older java versions and examples in java 8.

And alos let us explore how to iterate the keys of TreeMap sorted that means in the ascending order.

TreeMap can be used where we want the map sorted based on the key by default in the ascending or descending order use cases.

java 8 TreeMap Iterate Examples


2. Example to Iterate the TreeMap before JDK 8


In the below code we have created the TreeMap object and added few key value pairs. Here key is the type String and Value is type of Integer.


package com.javaprogramto.collections.treemap;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapIterate {

	public static void main(String[] args) {
		
		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();
		
		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);
		
		// Getting the Set object using keySet() method
		Set<String> keysSet = studentsCountMap.keySet();
		
		// Getting the iterator object
		Iterator<String > it = keysSet.iterator();
		
		// Iterating the map using regular method of iterator.
		while (it.hasNext()) {
			String key = it.next();
			System.out.println("Key - "+key+", Value - "+studentsCountMap.get(key));
		}

	}

}

Output:

Key - 1nd class, Value - 100
Key - 2nd class, Value - 200
Key - 3nd class, Value - 300
Key - 4nd class, Value - 400
Key - 5nd class, Value - 500

In the above program, we have first got the all the keys of treemap using keySet() method and next used the iterator() method to get the Iterator instance.

Finally, used the traditional iterate method workflow to get the each key from iterator and passed the key to treemap to get the value of the corresponding key.

3. Java 8 Lamdba Foreach TreeMap


Next, Look at the below program to get the keys and values of TreeMap using Java 8 Lambda expressions with forEach() method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// Java 8 lambda foreach
		studentsCountMap.forEach((key, value) -> {
			System.out.println("Key - " + key + ", Value - " + value);
		});
	}
}

This ways also produces the same output as seen in the above section. This is the simplified version in java 8 and it internally uses the BiConsumer functional interface.


4. Java 8 Stream Foreach TreeMap EntrySet


Finally, explore the java 8 stream construct to get the Entry object from stream and pass it to forEach method.

package com.javaprogramto.collections.treemap;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapIterateJava8 {

	public static void main(String[] args) {

		// Creating the TreeMap object
		Map<String, Integer> studentsCountMap = new TreeMap<>();

		// Adding students class and no of students in the class
		studentsCountMap.put("2nd class", 200);
		studentsCountMap.put("1nd class", 100);
		studentsCountMap.put("4nd class", 400);
		studentsCountMap.put("5nd class", 500);
		studentsCountMap.put("3nd class", 300);

		// java 8 Stream entry forEach
		studentsCountMap.entrySet().stream().forEach(
				entry -> System.out.println("entry key - " + entry.getKey() + ", entry value - " + entry.getValue()));
	}
}


Output:
entry key - 1nd class, entry value - 100
entry key - 2nd class, entry value - 200
entry key - 3nd class, entry value - 300
entry key - 4nd class, entry value - 400
entry key - 5nd class, entry value - 500

5. Conclusion


In this article, We have seen how to iterate the TreeMap in older and new JDK versions with examples.





Thursday, January 7, 2021

How To Convert String to Float in Kotlin?

1. Overview

In this tutorial, We will learn how to convert the String value to Float in Kotlin. This conversion is done using toFloat() method of String class.

But there are many cases where it gives parsing errors for wrong inputs.

How To Convert String to Float in Kotlin?


2. Kotlin String to Float using toFloat() Method

Converting string to float is done with toFloat() method of string class.

toFloat() method is to parse the String value into Float. If the string is not a valid form of a number or any non-number presents then it throws NumberFormatException.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String<) {

    var str : String = "12345.678"
    var float1 : Float = str.toFloat();
    println("string to float - float1 $float1")

    var str2 : String = "A123"
    var float2 : Float = str2.toFloat();
    println("string to float - float2 $float2")
    
}


Output:


string to float - float1 12345.678
Exception in thread "main" java.lang.NumberFormatException: For input string: "A123"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.base/java.lang.Float.parseFloat(Float.java:461)
	at com.javaprogramto.kotlin.conversions.StringToFloatExampleKt.main(StringToFloatExample.kt:10)


3. Kotlin String to Float using toFloatOrNull() Method

Next, use the another method for string to float conversion if the input string is not a valid number.

Call toFloatOrNull() method to get the null value if the string is having at least one non-digit.

Method toFloatOrNull() will convert String to Float.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String>) {

    var str : String = "456.75F"
    var float3 = str.toFloatOrNull();
    println("string to float - float3 $float3")

    var str2 : String = "PI3.14"
    var float4 = str2.toFloatOrNull();
    println("string to float - float4 $float4")
}


Output:

string to float - float3 456.75
string to float - float4 null


Note: When you are calling the toFloatOrNull() method, you should not specify the type to hold the value like var float3 : Float = str.toFloatOrNull(). This will give the compile error "Kotlin: Type mismatch: inferred type is Float? but Float was expected"


4. Conclusion

In this article, We've seen how to convert the string values into Float in Kotlin. And also how to handle if the string is containing the characters other than numbers.

GitHub

Kotlin Ternary Operator


Wednesday, January 6, 2021

Kotlin Variables and Basic Types With Examples - Kotlin Tutorial

1. Overview

In this tutorial, We will learn how to create the variables in Koltin for basic types using var.

var is a keyword in kotlin which is used to declare the any type of variable.

Kotlin has another keyword "val" to declare the variables.

Any variable is declared using var that value can be changed at anytime whereas variable declared with val keyword value can not modified one it is initialized.

Mainly val is used to define the constants in kotlin.

Kotlin Variables and Basic Types



2. Variable var examples


var keyword is used in the variable declaration. When you are using var keyword, that indicates the value can be changed at any time and the variable type is optional. If we are not provided the type then it takes the type implicitly based on the value assigned.

Syntax:

var <variable-name> : <variable-type-optional> = value;

Examples:

Below are the few examples on with and without variable type.

First created a double variable with var keyword with 3.14 value. Next used only var and did not mention any type but assigned the value. So it takes it as double internally because value is double type.

Additionally, created a variable with string content and not mentioned its type. But, kotlin has the intelligence to inspect the value and assign the right type.

if you call the welcome.toUpperCase() method, it does not throw any error. because it knows that object is type of String. So, We can use all methods from String class.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // double type
    var pi : Double = 3.14
    println("Double PI value $pi")

    // without type but it takes the double type internally based on the value
    var doubleValue = 3.14;
    println("Default type double $doubleValue")

    // Without type but it takes as String type from assigned value
    var welcome = "hello world"
    println("string welcome note $welcome")

    var str : String = "i am string"
    println("string type note $str")
}

Output:
Double PI value 3.14
Default type double : doubleValue
string welcome note hello world
string type note i am string

3. val Variable Examples


val is an another keyword in koltin and it is alos used to declare the variables.

Let us create a variable and try to change the value to new one using var and val variables.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {

    // int type varaible with var keyword
    var number: Int = 12345;
    println("old value of number : $number")
    number = 10000
    println("new value of number : $number")

    // int type variable with val keyword
    val highestMark: Int = 99;
    println("old value of highestMark : $number")
    highestMark = 98
    println("new value of highestMark : $number")
}


Output:
Kotlin: Val cannot be reassigned

It will produce the compile time error saying value can not be reassigned for val type variable.

So, val keyword is only to declare the constant values because it will not allow to change the value.

4. Difference between var and val


The main difference between the val and var keywords - is var type variables values can be modified and reassigned with the new values but val type variables can not be reassigned with the new values.

5. Assigning the large numbers to variables


When you are using the kotlin in the real time applications, there will be a need to hold the credit card or debit card numbers and phone numbers. 

var creditCardNumber : Long = 4320123456782468;

The above number is not readable but it holds the actual value. To make the numbers more readable, we can use the underscore(_) delimiter in between the numbers.

We can use the underscore for any numbers even it is good to use for currency values or time values.

but when you print or use for different operations, it does not print or get error because of underscore usage. It removes the underscore while performing any mathematical operations. This delimiter just makes the data readable form.

Look the below example for better understanding.

package com.javaprogramto.kotlin.variables

fun main(args: Array<String>) {
    // long numbers with underscore for readable

    var creditCardNumber: Long = 4320_3456_9808_4389
    var debitCardNumber = 1234_45678_1234_9876L
    var timeInMilliSeconds = 60_000

    // printing
    println("Credit card number : $creditCardNumber")
    println("Debit card number : $debitCardNumber")
    println("Time in milli seconds : $timeInMilliSeconds")
}

Output:

Credit card number : 4320345698084389
Debit card number : 12344567812349876
Time in milli seconds : 60000

6. Kotlin Variable With Null Values - Null Safe (?)


As of now, we have seen the variable declaration and its initialization in single line. But now you want to do only the declaration with null value.

Now, how can we create a variable with null value in kotlin?

Use the ? symbol at the end of the variable declaration to assign with null value. Look at the below syntax.

val/var <variable-name> : <variable-type-optional> ?;

Sample example program to show variable nullable.

 // declaring a variable with the null
 val noValue : String?

 // assigning value
 noValue = "assigned value"

 // printing the value
 println("novalue is now : $noValue")

Output:

novalue is now : assigned value


Note: We can not use the null variable without initializing to a value. It show the compile time error "Kotlin: Variable 'noValue' must be initialized"

7. Type Conversions


Next, let us focus on the type conversions in kotlin.

We will try to convert Int to Long value without any casting. Just assign the Int variable to Long variable.

var number1 : Int = 10;
var number2 : Long = 12345678;

// compile time error : Kotlin: Type mismatch: inferred type is Int but Long was expected
// number2 = number1;

// right conversion
number2 = number1.toLong();
println("number 2 : $number2")

Output:

number 2 : 10

In the above program first directly assigned the int value to the long value but it give compile time error.

Kotlin does not support the direct assignment conversions when the type is mentioned in the declaration. Use toLong() method to do the explicit conversion from Int to Long. This is the process to convert from any type to any type in kotlin.

If the type is not mentioned in the declaration then it is allowed for direct assignment conversion.

var number3 = 10;
var number4= 12345678;

// no compile time error
 number4 = number3;

println("number4 : $number4")

Output:

number4 : 10

Type conversion with nullable type:

When you are using the nullable value type (?) in the declaration then you must use always the variable usage.

Use the null safe(?) operator when calling methods on the variable otherwise will get the compile time error.

// variable with null type and value assignment
var number5 : Int? = 100
var number6 : Long? = 200

// compile time error - Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int?
// number6 = number5.toLong()

// no error with null safe
number6 = number5?.toLong();

println("number 6 : $number6")

Output:

number 6 : 100

8. Kotlin Basic Types 


Kotlin has the basic type supports as similar to the Java.

  • Numbers
                Byte
                Short
                Int
                Long
                Float
                Double
  • Char
  • Boolean
  • Array

let us explore the different examples on how to create the numbers, characters, booleans and arrays type variables in kotlin.

// Numbers
// Byte : range -128 to 127
var byteVar: Byte = 100
println("Byte variable : $byteVar")

// Short : range -32768 to 32767
var shortVar: Short = -1000
println("Short variable : $shortVar")

// Int : range -2^31 to 2^31-1
var intVar: Int = 12345
println("Int variable : $intVar")

// Long : range -2^63 to 2^63-1
var longVar: Long = 12345678900
println("Long variable : $longVar")

// Float : single precision 32 bit float point
var floatVar: Float = 123.4F // F is mandatory at end else compile time error
println("Float variable : $floatVar")

// Double : precision 64 bit floating value
var doubleVar: Double = 1234.56
println("Double variable : $doubleVar")


// Characters
// Char
var charVar: Char = 'A'
println("Char variable : $charVar")

// Boolean - this takes only two values - true/false
var booleanVar: Boolean = true
println("Boolean variable : $booleanVar")

var booleanVarFalse: Boolean = false
println("Boolean variable false : $booleanVarFalse")

// Arrays
// implicit type declaration
var array1  = listOf(1,2,3,4,5)

// explcit type declaration
var array2  = listOf<Long>(1,2,3,4,5)

Output:
Byte variable : 100
Short variable : -1000
Int variable : 12345
Long variable : 12345678900
Float variable : 123.4
Double variable : 1234.56
Char variable : A
Boolean variable : true
Boolean variable false : false

9. Conclusion


In this tutorial, we have seen how declare the variables example programs and other interesting stuff for kotlin programmers.