Java For Testers: Learn Java fundamentals fast by Alan Richardson

Java For Testers: Learn Java fundamentals fast by Alan Richardson

Author:Alan Richardson [Richardson, Alan]
Language: eng
Format: epub
Publisher: Compendium Developments Ltd
Published: 2015-03-01T05:00:00+00:00


Bob said "hello" to his cat's friend

This is a single backslash \

Exercise: Try using the other escape characters

Experiment with some @Test methods which use the other escape characters in a string e.g. "\t", "\b",

"\n", "\r" and see the effect when you use System.out.println to print to the console output.

String Concatenation

We have already seen as a method of concatenating strings. The is also useful as a way of adding primitives and other objects on to the String.

String ps1 = "This is " "String2";

assertThat(ps1, is("This is String2"));

String ps2 = "This is " 4;

assertThat(ps2, is("This is 4"));

The String class has a concat method which allows us to concatenate other strings. This does not allow us to concatenate other objects on to the String.

String thisIs = "This is ";

String s1 = thisIs.concat("String1");

assertThat(s1, is("This is String1"));

Converting to/from a String

Converting to a String with toString

Most classes override the toString method to provide a way of creating a String representation of the object.

This provides a useful way of converting to a String, and this is the method called when you concatenate a String with a different type using .

For primitive types, the associated object version is used e.g. for int the Integer.toString is used.

String intConcatConvert = "" 1;

assertThat(intConcatConvert, is("1"));

String integerIntConvert = Integer.toString(2);

assertThat(integerIntConvert, is("2"));

The String class itself has the valueOf method which takes objects and primitives and converts them to a String. For objects, the object’s toString method is used for the conversion.

String integerStringConvert = String.valueOf(3);

assertThat(integerStringConvert, is("3"));

In addition you can convert from byte[] and char[] (and other objects) to a String using the String constructor.

Converting from a String



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.