Working with Strings

Introduction to Java

Jim White

Java Developer

String recap

Strings have built-in functionality for us to manipulate them

Introduction to Java

String.length()

  • Number of characters in the String = the length of the String
  • String.length() returns int for number of characters
String userName = "JSmith13";

int userNameLength = userName.length(); // Value is 8
Introduction to Java

Changing case

.toLowerCase()

  • Changes all letters to lowercase
class StringMethods1 {
  public static void main (String[] args){

    String yes = "Yes";
    System.out.println(yes.toLowerCase());

  }
}
yes

.toUpperCase()

  • Changes all letter to uppercase
class StringMethods2 {
  public static void main (String[] args){

    String yes = "Yes";
    System.out.println(yes.toUpperCase());

  }
}
YES
Introduction to Java

String concatenation

  • Use + to combine two Strings together
class StringMethodsCont {
  public static void main (String[] args){

    String message1 = "Java is";
    String message2 = "awesome";
    // Use " " to nicely format the final message
    System.out.println(message1 + " " + message2);
  }
}
Java is awesome
Introduction to Java

Concatenation with numbers

  • + automatically converts numbers to String when used with a String
class StringMethodsCont {
  public static void main (String[] args){

    String message1 = "Java is";
    int message2 = 29;
    // Use " " to nicely format the final message
    System.out.println(message1 + " " + message2);
  }
}
Java is 29
Introduction to Java

Declare now, assign later

  • Declare variable without giving them value, assign the value later
  • Useful for
    • Large amounts of text
    • When the value is not yet known
    • Effective structuring of code
// Define now
String courseCreators;



// Assign value later courseCreators = "Instructor: Jim White; Collaborators: Kat, George, Arne, Eduardo";
Introduction to Java

Recap

  • String = collection of characters in double quotes, with built-in functionality
// Declare now
String testMessage;
// Assign later
testMessage = "This is a test";

// Method to return the String's length (number of characters)
int msgLength = testMessage.length(); // Value is 14

// Methods to convert String to lower or upper case
String lowerMessage = testMessage.toLowerCase(); // Value is "this is a test"

String upperMessage = testMessage.toUpperCase(); // Value is "THIS IS A TEST"
Introduction to Java

Let's practice!

Introduction to Java

Preparing Video For Download...