Techoceanhub logo

How to write HelloWorld program in kotlin-Chapter-3

In the previous blog, I wrote about val and var use and their differences. In this post, I am going to introduce you to the basic steps to write a program in Android with Kotlin. Just follow simple steps below:-

1)First, declare a string type variable. You can either use val or var for initializing your variable and keep in mind that if you are reinitializing a variable do not use val. write a simple line :-

                            var str=”Hello World” or

                            var str: String=”Hello World” or

                            val str=”Hello World” or

                            val str: String=”Hello World” 

2)In second step, you have to add the textView element in activity_main.xml like below and give a unique id

                              <TextView
                                 android:id=”@+id/textView”
                                 android:layout_width=”wrap_content”
                                 android:layout_height=”wrap_content”
                                 app:layout_constraintBottom_toBottomOf=”parent”
                                 app:layout_constraintLeft_toLeftOf=”parent”
                                 app:layout_constraintRight_toRightOf=”parent”
                                 app:layout_constraintTop_toTopOf=”parent” />

3)In the MainActivity.kt. we will initialize a textview using findViewById method like below:-

                       var textview=findViewById(R.id.textView) as TextView

4)In the last, you have to assign string value inside textview using text function.

                                 textview.text=str

5)You are done. Now just run your program. Below is a full code snippet for you to see.

package adapter.manasvi.com.simpleproject

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class HelloWorld : AppCompatActivity() {
val str:String="Hello World"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var textview=findViewById(R.id.textView) as TextView
textview.text=str
}
}

You will get an Output as “Hello World”.

Feel free to try this code and comment below.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .