Snippets Collections
java 
Copy code 
import java.sql.Connection; 
import java.sql.DatabaseMetaData; 
import java.sql.DriverManager; 
 
public class DatabaseMetadata { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      DatabaseMetaData dbMeta = con.getMetaData(); 
      System.out.println("Database Product Name: " + dbMeta.getDatabaseProductName()); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
Database Product Name: MySQL
[OR]
import java.sql.*;

public class App {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:mysql://localhost:3306/your_database_name";
        String username = "your_username";
        String password = "your_password";
        Connection connection = null;

        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish connection to the database
            connection = DriverManager.getConnection(jdbcURL, username, password);

            // Retrieve and print database metadata
            DatabaseMetaData metaData = connection.getMetaData();
            System.out.println("Database Product Name: " + metaData.getDatabaseProductName());
            System.out.println("Database Product Version: " + metaData.getDatabaseProductVersion());
            System.out.println("Driver Name: " + metaData.getDriverName());
            System.out.println("Driver Version: " + metaData.getDriverVersion());
        } catch (Exception e) {
            // Handle exceptions
            e.printStackTrace();
        } finally {
            // Close the connection
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
java 
Copy code 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Statement; 
 
public class DatabaseConnection { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      Statement stmt = con.createStatement(); 
      stmt.executeUpdate("INSERT INTO books (title) VALUES ('Sample Book')"); 
      System.out.println("SQL Query Executed"); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
SQL Query Executed
[OR]
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
 
public class App { 
    public static void main(String[] args) { 
        // Database credentials 
        String url = "jdbc:mysql://localhost:3306/testdb"; 
        String user = "root"; 
        String password = "Varun13@"; 
 
        // SQL query 
        String query = "SELECT * FROM books"; 
 
        // Establish connection and execute query 
        try (Connection conn = DriverManager.getConnection(url, user, password); 
             Statement stmt = conn.createStatement(); 
             ResultSet rs = stmt.executeQuery(query)) { 
 
            System.out.println("Connected to the database!"); 
 
            // Process the result set 
            while (rs.next()) { 
                int id = rs.getInt("id"); 
                String name = rs.getString("name"); 
                System.out.println("ID: " + id + ", Name: " + name); 
            } 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
Connected to the database!
java 
Copy code 
import java.io.*;
import javax.xml.parsers.*;

public class DOMValidator {
    public static void main(String[] args) {
        try {
            System.out.println("Enter the XML file name:");
            File file = new File(new BufferedReader(new InputStreamReader(System.in)).readLine());
            if (file.exists() && isWellFormed(file)) {
                System.out.println(file.getName() + " is well-formed.");
            } else {
                System.out.println(file.exists() ? "Not well-formed." : "File not found.");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    private static boolean isWellFormed(File file) {
        try {
            DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

 
xml 
Copy code 
hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Java Programming</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>XML Development</title>
        <author>Jane Smith</author>
    </book>
</library>

 
output:XML is valid
1.// getter and setter properties

class CSE {
    var name: String = " "
        get() = field        // getter
        set(value) {         // setter
            field = value
        }
}
fun main(args: Array<String>) {
    val c = CSE()
    c.name = "WELCOME TO CSE-B"   // access setter
    println(c.name)               // access getter
}

Output:
WELCOME TO CSE-B



2.// object accessing

class CSE {
    fun Mobile() = println("WELCOME TO MAD LAB")
}
fun main(args: Array<String>) {     
    val obj = CSE()
    // calling Mobile() method using object obj
    obj.Mobile()
}

Output:
WELCOME TO MAD LAB

3.// companion object
class CSE {
    companion object Test  {                 //companion object name Test
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }
}
fun main(args: Array<String>) {
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB


4.// accessing variable and method using class name in companion object 

class CSE
 {
    companion object Test  
   {                  //companion object name Test
        var v:Int=100
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }  
}
fun main(args: Array<String>) 
{
    println(CSE.v)    // accessing variable using class name
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB


5.// creating the employee class
class employee {
	// properties / member variables
	var name: String = "XYZ"
	var age: Int = 10
	var gender: Char = 'M'
	var salary: Double = 500.toDouble()
	
	// member functions
	fun display(){
         println("WELCOME TO CSE-B")
	}
}
fun main()
{
    var obj=employee()         //object creation for class
    obj.display()              // accessing member function using object name
    // accessing properties using object name
    println(obj.name)
    println(obj.age)
    println(obj.gender)
    println(obj.salary)
    
}

Output:

WELCOME TO CSE-B
XYZ
10
M
500.0


6.//DICE ROLLER PROGRAM USING CLASSES
// Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
//IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. 
//IntRange is a suitable data type for representing the possible values a dice roll can produce.
class Dice {
    var sides = 6
    fun roll(): Int {
        //random() function to generate random numbers. 
        //random() takes a series of numbers as an input and it returns a random Int as an output.
        val randomNumber = (1..sides).random()  
        return randomNumber
    }
}
fun main() {
    val myFirstDice = Dice()
    val diceRoll = myFirstDice.roll()
    println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!")

    myFirstDice.sides = 20
    println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!")
}

Output:
Your 6 sided dice rolled 4!
Your 20 sided dice rolled 7!


7.// random() function
fun main() {
   // random() generates a random number between 0 to 10
   println((0..10).random())
}

Output:
7



8.//primary constructor
fun main(args: Array<String>)
{
	val add = Add(5, 6)
	println("The Sum of numbers 5 and 6 is: ${add.c}")
}
class Add constructor(a: Int,b:Int)
{
	var c = a+b;
}

Output:
The Sum of numbers 5 and 6 is 11



9.//secondary constructor
fun main(args: Array<String>)
{
	Add(5, 6)
}
//class with one secondary constructor
class Add
{
	constructor(a: Int, b:Int)
	{
		var c = a + b
		println("The sum of numbers 5 and 6 is: ${c}")
	}
}


Output:
The Sum of numbers 5 and 6 is 11

10.//this keyword and  Constructor Declaration of Class
//Kotlin program of creating multiple objects and accessing the property and member function of class:
class employee {
	var name: String = ""
	var age: Int = 0
	var gender: Char = 'M'
	var salary: Double = 0.toDouble()

	fun insertValues(n: String, a: Int, g: Char, s: Double) {
		name = n
		age = a
		gender = g
		salary = s
		println("Name of the employee: $name")
		println("Age of the employee: $age")
		println("Gender: $gender")
		println("Salary of the employee: $salary")
	}
	
	fun insertName(n: String) {
		this.name = n
	}

}
fun main(args: Array<String>) {
	// creating multiple objects
	var obj = employee()
	
	// object 2 of class employee
	var obj2 = employee()

	//accessing the member function
	obj.insertValues("X1", 50, 'M', 500000.00)

	// accessing the member function
	obj2.insertName("X2")

	// accessing the name property of class
	println("Name of the new employee: ${obj2.name}")

}


Output:

Name of the employee: X1
Age of the employee: 50
Gender: M
Salary of the employee: 500000.0
Name of the new employee: X2




11.//INHERITENCE IN KOTLIN
//base class
open class baseClass{
	val name = "CSE-B"
	fun A(){
		println("Base Class")
	}
}
//derived class
class derivedClass: baseClass() {
	fun B() {
		println(name)		 //inherit name property
		println("Derived class")
	}
}
fun main(args: Array<String>) {
	val obj = derivedClass()
	obj.A()		 // inheriting the base class function
	obj.B()		 // calling derived class function
}


Output:

Base Class
CSE-B
Derived class




12. //DWELLINGS PROGRAM
 /**
* Program that implements classes for different kinds of dwellings.
* Shows how to:
* Create class hierarchy, variables and functions with inheritance,
* abstract class, overriding, and private vs. public variables.
*/

import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
   val squareCabin = SquareCabin(6, 50.0)
   val roundHut = RoundHut(3, 10.0)
   val roundTower = RoundTower(4, 15.5)

   with(squareCabin) {
       println("\nSquare Cabin\n============")
       println("Capacity: ${capacity}")
       println("Material: ${buildingMaterial}")
       println("Floor area: ${floorArea()}")
   }

   with(roundHut) {
       println("\nRound Hut\n=========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Carpet size: ${calculateMaxCarpetLength()}")
   }

   with(roundTower) {
       println("\nRound Tower\n==========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Carpet Length: ${calculateMaxCarpetLength()}")
   }
}


/**
* Defines properties common to all dwellings.
* All dwellings have floorspace,
* but its calculation is specific to the subclass.
* Checking and getting a room are implemented here
* because they are the same for all Dwelling subclasses.
*
* @param residents Current number of residents
*/
abstract class Dwelling(private var residents: Int) {
   abstract val buildingMaterial: String
   abstract val capacity: Int

   /**
    * Calculates the floor area of the dwelling.
    * Implemented by subclasses where shape is determined.
    *
    * @return floor area
    */
   abstract fun floorArea(): Double

   /**
    * Checks whether there is room for another resident.
    *
    * @return true if room available, false otherwise
    */
   fun hasRoom(): Boolean {
       return residents < capacity
   }

   /**
    * Compares the capacity to the number of residents and
    * if capacity is larger than number of residents,
    * add resident by increasing the number of residents.
    * Print the result.
    */
   fun getRoom() {
       if (capacity > residents) {
           residents++
           println("You got a room!")
       } else {
           println("Sorry, at capacity and no rooms left.")
       }
   }

   }

/**
* A square cabin dwelling.
*
*  @param residents Current number of residents
*  @param length Length
*/
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
   override val buildingMaterial = "Wood"
   override val capacity = 6

   /**
    * Calculates floor area for a square dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return length * length
   }

}

/**
* Dwelling with a circular floorspace
*
* @param residents Current number of residents
* @param radius Radius
*/
open class RoundHut(
       residents: Int, val radius: Double) : Dwelling(residents) {

   override val buildingMaterial = "Straw"
   override val capacity = 4

   /**
    * Calculates floor area for a round dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return PI * radius * radius
   }

   /**
    *  Calculates the max length for a square carpet
    *  that fits the circular floor.
    *
    * @return length of square carpet
    */
    fun calculateMaxCarpetLength(): Double {
        return sqrt(2.0) * radius
    }
}

/**
* Round tower with multiple stories.
*
* @param residents Current number of residents
* @param radius Radius
* @param floors Number of stories
*/
class RoundTower(
       residents: Int,
       radius: Double,
       val floors: Int = 2) : RoundHut(residents, radius) {

   override val buildingMaterial = "Stone"

   // Capacity depends on the number of floors.
   override val capacity = floors * 4

   /**
    * Calculates the total floor area for a tower dwelling
    * with multiple stories.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return super.floorArea() * floors
   }
}

Output:
Square Cabin
============
Capacity: 6
Material: Wood
Floor area: 2500.0

Round Hut
=========
Material: Straw
Capacity: 4
Floor area: 314.1592653589793
Has room? true
You got a room!
Has room? false
Sorry, at capacity and no rooms left.
Carpet size: 14.142135623730951

Round Tower
==========
Material: Stone
Capacity: 8
Floor area: 1509.5352700498956
Carpet Length: 21.920310216782976





13.//repeat  statement
fun main(args: Array<String>) {
    repeat(4) {
        println("WELCOME TO CSE-B!")
    }
}


Output:

WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!




14. // INIT BLOCK
class InitOrderDemo(name: String) {
    val firstProperty = "First property: $name".also(::println)
    
    init {
        println("First initializer block that prints $name")
}
  val secondProperty = "Second property:${name.length}".also(::println)
    
    init {
        println("Second initializer block that prints ${name.length}")
    }
}

fun main() {
    InitOrderDemo("hello")
}

Output:
First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5

15.//RANGETO() function
fun main(args : Array<String>){

	println("Integer range:")
	// creating integer range
	for(num in 1.rangeTo(5)){
		println(num)
	}
}

Output:
Integer range:
1
2
3
4
5




16. //downTo() function

fun main(args : Array<String>){

	println("Integer range in descending order:")
	// creating integer range
	for(num in 5.downTo(1)){
		println(num)
	}
}
Output:

Integer range in descending order:
5
4
3
2
1


17. //step keyword

fun main(args: Array<String>) {
	//for iterating over the range
	var i = 2
	// for loop with step keyword
	for (i in 3..10 step 2)
		print("$i ")
	println()
	// print first value of the range
	println((11..20 step 2).first)
	// print last value of the range
	println((11..20 step 4).last)
	// print the step used in the range
	println((11..20 step 5).step)
}

Output:

3 5 7 9 
11
19
5



18. //reversed function
fun main(args: Array<String>) {
	var range = 2..8
	for (x in range.reversed()){
		print("$x ")
	}
}

Output:
8 7 6 5 4 3 2 





19. //In Operator Example Program in Kotlin
 fun main(args: Array<String>) {
    val collection = 10..20
    val num2 = 5

    println("in operator in if condition")
    if (15 in collection) {
        println("15 is in $collection")
    }

    println("\nin operator in for loop")
    for(item in collection){
        println("$item is in $collection")
    }

    println("\nin operator in when statement")
    when{
        19 in collection -> println("19 in collection is true")
    }
}


Output:
in operator in if condition
15 is in 10..20

in operator in for loop
10 is in 10..20
11 is in 10..20
12 is in 10..20
13 is in 10..20
14 is in 10..20
15 is in 10..20
16 is in 10..20
17 is in 10..20
18 is in 10..20
19 is in 10..20
20 is in 10..20

in operator in when statement
19 in collection is true
1.//Standard Library Function 

fun main(args: Array<String>) 
{
   // arrayOf()-- to create an array by passing the values of the elements to the function.
	var sum = arrayOf(1,2,3,4,5,6,7,8,9,10).sum()

	println("The sum of all the elements of an array is: $sum")
}

Output:

The sum of all the elements of an array is: 55


2.//  Kotlin user-defined function student() having different types of parameters-
fun student(name: String , roll_no: Int , grade: Char) 
{
	println("Name of the student is : $name")
	println("Roll no of the student is: $roll_no")
	println("Grade of the student is: $grade")
    
}

fun main(args: Array<String>) {
    var result = student("CSE-B",66,'A')
    println("Details of Student: $result")
}
Output:
Name of the student is : CSE-B
Roll no of the student is: 66
Grade of the student is: A 

[OR]


//  Kotlin user-defined function student() having different types of parameters-
fun student(name: String , roll_no: Int , grade: Char) {
	println("Name of the student is : $name")
	println("Roll no of the student is: $roll_no")
	println("Grade of the student is: $grade")
    
}

fun main(args: Array<String>) {
    student("CSE-B",66,'A')
    
}

Output:
Name of the student is : CSE-B
Roll no of the student is: 66
Grade of the student is: A




3. //  function with parameter & with return type               
fun CSE_B(x: Int): Int 
{
  return (x + 5)
}

fun main() 
{
  var result = CSE_B(3)
  println(result)
}

Output:

8



4.//  function WITHOUT PARAMETERS & WITHOUT RETURN TYPE              
fun  CSE_B()
{
  println("WELCOME TO MAD LAB")
}

fun main() 
{
  CSE_B()
 
}

Output:

WELCOME TO MAD LAB




5.//  demonstrate how to pass a variable number of arguments to a function  Using vararg              
fun main (args: Array<String>)
{
   CSE_B ( "abc", "def", "ghi", "123", "sun")
}

fun CSE_B (vararg a: String) 
{
    for (a_ in a) 
    {
	    println(a_)
    }
}

Output:

abc
def
ghi
123
sun


6.//  lambda function              
fun main(args: Array<String>){  
   val myLambda: (Int) -> Unit= {s: Int -> println(s) } //lambdafunction  
    addNumber(5,10,myLambda)  
}  
//The variable mylambda in function definition is actually a lambdafunction.
fun addNumber(a: Int, b: Int, mylambda: (Int) -> Unit ){   
    //high level function lambda as parameter  
    val add = a + b  
    mylambda(add) // println(add)  
}

Output:
15 


7.//  lambda function              
// with type annotation in lambda expression
val sum1 = { a: Int, b: Int -> a + b }
// Kotlin program of using lambda expression-
//  without type annotation in lambda expression
val sum2:(Int,Int)-> Int = { a , b -> a + b}
fun main(args: Array<String>) 
{
	val result1 = sum1(2,3)
	val result2 = sum2(3,4)
	println("The sum of two numbers is: $result1")
	println("The sum of two numbers is: $result2")
	// directly print the return value of lambda
	// without storing in a variable.
	println(sum1(5,7))     
}

Output:

The sum of two numbers is: 5
The sum of two numbers is: 7
12


8.// anonymous function 

// anonymous function  with body as an expression
val anonymous1 = fun(x: Int, y: Int): Int = x + y
// anonymous function with body as a block
val anonymous2 = fun(a: Int, b: Int): Int 
{
			val mul = a * b
			return mul
}
fun main(args: Array<String>) 
{
	//invoking functions
	val sum = anonymous1(3,5)
	val mul = anonymous2(3,5)
	println("The sum of two numbers is: $sum")
	println("The multiply of two numbers is: $mul")
}

Output:
The sum of two numbers is: 8
The multiply of two numbers is: 15



9.//Kotlin program of lambda expression which returns Unit-	
var lambda = {println("WELCOME TO CSE-B MAD LAB")}  
   // lambda expression
	// higher-order function
fun higherfunc( lmbd: () -> Unit )
{	 // accepting lambda as parameter
	lmbd()		//invokes lambda expression
}
fun main(args: Array<String>) 
{
	//invoke higher-order function
	higherfunc(lambda)   // passing lambda as parameter
}


Output:

WELCOME TO CSE-B MAD LAB



10. //Kotlin program of lambda expression which returns Integer value –  	
var lambda = {a: Int , b: Int -> a + b }         // lambda expression
	// higher order function
fun higherfunc( lmbd: (Int, Int) -> Int) 
{	 
    // accepting lambda as parameter	
	var result = lmbd(2,4)               // invokes the lambda expression by passing parameters				
	println("The sum of two numbers is: $result")
}
fun main(args: Array<String>) 
{
	higherfunc(lambda)  //passing lambda as parameter
}

Output:

The sum of two numbers is: 6




11. //Take input from user using readline() method 
fun main(args : Array<String>) {
	println("Enter text: ")
	var input = readLine()
	print("You entered: $input")
}

Output:
Enter text:  CSE-B
You entered: CSE-B
1.Sample Program
/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
fun main() 
{
    println("Hello, world!!!")
}
------------------------------------------------------------------------------------------------
2.// main() function with parameters
fun main(args : Array<String>) {
println("Hello World")
}
3.// val / var demonstration
fun main()
{
var name = "Kotlin"          // String (text)
val birthyear = 2023         // Int (number)

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear

}



OR

// val / var demonstration
fun main()
{
var name: String = "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int

println(name)
println(birthyear)

}



OR

// val / var demonstration
fun main()
{
var name: String 
    name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}


OR

// val / var demonstration
fun main()
{
var name
    name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}



//  var demonstration
fun main()
{
var name= "CSE B"
 name = "CVR"  //  can be reassigned
println(name)   
}


//  val demonstration
fun main()
{
val name= "CSE B"
 name = "CVR"  //  cannot be reassigned
println(name)   
}

4.//  DATA TYPE demonstration
fun main()
{
val a: Int = 5                // Int
val b: Double = 5.99        // Double
val c: Char = 'v'          // Char
val d: Boolean = true     // Boolean
val e: String = "CSE B"      // String
val f: Float = 100.00f      // float
println("a value is:" +a)
println("b value is:" +b)
println("c value is:" +c)
println("d value is:" +d)
println("e value is:" +e) 
println("f value is:" +f)
}

5.//  escape sequences of character demonstration
fun main()
{
println('\n') //prints a newline character
println('\t') //prints a  tab character
println('\b') //prints a backspace character
println('\r') //prints a form feed character
println('\'') //prints a single quote character
println('\"') //prints a double quote character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
}

6.//  ARRAY  demonstration
fun main()
{
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5)
 println("Value at 3rd position : " + n[2])
}
7.//  TYPE CONVERSION demonstration
fun main()
{
    val x: Int = 100
   val y: Long = x.toLong()
   println(y)
}



8.//  ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}

9.//  ASSIGNMENT OPERATOR demonstration
fun main()
{
    var sum1 = 100       // ASSIGN A VALUE
    println(sum1)
}


10.// COMPARISION  OPERATOR demonstration
fun main() {  
  var x = 5
 var y = 3
  println(x > y) // returns true because 5 is greater than 3
}
11.// logical  OPERATOR demonstration
fun main() {  
    var x = 5
  println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10

}


12.// STRING demonstration
fun main() {  
    var a:String="CSE B"
  println(a[2]) // DISPLAYS CHARACTER AT LOACTION OR INDEX 2

}




13.// IF ELSE demonstration
fun main() {  
  val x = 20
val y = 18
if (x > y) {
  println( "x is greater than y" )
}
else {
        println( "x is lesser than y" ) 
    } }

14.// WHEN demonstration
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}


15.// WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.// DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}



17.// FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}


18.// BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}



19.//CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}



20.//RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}



21.//ARRAY  demonstration
 fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
XML File (books.xml): 
 
xml 
Copy code 
 
<?xml version="1.0" encoding="UTF-8"?>
<books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="books.xsd">
    <book>
        <title>Wings of Fire</title>
        <author>A.P.J Abdul Kalam</author>
        <isbn>81-7371-146-1</isbn>
        <publisher>Arun Tiwar</publisher>
        <edition>1st</edition>
        <price>180</price>
    </book>
<book>
        <title>Introduction to xml</title>
        <author>Jane doe</author>
        <isbn>978-0451524935</isbn>
        <publisher>Tech Books Publisher</publisher>
        <edition>1st</edition>
        <price>29.99</price>
    </book>
</books>

 
 
XSD File (books.xsd):
 
xsd 
Copy code 
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
	xmlns:xs="http://www.w3.org/2001/XMLSchema">
	<xs:element name="books">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="title" type="xs:string" />
				<xs:element name="author" type="xs:string" />
				<xs:element name="isbn" type="xs:string" />
				<xs:element name="publisher" type="xs:string" />
				<xs:element name="edition" type="xs:string" />
				<xs:element name="price" type="xs:decimal" />
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>
XML File (books.xml): 
 
xml 
Copy code 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books SYSTEM "books.dtd">
<books>
    <book>
        <title>Wings of Fire</title>
        <author>A.P.J Abdul Kalam</author>
        <isbn>81-7371-146-1</isbn>
        <publisher>Arun Tiwar</publisher>
        <edition>1st</edition>
        <price>180</price>
    </book>
    <book>
        <title>Introduction to xml</title>
        <author>Jane doe</author>
        <isbn>978-0451524935</isbn>
        <publisher>Tech Books Publisher</publisher>
        <edition>1st</edition>
        <price>29.99</price>
    </book>
</books>
 

DTD File (books.dtd):

dtd 
Copy code 
<!ELEMENT books (book+)>
<!ELEMENT book (title, author, isbn, publisher, edition, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT isbn (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>

1.Develop an Android  Application to display message using Toast Class.

Activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

              //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}



Output:





2. Develop an Android  Application showing clipboard by performing Copy and Paste Operations.

Activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

            //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}



Outpu
<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <title>JavaScript Callbacks, Promises, Async/Await</title> 
</head> 
<body> 
  <h1>JavaScript Callbacks, Promises, and Async/Await Demo</h1> 
  <script> 
    // Callback Example 
    function doSomething(callback) { 
      setTimeout(() => { 
        callback("Callback done!"); 
      }, 1000); 
    } 
    doSomething(console.log); 
 
    // Promise Example 
    let promise = new Promise((resolve, reject) => { 
      setTimeout(() => resolve("Promise resolved!"), 1000); 
    }); 
    promise.then(console.log); 
 
    // Async/Await Example 
    async function asyncFunction() { 
      let result = await promise; 
      console.log(result); 
    } 
    asyncFunction(); 
  </script> 
</body> 
</html>
ACTIVITY_MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity"
 android:padding="20dp">
 <EditText
 android:id="@+id/eTxt"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 app:layout_constraintBottom_toTopOf="@+id/btn_click"
 android:hint="Type Here"
 android:layout_margin="20dp"
 android:textSize="20sp"
 android:textColor="@color/purple_500"
 />
 <Button
 android:id="@+id/btn_click"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="Click Here"
 android:textSize="20sp"
 android:textColor="#fff"
 android:layout_margin="20dp"
 android:background="@color/black"
 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintLeft_toLeftOf="parent"
 app:layout_constraintRight_toRightOf="parent"
 app:layout_constraintTop_toTopOf="parent"
 />
 <TextView
 android:id="@+id/tvShow"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="20dp"
 app:layout_constraintTop_toBottomOf="@+id/btn_click"
 android:textSize="20sp"
 android:textStyle="bold"
 android:text="Show"
 android:textColor="#FF5722"
 />
</androidx.constraintlayout.widget.ConstraintLayout>
MAINACTIVITY.kt
package com.example.my_viewbinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.example.my_viewbinding.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 //setContentView(R.layout.activity_main)
 var binding = ActivityMainBinding.inflate(layoutInflater)
 val view = binding.root
 setContentView(view)
 // var btn1 : Button = findViewById(R.id.btn_click)
 // btn1.setOnClickListener(){
 //var etxt1 : EditText = findViewById(R.id.eTxt)
 //var tv1: TextView = findViewById(R.id.tvShow)
 // var msg: String= etxt1.text.toString()
 //tv1.text=msg
 //}
 binding.btnClick.setOnClickListener(){
 binding.tvShow.setText(binding.eTxt.text)
 }
 }
}
NOTE:
build.gradle:
plugins {
 id 'com.android.application'
 id 'org.jetbrains.kotlin.android'
}
android {
 namespace 'com.example.my_viewbinding'
 compileSdk 33
 defaultConfig {
 applicationId "com.example.my_viewbinding"
 minSdk 24
 targetSdk 33
 versionCode 1
 versionName "1.0"
 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
 }
 viewBinding{
 enabled true
 }
 [OR]
buildFeatures {
 viewBinding = true
}
 buildTypes {
 release {
 minifyEnabled false
 proguardFiles 
getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
 }
 }
 compileOptions {
 sourceCompatibility JavaVersion.VERSION_1_8
 targetCompatibility JavaVersion.VERSION_1_8
 }
 kotlinOptions {
 jvmTarget = '1.8'
 }
}
dependencies {
 implementation 'androidx.core:core-ktx:1.7.0'
 implementation 'androidx.appcompat:appcompat:1.6.1'
 implementation 'com.google.android.material:material:1.9.0'
 implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
 testImplementation 'junit:junit:4.13.2'
 androidTestImplementation 'androidx.test.ext:junit:1.1.5'
 androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
OUTPUT:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Responsive Web Design</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }


        header {
            background-color: #3498db;
            color: white;
            padding: 20px;
            text-align: center;
        }


        .container {
            padding: 20px;
        }


        .content {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
        }

        .content div {
            background-color: #2980b9;
            color: white;
            text-align: center;
            padding: 20px;
            border-radius: 8px;
        }

        @media (max-width: 768px) {
            .content {
                grid-template-columns: repeat(2, 1fr);

            }
        }


        @media (max-width: 480px) {
            .content {
                grid-template-columns: 1fr;

            }

            header {
                padding: 15px;

            }

            .content div {
                font-size: 14px;

            }
        }
    </style>
</head>

<body>
    <header>
        <h1>Responsive Web Design</h1>
    </header>

    <div class="container">
        <div class="content">
            <div>Item 1</div>
            <div>Item 2</div>
            <div>Item 3</div>
        </div>
    </div>
</body>

</html>
popUpDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Pop-Up Boxes</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }

        button {
            padding: 10px 15px;
            font-size: 16px;
            margin: 10px;
        }
    </style>
</head>
<body>

    <h1>JavaScript Pop-Up Box Demonstration</h1>
    <button onclick="showAlert()">Show Alert</button>
    <button onclick="showConfirm()">Show Confirm</button>
    <button onclick="showPrompt()">Show Prompt</button>

    <script>
        function showAlert() {
            alert("This is an alert box!");
        }

        function showConfirm() {
            const result = confirm("Do you want to proceed?");
            if (result) {
                alert("You clicked OK!");
            } else {
                alert("You clicked Cancel!");
            }
        }

        function showPrompt() {
            const name = prompt("Please enter your name:");
            if (name) {
                alert("Hello, " + name + "!");
            } else {
                alert("No name entered.");
            }
        }
    </script>

</body>
</html>
<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Advanced Flexbox with Animations</title> 
<style> 
* { 
margin: 0; 
padding: 0; 
box-sizing: border-box; 
} 
body { 
font-family: Arial, sans-serif; 
background: linear-gradient(to right, #ff7e5f, #feb47b); 
color: #333; 
      display: flex; 
      justify-content: center; 
      align-items: center; 
      height: 100vh; 
      overflow: hidden; 
    } 
 
    .container { 
      display: flex; 
      flex-wrap: wrap; 
      justify-content: space-around; 
      align-items: center; 
      gap: 20px; 
      padding: 20px; 
      max-width: 900px; 
      background-color: rgba(255, 255, 255, 0.2); 
      border-radius: 15px; 
      box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2); 
      animation: fadeIn 1.5s ease-in-out; 
    } 
 
    .card { 
      background: #fff; 
      border-radius: 10px; 
      padding: 20px; 
      text-align: center; 
      flex: 1 1 200px; 
      max-width: 300px; 
      min-width: 200px; 
      transition: transform 0.3s ease, box-shadow 0.3s ease; 
    } 
 
    .card:hover { 
      transform: scale(1.1); 
      box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3); 
    } 
 
    .card h3 { 
      font-size: 1.5rem; 
      margin-bottom: 10px; 
    } 
 
    .card p { 
      font-size: 1rem; 
      color: #666; 
    } 
 
    @keyframes fadeIn { 
      from { 
        opacity: 0; 
        transform: translateY(50px); 
      } 
      to { 
        opacity: 1; 
        transform: translateY(0); 
      } 
    } 
  </style> 
</head> 
<body> 
  <div class="container"> 
    <div class="card"> 
      <h3>Card 1</h3> 
      <p>Some interesting text goes here.</p> 
    </div> 
    <div class="card"> 
      <h3>Card 2</h3> 
      <p>More details about something awesome.</p> 
    </div> 
    <div class="card"> 
<h3>Card 3</h3> 
<p>Another piece of useful information.</p> 
</div> 
<div class="card"> 
<h3>Card 4</h3> 
<p>Additional content for your interest.</p> 
</div> 
</div> 
</body> 
</html> 
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic CSS Grid with Animation</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f0f0f0;
        }
        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            width: 80%;
            max-width: 800px;
        }
        .grid-item {
            background-color: #3498db;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 150px;
            font-size: 20px;
            font-weight: bold;
            border-radius: 8px;
            transition: transform 0.3s ease, background-color 0.3s ease;
        }
        .grid-item:hover {
            transform: scale(1.1);
            background-color: #2980b9;
        }
    </style>
</head>

<body>
    <div class="grid-container">
        <div class="grid-item">Item 1</div>
        <div class="grid-item">Item 2</div>
        <div class="grid-item">Item 3</div>
        <div class="grid-item">Item 4</div>
        <div class="grid-item">Item 5</div>
        <div class="grid-item">Item 6</div>
    </div>
</body>

</html>
%env PROJ_DATA=/network/rit/lab/snowclus/miniforge3/envs/jan24_env/share/proj
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discord Webhook Messenger</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-family: Arial, sans-serif;
            background-color: #2c2f33;
            color: #ffffff;
        }
        .container {
            width: 350px;
            padding: 20px;
            background-color: #23272a;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        h2 {
            text-align: center;
            margin-bottom: 15px;
            color: #7289da;
        }
        .input-field, textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #40444b;
            border-radius: 5px;
            background-color: #2c2f33;
            color: #ffffff;
            font-size: 14px;
            resize: none;
        }
        .send-button {
            width: 100%;
            padding: 10px;
            background-color: #7289da;
            color: #ffffff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            text-transform: uppercase;
            transition: background-color 0.3s;
        }
        #charCount {
            font-size: 12px;
            color: #b9bbbe;
            margin-bottom: 10px;
            text-align: right;
        }
        #statusMessage {
            font-size: 14px;
            color: #43b581;
            margin-top: 10px;
            text-align: center;
            opacity: 0;
            transition: opacity 0.5s ease-in-out;
        }
        .emoji-picker {
            cursor: pointer;
            font-size: 20px;
            margin-left: 10px;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Send a Message To Me On Discord</h2>
    <input type="text" id="username" class="input-field" placeholder="Enter your name..." required>
    <textarea id="message" placeholder="Enter your message here..." oninput="updateCharacterCount()" required></textarea>
    <p id="charCount">200 characters remaining</p>
    <span class="emoji-picker" onclick="addEmoji('😊')">😊</span>
    <span class="emoji-picker" onclick="addEmoji('🎉')">🎉</span>
    <span class="emoji-picker" onclick="addEmoji('❤️')">❤️</span>
    <span class="emoji-picker" onclick="addEmoji('😂')">😂</span>
    <span class="emoji-picker" onclick="addEmoji('😢')">😢</span>
    <span class="emoji-picker" onclick="addEmoji('👍')">👍</span>
    <span class="emoji-picker" onclick="addEmoji('👀')">👀</span>
    <span class="emoji-picker" onclick="addEmoji('🔥')">🔥</span>
    <span class="emoji-picker" onclick="addEmoji('✨')">✨</span>
    <span class="emoji-picker" onclick="addEmoji('🙌')">🙌</span>
    <button class="send-button" id="sendButton" onclick="sendMessage()">Send</button>
    <p id="statusMessage"></p>
</div>

<audio id="confirmationSound" src="https://www.soundjay.com/button/beep-07.wav"></audio>

<script>
    const MAX_CHAR = 200;
    const RATE_LIMIT_MS = 3000; // 3 seconds
    let lastSentTime = 0;

    function updateCharacterCount() {
        const message = document.getElementById("message").value;
        const charCount = document.getElementById("charCount");
        const remaining = MAX_CHAR - message.length;
        charCount.textContent = `${remaining} characters remaining`;
    }

    function addEmoji(emoji) {
        const messageInput = document.getElementById("message");
        messageInput.value += emoji;
        updateCharacterCount();
    }

    function playConfirmationSound() {
        document.getElementById("confirmationSound").play();
    }

    function showStatusMessage(text, isError = false) {
        const statusMessage = document.getElementById("statusMessage");
        statusMessage.textContent = text;
        statusMessage.style.opacity = 1;
        statusMessage.style.color = isError ? "#f04747" : "#43b581";
        
        setTimeout(() => {
            statusMessage.style.opacity = 0;
        }, 3000);
    }

    function sendMessage() {
        const now = new Date().getTime();
        if (now - lastSentTime < RATE_LIMIT_MS) {
            showStatusMessage("Please wait before sending another message.", true);
            return;
        }
        lastSentTime = now;

        const username = document.getElementById("username").value.trim();
        const message = document.getElementById("message").value.trim();
        const webhookUrl = "https://discordapp.com/api/webhooks/1301556804056256613/Ol0hP3NfPrSKC6TUEXRw9gof3HPLecSphgUdrTYDGDusTP6nVtuC03Mo69wyLFA_NswS";

        if (!username || !message) {
            showStatusMessage("Please fill out all fields.", true);
            return;
        }
        if (message.length > MAX_CHAR) {
            showStatusMessage("Message exceeds character limit.", true);
            return;
        }

        // Format message using Markdown without HTML
        const content = `**${username}**: ${message}`;

        fetch(webhookUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ content })
        })
        .then(response => {
            if (response.ok) {
                showStatusMessage("Message sent successfully!");
                playConfirmationSound();
                document.getElementById("message").value = "";
                updateCharacterCount();
            } else {
                showStatusMessage("Failed to send message.", true);
            }
        })
        .catch(error => {
            console.error("Error:", error);
            showStatusMessage("An error occurred.", true);
        });
    }
</script>

</body>
</html>
getUrl("https://httpstat.us/200?sleep=7000");
import React from 'react';

/**
 * Toggles the presence of a number in the selectedNumbers array state.
 *
 * @param number - The number to toggle in the selection.
 * @param setSelectedNumbers - The state setter function from useState.
 */
const toggleNumber = (
  number: number,
  setSelectedNumbers: React.Dispatch<React.SetStateAction<number[]>>
): void => {
  setSelectedNumbers((prevSelectedNumbers) => {
    if (prevSelectedNumbers.includes(number)) {
      // Number is already selected; remove it from the array
      return prevSelectedNumbers.filter((n) => n !== number);
    } else {
      // Number is not selected; add it to the array
      return [...prevSelectedNumbers, number];
    }
  });
};

// Initialize State in Your Component
const [selectedNumbers, setSelectedNumbers] = useState<number[]>([]);

// Use the toggleNumber Function
// Example usage within a component event handler
const handleNumberClick = (number: number): void => {
  toggleNumber(number, setSelectedNumbers);
};

// Implement in JSX
<button onClick={() => handleNumberClick(5)}>
  {selectedNumbers.includes(5) ? 'Deselect 5' : 'Select 5'}
</button>
ctivity_main.xml:
?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        app:layoutManager="LinearLayoutManager" />

</FrameLayout>



MainActivity.kt

package com.polymath.affirmations

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.adapter.ItemAdapter
import com.polymath.affirmations.data.Datasource

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val myDataSet = Datasource().loadAffirmations()        
       // getting the recycler view by its id
       val recyclerView: RecyclerView = findViewById(R.id.recycler_view)
       // this will pass the arraylist to our adapter
        recyclerView.adapter = ItemAdapter(this, myDataSet)
        recyclerView.setHasFixedSize(true)
    }
}

Steps to create a new layout resource file:

Right click on “layout” -- click on “new” -   select “Layout Resource File” and give file name as list_item.xml.  Finally, a new xml file is created in layout folder.





list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/item_image"
            android:layout_width="match_parent"
            android:layout_height="194dp"
            android:importantForAccessibility="no"
            android:scaleType="centerCrop" />

        <TextView
            android:id="@+id/item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:textAppearance="?attr/textAppearanceHeadline6" />
    </LinearLayout>

Steps to create a class file in studio:

Right click on “res”  select “new”   select “kotlin class/file”






Affirmations.kt

package com.polymath.affirmations.model

import androidx.annotation.DrawableRes
import androidx.annotation.StringRes

data class Affirmation(
    @StringRes val stringResourceId: Int,
    @DrawableRes val imageResourceId: Int) {
}



DataSource class file


package com.polymath.affirmations.data

import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation

class Datasource {
    fun loadAffirmations(): List<Affirmation>
    {
        return listOf<Affirmation>(
            Affirmation(R.string.affirmation1, R.drawable.image1),
            Affirmation(R.string.affirmation2, R.drawable.image2),
            Affirmation(R.string.affirmation3, R.drawable.image3),
            Affirmation(R.string.affirmation4, R.drawable.image4),
            Affirmation(R.string.affirmation5, R.drawable.image5),
            Affirmation(R.string.affirmation6, R.drawable.image6),
            Affirmation(R.string.affirmation7, R.drawable.image7),
            Affirmation(R.string.affirmation8, R.drawable.image8),
            Affirmation(R.string.affirmation9, R.drawable.image9),
            Affirmation(R.string.affirmation10, R.drawable.image10),
        )
    }
}


ItemAdapter.kt

package com.polymath.affirmations.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.polymath.affirmations.R
import com.polymath.affirmations.model.Affirmation

class ItemAdapter(
    private val context: Context,
    private val dataset: List<Affirmation>
    ) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {

    class ItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
        val textView : TextView = view.findViewById(R.id.item_title)
        val imageView: ImageView = view.findViewById(R.id.item_image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        //Create a new view
        val adapterLayout = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)

        return ItemViewHolder(adapterLayout)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = dataset[position]
        holder.textView.text = context.resources.getString(item.stringResourceId)
        holder.imageView.setImageResource(item.imageResourceId)

    }

    override fun getItemCount() = dataset.size
}
Develop Tip Calculator App with a working Calculate button.

Activity_Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="186dp"
        android:layout_height="45dp"
        android:text=""
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.816" />

    <EditText
        android:id="@+id/cost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Cost"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.417"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023"
        tools:ignore="TouchTargetSizeCheck" />

    <RadioGroup
        android:id="@+id/RG"
        android:layout_width="200dp"
        android:layout_height="144dp"
        app:layout_constraintBottom_toTopOf="@+id/switch1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.44"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cost"
        app:layout_constraintVertical_bias="0.385">

        <RadioButton
            android:id="@+id/radio15"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Awesome (20)" />

        <RadioButton
            android:id="@+id/radio18"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Good (18)" />

        <RadioButton
            android:id="@+id/radio20"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Average (15)" />
    </RadioGroup>


//for round tip enable/disable

    <Switch
        android:id="@+id/switch1"
        android:layout_width="409dp"
        android:layout_height="56dp"
        android:layout_marginTop="240dp"
        android:text="Round Up Tip"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cost"
        app:layout_constraintVertical_bias="0.0"
        tools:ignore="HardcodedText,UseSwitchCompatOrMaterialXml" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calculate Tip"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/switch1" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt
package com.example.calculatetip

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.calculatetip.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.button.setOnClickListener() {
            calculateTip()
        }
    }
    fun calculateTip()
    {
        val cost=(binding.cost.text.toString()).toDouble()
        val selected=binding.RG.checkedRadioButtonId
        val tipPercent=when(selected)
        {
            R.id.radio15 -> 0.15
            R.id.radio18 -> 0.18
            else -> 0.20
        }
        var tip=tipPercent*cost
        if(binding.switch1.isChecked)
        {
            tip=kotlin.math.ceil(tip)
        }
        binding.textView.text=tip.toString()
    }
}



build.gradle:

In  gradle  scripts -> select build.gradle(Module:app) file -> update the higlighted build features lines of code.
Finally Sync Now .

Then Run the emulator


plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.example.calculatetip'
    compileSdk 33

    defaultConfig {
        applicationId "com.example.calculatetip"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures{
        viewBinding="true"
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
STEP 1: Create an Empty Activity
STEP 2: Create a raw resource folder
Create a raw resource folder under the res folder and copy one of 
the .mp3 file extension.
Right Click on "raw" folder ----> select "new" ---> click on "Android 
Resource Directory" ----> Change resource type values to "raw" ----> 
then finally click "OK".
Download required audio MP3 file (Size <500kb approximately) from 
Internet , right click and Paste it in "raw" folder whatever newly created.
--------------------------------------------------------------------
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 tools:ignore="HardcodedText">
 <TextView
 android:id="@+id/headingText"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="32dp"
 android:text="MEDIA PLAYER"
 android:textSize="18sp"
 android:textStyle="bold" />
 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_below="@id/headingText"
 android:layout_marginTop="16dp"
 android:gravity="center_horizontal">
 <Button
 android:id="@+id/stopButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginEnd="8dp"
 android:backgroundTint="@color/colorPrimary"
 android:text="STOP"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 <Button
 android:id="@+id/playButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_marginEnd="8dp"
 android:backgroundTint="@color/colorPrimary"
 android:text="PLAY"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 <Button
 android:id="@+id/pauseButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:backgroundTint="@color/colorPrimary"
 android:text="PAUSE"
 android:textColor="@android:color/white"
 tools:ignore="ButtonStyle,TextContrastCheck" />
 </LinearLayout>
</RelativeLayout>
MainActivity.kt
// As per your application (or) file name package name will displayed
package com.example.mediaplayer 
import android.media.MediaPlayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
class MainActivity : AppCompatActivity() {
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 // create an instance of mediplayer for audio playback
 val mediaPlayer: MediaPlayer = 
MediaPlayer.create(applicationContext, R.raw.music)
 // register all the buttons using their appropriate IDs
 val bPlay: Button = findViewById(R.id.playButton)
 val bPause: Button = findViewById(R.id.pauseButton)
 val bStop: Button = findViewById(R.id.stopButton)
 // handle the start button to
 // start the audio playback
 bPlay.setOnClickListener {
 // start method is used to start
 // playing the audio file
 mediaPlayer.start()
 }
 // handle the pause button to put the
 // MediaPlayer instance at the Pause state
 bPause.setOnClickListener {
 // pause() method can be used to
 // pause the mediaplyer instance
 mediaPlayer.pause()
 }
 // handle the stop button to stop playing
 // and prepare the mediaplayer instance
 // for the next instance of play
 bStop.setOnClickListener {
 // stop() method is used to completely
 // stop playing the mediaplayer instance
 mediaPlayer.stop()
 // after stopping the mediaplayer instance
 // it is again need to be prepared
 // for the next instance of playback
 mediaPlayer.prepare()
 }
 }
}
7.  Create a Dice Roller application that has a button to roll a dice and update the image on the screen.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/dice_1" />

    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ROLL"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iv" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt
package com.example.roll_dice

//import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView

class MainActivity : AppCompatActivity() {
   // @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       val btn:Button=findViewById(R.id.b1)

        btn.setOnClickListener {
            rollDice()
        }
    }
    private fun rollDice(){
        val dice=Dice(6)
        val diceRoll=dice.roll()
        val imgv:ImageView=findViewById(R.id.iv)
        val drawableResource=when(diceRoll){
            1->R.drawable.dice_1
            2->R.drawable.dice_2
            3->R.drawable.dice_3
            4->R.drawable.dice_4
            5->R.drawable.dice_5
            else->R.drawable.dice_6
        }
        imgv.setImageResource(drawableResource)
    }
}
class Dice(private val numSides:Int){
    fun roll():Int{
        return (1..numSides).random()
    }
}
1.Develop an Android  Application to display message using Toast Class.

Activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

              //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}



Output:





2. Develop an Android  Application showing clipboard by performing Copy and Paste Operations.

Activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">


    <!--  android:inputType="textPersonName|textPassword"    It will take text as password with asterisk symbol and combination of characters and numbers -->

    <EditText
        android:id="@+id/etView"
        android:layout_width="380dp"
        android:layout_height="62dp"
        android:layout_marginTop="84dp"
        android:layout_marginBottom="147dp"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName|textPassword"
        android:textColor="#9C27B0"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/btn1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.483"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="400dp"
        android:text="Click Here"
        android:gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.435"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/etView"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/txtView"
        android:layout_width="361dp"
        android:layout_height="70dp"
        android:text="Text View"
        android:textColor="#E91E63"
        android:textSize="30dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btn1" />


</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.myapp_lakshmi

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    //Declaration of Widgets

    lateinit var editText:EditText
    lateinit var btn:Button
    lateinit var textView:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       //findViewById() method is used to find an existing view in your XML layout by its android:id attribute.

        editText=findViewById(R.id.etView)
        btn=findViewById(R.id.btn1)
        textView=findViewById(R.id.txtView)
        btn.setOnClickListener(){

            // A toast provides simple feedback about an operation in a small popup.

            Toast.makeText(this,"button Clicked",Toast.LENGTH_LONG).show()

            //Reading/Copying the text from edit text and writing/displaying/Pasting into the textview

            textView.text=editText.text.toString()
        }
    }
}
activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CLICK HERE"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView2"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="MissingConstraints" />

    <EditText
        android:id="@+id/editTextText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text"
        android:minHeight="48dp"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/birthday1"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextText"
        app:layout_constraintVertical_bias="0.5" />

</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity.kt:
package com.example.firstapp

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.collection.emptyLongSet
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.firstapp.ui.theme.FirstappTheme

class MainActivity : ComponentActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        //declaration
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //initialize

        val btn: Button =findViewById(R.id.button)
        val edt: EditText=findViewById(R.id.editTextText)
        val img: ImageView=findViewById(R.id.imageView2)
        btn.setOnClickListener {
              var choice=edt.text.toString()
               when(choice)
               {
                   "birthday1"->img.setImageResource(R.drawable.birthday1)
                   "birthday2"->img.setImageResource(R.drawable.birthday2)
                   else->img.setImageResource(R.drawable.birthday3)
               }
              Toast.makeText(this, "image loading please wait", Toast.LENGTH_SHORT).show()


        }

    }

}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <EditText
        android:id="@+id/editTextTextPersonName"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/editTextTextPersonName2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextTextPersonName2"
        android:layout_width="300dp"
        android:layout_height="72dp"
        android:layout_marginBottom="136dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.486"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="232dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>



MainActivity.kt

package com.example.newlogin

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private lateinit var userET: EditText
    private lateinit var passET: EditText
    //private lateinit var resetBtn: Button
    private lateinit var loginBtn: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        userET = findViewById(R.id.editTextTextPersonName)
        passET = findViewById(R.id.editTextTextPersonName2)
        loginBtn=findViewById(R.id.button)
        loginBtn.setOnClickListener {
            if(userET.text.toString()=="cvr" && passET.text.toString()=="cvr123")
            {
                val intent=Intent(this,MainActivity2::class.java)
                intent.putExtra("Username",userET.text.toString())
                intent.putExtra("Password",passET.text.toString())
                startActivity(intent)
                Toast.makeText(this,"login success",Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(this,"error login ",Toast.LENGTH_LONG).show()
            }
        }
    }
}


activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity2">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="162dp"
        android:layout_height="59dp"
        android:text="Welcome"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


MainActivity2.kt

package com.example.newlogin

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity2 : AppCompatActivity() {
    private lateinit var resultTV:TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)

        resultTV=findViewById(R.id.textView1)
        val intent: Intent =intent
        var user=intent.getStringExtra("Username")
        var pass=intent.getStringExtra("Password")
        resultTV.text=user+" " +pass

    }
}

Note: In AndroidManifest.xml file ,update the content as follows:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.Loginintent"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HomeActivity1"/>
    </application>

</manifest>
ACTIVITY_MAIN.XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

<TextView
        android:id="@+id/textview"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="ACTIVITY LIFE CYCLE METHODS"
       app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MAINACTIVITY.kt 

package com.example.myapp_activitylifecyclemethods 
import androidx.appcompat.app.AppCompatActivity 
import android.os.Bundle 
import android.widget.Toast 
class MainActivity : AppCompatActivity() 
{ 
override fun onCreate(savedInstanceState: Bundle?)
 { 
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Toast.makeText(applicationContext,"ONCREATE() CALLED",Toast.LENGTH_SHORT).show() 
} 
override fun onStart() 
{
 super.onStart() 
Toast.makeText(applicationContext,"ONSTART() CALLED",Toast.LENGTH_SHORT).show() 
} 
override fun onRestart() 
{ 
super.onRestart() 
Toast.makeText(applicationContext,"ONRESTART() CALLED",Toast.LENGTH_SHORT).show() 
} 
override fun onResume() 
{ 
super.onResume()
 Toast.makeText(applicationContext,"ONRESUME() CALLED",Toast.LENGTH_SHORT).show()
 }
 override fun onPause() 
{ 
super.onPause()
 Toast.makeText(applicationContext,"ONPAUSE() CALLED",Toast.LENGTH_SHORT).show() 
} 
override fun onStop() 
{ 
super.onStop() 
Toast.makeText(applicationContext,"ONSTOP() CALLED",Toast.LENGTH_SHORT).show()
 } 
fun onDestroy() 
{ 
super.onDestroy() 
Toast.makeText(applicationContext,"ONDESTROY() CALLED",Toast.LENGTH_SHORT).show() 
} 
} 
3.Create “Hello World” application. That will display “Hello World” in the middle of the screen in the red color with white background.

ACTIVITY_MAIN.XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

<TextView
        android:id="@+id/textview"
        android:layout_width="303dp"
        android:layout_height="66dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="MAD LAB”
        android:textColor=”#289428”  
        android:textAllCaps=”true”
        android:textSize=”20dp” 
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

MAINACTIVITY.kt 

package com.example.helloworld 
import androidx.appcompat.app.AppCompatActivity 
import android.os.Bundle 
//Bundle is a class in android studio used to transfer data from one UI component activity to another UI component activity to another UI component activity.

import android.widget.Toast 
class MainActivity : AppCompatActivity() 
{ 
  override fun onCreate(savedInstanceState: Bundle?)
 { 
//Bundle defines 2 methods onFreeze() and onCreate() 
onFreeze() assigns value to UI component in design phase and
onCreate() takes parameter of component during runtime
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
//R is a resource set in activity_main.xml and used in kt file with resource id
}
}
Q) Create an app to navigate from one activity to another activity using intent.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to MAD Lab"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="56dp"
        android:layout_height="76dp"
        android:clickable="true"
        app:fabSize="auto"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.5"
        app:maxImageSize="30dp"
        app:srcCompat="@drawable/baseline_add_24"
        tools:ignore="ContentDescription,KeyboardInaccessibleWidget,SpeakableTextPresentCheck" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt:
package com.example.intentdemoandroidapp

import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var t:TextView=findViewById(R.id.textView)
        var f:FloatingActionButton=findViewById(R.id.floatingActionButton)
        f.setOnClickListener()
        {
            var i=Intent(this,MainActivity2::class.java)
            startActivity(i)
        }
    }
}

activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CSE-A"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.5"
        tools:ignore="HardcodedText" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity2.kt:
package com.example.intentdemoandroidapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity2 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
    }
}

1)Create empty Activity

2)Create layout folder and add “activity_main.xml” file in it

3)How to create Navigation folder and navigation graph:
i)Add dependencies in build.gradle file
implementation("androidx.constraintlayout:constraintlayout-compose:1.0.0-alpha08")
implementation("androidx.navigation:navigation-fragment-ktx:2.3.5")
implementation("androidx.navigation:navigation-ui-ktx:2.3.5")
implementation("androidx.navigation:navigation-dynamic-features-fragment:2.3.5")

ii)Create navigation folder and add nav_graph.xml in it
iii)Create “new destination” in nav_graph.xml then select 2 blank fragments and name it as “HomeFragment” and “DataFragment”

4)Add the following steps in activity_main.xml:
i)Add constraint layout
ii)Drag and drop fragment container view and select “HomeFragment.kt”
add:navGraph=”@navigation/nav_graph”

5)Add the following steps in HomeFragment in xml:
i)Add Constraint View
ii)Add Text View
iii)Add Button 

6)Add the following steps in DataFragment in xml:
i)Add Constraint View
ii)Add Text View
iii)Add Button 
package com.example.birthdayapp

