Kotlin Complete Tutorial by Shiva sir, Android Kotlin step by step?

3

What is Kotlin? 

Kotlin is a modern, statically-typed programming language developed by JetBrains, known for its conciseness, safety, and interoperability with Java. It's designed to be fully compatible with Java and runs on the Java Virtual Machine (JVM), making it a popular choice for Android app development, server-side applications, and more. Kotlin offers many features that improve productivity and code safety, such as null safety, extension functions, and a more expressive syntax.



Step-by-Step Guide to Install Kotlin on Windows

Step 1: Install Java Development Kit (JDK)

Kotlin runs on the JVM, so you'll need to install the Java Development Kit (JDK) first.


Download JDK:


Visit the Oracle JDK download page or AdoptOpenJDK (open-source version).

Choose the Windows version and download the installer.

Install JDK:

Run the downloaded installer.

Follow the on-screen instructions and complete the installation.

Set JAVA_HOME Environment Variable:

Open Control Panel > System and Security > System > Advanced system settings.

Click on Environment Variables.

Under System variables, click New.

Set Variable name as JAVA_HOME and Variable value as the path where JDK is installed (e.g., C:\Program Files\Java\jdk-11).

Click OK.

Add JDK to Path:


In the System variables section, find the Path variable and select it.

Click Edit, then New, and add %JAVA_HOME%\bin.

Click OK to save and close all dialog boxes.

Verify the Installation:


Open Command Prompt and type java -version and javac -version to verify the installation.


Step 2: Install an Integrated Development Environment (IDE)


Kotlin can be developed in several IDEs. The most popular one is IntelliJ IDEA by JetBrains.


Download IntelliJ IDEA:


Visit the IntelliJ IDEA download page.

Choose the Community edition (free) or the Ultimate edition (paid) and download the installer.

Install IntelliJ IDEA:


Run the downloaded installer.

Follow the on-screen instructions to complete the installation.

Step 3: Install Kotlin Plugin (If Needed)

IntelliJ IDEA comes with Kotlin support out of the box, but if you’re using another IDE, you may need to install the Kotlin plugin.


Open IntelliJ IDEA:


Launch IntelliJ IDEA.

Create a New Project:


Click on New Project.

Select Kotlin as the project type and choose Kotlin/JVM.

Follow the steps to create a new project.

Install Kotlin Plugin in Other IDEs:


If using Eclipse or another IDE, go to the IDE's plugin marketplace and search for Kotlin.

Install the Kotlin plugin and restart the IDE.

Step 4: Write and Run Your First Kotlin Program

Create a Kotlin File:


In IntelliJ IDEA, right-click on src > New > Kotlin File/Class.

Name your file Main.kt.

Write a Simple Program:


kotlin

Copy code

fun main() {

    println("Hello, Kotlin!")

}

Run the Program:


Right-click on the Main.kt file and select Run 'MainKt'.

You should see Hello, Kotlin! in the output console.

Congratulations, you've installed Kotlin and run your first program on Windows!

......................................................................................................................................................

How to declare variable in Kotlin?


In Kotlin, variables can be declared using the val and var keywords, depending on whether you want the variable to be immutable (unchangeable) or mutable (changeable).


1. val (Immutable Variable)

A variable declared with val cannot be reassigned once it is initialized. It’s similar to a final variable in Java.


kotlin

Copy code

val name: String = "John"

val age: Int = 30

val height = 5.9  // Type is inferred as Double

Type Inference: If you don’t specify the type, Kotlin can infer it based on the value you assign.

Example: The variable name is of type String, and age is of type Int.

2. var (Mutable Variable)

A variable declared with var can be reassigned to another value of the same type.


kotlin

Copy code

var name: String = "John"

name = "Doe"  // Reassignment is allowed


var age: Int = 30

age = 31  // Reassignment is allowed

3. Type Inference in Variable Declarations

You can declare variables without specifying their types explicitly. Kotlin will infer the type from the initializer expression.


kotlin

Copy code

val city = "New York"  // Type inferred as String

var temperature = 25.5  // Type inferred as Double

4. Declaring Variables Without Initialization

You can declare variables without initializing them immediately, but in this case, you must specify the type explicitly.


kotlin

Copy code

val name: String  // Type specified

name = "John"  // Initialized later


var age: Int

age = 30  // Initialized later

Examples:

kotlin

Copy code

val pi: Double = 3.14159  // Immutable variable with a specified type

var count = 10  // Mutable variable with inferred type

Program of addition:

..........................................................................

fun main()
{
var a=10
var b=200
var c = a+b
print("result is " + c)
}


Program of Addition using val

fun main()
{
val a:Int=10
// a=100 can not reassign
val b:Int=200
var c:Int = a+b
print("result is " + c)
}


Assignments:

Basic Program

WAP to calculate the difference of two dates in the year, a date should be assigned on DDMMYYYY 

