Created: 2023-08-26 16:05
Status: #concept
Subject: Programming
Tags: Java Java Data Type java.util.Scanner java.lang.StringBuilder
Java String Class
It is an object type, which is also built-into Java with the java.lang Java Package.
- we can use it like a primitive data type to declare variables.
- we use the java.util.Scanner utility object to scan strings from
System.in
(stdin) or Java Files.
Scanner scan = new Scanner(System.in);
// getting user input
String userInput = scan.nextLine();
// string concatenation & string interpolation
System.out.println("You inputted: " + userInput);
System.out.println(String.format("You inputted: %s", userInput));
// typecasting to string
Integer someInteger = 777;
System.out.println(String.valueOf(someInteger));
System.out.println(someInteger.toString());
System.out.println("" + someInteger);
static
Methods
String.format(fmt, ...args)
acts like stdio.h'sprintf
function which converts a Format String's Conversion Specifiers based on the...args
and returns it.- to pad integers, we need to use
%0Pd
, whereP
is the maximum number of padding to occupy like%.Pd
inprintf
see here.
- to pad integers, we need to use
String.valueOf(anyTypeValue)
convertsanyTypeValue
into aString
.
Instance Methods
.length()
returns the number of characters in the string..isEmpty()
returnstrue
if.length()
is0
.
.equals(String aString)
checks if the instance is equal toaString
..startsWith(String aString): boolean
same as JavaScript..repeat(int num)
concatenates the string instance by itselfnum
times..split(Pattern delimiter)
returns aString[]
containing the strings in between eachdelimiter
, similar to JavaScript.- if
delimiter.equals("")
, it will split each letter into individual strings.
- if
.join(String delimiter, Iterable<String> iterable)
joins aniterable
string or java.lang.StringBuilderCharSequence
..trim(): String
removes any leading & trailing whitespaces..contains(String substr)
returnstrue
if the instance contains asubstr
, otherwisefalse
..charAt(int index)
returns aString
of the character at theindex
..compareTo(String s)
returns anint
for java.util.Comparable interfaces..compareToIgnoreCase(String s)
does the same, but ignores capitalization.