Programming Basics - Casting and Operators
Programming Basics - Casting and Operators
Introduction to Casting
- In programming, casting is the process of transforming data from one type to another.
- This is important when we want to perform operations that are not compatible with the existing data type.
- For example, if we want to perform arithmetic operation on a string that contains a number, we need to cast that string to an integer or a float.
- There are two types of casting, implicit casting (auto conversion by the compiler) and explicit casting (forced conversion by the programmer).
- Implicit casting happens when the conversion is safe and no data will be lost, e.g., converting an integer to a float.
- Explicit casting is necessary when there’s a possibility of data loss or when the conversion might not make sense without specific instruction, e.g., converting a float to an integer.
Introduction to Operators
- Operators are special symbols in programming that perform specific operations on one, two, or three operands, and then return a result.
- The basic types of operators in programming include:
- Arithmetic operators for carrying out basic mathematical operations.
- Relational operators for comparing values.
- Logical operators for performing logical operations.
- Bitwise operators for manipulating individual bits of a data.
- The data that an operator works on are called operands. For example, in 4 + 5, 4 and 5 are the operands and ‘+’ is the operator.
Arithmetic Operators
- Basic arithmetic operators include:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
- Modulus (%) which gives the remainder of a division.
- Exponentiation (**) which raises the first operand to the power of the second operand.
Relational Operators
- Relational operators are used to compare two values and return a Boolean result. They include:
- Greater than (>)
- Less than (<)
- Equal to (==)
- Not equal to (!=)
- Greater than or equal to (>=)
- Less than or equal to (<=)
Logical Operators
- Logical operators are used to combine or invert Boolean values. They include:
- AND (&&) returns true if both operands are true.
-
OR ( ) returns true if at least one of the operands is true. - NOT (!) inverts the value of a single Boolean operand.
Bitwise Operators
- Bitwise operators manipulate individual bits of data. They include:
- Bitwise AND (&)
-
Bitwise OR ( ) - Bitwise XOR (^)
- Bitwise NOT (~)
- Left shift («)
- Right shift (»)
Logic of using Casting and Operators together
- In many cases, you’ll need to cast data types before performing certain operations.
- Always remember to consider the current data type and what you want to manipulate or calculate before deciding whether you need to cast.
- When using operators, always be aware of operator precedence which dictates the order in which operations are performed. When in doubt, use brackets to make your intention clear.