12052016

13062019

o/p  2019-2016  3

WAP to calculate the sum of all digits in date of birth?

WAP to Convert feet to inch and inch to feet?

WAP to convert km to meter?

WAP to convert decimal to binary?

WAP to calculate basic, ta, da, comm, pf,  HRA, Leave, number of leave will be entered by the users?

WAP to display the middle number is a three-digit number?  a 145,154,451   

WAP to calculate Square and Cube of any assigned number?

WAP to calculate electricity bill where unit price, total consumption, the extra load will be entered by the users?

WAP to calculate Simple Interest where rate and time will be constant and the principal will be an integer?

WAP to calculate the area of a triangle, circle, and rectangle in the same program where the value of pi, the base of the triangle, and the height of the rectangle will be constant.

 WAP to convert temperature from  Celsius to Fahrenheit?

Data Type in Kotlin:

It is used to decide pattern and size of data in memory, Kotlin support primitive and modern data type both.


Kotlin provides a variety of data types that are similar to those found in other programming languages, with a few unique features. Here's a breakdown of the primary data types in Kotlin:


1. Basic Data Types

Numbers

Kotlin supports different types of numbers:


Integer Types:


Byte: 8-bit signed integer (-128 to 127)

Short: 16-bit signed integer (-32,768 to 32,767)

Int: 32-bit signed integer (-2^31 to 2^31-1)

Long: 64-bit signed integer (-2^63 to 2^63-1)

Example:


kotlin

Example

val byteValue: Byte = 127

val shortValue: Short = 32767

val intValue: Int = 2147483647

val longValue: Long = 9223372036854775807L

Floating-Point Types:


Float: 32-bit floating-point number

Double: 64-bit floating-point number

Example:


kotlin

Example

val floatValue: Float = 3.14F

val doubleValue: Double = 3.141592653589793

Boolean

Boolean: Represents true or false.


Example:


kotlin

Example

val isKotlinFun: Boolean = true

Character

Char: Represents a single 16-bit Unicode character.


Example:


kotlin

Example

val letter: Char = 'A'

String

String: Represents a sequence of characters.


Example:


kotlin

Example

val greeting: String = "Hello, Kotlin!"

Strings in Kotlin are immutable. You can also create multi-line strings using triple quotes """.


Example:


kotlin

Example

val multiLine: String = """

    This is a 

    multi-line 

    string.

