Skip to main content

MORE-FUNDAMENTALS IN KOTLINE

 Arrays ------------------------->>

**************Creating an array :

val number:IntArray = intArrayOf(1,2,3,4)
val number: = intArrayOf(1,2,3,4)
val number = arrayOf(1,2,3,4)


**************For loop on arraya:

for(element in number){ // code containing element keyword , element refers to elements of number one by one from index 0 to last element for each cycle of loop}

example
var i =1
for( element in number ) {
    println(" increment of  $i th element of number array is ${element +1}")
}
    

**************Targeting element of array by index:

number[i] = element at (i+1)the index 
number[i] = 45 // will set value 45 at i+1 the position even if array is val

**************Printing Array :

println(number.contentToString())
for( keyword in arrayName) { // to operate on element level
    println(" element are ${keyword})
}

for( index in arrayName.indices){ // to operate on index level
    println("$index  ${arrayName[index]")
}


Lists -------------------------------------->>

can be resized
store objects / elements like array but still resizeable



Visibility Modifiers ------------------------------------------->>
decides visibility

Public :
    A public modified element is accessible from everywhere in the project
    It is a default modifier in Kotlin .
    Syntax ::
    public class Example {
    class Demo {
    }
    }
public fun hello()
fun demo ()
public val x = 5
val y = 10

Private :
    a private modifier allows the elemetn to be accessible only within block in which properties , fields ,etc. are declared .
    Teh private modifier declarartion does not allow access outside the scope
    A private package can be accessible within the specific file
Syntax :
    private class Example {
        private val x = 1
        private doSomething() {
            }
        }

Internal :
  1  Avaliable only in kotlin
  2  It makes field visible only inside the module in which it is implemented
  3  All the fields are declared as internal which are accessible only inside the module in which they are implemented

Syntax:
    internal class Example {
        internal val x =5
        internal fun getValue(){
   
            }    
        }

    internal val y = 10 


Open Keyword
    in kotlin all calasses re final by default , so they can't be inherited
    so we should use open keyword to make it inheritabel

Protected :

    allows visiblity to its class or subclass only.
    protected decleration in its subclass is also protected unless it is explicitly changed
    The Protected modifier Cannot be declared at top level
    Syntax:
    open class Base {
        protected val i = 0
    }
    

    class Derived : Base () {        

    fun getValue() : Int {
        return i 
    }
}


open class Base () {
    var a = 1 // public by default
    private var b = 2 // private to base class
    protected open val c = 3 // visible to the base and drived class
    internal val d =4 // visible inside the same module
    protected fun e () {} // visible to the base and the Derived class
}

class Derived : Base () {
    // a , c ,d and e() of the base class are visible
    // b is not visible
    override val c =9 // c is protected
}


fun main ( args : Array< string > ) {

val base = Base()
    // base.a and base.d are visible
    // base.b , base .c and base.e() are not visible
val derived = Derived ()
     // derived class c is not visible 

}


Nested class and inner class ------------------------------------------------>>

class in another class, key word inner is used 

class OuterClass {
    // outerclass code
    class NestedClass {
        // nested Class Code
        }
    }

advantage of inner class over nested class is that, it is able to access memebers of its outer class even it is private

class OuterClass {

    // outer class code
    inner class InnerClass { 

    // inner class code
    }
}

class OuterClass{
private var name: String = "Mr X"


class NestedClass {
var description: String = "Code inside nested class "
private var id : Int = 101
fun foo(){
// print("name is ${name}") // cannot acess the outer class member
println("Id is ${id}")

}
}

inner class InnerClass {
var description2: String = " code inside inner class "
private var id: Int = 101
fun foo(){
println("name is ${name}")// can acess the private outer class
println("Id is ${id}")
}
}
}

fun main( args: Array<String>){
//nested class must be initialized
println( OuterClass.NestedClass().description)// accessing property

var obj = OuterClass.NestedClass() // object creation
obj.foo()// acess member function

println(OuterClass().InnerClass().description2)// accessing property
var obj2 = OuterClass().InnerClass() // object creation
obj2.foo()// acess member function
}

The output is 

"Code inside nested class
 Id is 101
  code inside inner class
 name is Mr X
 Id is 101

 Process finished with exit code 0"


SAFE AND UNSAFE CAST OPERATOR:------------------------------------------------>>

 * A nullable string (String?) cannot be cast to non nullable string (String) , this throws an exception

fun main( args: Array<String>){
    val obj:Any? = null
    val str:String = obj as String
    println(str)

}


// output: exeption in thread main " kotlin Type Cast Exception : null cannot be cast to non-null type kotlin

* Trying to cast an integer value of the Any type inot a string type leads to a ClassCastException 

val obj: Any = 123
val str: String = obj as String

// Throws java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.string


    * Safe Cast operator : as?
     as? provides a safe cast operation to safely cast to a type 

    * It returns a null if casting is not possible rather than throwing an ClassCastException exception.

    val location : Any = "Kotlin"
    val SafeString: String? = location as? String
    val safeInt: Int? = location as? Int
    println(safeString)
    println(safeInt)

}

output
Kotlin
    null


EXCEPTION Handeling
    * An Exception is a runtime problem which occurs in the program and leads to program termination

1. running out of mem
2. array out of bound,
3. condition like divided by zero

 to handle such a exception we use techniques called exception handeling 

1. try : is a block contaning set of statment might generate exception
2. catch : catch the exception thrown from try block
3. finally : always get executed , to catch the exception from block
4. throw : to throw an error explicitly

Examples of unchecked exception :
1. Arithmetic Exception : thrown when we divide a number by zero
2. ArrayIndexOutOfBoundExecption: thrown when an array has been tried to access with incorrect index value
3. SecurityExecption: thrown by the security manager to indicate a security violation
4. NullPointerExecption: thrown when invoking a method or property on a null object

Checked E$xception
1.checked at compile time
2. This type extends the Throwable Class
example Ioe

tryCatch block
syntax 

val str = getNumber("10")// The variable 'str' is gettin the int value of "10"
println(str)

fun getNumber(str: String):Int{
    return try{
        // code that may throw the exception
    }catch ( e: ArithmeticException ){
        0
    } // output is 10

// if getNumber("10.5") is tead of "10" we will have output 0

***Multiple catch blocks
fun main (args:Array<String>){ 
    try{
        val a = IntArray(5)
        a[5] = 10/0
    }catch (e:ArithmeticException){
    println("Arethmetic Exception catch")
    }catch(e: ArrayOutOfBoundException){
    println("array index outofbound exception")
    }catch(e:Exception){
    println("parent exception class")
    }
    println("code after try catch....")
}

// Output will be
    arithmetic exception catch
    code after try-catch... 

     

*** Nested try-catch block 

..
try{
    // code block
        try{ // code block
    }catch(e:someException){
    //exception
    }

}catch(e:SomeException){
// final exception}


** finally block
fun main (args: Array<string>){
      try{     
            val data = 10/5
            println(data)
    }catch(e:NullPointException){
        println(e)
    }finally{
        println("finally block always executed")
    }
    println("below code...")
}

 

// output :
2
finally block always executes
below code....


*****The throw keyword
example

fun main(args: Array<string>){
    validate(15) // Another function
    println("code after validation check...")
}
fun validate (age:int){
    if(age<18){
        throw ArithmeticException("under age")
    }else{
    println("eligible for drive")
   

usefull additional informations :::::::::::::::::::::::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Interview Prep based on Kotlin lang

Comments