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

Lab of Ch3_Data Types

Uploaded by

Lëäňĝ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lab of Ch3_Data Types

Uploaded by

Lëäňĝ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

មហាវិទ&'ល័យ ព័ត៌មានវិទ&' និងវិទ&'សា2ស្ត

FACULTY OF INFORMATION TECHNOLGOY AND SCIENCE

្របឡងឆមាស ឆា)*ំទី III ឆមាសទី I


មុខវិជា4*៖ Mobile App Development I
សរុប ១០ពិន្ទ< រយៈេពល ៩០នាទី

I. String

Lab 1: String Basics and Interpolation

void main() {
String greeting = "Hello";
String name = "World";

print(greeting + ", " + name + "!"); // Concatenation


print("$greeting, $name!"); // Interpolation (preferred)
print('${greeting.toUpperCase()}, ${name.toLowerCase()}!'); // Expression interpolation

// Exercise: Create a string that says "My name is [your name] and I am [your age] years
old." using interpolation.
}

Lab 2: String Length and Indexing

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


1
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

void main() {
String message = "Dart is fun!";

print("Length: ${message.length}");
print("First character: ${message[0]}");
print("Last character: ${message[message.length - 1]}");

// Exercise: Print the middle character of the string. Handle both even and odd length
strings.
}

Lab 3: String Methods (toUpperCase, toLowerCase, trim)

void main() {
String mixedCase = "HeLlO wOrLd";
String withSpaces = " Dart ";

print("Uppercase: ${mixedCase.toUpperCase()}");
print("Lowercase: ${mixedCase.toLowerCase()}");
print("Trimmed: '${withSpaces.trim()}'"); // Show the effect of trim

// Exercise: Create a function that takes a string and returns it with the first letter
capitalized.
}

Lab 4: String Splitting and Joining

void main() {
String sentence = "Dart is a great language";
List<String> words = sentence.split(" ");
print("Words: $words");

String joinedSentence = words.join("-");


print("Joined sentence: $joinedSentence");

// Exercise: Split a comma-separated string into a list of items.


}

Lab 5: String Contains and Substring

void main() {
String text = "This is a Dart string";

print("Contains 'Dart': ${text.contains("Dart")}");


print("Contains 'Python': ${text.contains("Python")}");
print("Substring: ${text.substring(10)}"); // From index 10 to the end

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


2
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

print("Substring: ${text.substring(0, 4)}"); // From index 0 to 4 (exclusive)

// Exercise: Check if a string starts with a specific prefix.


}

Lab 6: String Comparison

void main() {
String str1 = "apple";
String str2 = "Apple";
String str3 = "apple";

print("str1 == str2: ${str1 == str2}"); // Case-sensitive comparison


print("str1 == str3: ${str1 == str3}");
print("str1.compareTo(str2): ${str1.compareTo(str2)}"); // Case-sensitive comparison,
returns -1, 0, or 1

// Exercise: Compare two strings ignoring case.


}

Lab 7: String Replacement

void main() {
String message = "I love Java";
String newMessage = message.replaceAll("Java", "Dart");
print(newMessage);

String replacedFirst = message.replaceFirst("a", "o");


print(replacedFirst);

// Exercise: Replace all occurrences of a specific character in a string with another


character.
}

II. Number data types (`int`, `double`, `num`)

Lab 1: Integer Basics

void main() {
int age = 30;
int score = 100;
int largeNumber = 1234567890;

print("Age: $age");
print("Score: $score");
print("Large Number: $largeNumber");

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


3
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

// Exercise: Declare an integer variable to store the number of days in a year.


}

Lab 2: Double Basics

void main() {
double price = 99.99;
double pi = 3.14159;
double temperature = 25.5;

print("Price: $price");
print("Pi: $pi");
print("Temperature: $temperature");

// Exercise: Declare a double variable to store the average rainfall in a month.


}

Lab 3: Arithmetic Operations

void main() {
int x = 10;
int y = 3;
double a = 7.0;
double b = 2.0;

print("x + y = ${x + y}");


print("x - y = ${x - y}");
print("x * y = ${x * y}");
print("x / y = ${x / y}"); // Integer division
print("a / b = ${a / b}"); // Double division
print("x % y = ${x % y}"); // Modulo (remainder)

// Exercise: Calculate the average of three numbers (int and/or double).


}

