In this tutorial we spend a little time in trying to learn by example. So again we will look at some topics that will be covered in more details later: conditional statements, try and catch blocks and the String.equals() method. However, in this way we are ensuring the examples can show code working and not just one or two like code snippets. We will see Strings being manipulated, this is for sure. Firstly we will start by revisiting StringBuilder that we looked at in the previous tutorial. This time though we will use the reverse() method. A couple of points to note with the code is that we can use the constructor of the StringBuilder class to feed the text string at the time we create the object and then of course the reverse method of the class can be used to reverse that string as we see by adding this code to our main method:
StringBuilder sb = new StringBuilder("This is it!"); System.out.println(sb.reverse());
We should see the text reverse when we run the code:
Now we have finished up with StringBuilder we will visit ways in which we can feed non String values through to items that requires Strings. in simple terms we will look at ways we can cast the values as String:
int a = 10;
- String b = a; // Will not works a the variable a holds an integer and variable b is a String.
- String b = “” + a; // This will work a concatenation is one way of casting values as Strings. The + operator is used for concatenation when the first item is a String; here we use an empty string, “” , as out first object.
- String b = String.valueOf(a); // The values of method will explicitly cast objects to a String, so , again, this will work.
The main code for this tutorial now will test user input against a CONSTANT. Constants do not change during code execution and are defines with the modifier final. We will read user input from stand input using a BufferedReader object and test it with the equals() method of String. To ensure the user input is of a know case we use the toLowerCase () method.
package objectlife; import java.io.*; public class ObjectLife { static String input; static final String ADMIN = "fred"; public static void main(String[] args){ try { BufferedReader br; br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter you name: "); input = br.readLine().toLowerCase(); } catch (IOException e) { System.out.println("Error reading input!!"); System.exit(42); } if (input.equals(ADMIN)) { System.out.println("Welcome my master: "); } } }
There is again item that we will cover in more detail later, but the video covers them well and gives a working piece of code for this tutorial.