Skip to content

Strings

Chris Ward edited this page Oct 7, 2022 · 2 revisions

Did you discover you can add strings? We actually did it earlier. It is really concatenation, but you can use the + to do it.

package examples.e_strings;

public class AddingStrings {

    public static void main(String[] args) throws Exception {
        String hello = "Hello";
        String world = "World";
        String greeting = hello + " " + world + "!";
        System.out.println(greeting);
    }
}

In the section on functions I asked you to create a function that took a name, like Sarah and returned 'Hello Sarah'. How did you do it? Did you do string concatenation, or use the print statement? If you didn't use concatenation, try creating a function that would add 'Hello ' to a name parameter and print it or return it.

Strings are objects.

We are really close to talking about classes and objects, but before we dig too deep into them, we will talk about Strings a bit more. Remember in Python when we imported cp we could then call functions from that library? Remember how in our first lesson we talked about the System class, and when we print something we access the out object and call the println function on it? The String class is kinda like that. When we create a String, we get a whole bunch of methods we can call on it. These are a few:

package examples.e_strings;

public class StringsHaveMethods {
    public static void main(String[] args) throws Exception {
        System.out.println("Hello".toLowerCase());
        System.out.println("Hello".toUpperCase());
        String hello = "Hello";
        System.out.println(hello.length());
        System.out.println(hello.charAt(0));
    }
}

Did you catch I called these things methods instead of functions. Up until now I have called them functions, just like in Python, but in Java, we call them methods. This is because these methods belong to the Class that defined them. It might seem like a very subtle difference, but we call them methods.

When we have created functions so far, they always take in parameters to work with. Notice that we called the methods right on the string, or the variable itself. No need to say `toUpperCase("Hello"). We will talk more about this soon.

Lets shift gears to Arrays

Clone this wiki locally