Lab 4: Integer Division vs. Double Division

void main() {
int x = 10;
int y = 3;

print("Integer division (x ~/ y): ${x ~/ y}"); // Integer division (truncates)


print("Double division (x / y): ${x / y}");

// Exercise: Explain the difference in the results of integer and double division.

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


4
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

Lab 5: Type Conversion (Parsing)

void main() {
String intStr = "123";
int intValue = int.parse(intStr);
print("Int value: $intValue");

String doubleStr = "3.14159";


double doubleValue = double.parse(doubleStr);
print("Double value: $doubleValue");

// Handling potential errors


try {
int invalidInt = int.parse("abc");
print(invalidInt); // This won't be executed due to the exception
} catch (e) {
print("Error parsing: $e");
}

// Exercise: Convert a string representing a price (e.g., "$99.99") to a double. Handle the
"$" character.
}

Lab 6: num Type

void main() {
num myNumber = 10; // Can be int
print("Initial type: ${myNumber.runtimeType}");
myNumber = 3.14; // Now it's a double
print("Changed type: ${myNumber.runtimeType}");

// Exercise: Perform arithmetic operations with num variables that hold different numeric
types.
}

Lab 7: Mathematical Functions (dart:math)

import 'dart:math';

void main() {
print("Square root of 16: ${sqrt(16)}");
print("Power of 2 to 3: ${pow(2, 3)}");
print("Maximum of 10 and 20: ${max(10, 20)}");
print("Minimum of 10 and 20: ${min(10, 20)}");

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


5
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

print("Rounding 3.7: ${3.7.round()}");

// Exercise: Calculate the hypotenuse of a right-angled triangle using the Pythagorean


theorem (a² + b² = c²).
}

III. Type Conversion

Lab 1: String to Integer Conversion

void main() {
String strNum = "123";
int num = int.parse(strNum);
print("String: $strNum, Integer: $num");

// Exercise: Convert "456" to an int and add it to the previous 'num' value.
}

Lab 2: String to Double Conversion

void main() {
String strDouble = "3.14159";
double doubleNum = double.parse(strDouble);
print("String: $strDouble, Double: $doubleNum");

// Exercise: Convert "2.718" to a double and multiply it by 'doubleNum'.


}

Lab 3: Integer to String Conversion

void main() {
int num = 42;
String strNum = num.toString();
print("Integer: $num, String: $strNum");

// Exercise: Convert the result of a mathematical operation (e.g., 10 * 5) to a string.


}

Lab 4: Double to String Conversion

void main() {
double pi = 3.14159;

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


6
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

String strPi = pi.toStringAsFixed(2); // Format to 2 decimal places


print("Double: $pi, String: $strPi");

// Exercise: Convert a double to a string with 3 decimal places.


}

Lab 5: Handling Parsing Errors (try-catch)

void main() {
String invalidNum = "abc";
try {
int num = int.parse(invalidNum);
print("Parsed number: $num"); // This will not execute if parsing fails
} catch (e) {
print("Error parsing '$invalidNum': $e");
}

String invalidDouble = "xyz";


try {
double doubleNum = double.parse(invalidDouble);
print("Parsed number: $doubleNum"); // This will not execute if parsing fails
} catch (e) {
print("Error parsing '$invalidDouble': $e");
}

// Exercise: Try parsing a string that might contain non-numeric characters (e.g., "123$").
Handle the exception.
}

Lab 6: Converting to `num`

void main() {
String numStr = "10";
num number = num.parse(numStr);
print("Num (from int string): $number, Type: ${number.runtimeType}");

numStr = "3.14";
number = num.parse(numStr);
print("Num (from double string): $number, Type: ${number.runtimeType}");

// Exercise: Parse a string that could be either an integer or a double and handle both
cases.
}

Lab 7: Boolean Conversions

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


7
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

void main() {
String strTrue = "true";
String strFalse = "false";

bool isTrue = strTrue.toLowerCase() == "true"; // Case-insensitive comparison


bool isFalse = strFalse.toLowerCase() == "true";

print("String 'true' to bool: $isTrue");


print("String 'false' to bool: $isFalse");

// Exercise: Convert a string like "1" or "0" to a boolean (treating "1" as true and "0" as
false).
}

