You are here
Home > Kotlin

Kotlin Arrays and Strings

kotlin Arrays and Strings

Kotlin Arrays and Strings

In this Post we will discuss how to get input from user, Strings, Array with example.

To get input from User

  • Sometimes it is necessary to get input from user like to fill user registration form, allow user to login etc.
  • For getting input from user in kotlin we use readLine() function. It accept input in string format because kotlin main function take argument in string so for integer and any other data type we have to explicitly convert string input in to given data type for that use wrapper class.

Example:

fun main(args: Array<String>)

{
print(“Enter name:”);
var name= readLine();
print(“Enter age:”);
var age:Int= readLine()!!.toInt();
print(“Enter email:”);
var email= readLine();
println(“***OUTPUT**”)
println(“Name=”+name);
println(“Age=”+age);
println(“Email=”+email);
}

output:

Explanantion:

In above example we take user name, age ,email using readLine() function. Here We have age in interger and kotlin accept input in string so use to toInt() wrapper Class to convert it into integer.

Strings

  • In kotlin strings are created using double and triple quotes. Same as java in kotlin strings are immutable means we cannot change its value.
  • If we declare sting using double quotes then we can create a escaped, like new line.
  • Using triple quotes, we create a raw sting. In this no escape is not necessary.

Example:

fun main(args:Array<String>) {
var s1 = “Hello \n Kotlin”;
println(“Double quotes string=” + s1);
var s2 = “”” Raw string”””;
println(“Raw string=” + s2);
}

output:

Arrays

  • For creating array in kotlin we use arrayOf() and Array() functions.

Syntax of arrayOf():

arrayOf(ele1,ele2,…);

Syntax of Array():

Array<data_type>(size){initial_value};

  • When we use Array() function for creating array we can specify its size and initial value

Example:

fun main(args:Array<String>)
{
val a= arrayOf(“Hello”,”Kotlin”,”Java”);
println(“Array using arrayof”);
for(b in a)
{
println(b);
}
val arr=Array<String>(3){“Kotlin”};
println(“Before element intialize”);
for(e in arr)
{
println(e);
}
arr[0]=”Hi”;
arr[1]=”How”;
arr[2]=”Are you???”
println(“After element intialize”);
for(e in arr)
{
println(e);
}
}

output:

Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info.

 

You can also by SQL 70-761 book write by me from Amazon.

You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Leave a Reply

Top