0% found this document useful (0 votes)
217 views

Android Development Question Bank

Kotlin is a statically typed programming language that runs on the JVM. It can be used to develop Android and server-side applications. Kotlin code is concise, null-safe, interoperable with Java, and has features like smart casts, fast compilation times, and extension functions. Kotlin uses if expressions that return values and support if-else, if-else-if-ladder, and nested if expressions. When expressions are Kotlin's replacement for switch statements. Kotlin loops include for loops to iterate over arrays, ranges, and collections. Visibility modifiers like public, protected, internal, and private restrict the scope of Kotlin classes, methods, and properties.

Uploaded by

Shubham Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
217 views

Android Development Question Bank

Kotlin is a statically typed programming language that runs on the JVM. It can be used to develop Android and server-side applications. Kotlin code is concise, null-safe, interoperable with Java, and has features like smart casts, fast compilation times, and extension functions. Kotlin uses if expressions that return values and support if-else, if-else-if-ladder, and nested if expressions. When expressions are Kotlin's replacement for switch statements. Kotlin loops include for loops to iterate over arrays, ranges, and collections. Visibility modifiers like public, protected, internal, and private restrict the scope of Kotlin classes, methods, and properties.

Uploaded by

Shubham Yadav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Android Development Question Bank with Answers

Unit I

1. Explain different features of Kotlin Language.

Kotlin is a general-purpose, statically typed, and open-source programming language. It runs on JVM
and can be used anywhere Java is used today. It can be used to develop Android apps, server-side
apps and much more.

o Concise: Kotlin reduces writing the extra codes. This makes Kotlin more concise.
o Null safety: Kotlin is null safety language. Kotlin aimed to eliminate the
NullPointerException (null reference) from the code.Interoperable.
o Interoperable: Kotlin easily calls the Java code in a natural way as well as Kotlin
code can be used by Java.
o Smart cast: It explicitly typecasts the immutable values and inserts the value in
its safe cast automatically.
o Compilation Time: It has better performance and fast compilation time.
o Tool-friendly: Kotlin programs are build using the command line as well as any
of Java IDE.
o Extension function: Kotlin supports extension functions and extension
properties which means it helps to extend the functionality of classes without
touching their code.

2. What are different forms of Kotlin If Expression. Explain any one with example.

In Kotlin, if is an expression is which returns a value. It is used for control the flow
of program structure. There is various type of if expression in Kotlin.

o if-else expression
o if-else if-else ladder expression
o nested if expression

Syntax of traditional if statement

if(condation){
//code statement
}
Syntax of traditional if else statement
if(condation){
//code statement
}
else{
//code statement
}

As if is an expression it is not used as standalone, it is used with if-else expression and


the result of an if-else expression is assign into a variable.

Syntax of if-else expression

val returnValue = if (condition) {


//code statement
} else {
// code statement
}
println(returnValue)

Kotlin if-else Expression Example

fun main(args: Array<String>) {


val num1 = 10
val num2 =20
val result = if (num1 > num2) {
"$num1 is greater than $num2"
} else {
"$num1 is smaller than $num2"
}
println(result)
}
Output:-
10 is smaller than 20
We can remove the curly braces of if-else body by writing if expression in only one
statement.

Example:-
fun main(args: Array<String>) {
val num1 = 10
val num2 =20
val result = if (num1 > num2) "$num1 is greater than $num2" else "$num1 is
smaller than $num2"
println(result)
}

Kotlin if-else if-else Ladder Expression


fun main(args: Array<String>) {
val num = 10
val result = if (num > 0){
"$num is positive"
}else if(num < 0){
"$num is negative"
}else{
"$num is zero"
}
println(result)
}
Output:- 10 is positive

Kotlin Nested if Expression


fun main(args: Array<String>) {
val num1 = 25
val num2 = 20
val num3 = 30
val result = if (num1 > num2){

val max = if(num1 > num3){


num1
}else{
num3
}
"body of if "+max
}else if(num2 > num3){
"body of else if"+num2
}else{
"body of else "+num3
}
println("$result")
}
Output:- body of if 30
3. Explain Kotlin when expression with example.

