Skip to content

Strings

Learn about the different things that can be done with strings

  • Lesson
  • 2 min read
  • 5 of 15 in this chapter

What is a string?

A string is multiple Char datasets arranged together. This can be used to form a word. For example the word "char" is just seen as "c"+"h"+"a"+"r"

Strings are useful to get information in the form of words. For example, to be able to use input we need to understand strings in order to put such input into a sentence.

This is how we declare a string...

Java
String aStringName = "This is where you put your sentence";

We can print this string out...

Java
String aStringName = "This is where you put your sentence";
System.out.println(aStringName);
//it will print out: This is where you put your sentence

String functions

Strings have functions that help the program obtain data about a string. Here are some useful functions...

Java
//you can print out the char value at an index by using charAt()
String characterIndex = "Java";
char firstCharacter = characterIndex.charAt(0);
System.out.println(firstCharacter);
//this will print out the letter J

You can also find the index of a phrase in a string...

Java
//you can find the first index of a phrase in a string
String mySentence= "Java is good";
int goodIndex = mySentence.indexOf("good");
/* this will return the number 8 because it counts
 the first letter in the string as the 0th spot in the index*/

You can get the length of a string too...

Java
//this will find the length of a string
String mySentence= "Java is good";
int mySentenceLength= mySentence.length();
System.out.println(mySentenceLength);
//this will return the length of the sentence, 12.

You can turn a string uppercase and lowercase...

Java
//this will find the length of a string
String mySentence= "Java is good";
mySentence = mySentence.toUpperCase();
//will return: JAVA IS GOOD
mySentence = mySentence.toLowerCase();
//will return: java is good

You can find the characters at a specific index of a string...

Java
//this will find the length of a string
String mySentence= "Java is good";
String javaSubstring = mySentence.substring(0,4);
//this will take the letters from index 0->|Java|<-to index 4
System.out.println(javaSubstring);
//this will print out the word java