Title: Strings and Methods
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Strings and Methods

So we have discussed variables that are primitives(int, double, etc) in previous lectures. All other variables will end up being an object of some class. What is a class and what is an object?

I will use the following analogy:

The blue print for creating a house can be compared to a class. A blue print defines all of the characteristics of a house, and so does a class definition.

We can use the blue print for a house to create an actual house. In the same way, we can use the "new" operator to construct an object of a specific class.

We could say that we have a subdivision that consists of a lot of similar houses created from the same blue print. In the same way, we can create many objects based on the same class definition using the "new" operator.

In order to give you some idea about classes and their associated methods, we will discuss the String class which happens to be one of the most commonly used classes in Java. Because of it's importance, Java has provided many shortcuts that work for Strings.

1. Create a new program in Eclipse called StringStuff ... click the check box to add main.
2. Add the following line to your main:
Scanner keyboard = new Scanner(System.in);
3. Note the compiler error ... why? Eclipse can be helpful in this case ... hold the following keys down simultaneously Ctlr-Shift-o
Eclipse can search through it's libraries and add appropriate imports that it finds for you.
4. We will first of all look at the normal way we create most classes where you will see the "new" operator explicitly used. Add the line:
String s1 = new String("my new string");
5. We would say we have an object with name of s1 that was created from the String class.
6. The String class is so heavily used, that the Java compiler recognizes the following shortcut which does that exact same thing as the statement in step 4.
String s1 = "my new string"; // Don't expect this kind of short cut with many other classes
7. We now use the length(), and charAt() methods to demonstrate some features of the String class. So add the following lines of code:


		int len = s1.length();  // len will now contain 13
		char c0 = s1.charAt(0); // c0 contains 'm'
		char c1 = s1.charAt(1); // c1 contains 'y'


8. Suppose that now I want read in a new String value from the keyboard. Add the following line to your code:
s1 = keyboard.nextLine();
9. Run your program and enter in some text followed by the Enter key. At this point, you have changed the contents of the s1 object so that it no longer contains
"my new string". It now contains whatever you just typed in. You can again add the code from step 7 to find the length of your new String and the first 2 characters.
10. Suppose that you really didn't want to change the original String, but rather you just wanted to add the typed in code at the end of the String. Then you replace the code in step 8 with the following code:
String s2 = keyboard.nextLine();
s1 = s1.concat(s2);
11. The previous step will read in a second object String named s2. Then the s1 object will be replaced with the results of concatenating itself to s2. The concat method is defined in the String class to do the operation we just described.
12. Because of the importance of the String class, the Java compiler provides a shortcut to the above 2 lines of code which uses the "+" operator to specify concatenation. So here is an alternative approache to the above:
s1 = s1 + s2; // This is equivalent to s1 = s1.concat(s2);
13. At this point, we might recognize that we really don't need the s2 object anymore, we could have just coded:
s1 = s1 + keyboard.nextLine();
// Or even shorter, how about:
s1 += keyboard.nextLine();
14. In fact, the Java compiler even goes the next step in making Strings to use with the "+" operator. Not all of the operands of the "+" operator need to be Strings. The compiler will make all of the appropriate conversions for you for free. So consider the following code:


  int x= 10;
		
  String s3 ="x=";
  s3 += x;  // Concatenating an int primitive to a String ... thank you Java compiler for converstions
  System.out.println(s3);

  // Consider the following more lengthy concatenation:
  double d= 2.3;
  boolean b = false;
  String s4 = "x=" + x + " d= " + d + " b =" + b;
  System.out.println(s4);


15. It turns out that the "left to right" calculations happen with "+" concatenation just as we noticed it occurred in normal arithmetic. Consider the the output from the following code:


  System.out.println(2 + 2 + " is the sum of 2 + 2");
  System.out.println(" When I add 2 +2, I get " + 2 + 2);
  System.out.println(" When I add 2 +2, I get " + (2 + 2));