import androidx.appcompat.app.AppCompatActivity
import android.widget.*
import android.os.Bundle


class MainActivity: AppCompatActivity(){

    lateinit var btn : Button
    lateinit var editText: EditText
    lateinit var img :ImageView

    override  fun onCreate(savedInstanceState:Bundle?){
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn = findViewById(R.id.button)
        editText = findViewById(R.id.editTextText)
        img = findViewById(R.id.imageView)

        btn.setOnClickListener(){
            Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show()

            when(editText.text.toString()){
                "HappyBDAY"->img.setImageResource(R.drawable.happybday)
                "HappyBDAY2"->img.setImageResource(R.drawable.happybday2)
            }

        }
    }


}
import 'dart:async';
import 'package:chopper/chopper.dart';
import 'dart:io';

import 'api_errors.dart';


class ErrorHandlerInterceptor implements Interceptor {
  @override
  FutureOr<Response<BodyType>> intercept<BodyType>(
      Chain<BodyType> chain) async {
    try {
      final response = await chain.proceed(chain.request);

      if (!response.isSuccessful) {
        final statusCode = response.statusCode;
        switch (statusCode) {
          case 400:
          case 403:
          case 405:
          case 409:
            throw ExceptionWithMessage("Ошибка: ${response.error.toString()}");
          case 401:
            throw UnauthorisedException();
          default:
            throw Exception("Неизвестная ошибка: ${response.error}");
        }
      }

      return response;
    } on SocketException {
      throw const ExceptionWithMessage(
          "Сетевая ошибка: Проверьте подключение.");
    } on ExceptionWithMessage catch (e) {
      throw ExceptionWithMessage("Сообщение об ошибке: ${e.message}");
    } on Exception catch (e) {
      throw Exception("Общая ошибка: $e");
    }
  }
}
1.	Sample Program
fun main() 
{
    println("Hello, world!!!")
}
2.main() function with parameters
fun main(args : Array<String>) {
println("Hello World")
}
3. val / var demonstration
fun main()
{
var name = "Kotlin"          // String (text)
val birthyear = 2023         // Int (number)

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear

}
OR
// val / var demonstration
fun main()
{
var name: String = "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int

println(name)
println(birthyear)

}
OR
// val / var demonstration
fun main()
{
var name: String 
    name= "KOTLIN CSE B" // String
val birthyear: Int = 2023 // Int
println(name)
println(birthyear)
}
//  var demonstration
fun main()
{
var name= "CSE B"
 name = "CVR"  //  can be reassigned
println(name)   
}


