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

Android

The document covers various Kotlin programming concepts, including variable declaration, functions, control flow statements, and data types. It also discusses Android architecture, SQLite databases, internal storage, and Firebase, providing examples and explanations for each topic. Overall, it serves as a comprehensive guide for understanding Kotlin and its application in Android development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Android

The document covers various Kotlin programming concepts, including variable declaration, functions, control flow statements, and data types. It also discusses Android architecture, SQLite databases, internal storage, and Firebase, providing examples and explanations for each topic. Overall, it serves as a comprehensive guide for understanding Kotlin and its application in Android development.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit 1

1. How do you declare variables in Kotlin? How


does the declaration differ from the Java
counterpart?
Ans - In Kotlin, you declare variables using the "val" or "var" keywords.
The "val" keyword is used to declare read-only variables, which are similar
to Java's final variables. Once initialized, the value of a read-only variable
cannot be changed.
The "var" keyword is used to declare mutable variables, which are similar
to regular Java variables. The value of a mutable variable can be changed
throughout the code.
Here's an example of declaring a variable using the "val" keyword:
val greeting: String = "Hello, world!"

var count: Int = 0

The main difference between Kotlin and Java when it comes to variable
declaration is that Kotlin requires you to specify the type of the variable
explicitly, whereas in Java, the type can be inferred from the value being
assigned to the variable.

2.Write a kotlin program to display given number


is palindrome or not.
Ans - fun main() {
var n = 1214
val origN = n
var reverseN = 0
while (n != 0) {
val remainder = n % 10
reverseN = reverseN * 10 + remainder
n /= 10
}
if(reverseN == origN){
print("$origN is palindrome")
}
else {
print("$origN is not palindrome")
}

}
3. Write a program to print factorial of number
24 in kotlin.
Ans - fun main(args: Array<String>) {
val num = 5
var factorial = 1
for (i in 1..num) {
factorial *= i
}
println("Factorial of $num = $factorial")
}

4. Write a program to check given String is


Palindrome or not
Ans – fun main() {
val str = "racecar" // replace with your string input
val isPalindrome = isPalindrome(str)
if (isPalindrome) {
println("$str is a palindrome")
} else {
println("$str is not a palindrome")
}
}

fun isPalindrome(str: String): Boolean {


val reversed = str.reversed()
return str == reversed
}

5. Write a program to check given number is


Armstrong or not
Ans –

6. Write a Program to use function in


Kotlin(add,Sub,Mult,divide).
Ans – fun main() {
val num1 = 10
val num2 = 5

println("Add :" + add(num1,num2))


println("Sub :" + sub(num1,num2))
println("Multi :" + mult(num1,num2))
println("Div :" + div(num1,num2))
}
fun add(a: Int, b: Int): Int {
return a + b
}

fun sub(a: Int, b: Int): Int {


return a - b
}

fun mult(a: Int, b: Int): Int {


return a * b
}

fun div(a: Int, b: Int): Double {


return a.toDouble() / b.toDouble()
}

7. What is function in Kotlin and how it is


