# Default Value & Type Conversion in Dart

## Default Values and Type Conversion in Dart

**Default Values:**

* **Uninitialized variables:** In Dart, by default, all uninitialized variables have a value of `null`. This applies to all data types, including:
    
    * **Numeric types:** `int`, `double` (default: 0 and 0.0 respectively)
        
    * **String:** (default: null)
        
    * **Boolean:** `bool` (default: false)
        

**Example:**

Dart

```dart
int age; // age is null by default
double weight; // weight is null by default
String name; // name is null by default
bool isRegistered; // isRegistered is null by default
```

**Type Conversion:**

Dart offers various ways to convert between data types:

* **Implicit conversion:**
    
    * The compiler automatically performs certain conversions when assigning values.
        
    * For example, assigning a smaller integer value to a larger integer variable is allowed (e.g., `int bigNumber = 10; int smallNumber = 5; bigNumber = smallNumber;`).
        
* **Explicit conversion:**
    
    * You can explicitly convert a value from one type to another using casting operators:
        
        * `as`: Attempts conversion but throws an exception if unsuccessful (e.g., `String numberString = "123"; int convertedNumber = numberString as int;`).
            
        * `toInt()`, `toDouble()`, etc.: These methods are available for specific data types to perform the conversion (e.g., `double d = 3.14; int convertedInt = d.toInt();`).
            
* **Parsing:**
    
    * Use the `parse` method from the `int` and `double` classes to convert strings to numeric values (e.g., `String numberString = "456"; int parsedInt = int.parse(numberString);`).
        

**Important points:**

* **Data loss during conversion:** Be cautious when explicitly converting between incompatible types. Conversions might lead to data loss (e.g., converting a large double to an int can truncate the decimal part).
    
* **Null safety:** With null safety enabled (introduced in Dart 2.12), attempting to assign `null` to a non-nullable variable will result in a compilation error.
    
    * You can explicitly mark a variable as nullable using the `?` symbol after the type (e.g., `int? maybeAge;`).
        

**Here's a table summarizing the default values and conversion methods:**

| Data Type | Default Value | Explicit Conversion (Example) | Parsing (Example) |
| --- | --- | --- | --- |
| int | null | `int convertedValue = value as int;` | `int parsedValue = int.parse(stringValue);` |
| double | null | `double convertedValue = value as double;` | `double parsedValue = double.parse(stringValue);` |
| String | null | \- | \- |
| bool | false | \- | \- |

By understanding default values and type conversion mechanisms, you can effectively manage data within your Dart applications and ensure accurate results when working with different data types.