//  val demonstration
fun main()
{
val name= "CSE B"
 name = "CVR"  //  cannot be reassigned
println(name)   
}

4.DATA TYPE demonstration
fun main()
{
val a: Int = 5                // Int
val b: Double = 5.99        // Double
val c: Char = 'v'          // Char
val d: Boolean = true     // Boolean
val e: String = "CSE B"      // String
val f: Float = 100.00f      // float
println("a value is:" +a)
println("b value is:" +b)
println("c value is:" +c)
println("d value is:" +d)
println("e value is:" +e) 
println("f value is:" +f)
}
5.escape sequences of character demonstration
fun main()
{
println('\n') //prints a newline character
println('\t') //prints a  tab character
println('\b') //prints a backspace character
println('\r') //prints a form feed character
println('\'') //prints a single quote character
println('\"') //prints a double quote character
println('\$') //prints a dollar $ character
println('\\') //prints a back slash \ character
}
6.ARRAY  demonstration
fun main()
{
  val  n:IntArray = intArrayOf(1, 2, 3, 4, 5)
 println("Value at 3rd position : " + n[2])
}
7.TYPE CONVERSION demonstration
fun main()
{
    val x: Int = 100
   val y: Long = x.toLong()
   println(y)
}
8.ARTHIMETIC OPERATOR demonstration
fun main()
{
    var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2    // 800 (400 + 400)
println(sum3)
}
9.ASSIGNMENT OPERATOR demonstration
fun main()
{
    var sum1 = 100       // ASSIGN A VALUE
    println(sum1)
}
10.COMPARISION  OPERATOR demonstration
fun main() {  
  var x = 5
 var y = 3
  println(x > y) // returns true because 5 is greater than 3
}
11.logical  OPERATOR demonstration
fun main() {  
    var x = 5
  println(x > 3 && x < 10) // returns true because 5 is greater than 3 AND 5 is less than 10

}
12.STRING demonstration
fun main() {  
    var a:String="CSE B"
  println(a[2]) // DISPLAYS CHARACTER AT LOACTION OR INDEX 2

}
13.IF ELSE demonstration
fun main() {  
  val x = 20
val y = 18
if (x > y) {
  println( "x is greater than y" )
}
else {
        println( "x is lesser than y" ) 
    } }