Kotlin when Expression


Kotlin, when expression is a conditional expression which returns the value. Kotlin,
when expression is replacement of switch statement. Kotlin, when expression works as
a switch statement of other language (Java, C++, C).

fun main(args: Array<String>){


var number = 4
var numberProvided = when(number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
4 -> "Four"
5 -> "Five"
else -> "invalid number"
}
println("You provide $numberProvided")
}
Output:- Your provide Four

Using when Without Expression


It is not mandatory to use when as an expression, it can be used as normally as it used in
other language.

Example:-

fun main(args: Array<String>){

var number = 4
when(number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
4 -> println("Four")
5 -> println("Five")
else -> println("invalid number")
}

}
Output:- Four

4. What are different forms of for Loop in Kotlin? Explain any one in detail.

Kotlin for loop is used to iterate a part of program several times. It iterates through arrays,
ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to
the foreach loop in languages like C#.

for (item in collection){


//body of loop
}
Iterate through array

fun main(args : Array<String>) {


val marks = arrayOf(80,85,60,90,70)
for(item in marks){
println(item)
}
}
Output:-
80
85
60
90
70

If the body of for loop contains only one single line of statement, it is not necessary to
enclose within curly braces {}.

fun main(args : Array<String>) {


val marks = arrayOf(80,85,60,90,70)
for(item in marks)
println(item)
}
The elements of an array are iterated on the basis of indices (index) of array. For example:
fun main(args : Array<String>) {

val marks = arrayOf(80,85,60,90,70)


for(item in marks.indices)
println("marks[$item]: "+ marks[item])
}
Output:-
marks[0]: 80
marks[1]: 85
marks[2]: 60
marks[3]: 90
marks[4]: 70
Iterate through range
fun main(args : Array<String>) {

print("for (i in 1..5) print(i) = ")


for (i in 1..5) print(i)
println()
print("for (i in 5..1) print(i) = ")
for (i in 5..1) print(i) // prints nothing
println()
print("for (i in 5 downTo 1) print(i) = ")
for (i in 5 downTo 1) print(i)
println()
print("for (i in 5 downTo 2) print(i) = ")
for (i in 5 downTo 2) print(i)
println()
print("for (i in 1..5 step 2) print(i) = ")
for (i in 1..5 step 2) print(i)
println()
print("for (i in 5 downTo 1 step 2) print(i) = ")
for (i in 5 downTo 1 step 2) print(i)
}
Output:-
for (i in 1..5) print(i) = 12345
for (i in 5..1) print(i) =
for (i in 5 downTo 1) print(i) = 54321
for (i in 5 downTo 2) print(i) = 5432
for (i in 1..5 step 2) print(i) = 135
for (i in 5 downTo 1 step 2) print(i) = 531

5. Write a note on Kotlin visibility modifiers.

Kotlin Visibility Modifier


Visibility modifiers are the keywords which are used to restrict the use of class,
interface, methods, and property of Kotlin in the application. These modifiers are used
at multiple places such as class header or method body.

In Kotlin, visibility modifiers are categorized into four different types:

o public
o protected
o internal
o private

public modifier
A public modifier is accessible from everywhere in the project. It is a default modifier
in Kotlin. If any class, interface etc. are not specified with any access modifier then that
class, interface etc. are used in public scope.

public class Example{


}
class Demo{
}
public fun hello()
fun demo()
public val x = 5
val y = 10
All public declaration can be placed at top of the file. If a member of class is not
specified then it is by default public.

protected modifier
A protected modifier with class or interface allows visibility to its class or subclass only.
A protected declaration (when overridden) in its subclass is also protected modifier
unless it is explicitly changed.

open class Base{


protected val i = 0
}

class Derived : Base(){

fun getValue() : Int


{
return i
}
}
In Kotlin, protected modifier cannot be declared at top level.
Overriding of protected types
open class Base{
open protected val i = 5
}
class Another : Base(){
fun getValue() : Int
{
return i
}
override val i =10
}