IV. Null safety

Lab 1: Declaring Nullable Variables

void main() {
String? name; // Nullable String
int? age; // Nullable int
double? price; // Nullable double
bool? isActive; // Nullable bool

print("Name: $name"); // Output: null


print("Age: $age"); // Output: null
print("Price: $price");
print("Is Active: $isActive");

// Exercise: Declare a nullable List of integers and a nullable Map of String to dynamic.
}

Lab 2: Checking for Null (if null)

void main() {
String? message;

if (message != null) {
print("Message: $message");
} else {
print("Message is null.");
}

message = "Hello!";
if (message != null) {
print("Message: $message");
}

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


8
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

// Exercise: Create a nullable int and print its value only if it's not null.
}

Lab 3: Null-Coalescing Operator (??)

void main() {
String? message;
String displayMessage = message ?? "No message provided.";
print(displayMessage); // Output: No message provided.

message = "Hello!";
displayMessage = message ?? "No message provided.";
print(displayMessage); // Output: Hello!

int? score;
int finalScore = score ?? 0; //Default value if null
print(finalScore);

// Exercise: Use the null-coalescing operator to provide a default value for a nullable int.
}

Lab 4: Null-Assignment Operator (??=)

void main() {
String? message;
message ??= "Default message"; // Assigns "Default message" only if message is null.
print(message); // Output: Default message

message ??= "Another message"; // message is not null so this does nothing
print(message); // Output: Default message

// Exercise: Use the null-assignment operator to assign a default value to a nullable List
only if it's null.
}

Lab 5: Non-Nullable by Default

void main() {
String message = "Hello"; // Non-nullable String
// message = null; // Compile-time error: A value of type 'Null' can't be assigned to a
variable of type 'String'.

int age = 25; // Non-nullable int


// age = null; // Compile-time error

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


9
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

// Exercise: Try assigning null to non-nullable variables of different types and observe the
compile-time errors.
}

V. `var` keyword in Dart

1. Basic Type Inference:

void main() {
var name = "Alice"; // Inferred as String
var age = 30; // Inferred as int
var price = 99.99; // Inferred as double

print("Name: $name (${name.runtimeType})");


print("Age: $age (${age.runtimeType})");
print("Price: $price (${price.runtimeType})");
}

2. List and Map Literals:

void main() {
var numbers = [1, 2, 3, 4, 5]; // Inferred as List<int>
var fruits = <String>["apple", "banana", "orange"]; // Explicit type argument
var person = {"name": "Bob", "age": 25}; // Inferred as Map<String, Object> or Map<String,
dynamic>
var mixedList = <dynamic>[1, "Hello", 3.14];

print("Numbers: $numbers (${numbers.runtimeType})");


print("Fruits: $fruits (${fruits.runtimeType})");
print("Person: $person (${person.runtimeType})");
print("Mixed List: $mixedList (${mixedList.runtimeType})");
}

3. Type Inference with Expressions:

void main() {
var x = 10;
var y = 3.14;
var result = x + y; // Inferred as double (because of the double operand)

print("Result: $result (${result.runtimeType})");


}

4. `var` in Loops:

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


10
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

void main() {
for (var i = 0; i < 5; i++) {
print("Iteration: $i");
}

var fruits = ["apple", "banana", "orange"];


for (var fruit in fruits) {
print("Fruit: $fruit");
}
}

5. `var` in Functions (Local Variables):

String greet(var name) { // Parameter type is dynamic if not specified


var greeting = "Hello, $name!"; // Inferred as String
return greeting;
}

void main() {
var message = greet("MAD"); // Inferred as String
print(message);
}

VI. `const` keyword in Dart

1. Basic `const` Declaration:

void main() {
const String greeting = "Hello";
const int age = 30;
const double pi = 3.14159;
const bool isTrue = true;

print("Greeting: $greeting");
print("Age: $age");
print("Pi: $pi");
print("Is True: $isTrue");

// greeting = "Hi"; // Compile-time error: Cannot reassign a const variable.


}