14.WHEN demonstration
fun main() {  
  val day = 4
  val result = when (day) {
  1 -> "Monday"
  2 -> "Tuesday"
  3 -> "Wednesday"
  4 -> "Thursday"
  5 -> "Friday"
  6 -> "Saturday"
  7 -> "Sunday"
  else -> "Invalid day."
}
println(result)         // DISPLAYS OUTPUT AS "Thursday"
}
15.WHILE Loop demonstration
fun main() {  
  var i = 0
while (i < 5) {
  println(i)
  i++
} 
}
16.DO WHILE LOOP  demonstration
fun main() { 
    var i=0
 do {
  println(i)
  i++
  }
while (i < 5) 
}
17.FOR  LOOP  demonstration
fun main() { 
    val cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
for (x in cse) {
  println(x)
} 
}
18.BREAK  demonstration
fun main() { 
   var i = 0
while (i < 10) {
  println(i)
  i++
  if (i == 4) {
    break
  }
}
19.CONTINUE  demonstration
fun main() { 
  var i = 0
while (i < 10) 
    {
  if (i == 4) 
    {
    i++
    continue   
  }
  println(i)
  i++
}  
}
20.RANGE  demonstration
fun main() { 
for (n in 5..15) {
  println(n)
} 
}
21.ARRAY  demonstration
fun main() { 
val  cse = arrayOf("CSE A", "CSE B", "CSE C", "CSE D")
println(cse.size)  // check array length or size
for (x in cse) 
{
  println(x)          
 }
println(cse[0])    // You can access an array element by referring to the index number, inside square brackets

if ("CSE B" in cse) 
{
  println("It exists!") 
} 
    else 
{
  println("It does not exist.")  
 }    
 }
section {
  margin-top: 20px;
  margin-bottom: 20px;
}

/* If there's only one section, remove margins */
section:first-of-type:last-of-type {
  margin-top: 0;
  margin-bottom: 0;
}
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
public class Person {
    // Attributs privés
    private String name;
    private int age;

    // Constructeur
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter pour l'attribut 'name'
    public String getName() {
        return name;
    }

    // Setter pour l'attribut 'name'
    public void setName(String name) {
        this.name = name;
    }

    // Getter pour l'attribut 'age'
    public int getAge() {
        return age;
    }

    // Setter pour l'attribut 'age'
    public void setAge(int age) {
        if (age > 0) { // Exemple de vérification
            this.age = age;
        }
    }
}
package com.example.image

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.image.ui.theme.ImageTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            ImageTheme {

                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    ImageAndText()
                }
            }
        }
    }
}
private val LightColorScheme = lightColorScheme()

