Saturday, March 12, 2016

Intro To Java: Section 2.2 - Strings

Now that we've discussed manipulating integers with basic arithmetic operations it's time to start learning how to manipulate text!

Watch 2.2 Lecture Video

What is a String?

Strings are objects in Java which allow you to store and manipulate sequences of text. Just as you can create variables for integers, you can also create variables for strings. You create a new string in the same manner you create an integer except instead of creating an "int" you want to create a "String." Remember, capitalization matters. The example below demonstrates the hello world program using a string variable.

public class HelloWorldString{
     public static void main(String []args){
        //hello world is stored in string message
        String message = "hello, world";
        //print string message
hello, world

The output of this program is "hello, world" - just like the example in the previous topic.

In Java it is possible to "add" two strings together using the plus + operator. This is known as concatenation of strings, when you're appending one string to the end of another. The example below takes three strings and combines them into a fourth, before printing them to the screen.

public class CombineStrings{
     public static void main(String []args){
        //Create 3 strings
        String partA = "Java is a OOP ";
        String partB = "language because ";
        String partC = "it uses objects.";
        String combined = partA + partB + partC;
        //Print Result
Java is a OOP language because it uses objects.

Splitting Strings

Once useful method for splitting strings is the substring() method. The substring() method allows you to extract the values from a portion of a string. The syntax for using it is as follows:

stringName.substring(beginning index, ending index)

The beginning index is the number of the index that you would like to start extracting the substring from. This number is zero based - so the first character in a string would be zero. The ending index is the index is used to determine where your substring will end. The end index is exclusive - meaning it stops at this value, but does not include it in the substring. The end index parameter is optional - if you do not include it Java will assume you want to take all of the rest of the string.

The following example demonstrates the use of the substring method to create new strings based on an old string.

String myString = "Hello, cows are cool animals.";
String aSubString = myString.substring(7,20);
String bSubString = myString.substring(7);

The output of this code is as follows:

cows are cool
cows are cool animals.

String Length

The length of a string is how long it is in terms of characters starting from one. You can get the string length using the .length() method. The following example prints out the string length of aSubString from the previous example:

System.out.println("The length of the aSubString is " + aSubString.length());
The length of the aSubString is 13

Printing Formatted Data

In all of the examples above the variables' values were printed separately from the text. We will now learn how to put the two together and place variables within the strings. We will do this using the formatted print method printf (the f stands for formatted). It works similarly to the print and println methods discussed in the previous topic. The printf method allows you to place format specifiers within the string of text. Format specifiers begin with a % and end with a converter. To print variables within strings, you simply add format specifiers to the string of text in first argument of the printf method and then fill all the additional arguments with the variables you wish to take the place of that particular specifier. The format specifier for an integer is %d.

This may be simpler to understand if you look at the code below:

int i = 5;
System.out.printf("the value of i is %d",i);

The above code produces the following console output. Note that %d is replaced with the value of i.

the value of i is 5

Note the comma in the line between the string and the variable i. Whenever you are entering multiple arguments into a method's parameters they are separated by commas. It is possible to have multiple variables and display them all at once this way.

public class Values{
     public static void main(String []args){
        int a = 1;
        int b = 2;
        int c = 3;
        System.out.printf("The value of a is %d, the value of b is %d, and the value of c is %d.",a,b,c);

The output of this program is:

The value of a is 1, the value of b is 2, and the value of c is 3.

It is possible to output the contents of strings in the same manner. The format specifier for a string is %s.

public class main {
 public static void main(String[] args) {
  String name = "Billy Bob";
  String message = "Hello";
  System.out.printf("%s says: %s",name,message);

Billy Bob says: Hello

Escape Sequences

When using the print methods there will be times when you need to insert characters or text elements that you simply cannot insert normally due to restrictions by the Java language. For example, you cannot print out a quotation mark simply by typing the quotation sign as this would end the string prematurely. Instead you need to use special escape sequences which enable you to print out the character you need. Each escape sequence begins with a backslash. Below is a list of some of the key escape sequences:

  • \t - Insert tab
  • \n - Inserts a new line
  • \' - Inserts a single quotation
  • \" - Inserts a double quotation
Additional escape sequences can be found in the official Java Documentation located here.

Example using new line escape sequence:

public class HelloWorld{
     public static void main(String []args){




Post a Comment