Lab of Ch3_Data Types
Lab of Ch3_Data Types
I. String
void main() {
String greeting = "Hello";
String name = "World";
// Exercise: Create a string that says "My name is [your name] and I am [your age] years
old." using interpolation.
}
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.
}
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.
}
void main() {
String sentence = "Dart is a great language";
List<String> words = sentence.split(" ");
print("Words: $words");
void main() {
String text = "This is a Dart string";
void main() {
String str1 = "apple";
String str2 = "Apple";
String str3 = "apple";
void main() {
String message = "I love Java";
String newMessage = message.replaceAll("Java", "Dart");
print(newMessage);
void main() {
int age = 30;
int score = 100;
int largeNumber = 1234567890;
print("Age: $age");
print("Score: $score");
print("Large Number: $largeNumber");
void main() {
double price = 99.99;
double pi = 3.14159;
double temperature = 25.5;
print("Price: $price");
print("Pi: $pi");
print("Temperature: $temperature");
void main() {
int x = 10;
int y = 3;
double a = 7.0;
double b = 2.0;
void main() {
int x = 10;
int y = 3;
// Exercise: Explain the difference in the results of integer and double division.
void main() {
String intStr = "123";
int intValue = int.parse(intStr);
print("Int value: $intValue");
// Exercise: Convert a string representing a price (e.g., "$99.99") to a double. Handle the
"$" character.
}
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.
}
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)}");
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.
}
void main() {
String strDouble = "3.14159";
double doubleNum = double.parse(strDouble);
print("String: $strDouble, Double: $doubleNum");
void main() {
int num = 42;
String strNum = num.toString();
print("Integer: $num, String: $strNum");
void main() {
double pi = 3.14159;
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");
}
// Exercise: Try parsing a string that might contain non-numeric characters (e.g., "123$").
Handle the exception.
}
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.
}
void main() {
String strTrue = "true";
String strFalse = "false";
// Exercise: Convert a string like "1" or "0" to a boolean (treating "1" as true and "0" as
false).
}
void main() {
String? name; // Nullable String
int? age; // Nullable int
double? price; // Nullable double
bool? isActive; // Nullable bool
// Exercise: Declare a nullable List of integers and a nullable Map of String to dynamic.
}
void main() {
String? message;
if (message != null) {
print("Message: $message");
} else {
print("Message is null.");
}
message = "Hello!";
if (message != null) {
print("Message: $message");
}
// Exercise: Create a nullable int and print its value only if it's not null.
}
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.
}
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.
}
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'.
// Exercise: Try assigning null to non-nullable variables of different types and observe the
compile-time errors.
}
void main() {
var name = "Alice"; // Inferred as String
var age = 30; // Inferred as int
var price = 99.99; // Inferred as double
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];
void main() {
var x = 10;
var y = 3.14;
var result = x + y; // Inferred as double (because of the double operand)
4. `var` in Loops:
void main() {
for (var i = 0; i < 5; i++) {
print("Iteration: $i");
}
void main() {
var message = greet("MAD"); // Inferred as String
print(message);
}
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");
void main() {
const message = "Dart is awesome!"; // Inferred as String
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");
void main() {
const numbers = [1, 2, 3]; // Creates a const List<int> (unmodifiable)
// numbers.add(4); // Error: Cannot modify an unmodifiable list
print("Numbers: $numbers");
print("Fruits: $fruits");
print("Unique Numbers: $uniqueNumbers");
}
void main() {
const compileTimeConstant = 10; // Value known at compile time
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.
}
void main() {
final message = "Dart is cool!"; // Inferred as String
final number = 123; // Inferred as int
final price = 49.95; // Inferred as double
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
void main() {
final numbers = [1, 2, 3];
numbers.add(4); // Allowed: Modifying the contents is fine
print("Numbers: $numbers"); // Output: [1, 2, 3, 4]
// numbers = [4, 5, 6]; // Compile-time error: Cannot reassign the final variable 'numbers'.
}
void main() {
const compileTimeConstant = 10; // Value known at compile time
final runTimeConstant = DateTime.now(); // Value known at runtime
Good Luck!