internal modifier
The internal modifiers are newly added in Kotlin, it is not available in Java. Declaring
anything makes that field marked as internal field. The internal modifier makes the
field visible only inside the module in which it is implemented.
internal class Example{
internal val x = 5
internal fun getValue(){

}
}
internal val y = 10

In above, all the fields are declared as internal which are accessible only inside the module
in which they are implemented.

private modifier
A private modifier allows the declaration to be accessible only within the block in which
properties, fields, etc. are declare. The private modifier declaration does not allow to access
the outside the scope. A private package can be accessible within that specific file.
private class Example {
private val x = 1
private valdoSomething() {
}
}
In above class Example,val x and function doSomthing() are declared as private. The class
"Example" is accessible from the same source file, "val x" and "fun doSomthing()" are
accessible within Example class.
Example of Visibility Modifier

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 the Derived 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.c is not visible
}

6. What are types of constructors in Kotlin? Explain Primary/Secondary constructor with


example.

Kotlin Constructor
In Kotlin, constructor is a block of code similar to method. Constructor is declared
with the same name as the class followed by parenthesis '()'. Constructor is used to
initialize the variables at the time of object creation.

Types of Kotlin constructors


There are two types of constructors in Kotlin:

1. Primary constructor
2. Secondary constructor

There is only one primary constructor in a Kotlin class whereas secondary constructor
may be one or more.

Kotlin primary constructor


Primary constructor is used to initialize the class. It is declared at class header. Primary
constructor code is surrounded by parentheses with optional parameter.

Let's see an example of declaration of primary constructor. In the below code, we


declare a constructor myClass with two parameter name and id. Parameter name is
only read property whereas id is read and write property.

class myClass(valname: String,varid: Int) {


// class body
}

When the object of myClasss is created, it initializes name and id with "Ashu"
and "101" respectively.

