Chapter Table of Contents

Ch. 3 Data

Subsection Table of Contents

Word on Non-Primitives...

Non primitives such as array and String are used in Java as objects. Objects can be identified because they are (almost always) created using the keyword new. Objects, as you learned in the OOP lesson (see Ch. 1), are a key to Java and are powerful in the way they are manipulated. Objects are vital because they give you key and easy access to the data being manipulated.

String

We've already done a bit with these, but now let's learn some handy methods that we will apply later. Manipulating strings is a big part of Java. Some examples are breaking up a string or setting all of the characters to lowercase or uppercase. Now why would this be important? Well it could be applicable in a user login system for example. So let's take a look at these methods.

// *strings*
String username = "JYOTI";
String password = "rani";

System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println(username.charAT(3));

// string methods
System.out.println(username.toLowerCase());
System.out.println(password.toUpperCase());

// *strings are immutable - even after method calls,*
// *username and password remain unchanged*
System.out.println("Username: " + username);
System.out.println("Password: " + password);

Output of the code above:

Username: JYOTI;
Password: rani;
T
jyoti
RANI
JYOTI
Username: JYOTI
Password: rani

In the above example, we use 4 new String methods. Methods are always followed by a set of parentheses, which is where the list of arguments (things that let you customize what a method does) goes. The 4 methods are:

  1. toUpperCase() returns a String where all of the characters are uppercase
  2. toLowerCase() ****- returns a String where all of the characters are lowercase
  3. substring(start, end) - returns a substring from the start index to the end index, exclusive (the character at the end index is not included)
  4. charAt(index) ****- returns the character at that index

Credit: Jyoti Rani

Credit: Jyoti Rani

The picture represents how data in Strings are stored. Each character is at a certain position, or index, denoted by a number. Notice the indexing starts at 0, as with many aspects in Java. Usually, counting in the coding world starts with 0. With the word “HELLO” the substring specified at index from 0-4 would be “HELL” because the substring method does not include the character at the ending index (index 4).

We’ll learn more String methods in Ch. 10.