16. Remember the only difference between print and println is that println tacks on a new line at the end.

System.out.print("she ");
System.out.print(" sells ");
System.out.print(" shells ");
System.out.println("**************************");
		
System.out.println("she ");
System.out.println(" sells ");
System.out.println(" shells ");
System.out.println("**************************");


17. Additional Scanner class methods


  //In the above example where we had a Scanner variable named "keyboard",
//we could read in variables other than a complete line using nextLine.

int x = keyboard.nextInt();  // reads in a single integer
double d = keyboard.nextDouble(); // reads in a single double
String s = keyboard.next(); // Reads in a single word delimited by white space instead of:
                            // nextLine which reads in a complete line


Programs created on the video:


import java.util.Scanner;

public class StringStuff {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter an integer");
        int x = scan.nextInt();
        System.out.println("x="+x);


        System.out.println("Enter an double");
        double d = scan.nextDouble();
        System.out.println("d="+d);



        System.out.println("Enter a String");
        String s = scan.next();
        System.out.println("s="+s);

        s = scan.next();
        System.out.println("second next call="+ s);

        s = scan.nextLine();
        System.out.println("nextLine called = " + s);
    }

}





public class StringStuff2 {

    public static void main(String[] args) {
        String s = new String("abc");
        //String s2 = new String ("xyz");
        String s2 = "xyz";

        //s2 = s2.concat("123");
        //s2 = s2 + "123";
        s2 += "123";

        System.out.println("s2="+ s2);

        int len = s2.length();
        System.out.println("len="+len);

        char c0 = s2.charAt(0);
        char c1 = s2.charAt(1);
        char c5 = s2.charAt(5);

        System.out.println(c0 + " "+ c1 + " " + c5);

        //char c6 = s2.charAt(6);


        System.out.println("The sum of 2 plus 2 is " + 2 + 2);
        System.out.println("The sum of 2 plus 2 is " +( 2 + 2));
        System.out.println(2 + 2 +" is the sum of 2 plus 2 " );

        int x=123;
        double d=123.567;
        boolean b = false;

        String stotal = "x="+ x + " d="+d + " b="+b;
        System.out.println(stotal);

        System.out.println("**************************");
        System.out.print("She");
        System.out.print(" sells");
        System.out.print(" shells");
        System.out.println();

        System.out.println("**************************");
        System.out.println("She");
        System.out.println(" sells");
        System.out.println(" shells");

    }

}



Java Practice(JPHC): Enter your answers in a text file with numbers for the questions 1,2,3, .....

1. ( 1 point) What is the output produced by the following?


  String verbPhrase = "is money";
  System.out.println("Time " + verbPhrase);


2. (1 point) How does output from section A differ from section B:


  // Section A
  System.out.print('a');
  System.out.print('b');
  System.out.print('c');

  // Section B
  System.out.println('a');
  System.out.println('b');
  System.out.println('c');



3. (1 point) What is the output produced by the following:


  String test = "abcdefg";
  int len = test.length();
  System.out.println("len=" + len);

  char c0 = test.charAt(0);
  char c2 = test.charAt(1);
  char c6 = test.charAt(6);
  // char c7 = test.charAt(7); // Error occurs if we execute this
  System.out.println("c0=" + c0 + " c2=" + c2 + " c6=" + c6);


4. (1 point) What is the output of the following two lines of Java code?


  System.out.println("2 + 2 = " + (2+2));
  System.out.println("2 + 2 = " + 2 +2 );



5. (1 points) Consider the following code segment. Our user types in:
abc 10 20 30


  Scanner keyboard = new Scanner(System.in);
  String s = keyboard.next();
  int x = keyboard.nextInt();

// What value will be in "s" and "x"

// If we change the "keyboard.next()" to "keyboard.nextLine()"
//     then what value will "s" have in it.

Last Modified: December 23, 2014 3:26 PM