class myClass(val name: String, var id: Int) {

fun main(args: Array<String>){

val myclass = myClass ("Ashu", 101)

println("Name = ${ myclass.name}")

println("Id = ${ myclass.id}")

Output:

Name = Ashu

Id = 101

Primary constructor with initializer block


The primary constructor does not contain any code. Initializer blocks are used to
initialization of code. This block is prefixed with init keyword. At the period of instance
initialization, the initialized blocks are executed in the same order as they appear in
class body.

Let's rewrite the above code using initialize block:

class myClass(name: String, id: Int) {


val e_name: String
var e_id: Int
init{
e_name = name.capitalize()
e_id = id

println("Name = ${e_name}")
println("Id = ${e_id}")
}
}
1. fun main(args: Array<String>){
2. val myclass = myClass ("Ashu", 101)
3.
4. }

Output:

Name = Ashu
Id = 101

In above code, parameters name and id accept values "Ashu" and "101" when myclass
object is created. The properties name and id are used without "val" or "var", so they
are not properties of myClass class.

When object of myClass class is created, it executes initializer block which


initializese_name and e_id.

Kotlin secondary constructor


In Kotlin, secondary constructor can be created one or more in class. The secondary
constructor is created using "constructor" keyword.

Let's see an example of declaration of secondary constructor. In the below code, we


declare two constructor of myClass with two parameter name and id.

class myClass{

constructor(id: Int){
//code
}
constructor(name: String, id: Int){
//code
}
}

Let's see an example of secondary constructor assigning the value while object of class
is created.

class myClass{

constructor(name: String, id: Int){


println("Name = ${name}")
println("Id = ${id}")
}
}
fun main(args: Array<String>){
val myclass = myClass ("Ashu", 101)

Output:

Name = Ashu
Id = 101

We can also use both primary as well as secondary constructor in a same class. By
using primary as well secondary constructor in same class, secondary constructor
needs to authorize to primary constructor. Authorization to another constructor in
same class is done using this() keyword.

AD

For example:

1. class myClass(password: String){


2.
3. constructor(name: String, id: Int, password: String): this(password){
4. println("Name = ${name}")
5. println("Id = ${id}")
6. println("Password = ${password}")
7. }
8. }
9. fun main(args: Array<String>){
10. val myclass = myClass ("Ashu", 101, "mypassword")
11.
12. }

Output:

Name = Ashu
Id = 101
Password = mypassword
Calling one secondary constructor from another
secondary constructor of same class
In Kotlin, one secondary constructor can call another secondary constructor of same
class. This is done by using this() keyword.

For example:

class myClass{

constructor(name: String, id: Int): this(name,id, "mypassword"){


println("this executes next")
println("Name = ${name}")
println("Id = ${id}")
}

constructor(name: String, id: Int,pass: String){


println("this executes first")
println("Name = ${name}")
println("Id = ${id}")
println("Password = ${pass}")
}
}
fun main(args: Array<String>){
val myclass = myClass ("Ashu", 101)

Output:

AD

this executes first


Name = Ashu
Id = 101
Password = mypassword
this executes next
Name = Ashu
Id = 101
AD
Calling supper class secondary constructor from
derived class secondary constructor
In Kotlin, one derived class secondary constructor can call the base class secondary
constructor. This is done using super keyword, this is the concept of inheritance.

open class Parent{

constructor(name: String, id: Int){


println("this executes first")
println("Name = ${name}")
println("Id = ${id}")
}

constructor(name: String, id: Int,pass: String){


println("this executes third")
println("Name = ${name}")
println("Id = ${id}")
println("Password = ${pass}")
}
}
class Child: Parent{
constructor(name: String, id: Int): super(name,id){
println("this executes second")
println("Name = ${name}")
println("Id = ${id}")
}

constructor(name: String, id: Int,pass: String):super(name,id,"password"){


println("this executes forth")
println("Name = ${name}")
println("Id = ${id}")
println("Password = ${pass}")
}
}
fun main(args: Array<String>){
val obj1 = Child("Ashu", 101)
val obj2 = Child("Ashu", 101,"mypassword")
}

Output:

this executes first


Name = Ashu
Id = 101
this executes second
Name = Ashu
Id = 101
this executes third
Name = Ashu
Id = 101
Password = password
this executes forth
Name = Ashu
Id = 101
Password = mypassword

7. How Kotlin functions are defined? Explain named and default argument in Kotlin.

Kotlin Function
Function is a group of inter related block of code which performs a specific task.
Function is used to break a program into different sub module. It makes reusability of
code and makes program more manageable.

In Kotlin, functions are declared using fun keyword. There are two types of functions
depending on whether it is available in standard library or defined by user.

o Standard library function


o User defined function

Standard Library Function


Kotlin Standard library function is built-in library functions which are implicitly present
in library and available for use.

For example

fun main(args: Array<String>){


var number = 25
var result = Math.sqrt(number.toDouble())
print("Square root of $number is $result")
}

Output:

Square root of 25 is 5.0

o Here, sqrt() is a library function which returns square root of a number (Double value).
o print() library function which prints a message to standard output stream.

AD

User defined Function


User defined function is a function which is created by user. User defined function takes
the parameter(s), perform an action and return the result of that action as a value.

Kotlin functions are declared using the fun keyword. For example:

fun functionName(){
// body of function
}

We have to call the function to run codes inside the body of the function.

functionName()
Kotlin simple function example
fun main(args: Array<String>){
sum()
print("code after sum")
}
fun sum(){
var num1 =5
var num2 = 6
println("sum = "+(num1+num2))
}

Output:

sum = 11
code after sum
Kotlin Parameterize Function and Return Value
Functions are also takes parameter as arguments and return value. Kotlin functions are
defined using Pascal notation, i.e. name:type (name of parameter and its type).
Parameters in function are separated using commas.

If a function does not returns any value than its return type is Unit. It is optional to
specify the return type of function definition which does not returns any value.

fun functionName(number1: Int, number2: Int){


.. .. ..
}
.. .. ..
functionName(value1, value2)
.. .. ..
Kotlin parameterize function example
fun main(args: Array<String>){
val result = sum(5, 6)
print(result)
}
fun sum(number1: Int, number2:Int): Int{
val add = number1+number2
return add
}

Output:

11

8. Explain method overriding in Kotlin with example.

In any object-oriented programming language, Overriding is a feature that allows a subclass or


child class to provide a specific implementation of a method that is already provided by one of
its super-classes or parent classes. You decided your new class has to redefine one of the
methods inherited from one of the parent classes. This is known as overriding;

If you have already programmed in Java, you will find Kotlin a more explicit language. In Java,
every method is virtual by default; therefore, each method can be overridden by any derived
class. In Kotlin, you would have to tag the function as being opened to redefine it. To do so, you
need to add the open keyword as a prefix to the method definition, and when you redefine the
method, you specifically have to mark it using the override keyword:

Example:-

abstract class SingleEngineAirplane protected constructor() {

abstract fun fly()

class CesnaAirplane : SingleEngineAirplane() {

override fun fly() {

println("Flying a cessna")

class CesnaAirplane : SingleEngineAirplane() {

final override fun fly() {

println("Flying a cessna")

open class Base {

open val property1: String

get() = "Base::value"

class Derived1 : Base() {

override val property1: String

get() = "Derived::value"

class Derived2(override val property1: String) : Base() {}

open class BaseB(open val propertyFoo: String) {}

class DerivedB : BaseB("") {


private var _propFoo: String = ""

override var propertyFoo: String

get() = _propFoo

set(value) {

_propFoo = value

fun main(args: Array<String>) {

val baseB = BaseB("BaseB:value")

val derivedB= DerivedB()

derivedB.propertyFoo = "on the spot value"

println("BaseB:${baseB.propertyFoo}")

println("DerivedB:${derivedB.propertyFoo}")

open class Image {

open fun save(output: OutputStream) {

println("Some logic to save an image")

interface VendorImage {

fun save(output: OutputStream) {

println("Vendor saving an image")

class PNGImage : Image(), VendorImage {

override fun save(output: OutputStream) {

super<VendorImage>.save(output)

super<Image>.save(output)
}

fun main(args: Array<String>) {

val pngImage = PNGImage()

val os = ByteArrayOutputStream()

pngImage.save(os)

9. Explain Android architecture with the help of diagram.

Android Architecture
android architecture or Android software stack is categorized into five parts:

1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications

Let's see the android architecture first.


1) Linux kernel
It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power management,
memory management, device management and resource access.

2) Native Libraries
On the top of linux kernel, their are Native libraries such as WebKit, OpenGL,
FreeType, SQLite, Media, C runtime library (libc) etc.

The WebKit library is responsible for browser support, SQLite is for database, FreeType
for font support, Media for playing and recording audio and video formats.

3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik Virtual Machine) which is
responsible to run android application. DVM is like JVM but it is optimized for mobile
devices. It consumes less memory and provides fast performance.

AD

4) Android Framework
On the top of Native libraries and android runtime, there is android framework.
Android framework includes Android API's such as UI (User Interface), telephony,
resources, locations, Content Providers (data) and package managers. It provides a lot
of classes and interfaces for android application development.

5) Applications
On the top of android framework, there are applications. All applications such as home,
contact, settings, games, browsers are using android framework that uses android
runtime and libraries. Android runtime and native libraries are using linux kernal.

10. Describe Android activity life cycle with the help of diagram.

Android Activity Lifecycle

Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class.


The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single
screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.

Android Activity Lifecycle methods


Let's see the 7 lifecycle methods of android activity.

Let's see the 7 lifecycle methods of android activity.

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

onStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.
android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.activitylifecycle.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Android Activity Lifecycle Example
It provides the details about the invocation of life cycle methods of activity. In this
example, we are displaying the content on the logcat.

File: MainActivity.java

package example.javatpoint.com.activitylifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

You might also like