The String Class


Collapse Content

You've already used some Java Classes - Arrays and Strings. These classes are very basic, so all Java code has built-in access to them. As covered before, you can create Strings with the following syntax:

String name = "jim";

This is a shortcut Java provides since Strings are so common: they can be handled like primitive data types. Strings can also be created like other Objects are, with a new keyword and ():

String name = new String("jim");  //equivalent to previous code

You never need to use the above code form, but it demonstrates that Strings are real Objects.

The String Class
All Strings are instances of the Java String Class. This means that every String instance will have access to all of the methods of the String Class. For example, you can get the length of any Java String with the length() method:

int num = name.length(); 

num will now equal 3 since name was 3 characters long.

There are many other methods in the String Class that do things like splitting strings, concatenating them, pulling out substrings and more. You don't need to have any idea how these methods are implemented in order to use them. You just need to know what they take in as parameters, what they do, and what they return. To find this information, you need to use some documentation, which will be covered later. To get started using the String Class, we will cover some of its common methods in the next Node.

Project

Your Note-taking app recently shut down, so you decide to create a new one in Java. You will use a Note instance to store each note. To get started, complete the Note Class so that it satisfies the requirements below.

As a member, make sure to download the BlueJ project that accompanies this module! (See Programming in Java on Your Computer to review using BlueJ.)

Note: The goal of this project will be to explore some methods from a couple Java Library Classes, not to make the next Angry Birds.

Challenge

Complete the Note Class so the String content is set to a String parameter whenever a Note is created. In addition, complete the method getContent() so it returns the content of the Note. Also, create a new method called noteLength() which should return the int length of the Note.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Challenge

You have a String named paragraph. In one line of code create an int variable length and sets its value to the length of paragraph.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • public Note(String bericht)
    {content=bericht;
    
    }
    
    //complete this accessor method
    public String getContent()
    {return content;
    
    }
    
    public int noteLength(){
        return content.length();
    }
    
Contact Us
Sign in or email us at [email protected]