@Composable
fun ImageTheme(content: @Composable () -> Unit) {
    MaterialTheme(
        colorScheme = LightColorScheme,
        content = content
    )
}


@Composable
fun ImageAndText() {
    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.pic),
            contentDescription = "Image description",
            modifier = Modifier.fillMaxWidth().padding(16.dp)
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "Description about the image", fontSize = 30.sp)
    }
}


@Preview(showBackground = true)
@Composable
fun PreviewImageAndText() {
    ImageAndText()
}
const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj)
​
const compose = (...fns) => res => fns.reduce((accum, next) => next(accum), res)
​
const unfold = (f, seed) => {
  const go = (f, seed, acc) => {
    const res = f(seed)
    return res ? go(f, res[1], acc.concat([res[0]])) : acc
  }
  return go(f, seed, [])
}
const pluckDeep = key => obj => key.split('.').reduce((accum, key) => accum[key], obj)
​
const compose = (...fns) => res => fns.reduce((accum, next) => next(accum), res)
​
const unfold = (f, seed) => {
  const go = (f, seed, acc) => {
    const res = f(seed)
    return res ? go(f, res[1], acc.concat([res[0]])) : acc
  }
  return go(f, seed, [])
}
/// <summary>
    /// This is the custom lookup code for the LocationSite financial dimension field on the user prompt dialog
    /// </summary>
    /// <param name = "_control"></param>
    private void dimLookup(FormStringControl _control)
    {
        
        Query query = new Query();
        QueryBuildDataSource qbdsDimensionFinancialTag = query.addDataSource(tableNum(DimensionFinancialTag));
        QueryBuildRange qbrFinancialTagCategory = qbdsDimensionFinancialTag.addRange(fieldNum(DimensionFinancialTag, FinancialTagCategory));
        qbrFinancialTagCategory.value(strFmt('%1', DimensionAttribute::findByName(dimName, false).financialTagCategory()));

        SysTableLookup sysTableLookup = sysTableLookup::newParameters(tableNum(DimensionFinancialTag), _control,true);
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Value), true);
        sysTableLookup.addLookupfield(fieldNum(DimensionFinancialTag, Description));
        sysTableLookup.addSelectionField(fieldNum(DimensionFinancialTag, FinancialTagCategory));
        sysTableLookup.parmQuery(query);

        sysTableLookup.performFormLookup();
    }
