Author: Saim Khalid

  • Arrays

    Arrays are used to store multiple items of the same data-type in a single variable, such as an integer or string under a single variable name.

    For example, if we need to store names of 1000 employees, then instead of creating 1000 different string variables, we can simply define an array of string whose capacity will be 1000.

    Like any other modern programming languages, Kotlin also supports arrays and provide a wide range of array properties and support functions to manipulate arrays.

    Creating Arrays in Kotlin

    To create an array in Kotlin, we use the arrayOf() function, and place the values in a comma-separated list inside it:

    val fruits =arrayOf("Apple","Mango","Banana","Orange")

    Optionally we can provide a data type as follows:

    val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")

    Alternatively, the arrayOfNulls() function can be used to create an array of a given size filled with null elements.

    Primitive type Arrays

    Kotlin also has some built-in factory methods to create arrays of primitive data types. For example, the factory method to create an integer array is:

    val num =intArrayOf(1,2,3,4)

    Other factory methods available for creating arrays:

    • byteArrayOf()
    • charArrayOf()
    • shortArrayOf()
    • longArrayOf()

    Get and Set the Elements of an Array

    We can access an array element by using the index number inside square brackets. Kotlin array index starts with zero (0). So if you want to access 4th element of the array then you will need to give 3 as the index.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println( fruits [0])println( fruits [3])}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Orange
    

    Kotlin also provides get() and set() member functions to get and set the value at a particular index. Check the following example:

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println( fruits.get(0))println( fruits.get(3))// Set the value at 3rd index
       fruits.set(3,"Guava")println( fruits.get(3))}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Orange
    Guava
    

    Kotlin Array Length

    Kotlin provides array property called size which returns the size i.e. length of the array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")println("Size of fruits array "+ fruits.size )}

    When you run the above Kotlin program, it will generate the following output:

    Size of fruits array 4
    

    We can also use count() member function to get the size of the array.

    Loop Through an Array

    We can use for loop to loop through an array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")for( item in fruits ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Mango
    Banana
    Orange
    

    Check if an Element Exists

    We can use the in operator alongwith if…else to check if an element exists in an array.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange")if("Mango"in fruits){println("Mango exists in fruits")}else{println("Mango does not exist in fruits")}}

    When you run the above Kotlin program, it will generate the following output:

    Mango exists in fruits
    

    Distinct Values from Array

    Kotlin allows to store duplicate values in an array, but same time you can get a set of distinct values stored in the array using distinct() member function.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange","Apple")val distinct = fruits.distinct()for( item in distinct ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Apple
    Mango
    Banana
    Orange
    

    Dropping Elements from Array

    We can use drop() or dropLast() member functions to drop elements from the beginning or from the last respectively.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>("Apple","Mango","Banana","Orange","Apple")val result = fruits.drop(2)// drops first two elements.for( item in result ){println( item )}}

    When you run the above Kotlin program, it will generate the following output:

    Banana
    Orange
    Apple
    

    Checking an Empty Array

    We can use isEmpty() member function to check if an array is empty or not. This function returns true if the array is empty.

    Example

    funmain(args: Array<String>){val fruits = arrayOf<String>()println("Array is empty : "+ fruits.isEmpty())}

    When you run the above Kotlin program, it will generate the following output:

    "Array is empty : true
    
  • Data Types

    In the Go programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

    The types in Go can be classified as follows −

    Sr.No.Types and Description
    1Boolean typesThey are boolean types and consists of the two predefined constants: (a) true (b) false
    2Numeric typesThey are again arithmetic types and they represents a) integer types or b) floating point values throughout the program.
    3String typesA string type represents the set of string values. Its value is a sequence of bytes. Strings are immutable types that is once created, it is not possible to change the contents of a string. The predeclared string type is string.
    4Derived typesThey include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types f) Slice types g) Interface types h) Map types i) Channel Types

    Array types and structure types are collectively referred to as aggregate types. The type of a function specifies the set of all functions with the same parameter and result types. We will discuss the basic types in the following section, whereas other types will be covered in the upcoming chapters.

    Integer Types

    The predefined architecture-independent integer types are −

    Sr.No.Types and Description
    1uint8Unsigned 8-bit integers (0 to 255)
    2uint16Unsigned 16-bit integers (0 to 65535)
    3uint32Unsigned 32-bit integers (0 to 4294967295)
    4uint64Unsigned 64-bit integers (0 to 18446744073709551615)
    5int8Signed 8-bit integers (-128 to 127)
    6int16Signed 16-bit integers (-32768 to 32767)
    7int32Signed 32-bit integers (-2147483648 to 2147483647)
    8int64Signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

    Floating Types

    The predefined architecture-independent float types are −

    Sr.No.Types and Description
    1float32IEEE-754 32-bit floating-point numbers
    2float64IEEE-754 64-bit floating-point numbers
    3complex64Complex numbers with float32 real and imaginary parts
    4complex128Complex numbers with float64 real and imaginary parts

    The value of an n-bit integer is n bits and is represented using two’s complement arithmetic operations.

    Other Numeric Types

    There is also a set of numeric types with implementation-specific sizes −

    Sr.No.Types and Description
    1bytesame as uint8
    2runesame as int32
    3uint32 or 64 bits
    4intsame size as uint
    5uintptran unsigned integer to store the uninterpreted bits of a pointer value
  • Basic Syntax

    We discussed the basic structure of a Go program in the previous chapter. Now it will be easy to understand the other basic building blocks of the Go programming language.

    Tokens in Go

    A Go program consists of various tokens. A token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Go statement consists of six tokens −

    fmt.Println("Hello, World!")
    

    The individual tokens are −

    fmt
    .
    Println
    (
       "Hello, World!"
    )

    Line Separator

    In a Go program, the line separator key is a statement terminator. That is, individual statements don’t need a special separator like “;” in C. The Go compiler internally places “;” as the statement terminator to indicate the end of one logical entity.

    For example, take a look at the following statements −

    fmt.Println("Hello, World!")
    fmt.Println("I am in Go Programming World!")
    

    Comments

    Comments are like helping texts in your Go program and they are ignored by the compiler. They start with /* and terminates with the characters */ as shown below −

    /* my first program in Go */
    

    You cannot have comments within comments and they do not occur within a string or character literals.

    Identifiers

    A Go identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).

    identifier = letter { letter | unicode_digit }.

    Go does not allow punctuation characters such as @, $, and % within identifiers. Go is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in Go. Here are some examples of acceptable identifiers −

    mahesh      kumar   abc   move_name   a_123
    myname50   _temp    j      a23b9      retVal
    

    Keywords

    The following list shows the reserved words in Go. These reserved words may not be used as constant or variable or any other identifier names.

    breakdefaultfuncinterfaceselect
    casedeferGomapStruct
    chanelseGotopackageSwitch
    constfallthroughifrangeType
    continueforimportreturnVar

    Whitespace in Go

    Whitespace is the term used in Go to describe blanks, tabs, newline characters, and comments. A line containing only whitespace, possibly with a comment, is known as a blank line, and a Go compiler totally ignores it.

    Whitespaces separate one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement −

    var age int;
    

    There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement −

    fruit = apples + oranges;   // get the total fruit
    

    No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

  • Strings

    The Kotlin String data type is used to store a sequence of characters. String values must be surrounded by double quotes (” “) or triple quote (“”” “””).

    We have two kinds of string available in Kotlin – one is called Escaped String and another is called Raw String.

    • Escaped string is declared within double quote (” “) and may contain escape characters like ‘\n’, ‘\t’, ‘\b’ etc.
    • Raw string is declared within triple quote (“”” “””) and may contain multiple lines of text without any escape characters.

    Example

    funmain(args: Array<String>){val escapedString : String  ="I am escaped String!\n"var rawString :String  ="""This is going to be a
       multi-line string and will
       not have any escape sequence""";print(escapedString)println(rawString)}

    When you run the above Kotlin program, it will generate the following output:

    I am escaped String!
    This is going to be a
       multi-line string and will
       not have any escape sequence
    

    This is optional to specify the data type for a String, Kotlin can understand that the a variable is a String because of the given double or tripple quotes.

    If you want to create a String variable without assigning the value then you must specify the type while declaring the variable otherwise it will raise an error:

    funmain(args: Array<String>){val name : String
    
       name ="Zara Ali"println(name)}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    

    Kotlin String Templates

    Kotlin string templates are pieces of code that are evaluated and whose results are interpolated into the string. A template expression starts with a dollar sign ($) and may consist of either a name or an expression.

    funmain(args: Array<String>){val name : String ="Zara Ali"println("Name  - $name")// Using template with variable nameprintln("Name length - ${name.length}")// Using template with expression.}

    When you run the above Kotlin program, it will generate the following output:

    Name - Zara Ali
    Name length - 8
    

    Kotlin String Object

    Kotlin String is an object, which contains a number of properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable.

    We will see some of the important properties and functions in this chapter, remaining you can find in official documentation of Kotlin latest version.

    Kotlin String Indexes

    Kotlin String can be treated as a sequence of characters or you can say String is an array of characters. You can access its element by specifying the index of the element using a square brackets.

    String indexes start with 0, so if you want to access 4th element of the string then you should specify index as 3 to access the 4th element.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println(name[3])println(name[5])}

    When you run the above Kotlin program, it will generate the following output:

    a
    A
    

    Kotlin String Length

    We can use length property of Kotlin string to find out its length.

    Kotlin function count() also returns the length of a given string.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("The length of name :"+ name.length)println("The length of name :"+ name.count())}

    When you run the above Kotlin program, it will generate the following output:

    The length of name :8
    The length of name :8
    

    Kotlin String Last Index

    We can use lastIndex property of Kotlin string to find out the index of the last character in the char sequence. If a string is empty then it returns a -1.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("The index of last character in name :"+ name.lastIndex)}

    When you run the above Kotlin program, it will generate the following output:

    The index of last character in name :7
    

    Changing Case of Strings

    Kotlin provides toUpperCase() and toLowerCase() functions to convert a string into upper case and lower case respectively.

    Example

    funmain(args: Array<String>){val name : String ="Zara Ali"println("Upper case of name :"+ name.toUpperCase())println("Lower case of name :"+ name.toLowerCase())}

    When you run the above Kotlin program, it will generate the following output:

    Upper case of name :ZARA ALI
    Lower case of name :zara ali
    

    Kotlin String Concatenation

    We can use either + operator to concatenate two strings, or we can also use plus() function to concatenate two strings.

    Example

    funmain(args: Array<String>){var firstName : String ="Zara "var lastName : String ="Ali"println("Full Name :"+ firstName + lastName)println("Full Name :"+ firstName.plus(lastName))}

    When you run the above Kotlin program, it will generate the following output:

    Full Name :Zara Ali
    Full Name :Zara Ali
    

    Trim Characters from a String

    We can remove first few or last few characters from a string using drop() or dropLast() functions.

    Example

    funmain(args: Array<String>){var name : String ="Zara Ali"println("Remove first two characters from name : "+ name.drop(2))println("Remove last two characters from name : "+ name.dropLast(2))}

    When you run the above Kotlin program, it will generate the following output:

    Remove first two characters from name : ra Ali
    Remove last two characters from name : Zara A
    

    Quotes Inside a String

    To use quotes inside a string, use single quotes (‘):

    Example

    funmain(args: Array<String>){var str1 : String ="That's it"var str2 : String ="It's OK"println("str1 : "+ str1)println("str2 : "+ str2)}

    When you run the above Kotlin program, it will generate the following output:

    str1 : That's it
    str2 : It's OK
    

    Finding a String inside a String

    Kotlin provides indexOf() function to find out a text inside a string. This function returns the index of the first occurrence of a specified text in a string

    Example

    funmain(args: Array<String>){var str : String ="Meditation and Yoga are synonymous with India"println("Index of Yoga in the string - "+ str.indexOf("Yoga"))}

    When you run the above Kotlin program, it will generate the following output:

    Index of Yoga in the string - 15
    

    Comparing Two Strings

    Kotlin provides compareTo() function to compare two strings. This function returns 0 if two strings are equal otherwise it will return 1.

    Example

    funmain(args: Array<String>){var str1 : String ="Apple"var str2 : String ="Apple"println(str1.compareTo(str2))}

    When you run the above Kotlin program, it will generate the following output:

    0
    

    Kotlin getOrNull() function

    Kotlin getOrNull() function returns a character at the given index or null if the index is out of bounds of this char sequence.

    Example

    funmain(args: Array<String>){var name : String ="Zara"println(name.getOrNull(0))println(name.getOrNull(2))println(name.getOrNull(100))}

    When you run the above Kotlin program, it will generate the following output:

    Z
    r
    null
    

    Kotlin toString() function

    Kotlin toString() function returns a string representation of the object..

    Example

    funmain(args: Array<String>){var name : String ="Zara Ali"println(name.toString())}

    When you run the above Kotlin program, it will generate the following output:

    Zara Ali
    
  • Program Structure

    Before we study the basic building blocks of Go programming language, let us first discuss the bare minimum structure of Go programs so that we can take it as a reference in subsequent chapters.

    Hello World Example

    A Go program basically consists of the following parts −

    • Package Declaration
    • Import Packages
    • Functions
    • Variables
    • Statements and Expressions
    • Comments

    Let us look at a simple code that would print the words “Hello World” −

    Live Demo

    package main
    
    import "fmt"
    
    func main() {
       /* This is my first sample program. */
       fmt.Println("Hello, World!")
    }

    Let us take a look at the various parts of the above program −

    • The first line of the program package main defines the package name in which this program should lie. It is a mandatory statement, as Go programs run in packages. The main package is the starting point to run the program. Each package has a path and name associated with it.
    • The next line import “fmt” is a preprocessor command which tells the Go compiler to include the files lying in the package fmt.
    • The next line func main() is the main function where the program execution begins.
    • The next line /*…*/ is ignored by the compiler and it is there to add comments in the program. Comments are also represented using // similar to Java or C++ comments.
    • The next line fmt.Println(…) is another function available in Go which causes the message “Hello, World!” to be displayed on the screen. Here fmt package has exported Println method which is used to display the message on the screen.
    • Notice the capital P of Println method. In Go language, a name is exported if it starts with capital letter. Exported means the function or variable/constant is accessible to the importer of the respective package.

    Executing a Go Program

    Let us discuss how to save the source code in a file, compile it, and finally execute the program. Please follow the steps given below −

    • Open a text editor and add the above-mentioned code.
    • Save the file as hello.go
    • Open the command prompt.
    • Go to the directory where you saved the file.
    • Type go run hello.go and press enter to run your code.
    • If there are no errors in your code, then you will see “Hello World!” printed on the screen.
    $ go run hello.go
    Hello, World!
    

    Make sure the Go compiler is in your path and that you are running it in the directory containing the source file hello.go.

  • Environment Setup

    Local Environment Setup

    If you are still willing to set up your environment for Go programming language, you need the following two software available on your computer −

    • A text editor
    • Go compiler

    Text Editor

    You will require a text editor to type your programs. Examples of text editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

    The name and version of text editors can vary on different operating systems. For example, Notepad is used on Windows, and vim or vi is used on Windows as well as Linux or UNIX.

    The files you create with the text editor are called source files. They contain program source code. The source files for Go programs are typically named with the extension “.go”.

    Before starting your programming, make sure you have a text editor in place and you have enough experience to write a computer program, save it in a file, compile it, and finally execute it.

    The Go Compiler

    The source code written in source file is the human readable source for your program. It needs to be compiled and turned into machine language so that your CPU can actually execute the program as per the instructions given. The Go programming language compiler compiles the source code into its final executable program.

    Go distribution comes as a binary installable for FreeBSD (release 8 and above), Linux, Mac OS X (Snow Leopard and above), and Windows operating systems with 32-bit (386) and 64-bit (amd64) x86 processor architectures.

    The following section explains how to install Go binary distribution on various OS.

    Download Go Archive

    Download the latest version of Go installable archive file from Go Downloads. The following version is used in this tutorial: go1.4.windows-amd64.msi.

    It is copied it into C:\>go folder.

    OSArchive name
    Windowsgo1.4.windows-amd64.msi
    Linuxgo1.4.linux-amd64.tar.gz
    Macgo1.4.darwin-amd64-osx10.8.pkg
    FreeBSDgo1.4.freebsd-amd64.tar.gz

    Installation on UNIX/Linux/Mac OS X, and FreeBSD

    Extract the download archive into the folder /usr/local, creating a Go tree in /usr/local/go. For example −

    tar -C /usr/local -xzf go1.4.linux-amd64.tar.gz

    Add /usr/local/go/bin to the PATH environment variable.

    OSOutput
    Linuxexport PATH = $PATH:/usr/local/go/bin
    Macexport PATH = $PATH:/usr/local/go/bin
    FreeBSDexport PATH = $PATH:/usr/local/go/bin

    Installation on Windows

    Use the MSI file and follow the prompts to install the Go tools. By default, the installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin directory in Window’s PATH environment variable. Restart any open command prompts for the change to take effect.

    Verifying the Installation

    Create a go file named test.go in C:\>Go_WorkSpace.

    File: test.go

    package main
    
    import "fmt"
    
    func main() {
       fmt.Println("Hello, World!")
    }

    Now run test.go to see the result −

    C:\Go_WorkSpace>go run test.go
    

    Output

    Hello, World!
    
  • Booleans

    Many times we come across a situation where we need to take decision in Yes or No, or may be we can say True or False. To handle such situation Kotlin has a Boolean data type, which can take the values either true or false.

    Kotlin also has a nullable counterpart Boolean? that can have the null value.

    Create Boolean Variables

    A boolean variable can be created using Boolean keyword and this variable can only take the values either true or false:

    Example

    funmain(args: Array<String>){val isSummer: Boolean =trueval isCold: Boolean =falseprintln(isSummer)println(isCold)}

    When you run the above Kotlin program, it will generate the following output:

    true
    false
    

    In fact, we can create Kotlin boolean variables without using Boolean keyword and Kotlin will understand the variable type based on the assigned values either true or false

    Kotlin Boolean Operators

    Kotlin provides following built-in operators for boolean variables. These operators are also called Logical Operators:

    OperatorNameDescriptionExample
    &&Logical andReturns true if both operands are truex && y
    ||Logical orReturns true if either of the operands is truex || y
    !Logical notReverse the result, returns false if the operand is true!x

    Example

    Following example shows different calculations using Kotlin Logical Operators:

    funmain(args: Array<String>){var x: Boolean =truevar y:Boolean =falseprintln("x && y = "+(x && y))println("x || y = "+(x || y))println("!y = "+(!y))}

    When you run the above Kotlin program, it will generate the following output:

    x && y = false
    x || y = true
    !y = true
    

    Kotlin Boolean Expression

    A Boolean expression returns either true or false value and majorly used in checking the condition with if…else expressions. A boolean expression makes use of relational operators, for example >, <, >= etc.

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x > y = "+(x > y))println("x < y = "+(x < y))println("x >= y = "+(x >= y))println("x <= y = "+(x <= y))println("x == y = "+(x == y))println("x != y = "+(x != y))}

    When you run the above Kotlin program, it will generate the following output:

    x > y = true
    x < y = false
    x >= y = true
    x <= y = false
    x == y = false
    x != y = true
    

    Kotlin and()and or() Functions

    Kotlin provides and() and or() functions to perform logical AND and logical OR operations between two boolean operands.

    These functions are different from && and || operators because these functions do not perform short-circuit evaluation but they always evaluate both the operands.

    funmain(args: Array<String>){val x: Boolean =trueval y: Boolean =falseval z: Boolean =trueprintln("x.and(y) = "+  x.and(y))println("x.or(y) = "+  x.or(y))println("x.and(z) = "+  x.and(z))}

    When you run the above Kotlin program, it will generate the following output:

    x.and(y) = false
    x.or(y) = true
    x.and(z) = true
    

    Kotlin also provides not() and xor() functions to perform Logical NOT and XOR operations respectively.

    Boolean to String

    You can use toString() function to convert a Boolean object into its equivalent string representation.

    You will need this conversion when assigning a true or false value in a String variable.

    funmain(args: Array<String>){val x: Boolean =truevar z: String
       
       z = x.toString()println("x.toString() = "+  x.toString())println("z = "+  z)}

    When you run the above Kotlin program, it will generate the following output:

    x.toString() = true
    z = true
    
  • Overview

    Go is a general-purpose language designed with systems programming in mind. It was initially developed at Google in the year 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is strongly and statically typed, provides inbuilt support for garbage collection, and supports concurrent programming.

    Programs are constructed using packages, for efficient management of dependencies. Go programming implementations use a traditional compile and link model to generate executable binaries. The Go programming language was announced in November 2009 and is used in some of the Google’s production systems.

    Features of Go Programming

    The most important features of Go programming are listed below −

    • Support for environment adopting patterns similar to dynamic languages. For example, type inference (x := 0 is valid declaration of a variable x of type int)
    • Compilation time is fast.
    • Inbuilt concurrency support: lightweight processes (via go routines), channels, select statement.
    • Go programs are simple, concise, and safe.
    • Support for Interfaces and Type embedding.
    • Production of statically linked native binaries without external dependencies.

    Features Excluded Intentionally

    To keep the language simple and concise, the following features commonly available in other similar languages are omitted in Go −

    • Support for type inheritance
    • Support for method or operator overloading
    • Support for circular dependencies among packages
    • Support for pointer arithmetic
    • Support for assertions
    • Support for generic programming

    Go Programs

    A Go program can vary in length from 3 lines to millions of lines and it should be written into one or more text files with the extension “.go”. For example, hello.go.

    You can use “vi”, “vim” or any other text editor to write your Go program into a file.

  • Operators

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Kotlin is rich in built-in operators and provide the following types of operators:

    • Arithmetic Operators
    • Relational Operators
    • Assignment Operators
    • Unary Operators
    • Logical Operators
    • Bitwise Operations

    Now let’s look into these Kotlin Operators one by one.

    (a) Kotlin Arithmetic Operators

    Kotlin arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication and division etc.

    OperatorNameDescriptionExample
    +AdditionAdds together two valuesx + y
    SubtractionSubtracts one value from anotherx – y
    *MultiplicationMultiplies two valuesx * y
    /DivisionDivides one value by anotherx / y
    %ModulusReturns the division remainderx % y

    Example

    Following example shows different calculations using Kotlin Arithmetic Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x + y = "+(x + y))println("x - y = "+(x - y))println("x / y = "+(x / y))println("x * y = "+(x * y))println("x % y = "+(x % y))}

    When you run the above Kotlin program, it will generate the following output:

    x + y = 60
    x - y = 20
    x / y = 2
    x * y = 800
    x % y = 0
    

    (b) Kotlin Relational Operators

    Kotlin relational (comparison) operators are used to compare two values, and returns a Boolean value: either true or false.

    OperatorNameExample
    >greater thanx > y
    <less thanx < y
    >=greater than or equal tox >= y
    <=less than or equal tox <= y
    ==is equal tox == y
    !=not equal tox != y

    Example

    Following example shows different calculations using Kotlin Relational Operators:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x > y = "+(x > y))println("x < y = "+(x < y))println("x >= y = "+(x >= y))println("x <= y = "+(x <= y))println("x == y = "+(x == y))println("x != y = "+(x != y))}

    When you run the above Kotlin program, it will generate the following output:

    x > y = true
    x < y = false
    x >= y = true
    x <= y = false
    x == y = false
    x != y = true
    

    (c) Kotlin Assignment Operators

    Kotlin assignment operators are used to assign values to variables.

    Following is an example where we used assignment operator = to assign a values into two variables:

    funmain(args: Array<String>){val x: Int =40val y: Int =20println("x = "+  x)println("y = "+  y)}

    When you run the above Kotlin program, it will generate the following output:

    x = 40
    y = 20
    

    Following is one more example where we used assignment operator += to add the value of self variable and assign it back into the same variable:

    funmain(args: Array<String>){var x: Int =40
    
       x +=10println("x = "+  x)}

    When you run the above Kotlin program, it will generate the following output:

    x = 50
    

    Following is a list of all assignment operators:

    OperatorExampleExpanded Form
    =x = 10x = 10
    +=x += 10x = x – 10
    -=x -= 10x = x – 10
    *=x *= 10x = x * 10
    /=x /= 10x = x / 10
    %=x %= 10x = x % 10

    Example

    Following example shows different calculations using Kotlin Assignment Operators:

    funmain(args: Array<String>){var x: Int =40
    
       x +=5println("x += 5 = "+ x )
       
       x =40;
       x -=5println("x -= 5 = "+  x)
       
       x =40
       x *=5println("x *= 5 = "+  x)
       
       x =40
       x /=5println("x /= 5 = "+  x)
       
       x =43
       x %=5println("x %= 5 = "+ x)}

    When you run the above Kotlin program, it will generate the following output:

    x += 5 = 45
    x -= 5 = 35
    x *= 5 = 200
    x /= 5 = 8
    x %= 5 = 3
    

    (d) Kotlin Unary Operators

    The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

    Following is the list of Kotlin Unary Operators:

    OperatorNameExample
    +unary plus+x
    unary minus-x
    ++increment by 1++x
    decrement by 1–x
    !inverts the value of a boolean!x

    Example

    Following example shows different calculations using Kotlin Unary Operators:

    funmain(args: Array<String>){var x: Int =40var b:Boolean =trueprintln("+x = "+(+x))println("-x = "+(-x))println("++x = "+(++x))println("--x = "+(--x))println("!b = "+(!b))}

    When you run the above Kotlin program, it will generate the following output:

    +x = 40
    -x = -40
    ++x = 41
    --x = 40
    !b = false
    

    Here increment (++) and decrement (–) operators can be used as prefix as ++x or –x as well as suffix as x++ or x–. The only difference between the two forms is that in case we use them as prefix then operator will apply before expression is executed, but if use them as suffix then operator will apply after the expression is executed.

    (e) Kotlin Logical Operators

    Kotlin logical operators are used to determine the logic between two variables or values:

    Following is the list of Kotlin Logical Operators:

    OperatorNameDescriptionExample
    &&Logical andReturns true if both operands are truex && y
    ||Logical orReturns true if either of the operands is truex || y
    !Logical notReverse the result, returns false if the operand is true!x

    Example

    Following example shows different calculations using Kotlin Logical Operators:

    funmain(args: Array<String>){var x: Boolean =truevar y:Boolean =falseprintln("x && y = "+(x && y))println("x || y = "+(x || y))println("!y = "+(!y))}

    When you run the above Kotlin program, it will generate the following output:

    x && y = false
    x || y = true
    !y = true
    

    (e) Kotlin Bitwise Operations

    Kotlin does not have any bitwise operators but Kotlin provides a list of helper functions to perform bitwise operations.

    Following is the list of Kotlin Bitwise Functions:

    FunctionDescriptionExample
    shl (bits)signed shift leftx.shl(y)
    shr (bits)signed shift rightx.shr(y)
    ushr (bits)unsigned shift rightx.ushr(y)
    and (bits)bitwise andx.and(y)
    or (bits)bitwise orx.or(y)
    xor (bits)bitwise xorx.xor(y)
    inv()bitwise inversex.inv()

    Example

    Following example shows different calculations using Kotlin bitwise functions:

    funmain(args: Array<String>){var x:Int =60// 60 = 0011 1100  var y:Int =13// 13 = 0000 1101var z:Int
    
       z = x.shl(2)// 240 = 1111 0000println("x.shl(2) = "+  z)
       
       z = x.shr(2)// 15 = 0000 1111println("x.shr(2) = "+  z)
       
       z = x.and(y)// 12 = 0000 1100println("x.and(y)  = "+  z)
       
       z = x.or(y)// 61 = 0011 1101println("x.or(y)  = "+  z)
       
       z = x.xor(y)// 49 = 0011 0001println("x.xor(y)  = "+  z)
       
       z = x.inv()// -61 = 1100 0011println("x.inv()  = "+  z)}

    When you run the above Kotlin program, it will generate the following output:

    x.shl(2) = 240
    x.shr(2) = 15
    x.and(y)  = 12
    x.or(y)  = 61
    x.xor(y)  = 49
    x.inv()  = -61
    
  • Debugging Program

    A debugger tool is used to search for errors in the programs.

    A debugger program steps through the code and allows you to examine the values in the variables and other data objects during execution of the program.

    It loads the source code and you are supposed to run the program within the debugger. Debuggers debug a program by −

    • Setting breakpoints,
    • Stepping through the source code,
    • Setting watch points.

    Breakpoints specify where the program should stop, specifically after a critical line of code. Program executions after the variables are checked at a breakpoint.

    Debugger programs also check the source code line by line.

    Watch points are the points where the values of some variables are needed to be checked, particularly after a read or write operation.

    The gdb Debugger

    The gdb debugger, the GNU debugger comes with Linux operating system. For X windows system, gdb comes with a graphical interface and the program is named xxgdb.

    Following table provides some commands in gdb −

    CommandPurpose
    breakSetting a breakpoint
    runStarts execution
    contContinues execution
    nextExecutes only the next line of source code, without stepping into any function call
    stepExecute the next line of source code by stepping into a function in case of a function call.

    The dbx Debugger

    There is another debugger, the dbx debugger, for Linux.

    The following table provides some commands in dbx −

    CommandPurpose
    stop[var]Sets a breakpoint when the value of variable var changes.
    stop in [proc]It stops execution when a procedure proc is entered
    stop at [line]It sets a breakpoint at a specified line.
    runStarts execution.
    contContinues execution.
    nextExecutes only the next line of source code, without stepping into any function call.
    stepExecute the next line of source code by stepping into a function in case of a function call.