Tag Archives: variables

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 in Java

In this tutorial you will learn how to create variables in the Java programming language. Variables are used to store data in a program.  A variable is like a ‘container’ that can store a value that can be used within the program. These values can be accessed, used and modified throughout the code.

Examples of values that you might need to store in a program include the score in a game, the user’s name, a password, or numbers used in calculations. Variables can store values of different data types – we’ll look at these in the next tutorial.

Variables have three important properties:

  • Variable name (identifier) – the actual name of the variable eg. score, username, age, price. Each variable must have a unique name. Some variable names can’t be used if they are the same as a reserved word used elsewhere in the language for other things such as a function. Variable names often cannot contain spaces or start with digits (rules vary in different languages)
  • Data type – the type of data that the variable will be storing such as text or numbers. There are special names for different data types that we will look at in the next tutorial
  • Value – the actual information being stored in the variable such a “Bob” for a variable called firstName or 26 for a variable called age.

The example below shows a new variable called message being created in the Java language. The variable is of the String data type (text that can contain letters, numbers and different characters) and is given an initial value of “Hello“.

java_variables

When you create a variable in a program you declare the variable. This means you give it a name and specify the data type. You may decide to not give it a value at that point in the program and give it a value later on, or you may decide to initialise the variable with a value (that can also be changed later). In the example above, the variable is declared and given an initial value all in one line of code.

Sample code

The sample code below shows a variable called ‘message’ being declared and given a value of “Hello”. The value is displayed on the screen to the user. Then, the value is changed to “Hello there” and this is displayed as output on the screen. Lastly, the message is displayed and the text “friend.” is added on the end when displayed as output so that the message being displayed is “Hello there friend.”. This is an example of concatenation (a fancy word for joining) where two strings are joined together.

You might notice that some lines of code that begin with two // forward slashes. These are comments in the code explaining what is going on. Comments are not carried out as instructions in the code but are used to annotate your code with explanations of what the code is meant to do, or you can also use them to add information about the author of the code, the program’s purpose or when it was created/modified.

package myjavaproject;

public class CreatingVariables {
    public static void main (String[] args){
        String message = "Hello"; // create and initialise String variable
        System.out.println(message);  // output variable value
        message = "Hello there"; // modify variable value
        System.out.println(message); // output modified variable value
        System.out.println(message + " friend.");  // concatenate strings
    }
}

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#

Array extract function in PHP

This tutorial explains how to use the extract function in PHP on an array. The extract function is used to turn array elements into variables. It works on only associative arrays – the key becomes the variable name and the value for that key becomes the value of the new variable. Watch the video below and then scroll down for the sample code.

Sample PHP code:

<?php
  // The extract function turns array elements into variables
  // It works on associative arrays - the key becomes the variable name
  // and the value for that key becomes the value of the new variable.
  $characters = array('hero'=>'batman','villain'=>'joker');
  extract($characters);
  echo $hero , "</br>";
  echo $villain
?>

Variables in PHP

This tutorial explains what variables are, how to declare variables, and how to assign values to variables in PHP. It also explains how to include variables in an echo statement.

A variable is used to store data in a program. Variables are given a unique name when they are created and can be assigned values of different types. A variable name should not be the same as an existing function that already exists in PHP or the same as another variable that already exists in the program.

Variable names can contain uppercase and lowercase letters and numbers as well as underscores but should start with a letter. In PHP, variable names always start with a $ character eg. $myVariable. Variable names cannot contain spaces.

The main types of data variables can store in PHP are:

  • integer – whole numbers
  • float – numbers with a decimal point
  • string – text which can include letters, numbers, and other characters
  • boolean – true or false values

You can create a variable without immediately giving it a variable, for example: $myVariable; However, variables can be created and assigned a value in one statement eg: $number = 5; or $sentence = “Hello world”;

If you want to give a variable a name which contains more than one word, you can join the words together and use the camel case format where each new word starts with an uppercase letter eg: $myStringVariable;

If you wish to display the value stored in a variable you can use an echo statement eg: echo $myVariable;

Watch the video below to see how to create and use variables, and then scroll down to see the sample code.

There are a few rules to naming variables:

  • Names of variables must begin with a $ dollar sign
  • Letters, numbers and underscores can be used in variable names but no spaces
  • The first character of a variable name cannot be a number
  • Variable names are case-sensitive (that means, $myvariable, $myVariable, and $MYVARIABLE are three different variables).

Sample PHP code:

<?php
 // Variables are given a name after a dollar sign eg. $myvariable
 // Variables are assigned a value after the equals sign (assignment operator)
 // Variable declarations end with a semicolon
 
 $name = "Batman"; // this variable holds a string value
 $age = 25; // this variable holds an integer value
 
 echo "My name is " , $name , " and I am " , $age , " years old."; // concatenated string
?>

The above code is an example of concatenating (joining) a variable and string together. With concatenation, you can join variables and strings in a few different ways. The following different combinations of commas, periods and brackets will work:

<?php
 echo "My name is " , $name , " and I am " , $age , " years old.";
 echo ("My name is " . $name . " and I am " . $age . " years old.");
 echo "My name is " . $name . " and I am " . $age . " years old.";
?>

However, you cannot use the comma method of concatenation if the echo statement is placed inside brackets. Eg. the following will NOT work:

<?php
 echo ("My name is " , $name , " and I am " , $age , " years old.");
?>

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;

Operators

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

There are other operators used for calculations though such as adding, subtracting, multiplying, dividing, increasing and decreasing values, etc. Take a look at the source code to see what is available.

Make sure you also watch the video about operators here.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Operators</title>
 <script type="text/javascript">
 var x = 5, y = 10; //variables can be initialised on one line, separated by commas
 var z = x + y; // this is how variables can be added
 
 z++ //this increases the z variable value by 1
 
 z-- //this decreases the z variable value by 1
 
 // operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
 
 x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
 // variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
 
 document.write(z); // now let's see what the z variable displays after these modifications.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

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

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

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

<!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>

Operators in JavaScript

In this tutorial, you will learn how to use a range of operators in JavaScript to assign values, modify variables and make calculations.

If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).

Operators include:

Addition +
Subtraction
Division /
Multiplication *
Modulus %
Equals =

You can view the video below to see how to use these operators and scroll down to see the sample code.

 

The code below shows how you can use a range of operators when working variable assignments and calculations.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Operators</title>
 <script type="text/javascript">
 var x = 5, y = 10; //variables can be initialised on one line, separated by commas
 var z = x + y; // this is how variables can be added
 
 z++ //this increases the z variable value by 1
 
 z-- //this decreases the z variable value by 1
 
 // operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
 
 x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
 // variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
 
 document.write(z); // now let's see what the z variable displays after these modifications.
 
 </script>
 
</head>
<body>
 
 
</body>
</html>

Next tutorial: Strings

Variables and data types in Python

This tutorial explains how to use variables in Python to store integers and strings. It also explains how to concatenate (join) strings in Python.

In programming, a variable is used to store data in a program. A variable can only store one value at a time, for example some text, a number, or a true/false value.

The different data types that a variable can store include:

  • string – this is text which can include letters, numbers, and other characters. String values are stored inside quotation marks
  • integer – whole numbers
  • float – numbers with a decimal point
  • boolean – a true/false value

You can view the video below or click here to watch it on YouTube.