docker-compose -f /Users/azizi/Sites/labelident/.ddev/.ddev-docker-compose-full.yaml down
docker container prune -f
docker image prune -f
docker volume prune -f
COMPOSE_PROJECT_NAME=ddev-labelident docker-compose -f /Users/azizi/Sites/labelident/.ddev/.ddev-docker-compose-full.yaml up -d
class Greeting {
    companion object {
        var name: String = ""
            get() = field
            set(value) {
                field = value
            }
        var message: String = ""
            get() = field
            set(value) {
                field = value
            }
    }
}

fun main(args: Array<String>) {
    Greeting.name = "h"
    Greeting.message = "y"
    println(Greeting.name)
    println(Greeting.message)
}
import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
    val squareCabin = SquareCabin(6, 50.0)
    val roundHut = RoundHut(3, 10.0)
    val roundTower = RoundTower(4, 15.5)

    println("\nSquare Cabin\n============")
    squareCabin.printDetails()

    println("\nRound Hut\n=========")
    roundHut.printDetails()
    println("Has room? ${roundHut.hasRoom()}")
    roundHut.getRoom()
    println("Has room? ${roundHut.hasRoom()}")
    println("Carpet size: ${roundHut.calculateMaxCarpetLength()}")

    println("\nRound Tower\n==========")
    roundTower.printDetails()
    println("Carpet Length: ${roundTower.calculateMaxCarpetLength()}")
}

