⬅ Previous Topic
Complex Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
⬅ Previous Topic
Complex Data TypesA type system is a set of rules that assigns a property called "type" to the various components of a program, such as variables, expressions, functions, or modules. Types help the system ensure that operations are performed on compatible kinds of data.
In a statically typed language, the type of a variable is known at compile-time. This means the programmer must declare what type each variable is, and type checking is performed before the code runs.
int age = 25
string name = "Alice"
bool isStudent = true
Variable 'age' is of type int Variable 'name' is of type string Variable 'isStudent' is of type bool
In a dynamically typed language, the type of a variable is known at runtime. Variables can be assigned without declaring their type explicitly, and their types can change as the program runs.
var value = 42 // value is now a number
value = "hello" // value is now a string
value = true // value is now a boolean
value: number value: string value: boolean
Static Typing | Dynamic Typing |
---|---|
Type is checked at compile-time | Type is checked at runtime |
Errors caught early | Errors caught during execution |
More verbose (requires type declarations) | Less verbose (no explicit types needed) |
Examples: int age = 25 | Example: var age = 25 |
Understanding type systems helps you write safer and more maintainable code. Knowing whether you're working with static or dynamic typing changes how you approach debugging, error handling, and code organization.
Question: Why might a compiler reject this code in a statically typed system?
int age = "twenty-five"
Answer: Because you are assigning a string to a variable declared as an integer. The compiler detects this mismatch and throws an error before the program even runs.
Question: What happens if you run the same code in a dynamically typed system?
var age = "twenty-five"
Answer: The program will not throw an error immediately because dynamic typing allows this. However, if later operations assume age
is a number (e.g., age + 1
), a runtime error may occur.
Whether a language uses static or dynamic typing affects how you declare variables, handle errors, and structure programs. As a programmer, understanding these systems helps you choose the right approach based on your project’s needs.
⬅ Previous Topic
Complex Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.