Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet49/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   45   46   47   48   49   50   51   52   ...   245
Bog'liq
Java 17 Recipes

CHAPTER 3
Strings
This chapter focuses on some of the most common String methods and techniques 
for working with String objects. In fact, they are one of the most used data types in any 
programming language. They can be used to obtain text from a keyboard, print messages 
to a command line, and much more. Given that strings are used so often, there have 
been many features added to the String object over time to make them easier to work 
with. After all, a string is an object in Java, so it contains methods that can manipulate 
the contents of the string.
3-1. Compact Strings
Since the Java language was introduced, strings have been stored into an array of type 
UTF-16 char. The char array contains two bytes for each character, which eventually 
produces a large memory heap since strings are often used in our applications. In Java 
9, strings are stored in an array of type byte, and stored characters are encoded either 
as ISO-8859-1/Latin-1 (one byte per character) or as UTF-16 (two bytes per character). 
There is also an encoding flag on the char array, indicating which type of encoding is 
used for the string. These changes are otherwise known as compact strings.
3-2. Obtaining a Subsection of a String
 Problem
You want to retrieve a portion of a string.


80
 Solution
Use the substring() method to obtain a portion of the string between two different 
positions. In the following solution, a string is created, and then various portions of the 
string are printed out using the substring() method.
public static void substringExample(){
String originalString = "This is the original String";
System.out.println(originalString.substring(0,
originalString.length()));
System.out.println(originalString.substring(5, 20));
System.out.println(originalString.substring(12));
}
Running this method would yield the following results.
This is the original String
is the original
original String

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   45   46   47   48   49   50   51   52   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling