Tag Archives: strings

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#

String length in PHP

This tutorial covers a few things about strings in PHP:

  • the index of strings (each character has an index number)
  • how to find the length of a string (how many characters there are in a string)
  • how to ‘loop’ through each character of a string

Although this may not seem all that useful yet, being able to find the length of a string and process each character of a string is something that will become very useful later on.

Indexing and strings

In every string, each character has what is known as an index or index number. In PHP, indexing starts from the number 0. That means that the letter B in the word “Batman” has an index of 0, the second letter “a” will have an index of 1, the third letter “t” will have an index of 2 and so on… The image below shows an example of this.

strings
A string’s index.

You might, as an example, want to find out what the third character is in a string. You could do this by using its index number eg. $mystring[2]; would return the third character in the string.

Finding the length of a string

The length of a string is how many characters are in the string. The word “Batman” has 6 letters in it so its length is 6. Letters, numbers, spaces and other characters are all counted in a string. So the string “Hello world” will have a string length of 11 because there are 10 letters and 1 space in it.

As an example, finding the length of a string might be useful if you want to check how much text was entered into a form (eg. checking that a minimum of 10 characters was used for a password, or a maximum of 160 characters were used for a tweet). The strlen() function is used to find the length of a string. Eg.  strlen(“my string”); will return the length of a string. We will look at other string functions later on.

Looping through strings

A for loop can be used to go through every single character in a string and process it. In the video example, we do this to display every letter of a string on a new line. This example might not be all that useful, but there are many other ways that a for loop can be used to process characters in a string.

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

Sample PHP code for displaying the length of a string:

1
2
3
4
5
6
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 echo $nameLength;
 }
?>

Sample PHP code for displaying the third character in a string:

1
2
3
4
5
<?php
 $name = "Batman";
 echo $name[2];
 }
?>

Sample PHP code for looping through a string:

1
2
3
4
5
6
7
<?php
 $name = "Batman";
 $nameLength = strlen($name);
 for($i=0;$i<$nameLength;$i++){
 echo $name[$i] , '</br>';
 }
?>

PHP Manual references:

Using HTML tags in echo statements and string concatenation

This tutorial explains how to use HTML tags inside the PHP echo statement. It also explains how to join or ‘concatenate’ strings together. The echo statement is not just used to output simple messages or values of variables, but can also be used to output full HTML code which contains HTML tags, as well as CSS code and even JavaScript code!

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

PHP sample code:

<?php
 echo "<h3>This is a heading using the HTML h3 heading tag</h3>";
 echo "This string is joined to " , "this other string.";
 echo "</br>This string is on a new line.";
?>

Finding the length of arrays (and strings)

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

The video here also explains how to do this.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Strings

Quite a lot is going to be covered in the source code snippet below. You might want to watch the video which explains all about working with strings by clicking here.

The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.

Don’t try all of this in one go. Have a go at one string operation at a time and only move on to the next one when you feel comfortable to.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Strings</title>
 <script type="text/javascript">
 
 var firstName = "Nicolas";
 var lastName = "Cage";
 
 // Concatenation means joining (eg. joining two strings together to form one string
 // Below, is an example of a concatenated string being held in a variable
 var joinednames = firstName + lastName;
 
 // Below, is an example of concatention with spaces added between words.
 document.write(firstName,' ',lastName,' ',"says \"hello\".");
 
 var fullName = firstName + ' ' + lastName; // this combines two variables and a space between the strings into a new variable
 
 document.write(fullName)
 
 var nameLength = fullName.length; // this calculates the length of the string as an integer
 document.write(nameLength);
 
 var age = 20;
 document.write(fullName + age); // this prints the name string and then the variable (no spaces) 
 
 var ageString = age.toString(); // this converts the age integer variable to a string variable
 document.write(ageString);
 
 /* To convert a string to an integer, the variable must firstly contain ony numbers. It can simply be multiplied by 1 to convert to an integer
 eg. newIntVariable = stringVariable * 1
 or you can use parseInt and parseFloat functions eg parseInt('77');
 */
 
 var message = 'Hello world!';
 document.write(message.indexOf('w')) // the indexOf function finds the index number of a character in a string
 document.write(message.charAt(8)) // this gives the character at index number 8
 document.write(message.length) // this will give the length of the string
 
 var messageArray = new Array();
 messageArray = message.split(' '); //this splits the words (where there is a space) into a new array
 document.write(messageArray[0],"</br>"); // this would return "Hello" (and a new line)
 document.write(messageArray[1]); // this would return "world!"
 
 document.write(message.substring(4,8)); //this will show anything between index number 4 and 8
 document.write(message.substr(4,8)); //substr is different to substring. this will show the 8 characters after index number 4.
 
 document.write(message.toUpperCase()); // converts string to uppercase
 document.write(message.toLowerCase()); // converts string to lowercase
 document.write("<b>",message.toUpperCase(),"</b>"); // this prints the uppercase string in bold using the HTML bold element <b>
 document.write("<h1>This is a heading</h1>"); // HTML elements can be put straight into a string
 </script>
 
</head>
<body>
 
 
</body>
</html>

Finding the length of arrays and strings in JavaScript

This tutorial explains how to find the length of an array (how many elements are in an array), the length of an element in an array, and the length of a string of text (how many characters in a string). You can watch the video below or click here to view it on YouTube.

Sometimes you might need to find out how many elements exist in an array (that is, the length of the array). The sample code below shows exactly how to do that, and it also shows you how to find the length of a string using pretty much the same method.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - More Arrays</title>
 <script type="text/javascript">
 
 var cars = new Array();
 
 cars[0]="Mitsubishi";
 cars[1]="Honda";
 cars[2]="Audi";
 
 // to find the length (number of elements) of an array we can use arrayname.length eg.:
 
 document.write(cars.length);
 
 /* 
 We could also use the length method on a string like this:
 
 var word = "hello";
 document.write(word.length);
 
 */
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Multidimensional arrays

Working with Strings in JavaScript

This video tutorial explains how to concatenate (join) strings, convert between integers and strings, change text to uppercase and lowercase, and also introduces indexing and arrays.

You can watch the video below or click here to view it on YouTube.  This is the fourth video from the beginners JavaScript tutorial video series.

The sample code snippet below shows how to join (concatenate) strings, find the length of a string (the number of characters in a string), convert from integer to string, display specific characters in a string, split a string up and place each word in a separate array element, and convert string to uppercase and lowercase.

Don’t try all of this in one go. Have a go at one string operation at a time and only move on to the next one when you feel comfortable to.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Strings</title>
 <script type="text/javascript">
 
 var firstName = "Nicolas";
 var lastName = "Cage";
 
 // Concatenation means joining (eg. joining two strings together to form one string
 // Below, is an example of a concatenated string being held in a variable
 var joinednames = firstName + lastName;
 
 // Below, is an example of concatention with spaces added between words.
 document.write(firstName,' ',lastName,' ',"says \"hello\".");
 
 var fullName = firstName + ' ' + lastName; // this combines two variables and a space between the strings into a new variable
 
 document.write(fullName)
 
 var nameLength = fullName.length; // this calculates the length of the string as an integer
 document.write(nameLength);
 
 var age = 20;
 document.write(fullName + age); // this prints the name string and then the variable (no spaces) 
 
 var ageString = age.toString(); // this converts the age integer variable to a string variable
 document.write(ageString);
 
 /* To convert a string to an integer, the variable must firstly contain ony numbers. It can simply be multiplied by 1 to convert to an integer
 eg. newIntVariable = stringVariable * 1
 or you can use parseInt and parseFloat functions eg parseInt('77');
 */
 
 var message = 'Hello world!';
 document.write(message.indexOf('w')) // the indexOf function finds the index number of a character in a string
 document.write(message.charAt(8)) // this gives the character at index number 8
 document.write(message.length) // this will give the length of the string
 
 var messageArray = new Array();
 messageArray = message.split(' '); //this splits the words (where there is a space) into a new array
 document.write(messageArray[0],"</br>"); // this would return "Hello" (and a new line)
 document.write(messageArray[1]); // this would return "world!"
 
 document.write(message.substring(4,8)); //this will show anything between index number 4 and 8
 document.write(message.substr(4,8)); //substr is different to substring. this will show the 8 characters after index number 4.
 
 document.write(message.toUpperCase()); // converts string to uppercase
 document.write(message.toLowerCase()); // converts string to lowercase
 document.write("<b>",message.toUpperCase(),"</b>"); // this prints the uppercase string in bold using the HTML bold element <b>
 document.write("<h1>This is a heading</h1>"); // HTML elements can be put straight into a string
 </script>
 
</head>
<body>
 
 
</body>
</html>

Next tutorial: Events

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

Variables 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.