next up previous
Next: Invocation of a constructor Up: Unit 02 Previous: Example: initials of a

Use of "+" for string concanenation

String concatenation is so common that Java provides a specific abbreviation for using the method concat(). Specifically, the expression:

"xxx".concat("yyy")
can be rewritten as:
"xxx" + "yyy"

Example:

public class JFK {
  public static void main(String[] args) {
    String  first = "John";
    String  middle = "Fitzgerald";
    String  last = "Kennedy";
    String  initials;
    String  firstInit, middleInit, lastInit;
    firstInit = first.substring(0,1);
    middleInit = middle.substring(0,1);
    lastInit = last.substring(0,1);
    initials = firstInit + middleInit + lastInit;
    System.out.println(initials);
  }
}

// or simply
public class JFK2 {
  public static void main(String[] args) {
    String  first = "John";
    String  middle = "Fitzgerald";
    String  last = "Kennedy";
    System.out.println(first.substring(0,1) +
                       middle.substring(0,1) +
                       last.substring(0,1));
  }
}


next up previous
Next: Invocation of a constructor Up: Unit 02 Previous: Example: initials of a