2. Type Inference with `const`:

void main() {
const message = "Dart is awesome!"; // Inferred as String

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


11
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

const number = 42; // Inferred as int


const price = 99.99; // Inferred as double

print("Message: $message (${message.runtimeType})");


print("Number: $number (${number.runtimeType})");
print("Price: $price (${price.runtimeType})");
}

3. Compile-Time Constants (Crucial Concept):

void main() {
const sum = 10 + 20; // Valid: Calculation at compile time
const product = 5 * 3; // Valid: Calculation at compile time
const message = "Hello " + "World"; // Valid: String concatenation at compile time

print("Sum: $sum");
print("Product: $product");
print("Message: $message");

// final now = DateTime.now();


// const time = now; // Invalid: now() is a runtime value

// const input = stdin.readLineSync(); // Invalid: User input is a runtime value


}

4. `const` Lists and Sets:

void main() {
const numbers = [1, 2, 3]; // Creates a const List<int> (unmodifiable)
// numbers.add(4); // Error: Cannot modify an unmodifiable list

const fruits = <String>["apple", "banana"]; // Explicit type argument


// fruits[0] = "grape"; // Error: Cannot modify an unmodifiable list

const uniqueNumbers = {1, 2, 3}; // Creates a const Set<int> (unmodifiable)


// uniqueNumbers.add(4); // Error: Cannot modify an unmodifiable set

print("Numbers: $numbers");
print("Fruits: $fruits");
print("Unique Numbers: $uniqueNumbers");
}

5. `const` vs. `final`:

void main() {
const compileTimeConstant = 10; // Value known at compile time

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


12
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

final runTimeConstant = DateTime.now(); // Value known at runtime

print("Compile-time constant: $compileTimeConstant");


print("Run-time constant: $runTimeConstant");
}

VII. `final` keyword in Dart

1. Basic `final` Declaration:

void main() {
final String name = "SOK";
final int age = 30;
final double pi = 3.14159;

print("Name: $name");
print("Age: $age");
print("Pi: $pi");

// name = "Bob"; // Compile-time error: Final variables can only be set once.
}

2. Type Inference with `final`:

void main() {
final message = "Dart is cool!"; // Inferred as String
final number = 123; // Inferred as int
final price = 49.95; // Inferred as double

print("Message: $message (${message.runtimeType})");


print("Number: $number (${number.runtimeType})");
print("Price: $price (${price.runtimeType})");
}

3. Runtime Initialization:

import 'dart:math';

void main() {
final currentTime = DateTime.now(); // Value determined at runtime
final randomNumber = Random().nextInt(100); // Value determined at runtime

print("Current Time: $currentTime");


print("Random Number: $randomNumber");
}

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


13
សាកលវិទ'(ល័យ ែប៊លធី អន្តរជាតិ BELTEI INTERNATIONAL UNIVERSITY

4. `final` Lists and Maps (Shallow Immutability):

void main() {
final numbers = [1, 2, 3];
numbers.add(4); // Allowed: Modifying the contents is fine
print("Numbers: $numbers"); // Output: [1, 2, 3, 4]

final fruits = {"apple": 1, "banana": 2};


fruits["orange"] = 3; // Allowed: Modifying the contents is fine
print("Fruits: $fruits"); // Output: {apple: 1, banana: 2, orange: 3}

// numbers = [4, 5, 6]; // Compile-time error: Cannot reassign the final variable 'numbers'.
}

5. `final` and `const` Comparison (Key Difference):

void main() {
const compileTimeConstant = 10; // Value known at compile time
final runTimeConstant = DateTime.now(); // Value known at runtime

print("Compile-time Constant: $compileTimeConstant");


print("Run-time Constant: $runTimeConstant");

// compileTimeConstant = 20; // Error: Constant variables can't be assigned a value.


// runTimeConstant = DateTime.now(); // Error: Final variables can only be set once.
}

Good Luck!

កសាងអនាគតរបស់េលាកអ្នកក្ន>ងយុគសម័យបេច្ចកវិទ'( | Build Your Digital Career with Us.


14

You might also like