"""

2. Arrays

Array: Represents a collection of elements of a specific type.


Example:


kotlin

Example

val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)

Kotlin also provides specialized classes for arrays of primitive types to avoid boxing overhead:


IntArray, ByteArray, ShortArray, LongArray, FloatArray, DoubleArray, BooleanArray, CharArray.

Example:


kotlin

Example

val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5)

3. Collections

Kotlin provides standard collection types, such as List, Set, and Map, which can be either mutable or immutable:


List: Ordered collection of elements.


List<T> (Immutable)

MutableList<T> (Mutable)

Example:


kotlin

Example

val immutableList: List<String> = listOf("Apple", "Banana", "Cherry")

val mutableList: MutableList<String> = mutableListOf("Apple", "Banana", "Cherry")

Set: Collection of unique elements.


Set<T> (Immutable)

MutableSet<T> (Mutable)

Example:


kotlin

Example

val immutableSet: Set<Int> = setOf(1, 2, 3)

val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)

Map: Collection of key-value pairs.


Map<K, V> (Immutable)

MutableMap<K, V> (Mutable)

Example:


kotlin

Example

val immutableMap: Map<String, Int> = mapOf("one" to 1, "two" to 2)

val mutableMap: MutableMap<String, Int> = mutableMapOf("one" to 1, "two" to 2)

4. Nullable Types

Kotlin has nullable types to help avoid null pointer exceptions. You can declare a nullable type by adding a ? to the type.


Example:


kotlin

Example

val nullableString: String? = null

You must handle nullability explicitly, which makes your code safer.


5. Unit

Unit: Represents the absence of a value. It's the return type of functions that don't return anything (similar to void in Java).


Example:


kotlin

Example

fun printMessage() : Unit {

    println("Hello, Kotlin!")

}

6. Nothing

Nothing: Represents a value that never exists, usually used in functions that throw exceptions or have infinite loops.


Example:


kotlin

Example

fun fail(message: String): Nothing {

    throw IllegalArgumentException(message)

}


What is Operator:

it is used to perform operation using operand, kotlin support all type of operator of java language

1) unary:  work on single operand

1) increment:  it increase by one

                       ++a

                        a++


fun main()
{
var a:Int = 10
var b:Int
b=++a;
println(-a);

println(b);
}

2) decrement: it decrease value by one

                      --a

                       a--

3) - operator:  it convert +ve value to -ve value

2) binary

3) ternary:


fun main() {
var a: Int = 10
var b: Int = 20
var s: String = if (a > b) "a is greater"
  else "b is greater";
println(s)
}

Conditional Block Level Statement:


it provide if block and else block to define true condition and false condition based program.

Type of Conditional Statement:


Simple If:  it execute when condition is true.


if(condition)

{

    statement;    



Write a program to check even|odd using simple if?


If--else:  it execute the program with separate block for true condition and false condition.


if(condition)

{

    Statement;

}

else

{

    Statement;

}


Write a program to check number is one digit or above one digit, number can be +ve or -ve;


Else if: it provide multiple else if block to check multiple condition based program.


if(condition)

{

    statement;

}

else if(condition)

{

    statement;

}

else if(condition)

{

     statement;

}

else

{

     statement;

}


Write a program to check middle number into three different numbers?


Nested If--else:


it contains more than one if--else statement using nested sequence , it contains outer if and outer else that contains more than one if--else block.


if(condition)

{

    if(condition)

    {


    }

    else

    {


     }

}

else

{

    if(condition)

    {


    }

    else

    {


     }


}


Multiple If:


it provide combination of If to solve multiple condition based program with multiple result.


if(condition)

{


}

if(condition)

{


}



Assignment:


IF--ELSE BASED PROGRAM:-


Q) WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed.


Q) WAP to display the subject mark of the student which will be entered by the user's if the entered subject mark is eligible for grace then display mark including grace mark otherwise actual mark will display.


1)  WAP to increase the Salary of an employee from 500 if the entered salary is less than 10000 otherwise increase by 800?


2) WAP to Check Leap Year? 


3) WAP to check number is positive or negative?


Q WAP to display "YES" and "NO" when the user press 'y' and 'n'?


12)  WAP  TO CHECK THAT USERNAME AND PASSWORD BOTH ARE CORRECT OR NOT WHERE USERNAME IS YOUR FIRST NAME AND PASSWORD YOUR LASTNAME?

PROVIDE SEPARATE MESSAGES FOR INVALID USERNAME, INVALID PASSWORD, INVALID USERNAME, AND PASSWORD?

WAP to check greatest using four different numbers?

WAP to check that entered number is one digit negative number or a positive number?

Q WAP to check divisibility of number from 3,5 and 9 with all combination?

WAP to check that entered input is numeric char or alphabet char?

Q WAP to display "YES" and "NO" when the user press 'y' and 'n'?


Q WAP to check the middle number in a three-digit number?


Q) WAP to check that entered char is vowel and consonant without using or operator?


Q) WAP to Calculate Marksheet using five different subjects with the following condition.

1) all subject marks should be 0 to 100.

2) if only one subject mark is <33 then the student will be suppl.

3) if all subject marks are >=33 then percentage and division should be calculated.

4) if a student is suppl then five bonus marks can be applied to be pass and the result will be "pass by grace".

5) Display Grace Subject name, distinction subject name,suppl subject name, and failed subject name.


Loop in kotlin:



It provide separate block level statement to define program code. 


Type of Loop:


1) Entry control loop:  First check condition then execute statement


for loop


for(i in start..end)

{

      Statement

}



while loop:


init;

while(condition)

{

    Statement;

    Increment;

}


2) Exit Control loop:  First execute loop block then check condition


do--while Loop:


init;

do

{

       Statement;

        increment;


}while(condition);



Write a program to calculate factorial of any number? (all)


WAP to display the table of numbers? (all)


WAP to display Fibonacci series? (all)



WAP to reverse any digit number? (while, do-while)


Write a program to print table of any number? (all)


Write a program to calculate sum of one digit no? (all)


Write a program to create lift process where lift will run from first floor to fifth floor and again fifth floor to first floor? (for)


Write a program to move the ball to five step up and five step down? (for)


Write a program to convert decimal to binary and binary to decimal? (while and do--while)






Post a Comment

3Comments

POST Answer of Questions and ASK to Doubt

  1. // wap to check year is leap year or not.
    un main(){
    var year=2004
    if ((year % 4==0 && year % 100 !=0) || ( year % 400 ==0) ){
    println("leap year")
    }else{
    println("not a leap")
    }
    }

    ReplyDelete
  2. //wap to reverse a five digit number where first and last digit will be in the same position.
    fun main(){
    var number = 12345
    val firstDigit = number / 10000
    val lastDigit = number % 10

    val middlePart = number % 10000 / 10

    val newNumber = (lastDigit * 10000) + middlePart * 10 + firstDigit

    println("Original number: $number")
    println("Reversed number: $newNumber")
    }















    ReplyDelete
  3. //wap to calculate the simple interest.
    fun main(){
    val principle = 10000
    val rate = 10
    val time = 2
    var si= principle * rate * time / 100
    println("Simple Interest"+ si)
    }

    ReplyDelete
Post a Comment