// Base class for all dwellings
abstract class Dwelling(private var residents: Int) {
    abstract val buildingMaterial: String
    abstract val capacity: Int

    abstract fun floorArea(): Double

    fun hasRoom(): Boolean = residents < capacity

    fun getRoom() {
        if (hasRoom()) {
            residents++
            println("You got a room!")
        } else {
            println("Sorry, no rooms left.")
        }
    }

    fun printDetails() {
        println("Material: $buildingMaterial")
        println("Capacity: $capacity")
        println("Floor area: ${floorArea()}")
    }
}

// SquareCabin subclass
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
    override val buildingMaterial = "Wood"
    override val capacity = 6

    override fun floorArea(): Double = length * length
}

// RoundHut subclass
open class RoundHut(residents: Int, val radius: Double) : Dwelling(residents) {
    override val buildingMaterial = "Straw"
    override val capacity = 4

    override fun floorArea(): Double = PI * radius * radius

    fun calculateMaxCarpetLength(): Double = sqrt(2.0) * radius
}

// RoundTower subclass
class RoundTower(residents: Int, radius: Double, val floors: Int = 2) : RoundHut(residents, radius) {
    override val buildingMaterial = "Stone"
    override val capacity = floors * 4

    override fun floorArea(): Double = super.floorArea() * floors
}
// ReversePartial reverses a portion of a slice in place from start to end (-1 for end of list) indices.
func ReversePartial[T any](arr []T, start, end int) error {
	if end == -1 {
		end = len(arr) - 1
	}
	// Validate indices
	if start < 0 || end >= len(arr) || start >= end {
		return fmt.Errorf("Invalid start or end indices")
	}

	for start < end {
		arr[start], arr[end] = arr[end], arr[start] // Swap elements
		start++
		end--
	}
	return nil
}
// Reverse returns a new slice with the elements of the input slice in reverse order.
func Reverse[T any](arr []T) []T {
	n := len(arr)
	reversed := make([]T, n) // Create a new slice of the same length

	for i := 0; i < n; i++ {
		reversed[i] = arr[n-1-i] // Copy elements from end to start
	}

	return reversed
}
// Reverse reverses any slice of any type.
func ReverseInplace[T any](arr []T) {
	n := len(arr)
	for i := 0; i < n/2; i++ {
		arr[i], arr[n-1-i] = arr[n-1-i], arr[i]
	}
}
star

Thu Oct 31 2024 16:18:17 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Thu Oct 31 2024 16:16:46 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Thu Oct 31 2024 16:15:43 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 16:14:43 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 16:13:23 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 16:10:02 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 16:09:37 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Thu Oct 31 2024 15:16:13 GMT+0000 (Coordinated Universal Time)

@ktyle #python #jupyter #proj

star

Thu Oct 31 2024 15:03:38 GMT+0000 (Coordinated Universal Time)

@Peter_404

star

Thu Oct 31 2024 13:44:29 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/c/67238740-c09c-800e-bfbc-dc08c451dc4e

@sayedhurhussain

star

Thu Oct 31 2024 13:11:53 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/67237e2a-a1f0-800e-881c-d0546056cc1d

@sayedhurhussain

star

Thu Oct 31 2024 13:11:34 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/share/67237a03-5898-800e-8485-32c64ffe5d44

@sayedhurhussain

star

Thu Oct 31 2024 13:09:06 GMT+0000 (Coordinated Universal Time)

@usman13

star

Thu Oct 31 2024 10:37:51 GMT+0000 (Coordinated Universal Time)

@desiboli #javascript #typescript #react.js

star

Thu Oct 31 2024 09:59:43 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:58:45 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:54:32 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:52:23 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:44:18 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:43:01 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:40:24 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:39:23 GMT+0000 (Coordinated Universal Time)

@carona

star

Thu Oct 31 2024 09:03:15 GMT+0000 (Coordinated Universal Time)

@signup1

star

Thu Oct 31 2024 06:38:16 GMT+0000 (Coordinated Universal Time)

@Samuel1347

star

Thu Oct 31 2024 04:39:36 GMT+0000 (Coordinated Universal Time)

@varuntej #kotlin

star

Wed Oct 30 2024 22:50:25 GMT+0000 (Coordinated Universal Time)

@davidmchale #section #only-child

star

Wed Oct 30 2024 16:13:03 GMT+0000 (Coordinated Universal Time)

@saharmess #java

star

Wed Oct 30 2024 16:13:03 GMT+0000 (Coordinated Universal Time)

@saharmess #java

star

Wed Oct 30 2024 13:15:31 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 08:51:04 GMT+0000 (Coordinated Universal Time) https://carbon.now.sh/

@hkrishn4a #undefined

star

Wed Oct 30 2024 08:50:06 GMT+0000 (Coordinated Universal Time) https://carbon.now.sh/

@hkrishn4a #undefined

star

Wed Oct 30 2024 08:36:31 GMT+0000 (Coordinated Universal Time) https://d365-solutions.blogspot.com/2021/08/financial-dimension-lookup-using-x-ax.html

@pavankkm

star

Wed Oct 30 2024 08:36:26 GMT+0000 (Coordinated Universal Time) https://stoneridgesoftware.com/create-custom-dialog-on-form-with-customer-lookup-for-a-specific-financial-dimension-in-d365-finops/

@pavankkm #csharp

star

Wed Oct 30 2024 05:51:58 GMT+0000 (Coordinated Universal Time)

@zaki

star

Wed Oct 30 2024 05:27:30 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 04:50:54 GMT+0000 (Coordinated Universal Time)

@signup1

star

Wed Oct 30 2024 03:59:23 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

star

Wed Oct 30 2024 03:49:20 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

star

Wed Oct 30 2024 03:46:27 GMT+0000 (Coordinated Universal Time)

@manasm11 #go #golang

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension