Tag Archives: types

Converting variable types in C#

This tutorial explains how to convert variable types in the C# language (eg. convert from string to integer or float, or convert from integer or float to string). Here is a summary of the methods used:

  • float.Parse() – converts to float type
  • int.Parse() – converts to int type
  • .ToString() – converts to string type

Watch the video below and then scroll down to see the sample code.

Example of converting from string to float:

float myFloatVariable = float.Parse(myStringVariable);

Example of converting from string to int:

int myIntVariable = int.Parse(myStringVariable);

Example of converting from int or float to string:

string myStringVariable = myFloatVariable.ToString();

Here is the full sample code from the tutorial video:

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Enter your name: ");
      string username = Console.ReadLine(); // store user input as string
      Console.WriteLine("Hello there, " + username);

      Console.WriteLine("Enter two numbers");
      float num1 = float.Parse(Console.ReadLine()); // convert user input from string to float
      float num2 = float.Parse(Console.ReadLine()); // convert user input from string to float
      Console.WriteLine("The result is: " + (num1 + num2)); // display string of text and float result 

      int num3 = 5;
      int num4 = 10;
      Console.WriteLine(num3.ToString() + num4.ToString()); // convert int to string
    }
  }
}


Next tutorial: Making comparisons in C#

Combining types in output statements in C#

This tutorial shows you how you can combine types in a Console.WriteLine() output statement. For example, you can combine a string with an integer or float value. Watch the video below and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(message + result); // String and float value combined in output statement
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Converting variable types in C#

Variables, constants and data types in C#

In this tutorial you will learn about variables, constants and data types in the C# language.

Variables are like containers that can store data that you will use in your application. Variables can be given a value to store that can be accessed and modified or updated throughout the program whereas constants are given a value that can’t be changed in another part of the program – in other words the variable’s value is constant throughout the program.

Variables and constants must be given a unique name (starting with lowercase letter and cannot contain spaces or special characters) and they must have a certain type. A type specifies the kind of data that a variable can hold. A variable that has a name and a type can then have a value assigned to it.

Take a look at the following line of code:

int myNumber = 5;

The line of code above says that a new variable called myNumber is being declared. It is of the int (integer) type and is assigned a value of 5.

The table below shows the data types available in the C# language.

Type Description
int The integer data type stores positive or negative whole numbers eg. 5
float The float data type stores floating point numbers (numbers with decimal places).
double The double data type stores floating point numbers but with double precision.
bool The bool (short for Boolean) data type stores true or false values only eg. true
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is written in single quotes eg. ‘a’.
string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      const string mySentence = "The quick brown fox jumps over the lazy dog.";
      Console.WriteLine(mySentence);

      int myNumber = 5;
      Console.WriteLine(myNumber);

      float myFloat = 15.279f;
      Console.WriteLine(myFloat);

      double myDouble = 150.24649;
      Console.WriteLine(myDouble);

      bool myBool = false;

      Console.ReadLine();
    }
  }
}

Next tutorial: Arithmetic and assignment operators

Data types in Java

A data type classifies various types of data eg. String, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the most commonly used data types used in the Java programming language.

Type Description Example
int The integer (int) data type stores positive or negative whole number values. 20
float The float data type stores floating point numbers (numbers with decimal places) eg. 43.65 . Often, you will need to end a float value with an ‘f’ character eg. 43.65f 43.65f
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is always surrounded by single quotes eg. ‘a’. ‘a’
String The String data type stores letters, numbers and other characters in the form of words or sentences. A string value is always surrounded by double quotes eg. “Hello World”. “Hello world”
boolean The boolean data type stores true or false values only eg. true true

The table below shows some of the other data types used in the Java programming language.

Type Description Example
byte The byte data type stores integer numbers ranging from -128 to +127 118
short The short data type is used for integer numbers ranging from -32,768 to +32,767 -28,471
long The long data type is used for integer values exceeding 2.14 billion ‘a’
double The double data type is used for extremely long floating point numbers 1.7976931348623157 × 10^308

Sample code

The sample Java code below shows how some of the different data types can be stored in variables. Later on, we will look at how to actually work with the values of different data types (eg. math calculations with integers and floats, and decision making with booleans).

The code includes comments explaining each data type.

package myjavaproject;

public class DataTypes {
    public static void main (String[] args){
        String message = "Hello"; // variable of String data type
        char letter = 'a'; // variable of char data type
        int number = 20; // variabe of int (integer) data type
        float decimal = 43.65f; // variable of float (floating point) data type
        boolean result = true; // variable of Boolean data type
        
        // now let's output the values of the different variables
        System.out.println("Message is " + message);
        System.out.println("Letter is " + letter);
        System.out.println("Age is " + number);
        System.out.println("Score is " + decimal);
        System.out.println("The answer is " + result);
    }
}

Variables and strings in C#

This tutorial explains how to create variables and use strings in the C# programming language. Variables are used to store data that can be used throughout a program.

Variables can store data of different types. One data type is the string. Strings can contain characters such as letters, numbers or symbols. Strings can be a single character, a bunch of mixed characters, words, or sentences.

Other data types include integers (whole numbers eg. 4), floats, (numbers with decimal place eg. 3.56), and Booleans (true or false values). There are other data types that exist but these are the main ones we will start with. In this tutorial we will focus on strings and how they can be used in variables and statements.

When you create a variable you must declare its data type (eg. string), give it a name (eg. age, score, name), and then you can assign it a value. For example,  look at the following statement:

string firstName = "Joe";

The statement above would create a new variable called firstName of the string data type containing the value Joe. Strings are always contained inside single or double quotes.

Watch the video below and then scroll down to see the sample code.

Sample C# code

The code below contains comments to explain each statement.

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("What is your name?"); // this displays a message in console
      string message = "Hello there, "; // creates a string variable that contains a message
      string name = Console.ReadLine (); // creates a string that stores the user's name from input
      Console.WriteLine (message + name); // writes the message and name to the console
    }
  }
}

Next tutorial: Integers and floats in C#

Data types in PHP

This tutorial explains the range of data types that can be used in PHP including:

  • String (letters, numbers and other characters – stored inside quotation marks)
  • Integer (whole positive or negative numbers)
  • Float (positive or negative real numbers – numbers with decimal place)
  • Boolean (can be only one of two possible values – either true or false)
  • NULL (no value / nothing)

String values are always stored inside quotation marks (can be double or single quotation marks, but they must match) eg. $mySentence = “Hello world”;

Integer, float and boolean values are not contained inside quotation marks eg. myNumber = 5;

It is important to note that when working with numbers, if you intend to treat a value as a number (and it will be used for numeric comparisons and calculations) such as a score in a game, then it should be in the form of an integer or float and not stored inside quotation marks. However, if a number value is not going to be used for calculations eg. a phone number or ZIP code, then it can be stored as a string value inside quotation marks.

Watch the video below and scroll down to see the sample code.

PHP sample code:

<?php
 $name = "Batman"; // strings (letters, numbers and other characters)
 $age = 25; // integers (whole positive or negative numbers - no decimal places)
 $num = 30.256; // floats (positive or negative real numbers - can have decimal place)
 $myboolean = true; // Boolean (only one of two possible values - true or false)
 $myvariable = NULL; // NULL (no value / nothing)
?>

PHP Manual references:

Data types and variables in C#

In this tutorial we will look at how to store data in a game using variables and also the different data types that are used in the C# language – the language we are using for scripting in Unity.

C# Data Types

A data type classifies various types of data eg. string, integer, float, boolean, the types of accepted values for that data type, operations that can be performed on the data type, the meaning of the data, and the way that data of that type can be stored.

The table below shows the data types available in the C# language.

Type Description
int The integer data type stores positive or negative whole numbers eg. 5
float The float data type stores floating point numbers (numbers with decimal places). The float data type is the default number type in Unity eg. 5.25
double The double data type stores floating point numbers but can hold larger size numbers than floats. It is not the default number type in Unity though.
bool The bool (short for Boolean) data type stores true or false values only eg. true
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is written in single quotes eg. ‘a’.
string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

Variables

A variable is a location that can store temporary data in a program. It is like a ‘container’ that can store a value that can be used within the program. To create a variable it must firstly be given a name and a type. Variable declaration in C# uses the following syntax:

<variable type> <variable name>;

Variables should be given meaningful names. Variable names should never contain spaces. To declare a variable that is of the integer data type and is called myNumber, you would write the following:

int myNumber;

You can also assign a value to a variable during its declaration like this.

int myNumber = 5;

Or you can assign a value on another line after the variable has been declared like this:

myNumber = 5;

To declare a string variable, you would write something like this:

string message;

And you can also assign the value during declaration like this:

string message = "Hello World";

These are just a few examples of how to create variables in C#. Remember that strings are contained inside double quotes and chars are contained inside single quotes. Integers, floats, doubles, and boolean values are not placed inside quotes.

Variable scope

The scope of a variable dictates where it can be used. As mentioned earlier, classes and methods use opening and closing brackets and everything inside those brackets is called a ‘block’.

Variables can only be used within the block that they were created in. If a variable is created inside a class, it can only be used inside that class. If a variable is created inside a method (or function), it can only be used inside that method. For example, if you create a variable inside the Start method, it can’t be used inside the Update method because they are two different blocks.

However, if a variable is created in a class but outside of all of the methods on that class, it will be available in all of the methods in that class because those methods are in the same ‘block’ that the variable is in.

Public and private

In code, you might see the keywords public or private. These are known as access modifiers. Private variables can only be used inside the file that they were created in. This means that other scripts or code editors cannot see or modify these variables.

However, public variables are visible to other scripts and can even be seen and modified inside the Unity editor (Inspector). This makes it really easy to change values for variables right in the Unity editor without having to change the values in your code editor such as MonoDevelop.

To make a public or private variable, just add the private or public keyword before the variable type and name during declaration, for example:

public int myNumber;

Data Types

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

You can watch the video about variables and data types here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Variables and Data Types in JavaScript

In this second video from the beginners JavaScript tutorial series, you will learn how to create variables and work with strings, integers, and float data types in JavaScript.

Variables are used to store information in program such as text, numbers or true/false values. Variables are given a name and are assigned a value. To create a variable in JavaScript we use the var keyword, then specify the variable name, use the = sign to assign a value, and then specify the value to store (you can also create a variable without immediately assigning it a value). For example: var myNumber = 50;

Variable names must be unique and cannot contain spaces. They don’t begin with a number but can contain numbers. They generally begin with a lowercase letter and if the variable name contains multiple words, then they can be indicated by using camelcase (starting each new word with an uppercase letter) eg. myVariable.

Variables can store data of different types. The main types are:

  • string – text including letters, numbers and other special characters eg. “Hello world”
  • integer – whole number values eg. 5
  • float – numbers with a decimal point eg. 5.3
  • boolean – a true or false value

Watch the video below or click here to view it on YouTube.

The code snippet below shows how to declare variables in JavaScript and how to assign values to a variable. Pay attention to the //comments which explain the different ways of setting up variables.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Variables</title>
 <script type="text/javascript">
 
 var myVariable = 50;
 
 // Variable names (identifiers) have to begin with lower or uppercase letters or an underscore
 // Variable names cannot begin with a number, however they can contain a number
 // To declare a variable, use the keyword var
 // You can assign a value to a variable when you declare it, in one line (as above)
 // ...or you can declare a variable and then assign a value later, as below...
 
 var myVariable2;
 myVariable2 = "Hello there";
 
 document.write(myVariable);
 // This displays the value of myVariable in the browser window
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

This source code shows how create and use variables of different data types. Strings are text (letters, numbers and characters), integers are regular whole numbers (treated as numbers), and floats are real numbers (with decimal places eg. 4.5). Boolean is another data type which is used for true/false values. You’ll also see how to use the HTML br tag to add a new line between text that is displayed in the browser.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Data Types</title>
 <script type="text/javascript">
 //integer
 var age = 20;
 document.write(age);
 
 //float
 var price = 12.95;
 document.write(price);
 
 //string
 var name = "Smith";
 var sentence = "He said \"hello\".";
 
 /*
 Just like in Python, a backslash can be used as an escape character so that
 quotation marks can be used inside a string without any errors
 You can also use single quotes to enclose a string if you want to use double quotes inside a sting
 eg. var sentence = 'He said "hello".';
 */
 
 document.write("</br>", sentence);
 //You can concatenate (join) strings using a comma and you can also use HTML tags inside quotation marks eg. </br>
 //The </br> tag is used to add a new line when the string is displayed in the browser.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Hint: Have a look at the toFixed() method if you wish to display floats with a specified number of decimal places.

Next tutorial: Operators