declare.
Ans - Functions are an important feature of Kotlin programming language.
They are used to perform a specific task or set of instructions. Here are
some key points about functions in Kotlin:
Functions are declared using the fun keyword followed by the function
name, parameter list (if any), return type (if any), and the function body
enclosed in curly braces.
Functions can take zero or more parameters, which are enclosed in
parentheses after the function name. Each parameter consists of a name
and a type, separated by a colon.
Functions can return a value, which is specified by the return type. If the
function does not return a value, then the return type should be Unit.
Here is an example of a simple function in Kotlin:
fun sayHello() {

println("Hello, World!")

fun main() {

sayHello()

}
8. Explain Boolean operator with example in
kotlin
Ans - Kotlin has three Boolean operators: && (logical AND), || (logical OR),
and ! (logical NOT). Here are some examples of how these operators work
in Kotlin:
Logical AND (&&): This operator returns true only if both operands are
true. Otherwise, it returns false. For example:
fun main(){

val a = true
val b = false
println(a && b)

Logical OR (||): This operator returns true if either operand is true. If both
operands are false, it returns false. For example:
fun main(){

val a = true
val b = false
println(a || b)

Logical NOT (!): This operator negates the operand, returning true if it is
false, and false if it is true. For example:
fun main(){

val a = true
val b = !a
println(b)

These Boolean operators are often used in conditional statements and


loops to control the flow of the program based on the outcome of Boolean
expressions.

9. Explain arithmetic operator with example


Ans - An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. Arithmetic operators are used to
perform mathematical operations on numeric values. Kotlin supports
several arithmetic operators, including:
Addition (+): This operator adds two values together. For example:
fun main(){

val a = 5
val b = 3
println(a + b)

}
Subtraction (-): This operator subtracts one value from another. For
example:
fun main(){

val a = 5
val b = 3
println(a - b)

}
Multiplication (*): This operator multiplies two values together. For
example:
fun main(){

val a = 5
val b = 3
println(a * b)

}
Division (/): This operator divides one value by another. For example:
fun main(){

val a = 5
val b = 3
println(a / b)

}
Modulo (%): This operator returns the remainder of one value divided by
another. For example:
fun main(){

val a = 5
val b = 3
println(a % b)

10. What’s init block in Kotlin


Ans - In Kotlin, the init block is a special type of block that is executed
when an instance of a class is created. It is used to initialize properties or
perform other setup tasks for the class. It is similar to a constructor in
Java, but unlike a constructor, an init block can be used to initialize
properties that do not have default values.
The init block is defined inside the class body, and it can contain any code
that needs to be executed before the class can be used. The init block is
executed when an instance of the class is created. It can contain any code
that needs to be executed before the class can be used. For example:
class MyClass(val name: String) {
init {
println("Initializing MyClass with name $name")
}
}

fun main(){

var c = MyClass("Hello")

11. Explain with example the continue and break


Ans - In Kotlin, break and continue are control flow statements used inside
loops to alter the program flow.
The break statement is used to terminate a loop prematurely. When the
break statement is encountered inside a loop, the loop is immediately
terminated, and the program control resumes at the statement
immediately following the loop. Here's an example:
fun main(){

for (i in 1..10) {
if (i == 5) {
break
}
println(i)
}

}
In this example, the for loop prints the numbers from 1 to 10, but the loop
terminates when i becomes 5 due to the break statement. Therefore, the
output of the program is:
1234
The continue statement is used to skip the current iteration of a loop
and move to the next iteration. When the continue statement is
encountered inside a loop, the current iteration is skipped, and the loop
continues with the next iteration. Here's an example:
fun main(){

for (i in 1..10) {
if (i % 2 == 0) {
continue
}
println(i)
}

In this example, the for loop prints only the odd numbers from 1 to 10.
The if statement inside the loop checks if i is even using the modulo
operator %. If i is even, the continue statement is executed, and the loop
continues with the next iteration. Therefore, the output of the program is:
13579
Both break and continue statements can be used with while and do-while
loops as well.

12. Explain with example the while loop.


Ans - In Kotlin, the while loop is used to execute a block of code
repeatedly as long as a given condition is true. The condition is checked at
the beginning of each iteration, and if it is true, the loop body is executed.
If the condition is false, the loop is terminated.
Here's an example of using the while loop :
fun main() {
var i = 1
while (i <= 5) {
println(i)
i++
}
}

In this example, the loop iterates as long as the value of i is less than or
equal to 5. Inside the loop body, the current value of i is printed, and then
i is incremented by 1 using the ++ operator.

13.What’s Null Safety and Nullable Types in


Kotlin? What is the Elvis Operator?
Ans - Null safety is an important feature of Kotlin programming language
that helps prevent the common problem of NullPointerExceptions that are
prevalent in languages that don't have built-in null safety mechanisms.
Kotlin enforces null safety at compile-time, which means that the compiler
will check if a variable can be null or not, and it will enforce the necessary
checks to ensure that null values are not passed to non-nullable types.
In Kotlin, nullable types are explicitly defined by appending a question
mark ? to the type. This indicates that the variable can hold a value of the
given type or be null. For example, String? is a nullable type that can
hold a string value or null.
To access the value of a nullable type, you can use the Elvis operator ?:.
This operator allows you to provide a default value to use if the variable is
null. For example, val result = nullableVariable ?: defaultValue will
assign defaultValue to result if nullableVariable is null, or assign the
value of nullableVariable to result if it is not null.

14. List down the visibility modifiers available in


Kotlin. What’s the default visibility modifier?
Ans - In Kotlin, there are four visibility modifiers that can be used to
restrict the visibility of a class, object, interface, constructor, function,
property, or type alias:
public: The public modifier is the default modifier and it means that the
declaration is visible everywhere in the code, including outside the
defining module.
private: The private modifier restricts the visibility of the declaration to
within the file that contains the declaration. Private declarations are not
visible outside the file.
internal: The internal modifier restricts the visibility of the declaration to
within the same module. A module is a set of Kotlin files that are compiled
together. Internal declarations are not visible outside the module.
protected: The protected modifier restricts the visibility of a declaration
to within the same class or its subclasses. This modifier can only be used
with class members.
// public declaration
class PublicClass

// private declaration
private class PrivateClass

// internal declaration
internal class InternalClass

// protected declaration
open class ParentClass {
protected val protectedProperty = "protected"
}

class ChildClass : ParentClass() {


fun printParentProperty() {
println(protectedProperty)
}
}

15.Explain Architecture of android.


Ans - Android architecture contains different number of components to
support any android device needs. Android software contains an open-
source Linux Kernel having collection of number of C/C++ libraries which
are exposed through an application framework service.
The main components of android architecture are following: -
Applications - Applications is the top layer of android architecture. The
pre-installed applications like home, contacts, camera, gallery etc and
third-party applications downloaded from the play store like chat
applications, games etc. will be installed on this layer only.
Application Framework - Application Framework provides several
important classes which are used to create an Android application. It
provides a generic abstraction for hardware access and also helps in
managing the user interface with application resources.
Android Runtime-Android Runtime environment is one of the most
important parts of Android. It contains components like core libraries and
the Dalvik virtual machine (DVM).
Platform Libraries - The Platform Libraries includes various C/C++ core
libraries and Java based libraries such as Media, Graphics, Surface
Manager, OpenGL etc. to provide a support for android development.
Linux Kernel - Linux Kernel is heart of the android architecture. It
manages all the available drivers such as display drivers, camera drivers,
Bluetooth drivers, audio drivers, memory drivers, etc. which are required
during the runtime.

16. What are the types of constructors in Kotlin?


How are they different? How do you define them
in your class?
Ans - In Kotlin, there are two types of constructors: primary constructors
and secondary constructors.
Primary Constructor: The primary constructor is defined in the class
header, and it is used to define the class properties or member variables.
The primary constructor can be either empty or can have one or more
parameters. If the constructor has parameters, then they need to be
declared after the class name.
Here is an example of a class with a Primary constructor:
class Person(val name: String, var age: Int) {
// class body
}

Secondary Constructor: A secondary constructor is defined using the


constructor keyword and is used to provide additional functionality to
the class. A class can have one or more secondary constructors, but they
must call the primary constructor using the this keyword.
c
class Person {
var name: String = ""
var age: Int = 0

constructor(name: String, age: Int) {


this.name = name
this.age = age
}

// other methods and properties


}

17. What are the use of Using SQLite Databases.


Ans - SQLite is a lightweight, embedded database that is widely used in
mobile app development, including Android app development. Here are
some of the common use cases for using SQLite databases in mobile
apps:
Storing structured data: SQLite allows you to store structured data in a
relational database. This can be useful for storing user data, such as user
profiles, preferences, and settings.
Caching data: SQLite can be used to cache frequently accessed data,
such as images or frequently accessed server data, to improve app
performance and reduce network calls.
Offline data access: SQLite databases can be used to store data offline,
allowing the app to function even when the device is not connected to the
internet.
Data synchronization: SQLite can be used to store data on the device
that can be synchronized with a remote server when the device is
connected to the internet.
Analytics: SQLite can be used to store data for analytics purposes, such
as user behaviour or app usage metrics.
Content providers: In Android, SQLite databases can be used as a local
data store for content providers, which are used to share data between
apps.

18. Write short note on Internal Storage.


Ans - Internal storage is a private storage area within an Android device
that is allocated to an app by default. It is used to store private data that
is specific to the app, such as user settings, preferences, and app-specific
data. This data is stored in the device's internal memory, which is not
accessible to other apps or to the user.
To access the internal storage in an Android app, you can use the
getFilesDir() method to get a reference to the app's internal storage
directory. You can then use standard file I/O operations to read and write
files in this directory.
One of the main advantages of using internal storage is that it provides a
secure and reliable way to store sensitive app data. Since the internal
storage is private to the app, other apps and users cannot access the data
without the app's permission.
However, internal storage has some limitations. It has a limited amount of
space available, and if the device runs out of storage space, the app may
crash or behave unpredictably. Additionally, the data stored in internal
storage is lost when the app is uninstalled.

19. What is firebase where it is use?


Ans - Firebase is a mobile and web application development platform
developed by Google that provides a range of cloud-based services for
building, managing, and scaling mobile and web applications. Firebase
includes a variety of tools and services such as authentication, real-time
database, storage, hosting, cloud messaging, and more.
Firebase is used by developers to build and deploy high-quality
applications quickly and easily. It provides an all-in-one platform for
handling all the backend requirements of a mobile or web application.
Firebase provides a number of benefits such as:
Real-time data synchronization: Firebase's real-time database allows
developers to build real-time applications that synchronize data in real-
time across all connected devices.
Scalability: Firebase can scale to meet the needs of applications of any
size, from small to large.
Easy to use: Firebase provides a simple and intuitive API that makes it
easy for developers to integrate the platform into their applications.
Security: Firebase provides robust security features to ensure that data is
secure and protected.

20. Write note on Recycle view.


Ans - Recycler View is a flexible and powerful view for displaying lists and
grids of data in Android applications. It is a more advanced version of List
View and Grid View, with a more modular and efficient architecture.
Recycler View provides a number of benefits, including:
Improved performance: Recycler View is optimized for performance and
memory efficiency, which makes it ideal for displaying large data sets. It
uses a View Holder pattern to recycle views and optimize performance.
Flexibility: Recycler View is highly customizable and can be used to
display complex lists and grids with a wide range of item types and
layouts.
Animations and touch events: Recycler View support animations and
swipe gestures, which can improve the user experience and make the app
more engaging.
Integration with other Android components: Recycler View
integrates well with other Android components such as the View Pager
and Fragment, which makes it easier to build complex user interfaces.

21. Write how the switch statement is declare in


kotlin
Ans - In Kotlin, the switch statement is replaced with the when expression.
The when expression is more flexible and powerful than the traditional
switch statement and can be used to check the value of an expression
against multiple possible values and perform different actions based on
the match.
Here's an example of how to use the when expression in Kotlin:
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
3, 4 -> println("x is 3 or 4")
in 5..10 -> println("x is between 5 and 10")
else -> println("x is not in the range")
}

22. Explain Screen Navigation in detail


Ans - Screen navigation is an important aspect of mobile application
development as it allows users to move between different screens or
activities within an app. In Android, there are several ways to implement
screen navigation, including:
Intent-based navigation: This method uses intents to navigate between
screens. When the user clicks on a button or performs some other action,
an intent is created and sent to the system, which then starts a new
activity or service.
Fragment-based navigation: Fragments are reusable UI components
that can be used to build dynamic and flexible UIs. They can be used to
create reusable UI elements that can be shared across different screens in
an app.
Tab-based navigation: This method allows users to navigate between
different screens using tabs. Each tab represents a different screen or
activity within the app.
Drawer-based navigation: This method allows users to navigate
between different screens by using a navigation drawer. The drawer slides
out from the side of the screen and displays a list of available screens or
activities.

23. Explain Thread in details


Ans - Thread is one of the important concepts in Android. Thread is a
lightweight sub-process that provides us a way to do background
operations without interrupting the User Interface (UI). When an app is
launched, it creates a single thread in which all app components will run
by default. The thread which is created by the runtime system is known as
the main thread. The main thread’s primary role is to handle the UI in
terms of event handling and interaction with views in the UI. If there is a
task that is time-consuming and that task is run on the main thread, then
it will stop other tasks until it gets completed, which in turn may result in
displaying a warning “Application is unresponsive” to the user by the
operating system. So, we need different threads for such tasks and some
other tasks.
All threading components belong to one of two basic categories.
The fragment or activity attached threads: This category of threads
is bound to the lifecycle of the activity/fragment and these are terminated
as soon as the activity/fragment is destroyed.
The fragment or activity not attached threads: These types of
threads can continue to run beyond the lifetime of the activity or fragment
from which they were spawned.

24. What are different UI tools use in android.


Ans - There are several UI tools that are commonly used in Android
development. Some of the most popular ones include:
Layouts: These are used to define the visual structure of an app's user
interface. Android provides a variety of pre-built layout types, such as
LinearLayout and RelativeLayout, as well as tools for creating custom
layouts.
Views: These are the building blocks of the user interface, representing
the individual UI elements that are displayed on the screen, such as
buttons, text fields, and images.
Fragments: These are modular UI components that can be combined to
create complex user interfaces. Fragments can be dynamically added and
removed from an activity, allowing for more flexibility in designing the
user interface.
RecyclerView: This is a flexible and efficient way to display large sets of
data in a scrolling list or grid.
ViewPager: This is a UI component that allows users to swipe between
different pages or fragments. It is commonly used in apps that have
multiple screens or tabs.

25.Explain Broadcast Receivers.


Ans - Broadcast Receivers in Android are a component that enables your
app to receive system-wide or app-wide events and intents, even when
your app is not currently running. It allows you to listen and respond to
various system and app events, such as incoming calls, SMS messages,
device booting, network connectivity changes, battery status, and many
more.
Broadcast Receivers have three key components:
Intent Filters: A Broadcast Receiver must declare an intent filter that
specifies the types of broadcasts it wants to receive. The intent filter
specifies the action or event that the Broadcast Receiver will handle.
onReceive() method: This method is called when the Broadcast
Receiver receives the intent. It is where you define the behaviour of your
Broadcast Receiver when it receives a specific broadcast.
Context: A Broadcast Receiver is a subclass of Context, which means it
can perform various operations such as starting an Activity, launching a
Service, sending a broadcast, etc.

27.What is List View? where it is use?


Ans - List View is a view group that displays a list of items, where each
item can be selected or clicked, and it is one of the most commonly used
UI components in Android app development. List View is used to display a
scrollable list of items that can be dynamically updated based on user
interaction or other events.
List View is commonly used in Android app development to display various
types of content, such as contacts, music files, images, messages, and
more. It allows users to scroll through a list of items and select one or
more items based on their needs. List View is highly customizable, and it
supports various layout styles, such as simple lists, grids, and complex
layouts with multiple columns and rows.

28.Explain Content Provider


Ans - A Content Provider is one of the fundamental components of the
Android operating system that allows applications to securely share data
with other applications. It acts as a mediator between an application and
its data storage, providing a standardized interface for accessing data
from one application to another.
Content Providers enable the reuse of data across multiple applications,
and allow developers to create more powerful and flexible applications
that can interact with each other seamlessly.
Some examples of data that can be shared using Content Providers
include contacts, calendar events, media files, and settings information.
Each Content Provider defines a set of data that can be accessed by other
applications, and provides methods for querying, inserting, updating, and
deleting that data.

You might also like