Java Strings

This article covers the uses of Strings in Java.

Strings are an integral part of any programming language due to their ability to store text. In Java, Strings have dozens of different methods associated with them which are used to manipulate and retrieve data from them efficiently.

Most of these methods are designed for “String Parsing” which is the act of going through pieces of texts extracting information form them. We’ll discuss several such examples of string parsing below.

See other Datatypes in Java.


Declaring Strings

Strings are declared using the String keyword.

String text = "Hello World";

Any text assigned to the variable text must be in double quotations. Though it can vary from system to system, there is almost no limit to the amount of text a String can hold.

Converting Strings

Often, you’ll need to convert other data types into String format, mostly Integers to Strings. There are many ways in Java to do conversions, and one way may not apply to all data types, but the most reliable one is the valueof() function. It works on Long, Double, Float and Integers.

String a = String.valueof(123);
String b = String.valueof(1.5);

Sub-strings in Java

The substring function in Java is used to pick out certain parts of a string and return them. The substring function can takes either one or two parameters. If only one parameter is created, like the one below, the substring function will return all characters starting from the index specified. Remember that indexing starts from zero in Java.

String s = "Java Strings";
		
System.out.println(s.substring(7));