Type Hinting

  • In simple word, type hinting means providing hints to function to only accept the given data type.
  • In technical word we can say that Type Hinting is method by which we can force function to accept the desired data type.
  • In PHP, we can use type hinting for Object, Array and callable data type.

Example 1

<?php  
      
    class a  
    {  
        public $c= "hello javatpoint";  
    }  
    //create function with class name argument  
    function display(a $a1)  
    {  
        //call variable  
        echo $a1->c;  
    }  
    display(new a());  
?>  

Output:

hello protutorials

Example 2

<?php  
      
    class Test1  
    {  
        public $var= "hello protutorials and tech";  
    }  
    //create function with class name argument  
    function typehint(Test1 $t1)  
    {  
        //call variable  
        echo $t1->var;  
    }  
    //call function with call name as a argument  
    typehint(new Test1());  
?>  

Output:

hello protutorials and tech

Kotlin Type Conversion

In this article, you will learn about type conversion; how to convert a variable of one type to another with the help of example.

In Kotlin, a numeric value of one type is not automatically converted to another type even when the other type is larger. This is different from how Java handles numeric conversions. For example;

In Java,

int number1 = 55;
long number2 = number1;    // Valid code 

Here, value of number1 of type int is automatically converted to type long, and assigned to variable number2.

In Kotlin,

val number1: Int = 55
val number2: Long = number1   // Error: type mismatch.

Though the size of Long is larger than Int, Kotlin doesn’t automatically convert Int to Long

Instead, you need to use toLong() explicitly (to convert to type Long). Kotlin does it for type safety to avoid surprises.

val number1: Int = 55
val number2: Long = number1.toLong()

Here’s a list of functions in Kotlin used for type conversion:

  • toByte() 
  • toShort()
  • toInt()
  • toLong()
  • toFloat()
  • toDouble()
  • toChar()

Note, there is no conversion for Boolean types.


Conversion from Larger to Smaller Type

The functions mentioned above can be used in both directions (conversion from larger to smaller type and conversion from smaller to larger type).

However, conversion from larger to smaller type may truncate the value. For example,

fun main(args : Array<String>) {
    val number1: Int = 545344
    val number2: Byte = number1.toByte()
    println("number1 = $number1")
    println("number2 = $number2")
}

When you run the program, the output will be:

number1 = 545344
number2 = 64

Python Numbers, Type Conversion and Mathematics

In this article, you’ll learn about the different numbers used in Python, how to convert from one data type to the other, and the mathematical operations supported in Python.

Number Data Type in Python

Python supports integers, floating-point numbers and complex numbers. They are defined as intfloat, and complex classes in Python.

Integers and floating points are separated by the presence or absence of a decimal point. For instance, 5 is an integer whereas 5.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class.

Let’s look at an example:

a = 5

print(type(a))

print(type(5.0))

c = 5 + 3j
print(c + 3)

print(isinstance(c, complex))

When we run the above program, we get the following output:

<class 'int'>
<class 'float'>
(8+3j)
True

While integers can be of any length, a floating-point number is accurate only up to 15 decimal places (the 16th place is inaccurate).

The numbers we deal with every day are of the decimal (base 10) number system. But computer programmers (generally embedded programmers) need to work with binary (base 2), hexadecimal (base 16) and octal (base 8) number systems.

In Python, we can represent these numbers by appropriately placing a prefix before that number. The following table lists these prefixes.

Number SystemPrefix
Binary‘0b’ or ‘0B’
Octal‘0o’ or ‘0O’
Hexadecimal‘0x’ or ‘0X’

Here are some examples

# Output: 107
print(0b1101011)

# Output: 253 (251 + 2)
print(0xFB + 0b10)

# Output: 13
print(0o15)

When you run the program, the output will be:

107
253
13

Type Conversion

We can convert one type of number into another. This is also known as coercion.

Operations like addition, subtraction coerce integer to float implicitly (automatically), if one of the operands is float.

>>> 1 + 2.0
3.0

We can see above that 1 (integer) is coerced into 1.0 (float) for addition and the result is also a floating point number.

We can also use built-in functions like int()float() and complex() to convert between types explicitly. These functions can even convert from strings.

>>> int(2.3)
2
>>> int(-2.8)
-2
>>> float(5)
5.0
>>> complex('3+5j')
(3+5j)

When converting from float to integer, the number gets truncated (decimal parts are removed).


Python Decimal

Python built-in class float performs some calculations that might amaze us. We all know that the sum of 1.1 and 2.2 is 3.3, but Python seems to disagree.

>>> (1.1 + 2.2) == 3.3
False

What is going on?

It turns out that floating-point numbers are implemented in computer hardware as binary fractions as the computer only understands binary (0 and 1). Due to this reason, most of the decimal fractions we know, cannot be accurately stored in our computer.

Let’s take an example. We cannot represent the fraction 1/3 as a decimal number. This will give 0.33333333… which is infinitely long, and we can only approximate it.

It turns out that the decimal fraction 0.1 will result in an infinitely long binary fraction of 0.000110011001100110011… and our computer only stores a finite number of it.

This will only approximate 0.1 but never be equal. Hence, it is the limitation of our computer hardware and not an error in Python.

>>> 1.1 + 2.2
3.3000000000000003

To overcome this issue, we can use the decimal module that comes with Python. While floating-point numbers have precision up to 15 decimal places, the decimal module has user-settable precision.

Let’s see the difference:

import decimal

print(0.1)

print(decimal.Decimal(0.1))

Output

0.1
0.1000000000000000055511151231257827021181583404541015625

This module is used when we want to carry out decimal calculations as we learned in school.

It also preserves significance. We know 25.50 kg is more accurate than 25.5 kg as it has two significant decimal places compared to one.

from decimal import Decimal as D

print(D('1.1') + D('2.2'))

print(D('1.2') * D('2.50'))

Output

3.3
3.000

Notice the trailing zeroes in the above example.

We might ask, why not implement Decimal every time, instead of float? The main reason is efficiency. Floating point operations are carried out must faster than Decimal operations.

When to use Decimal instead of float?

We generally use Decimal in the following cases.

  • When we are making financial applications that need exact decimal representation.
  • When we want to control the level of precision required.
  • When we want to implement the notion of significant decimal places.

Python Fractions

Python provides operations involving fractional numbers through its fractions module.

A fraction has a numerator and a denominator, both of which are integers. This module has support for rational number arithmetic.

We can create Fraction objects in various ways. Let’s have a look at them.

import fractions

print(fractions.Fraction(1.5))

print(fractions.Fraction(5))

print(fractions.Fraction(1,3))

Output

3/2
5
1/3

While creating Fraction from float, we might get some unusual results. This is due to the imperfect binary floating point number representation as discussed in the previous section.

Fortunately, Fraction allows us to instantiate with string as well. This is the preferred option when using decimal numbers.

import fractions

# As float
# Output: 2476979795053773/2251799813685248
print(fractions.Fraction(1.1))

# As string
# Output: 11/10
print(fractions.Fraction('1.1'))

Output

2476979795053773/2251799813685248
11/10

This data type supports all basic operations. Here are a few examples.

from fractions import Fraction as F

print(F(1, 3) + F(1, 3))

print(1 / F(5, 6))

print(F(-3, 10) > 0)

print(F(-3, 10) < 0)

Output

2/3
6/5
False
True

Python Mathematics

Python offers modules like math and random to carry out different mathematics like trigonometry, logarithms, probability and statistics, etc.

import math

print(math.pi)

print(math.cos(math.pi))

print(math.exp(10))

print(math.log10(1000))

print(math.sinh(1))

print(math.factorial(6))

Output

3.141592653589793
-1.0
22026.465794806718
3.0
1.1752011936438014
720

Here is the full list of functions and attributes available in the Python math module.

import random

print(random.randrange(10, 20))

x = ['a', 'b', 'c', 'd', 'e']

# Get random choice
print(random.choice(x))

# Shuffle x
random.shuffle(x)

# Print the shuffled x
print(x)

# Print random element
print(random.random())

When we run the above program we get the output as follows.(Values may be different due to the random behavior)

18
e
['c', 'e', 'd', 'b', 'a']
0.5682821194654443

Here is the full list of functions and attributes available in the Python random module.

Python Type Conversion and Type Casting

In this article, you will learn about the Type conversion and uses of type conversion.

Before learning Type Conversion in Python, you should have knowledge about Python Data Types.


Type Conversion

The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn’t need any user involvement.

Let’s see an example where Python promotes the conversion of the lower data type (integer) to the higher data type (float) to avoid data loss.

Example 1: Converting integer to float

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

When we run the above program, the output will be:

datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>

Value of num_new: 124.23
datatype of num_new: <class 'float'>

In the above program,

  • We add two variables num_int and num_flo, storing the value in num_new.
  • We will look at the data type of all three objects respectively.
  • In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
  • Also, we can see the num_new has a float data type because Python always converts smaller data types to larger data types to avoid the loss of data.

Now, let’s try adding a string and an integer, and see how Python deals with it.

Example 2: Addition of string(higher) data type and integer(lower) datatype

num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))

print(num_int+num_str)

When we run the above program, the output will be:

Data type of num_int: <class 'int'> 
Data type of num_str: <class 'str'> 

Traceback (most recent call last): 
  File "python", line 7, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'str'

