Lesson 04 of 25
Data Types & Variables
Master Solidity's type system — integers, booleans, addresses, bytes, and strings.
BeginnerValue Types Overview
Solidity is statically typed — every variable must have a declared type. Value types are copied when assigned or passed to functions.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DataTypes {
// Unsigned integers (no negatives)
uint8 public smallNum = 255; // 0 to 2^8 - 1
uint256 public bigNum = 1e18; // 0 to 2^256 - 1
uint public defaultUint = 100; // uint = uint256
// Signed integers
int256 public signedNum = -42; // -2^255 to 2^255 - 1
int public defaultInt = -1; // int = int256
// Boolean
bool public isActive = true;
// Ethereum address (20 bytes)
address public owner = 0x1234...; // 42-hex-char address
// Fixed-size byte arrays
bytes32 public hash = keccak256("hello");
bytes1 public singleByte = 0xFF;
}
Strings and Dynamic Bytes
Strings in Solidity are UTF-8 encoded and stored as dynamic byte arrays. They are more expensive to use than
bytes32 for short values.
Solidity
contract StringDemo {
string public name = "Alice";
bytes public rawData = "0x1234";
// String concatenation (Solidity 0.8.12+)
function greet(string memory _name) public pure returns (string memory) {
return string.concat("Hello, ", _name, "!");
}
// String length (in bytes, not characters)
function nameLength() public view returns (uint256) {
return bytes(name).length;
}
}
State vs Local Variables
- State variables — declared at contract level, stored permanently in blockchain storage. Expensive to read/write.
- Local variables — declared inside functions, exist only during execution. Stored in memory or stack.
- Global variables — built-in:
msg.sender,block.timestamp,block.number.
Solidity
contract Variables {
uint256 public stateVar = 10; // state variable
function demo() public view returns (uint256, address, uint256) {
uint256 localVar = 99; // local variable
address caller = msg.sender; // global variable
uint256 time = block.timestamp; // global variable
return (localVar, caller, time);
}
}
Type Casting
Solidity requires explicit casting between numeric types. Implicit unsafe conversions are not allowed in 0.8+.
Solidity
contract Casting {
function cast() public pure returns (uint8, int256) {
uint256 big = 300;
uint8 small = uint8(big); // Truncates! small = 44 (300 % 256)
int256 signed = int256(big); // Safe upcast
return (small, signed);
}
}