In the above program,

  • We add two variables num_int and num_str.
  • As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions.
  • However, Python has a solution for these types of situations which is known as Explicit Conversion.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int()float()str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data type of the objects.

Syntax :

<required_datatype>(expression)

Typecasting can be done by assigning the required data type function to the expression.


Example 3: Addition of string and integer using explicit conversion

num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))

When we run the above program, the output will be:

Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>

Data type of num_str after Type Casting: <class 'int'>

Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>

In the above program,

  • We add num_str and num_int variable.
  • We converted num_str from string(higher) to integer(lower) type using int() function to perform the addition.
  • After converting num_str to an integer value, Python is able to add these two variables.
  • We got the num_sum value and data type to be an integer.

C++ Type Conversion

In this tutorial, we will learn about the basics of C++ type conversion with the help of examples.

C++ allows us to convert data of one type to that of another. This is known as type conversion.

There are two types of type conversion in C++.

  1. Implicit Conversion
  2. Explicit Conversion (also known as Type Casting)

Implicit Type Conversion

The type conversion that is done automatically done by the compiler is known as implicit type conversion. This type of conversion is also known as automatic conversion.

Let us look at two examples of implicit type conversion.


Example 1: Conversion From int to double

// Working of implicit type-conversion

#include <iostream>
using namespace std;

int main() {
   // assigning an int value to num_int
   int num_int = 9;

   // declaring a double type variable
   double num_double;
 
   // implicit conversion
   // assigning int value to a double variable
   num_double = num_int;

   cout << "num_int = " << num_int << endl;
   cout << "num_double = " << num_double << endl;

   return 0;
}

Run Code

Output

num_int = 9
num_double = 9

In the program, we have assigned an int data to a double variable.

num_double = num_int;

Here, the int value is automatically converted to double by the compiler before it is assigned to the num_double variable. This is an example of implicit type conversion.


Example 2: Automatic Conversion from double to int

//Working of Implicit type-conversion

#include <iostream>
using namespace std;

int main() {

   int num_int;
   double num_double = 9.99;

   // implicit conversion
   // assigning a double value to an int variable
   num_int = num_double;

   cout << "num_int = " << num_int << endl;
   cout << "num_double = " << num_double << endl;

   return 0;
}

Run Code

Output

num_int = 9
num_double = 9.99

In the program, we have assigned a double data to an int variable.

num_double = num_int;

Here, the double value is automatically converted to int by the compiler before it is assigned to the num_int variable. This is also an example of implicit type conversion.

Note: Since int cannot have a decimal part, the digits after the decimal point is truncated in the above example.


Data Loss During Conversion (Narrowing Conversion)

As we have seen from the above example, conversion from one data type to another is prone to data loss. This happens when data of a larger type is converted to data of a smaller type.

Data loss in C++ if a larger type of data is converted to a smaller type.
Possible Data Loss During Type Conversion

C++ Explicit Conversion

When the user manually changes data from one type to another, this is known as explicit conversion. This type of conversion is also known as type casting.

There are three major ways in which we can use explicit conversion in C++. They are:

  1. C-style type casting (also known as cast notation)
  2. Function notation (also known as old C++ style type casting)
  3. Type conversion operators

C-style Type Casting

As the name suggests, this type of casting is favored by the C programming language. It is also known as cast notation.

The syntax for this style is:

(data_type)expression;

For example,

// initializing int variable
int num_int = 26;

// declaring double variable
double num_double;

// converting from int to double
num_double = (double)num_int;

Function-style Casting

We can also use the function like notation to cast data from one type to another.

The syntax for this style is:

data_type(expression);

For example,

// initializing int variable
int num_int = 26;

// declaring double variable
double num_double;

// converting from int to double
num_double = double(num_int);

Example 3: Type Casting

#include <iostream>

using namespace std;

int main() {
    // initializing a double variable
    double num_double = 3.56;
    cout << "num_double = " << num_double << endl;

    // C-style conversion from double to int
    int num_int1 = (int)num_double;
    cout << "num_int1   = " << num_int1 << endl;

    // function-style conversion from double to int
    int num_int2 = int(num_double);
    cout << "num_int2   = " << num_int2 << endl;

    return 0;
}

Run Code

Output

num_double = 3.56
num_int1   = 3
num_int2   = 3

We used both the C style type conversion and the function-style casting for type conversion and displayed the results. Since they perform the same task, both give us the same output.


Type Conversion Operators

Besides these two type castings, C++ also has four operators for type conversion. They are known as type conversion operators. They are:

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast

We will learn about these casts in later tutorials.


Recommended Tutorials:

  • C++ string to int and Vice-versa
  • C++ string to float, double and Vice-versa