Examples for usage of all methods of 'java.lang.String' with console output of example code.
Please click on method from below list to go to code example for usage of that method. Click [↓ Imports] to get import statements used in examples. To read javadoc of methods, click on [⿺ Javadoc] for that method.
String string = "Its All Binary";
// Get first character of string
char firstChar = string.charAt(0);
System.out.println("firstChar = " + firstChar);
// Get last character of string.
char lastChar = string.charAt(string.length() - 1);
System.out.println("lastChar = " + lastChar);
// Non existing index char. Causes exception.
char nonExistingChar = string.charAt(9999);
System.out.println("nonExistingChar = " + nonExistingChar);
Output: firstChar = I lastChar = y java.lang.StringIndexOutOfBoundsException: String index out of range: 9999 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47) at java.base/java.lang.String.charAt(String.java:693) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_charAt(StringExamples.java:36)
Tag: Example for charAt method of class java.lang.String., String charAt function example with arguments int arg0, How to use charAt method of String?, Usage of String.charAt, String.charAt() examples
String string = "Its All Binary";
IntStream stringStream = string.chars();
stringStream.forEach(i -> {
char c = (char) i;
System.out.println(i + " = " + c);
});
Output: 73 = I 116 = t 115 = s 32 = 65 = A 108 = l 108 = l 32 = 66 = B 105 = i 110 = n 97 = a 114 = r 121 = y
Tag: Example for chars method of class java.lang.String., String chars function example , How to use chars method of String?, Usage of String.chars, String.chars() examples, Convert String.chars intStream int to char primitive
// UTF-8 character
String string = "Its All Binary";
int code = string.codePointAt(4);
char c = (char) code;
System.out.println("Code = " + code + " char = " + c + " " + Character.toString(code));
/*
* UTF-16 character. Java char primitive can store only 16 bits. So below single
* utf-16 character is represented as 2 characters of 16 bits each i.e. \uD801
* (higher surrogate) & \uDC00 (lower surrogate). So even though its single
* unicode character, it is counted as 2 char.
*
* codePointAt(0) will verify that this is higher surrogate & next char is lower
* surrogate, so the code point returned in for for surrogate pair together &
* not just for first char or higher surrogate.
*/
String utf16_Char = "\uD801\uDC00";// Decimal 66560
int utf16_code_0 = utf16_Char.codePointAt(0);
System.out.println("Code = " + utf16_code_0 + " Is surrogate pair? = "
+ Character.isSurrogatePair(utf16_Char.charAt(0), utf16_Char.charAt(1))
+ " Verify code point using Character class = "
+ Character.toCodePoint(utf16_Char.charAt(0), utf16_Char.charAt(1)));
/*
* Java string Code points for all numbers, small & capital alphabet letters &
* some special characters. Code points for unicode characters from 48 till 122
*/
String letters = "0123456789:;<=>?@ABCDEFJHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz";
String output = "";
for (int i = 0; i < letters.length(); i++) {
output += "{" + letters.charAt(i) + "=" + letters.codePointAt(i) + "}";
}
System.out.println(output);
Output: Code = 65 char = A A Code = 66560 Is surrogate pair? = true Verify code point using Character class = 66560 {0=48}{1=49}{2=50}{3=51}{4=52}{5=53}{6=54}{7=55}{8=56}{9=57}{:=58}{;=59}{<=60}{==61}{>=62}{?=63}{@=64}{A=65}{B=66}{C=67}{D=68}{E=69}{F=70}{J=74}{H=72}{I=73}{J=74}{K=75}{L=76}{M=77}{N=78}{O=79}{P=80}{Q=81}{R=82}{S=83}{T=84}{U=85}{V=86}{W=87}{X=88}{Y=89}{Z=90}{[=91}{\=92}{]=93}{^=94}{_=95}{`=96}{a=97}{b=98}{c=99}{d=100}{e=101}{f=102}{g=103}{h=104}{i=105}{j=106}{k=107}{l=108}{m=109}{n=110}{o=111}{p=112}{q=113}{r=114}{s=115}{t=116}{u=117}{v=118}{w=119}{x=120}{y=121}{z=122}
Tag: Example for codePointAt method of class java.lang.String., String codePointAt function example with arguments int index, How to use codePointAt method of String?, Usage of String.codePointAt, String.codePointAt() examples, Calculate code point for surrogate pair in java String., Convert String or char to int code points., Get unicode decimal code point for english alphabets & alphanumerics & special symbols
// UTF-8 character
String string = "Its All Binary";
int code = string.codePointBefore(9);
char c = (char) code;
System.out.println("Code = " + code + " char = " + c + " " + Character.toString(code));
/*
* UTF-16 character. Java char primitive can store only 16 bits. So below single
* utf-16 character is represented as 2 characters of 16 bits each i.e. \uD801
* (higher surrogate) & \uDC00 (lower surrogate). So even though its single
* unicode character, it is counted as 2 char.
*
* codePointBefore(2) which is code point at 1 (lower surrogate) will verify
* that this is lower surrogate & previous char is higher surrogate, so the code
* point returned in for for surrogate pair together & not just for first char
* or lower surrogate.
*/
String utf16_Char = "\uD801\uDC00A";// Decimal 66560 & then character A
int utf16_code_0 = utf16_Char.codePointBefore(2);
System.out.println("Code = " + utf16_code_0 + " Is surrogate pair? = "
+ Character.isSurrogatePair(utf16_Char.charAt(0), utf16_Char.charAt(1))
+ " Verify code point using Character class = "
+ Character.toCodePoint(utf16_Char.charAt(0), utf16_Char.charAt(1)));
/*
* Java string Code points for all numbers, small & capital alphabet letters &
* some special characters. Code points for unicode characters from 48 till 122
*/
String letters = "0123456789:;<=>?@ABCDEFJHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{";
String output = "";
for (int i = 1; i < letters.length(); i++) {
output += "{" + letters.charAt(i - 1) + "=" + letters.codePointBefore(i) + "}";
}
System.out.println(output);
Output: Code = 66 char = B B Code = 66560 Is surrogate pair? = true Verify code point using Character class = 66560 {0=48}{1=49}{2=50}{3=51}{4=52}{5=53}{6=54}{7=55}{8=56}{9=57}{:=58}{;=59}{<=60}{==61}{>=62}{?=63}{@=64}{A=65}{B=66}{C=67}{D=68}{E=69}{F=70}{J=74}{H=72}{I=73}{J=74}{K=75}{L=76}{M=77}{N=78}{O=79}{P=80}{Q=81}{R=82}{S=83}{T=84}{U=85}{V=86}{W=87}{X=88}{Y=89}{Z=90}{[=91}{\=92}{]=93}{^=94}{_=95}{`=96}{a=97}{b=98}{c=99}{d=100}{e=101}{f=102}{g=103}{h=104}{i=105}{j=106}{k=107}{l=108}{m=109}{n=110}{o=111}{p=112}{q=113}{r=114}{s=115}{t=116}{u=117}{v=118}{w=119}{x=120}{y=121}{z=122}
Tag: Example for codePointBefore method of class java.lang.String., String codePointBefore function example with arguments int index, How to use codePointBefore method of String?, Usage of String.codePointBefore, String.codePointBefore() examples, Calculate code point for surrogate pair in java String., Convert String or char to int code points., Get unicode decimal code point for english alphabets & alphanumerics & special symbols
// UTF-8 character
String string = "Its All Binary";
int codeCount = string.codePointCount(0, string.length());
System.out.println("Length = " + string.length() + " CodeCount = " + codeCount);
/*
* UTF-16 character. Java char primitive can store only 16 bits. So below single
* utf-16 character is represented as 2 characters of 16 bits each i.e. \uD801
* (higher surrogate) & \uDC00 (lower surrogate). So even though its single
* unicode character, it is counted as 2 char.
*/
String utf16_Char = "\uD801\uDC00";// Decimal 66560
int utf16_code_Count = utf16_Char.codePointCount(0, utf16_Char.length());
System.out.println("Length = " + utf16_Char.length() + " CodeCount = " + utf16_code_Count);
Output: Length = 14 CodeCount = 14 Length = 2 CodeCount = 1
Tag: Example for codePointCount method of class java.lang.String., String codePointCount function example with arguments int arg0, int arg1, How to use codePointCount method of String?, Usage of String.codePointCount, String.codePointCount() examples
String string = "Its All Binary";
string.codePoints().forEach(i -> System.out.println("Code Point = " + i + " char = " + ((char) i)));
/*
* Java string Code points for all numbers, small & capital alphabet letters &
* some special characters. Code points for unicode characters from 48 till 122.
*/
String letters = "0123456789:;<=>?@ABCDEFJHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz";
String output = letters.codePoints().mapToObj(i -> "{" + (char) i + "," + i + "}")
.collect(Collectors.joining(","));
System.out.println(output);
Output: Code Point = 73 char = I Code Point = 116 char = t Code Point = 115 char = s Code Point = 32 char = Code Point = 65 char = A Code Point = 108 char = l Code Point = 108 char = l Code Point = 32 char = Code Point = 66 char = B Code Point = 105 char = i Code Point = 110 char = n Code Point = 97 char = a Code Point = 114 char = r Code Point = 121 char = y {0,48},{1,49},{2,50},{3,51},{4,52},{5,53},{6,54},{7,55},{8,56},{9,57},{:,58},{;,59},{<,60},{=,61},{>,62},{?,63},{@,64},{A,65},{B,66},{C,67},{D,68},{E,69},{F,70},{J,74},{H,72},{I,73},{J,74},{K,75},{L,76},{M,77},{N,78},{O,79},{P,80},{Q,81},{R,82},{S,83},{T,84},{U,85},{V,86},{W,87},{X,88},{Y,89},{Z,90},{[,91},{\,92},{],93},{^,94},{_,95},{`,96},{a,97},{b,98},{c,99},{d,100},{e,101},{f,102},{g,103},{h,104},{i,105},{j,106},{k,107},{l,108},{m,109},{n,110},{o,111},{p,112},{q,113},{r,114},{s,115},{t,116},{u,117},{v,118},{w,119},{x,120},{y,121},{z,122}
Tag: Example for codePoints method of class java.lang.String., String codePoints function example , How to use codePoints method of String?, Usage of String.codePoints, String.codePoints() examples, Convert String or char to int code points., Get unicode decimal code point for english alphabets & alphanumerics & special symbols
String text = "AD";
String sametext = "AD";
String sametextSmallCase = "ad";
String text_lexicographically_Previous = "AA";
String text_lexicographically_After = "AE";
String text_lexicographically_Similar_but_4CharLonger = "ADAAAA";
// 0 = text is equal, positive = text is greater, negative = text is lesser
// Both are equal so gives 0
System.out.println(text + " compareTo " + sametext + " = " + text.compareTo(sametext));
// compareTo is case sensitive. For case insensitive use compareToIgnoreCase()
System.out.println(text + " compareTo " + sametextSmallCase + " = " + text.compareTo(sametextSmallCase));
// Both are not equal but other String lexicographically falls before text
// string in sorting order. So text is greater.
System.out.println(text + " compareTo " + text_lexicographically_Previous + " = "
+ text.compareTo(text_lexicographically_Previous));
// Both are not equal but other String lexicographically falls after text
// string in sorting order. So text is lesser.
System.out.println(text + " compareTo " + text_lexicographically_After + " = "
+ text.compareTo(text_lexicographically_After));
// Both string have similar first to char but other string has 4 extra
// character. This will compare & return difference in lengths.
System.out.println(text + " compareTo " + text_lexicographically_Similar_but_4CharLonger + " = "
+ text.compareTo(text_lexicographically_Similar_but_4CharLonger));
// Use String.compare to sort list of strings like names using lambda & streams.
String sortedNames = Arrays.asList("Josh", "John", "Ravi", "James", "Amber", "Zoey", "Amy").stream()
.sorted((a, b) -> a.compareTo(b)).collect(Collectors.joining(","));
System.out.println("Sorted names using compare = " + sortedNames);
// compareTo null. Not null safe so causes NullPointerException. Make sure to do
// null checks.
text.compareTo(null);
Output: AD compareTo AD = 0 AD compareTo ad = -32 AD compareTo AA = 3 AD compareTo AE = -1 AD compareTo ADAAAA = -4 Sorted names using compare = Amber,Amy,James,John,Josh,Ravi,Zoey java.lang.NullPointerException at java.base/java.lang.String.compareTo(String.java:1196) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_compareTo_String(StringExamples.java:209)
Tag: Example for compareTo method of class java.lang.String., String compareTo function example with arguments java.lang.String arg0, How to use compareTo method of String?, Usage of String.compareTo, String.compareTo() examples
String text = "AD";
String sametext = "AD";
String sametextSmallCase = "ad";
String text_lexicographically_Previous = "aA";
String text_lexicographically_After = "Ae";
String text_lexicographically_Similar_but_4CharLonger = "AdAAAA";
// 0 = text is equal, positive = text is greater, negative = text is lesser
// Both are equal so gives 0
System.out.println(text + " compareToIgnoreCase " + sametext + " = " + text.compareToIgnoreCase(sametext));
// compareToIgnoreCase is case insensitive
System.out.println(text + " compareToIgnoreCase " + sametextSmallCase + " = "
+ text.compareToIgnoreCase(sametextSmallCase));
// Both are not equal but other String lexicographically falls before text
// string in sorting order. So text is greater.
System.out.println(text + " compareToIgnoreCase " + text_lexicographically_Previous + " = "
+ text.compareToIgnoreCase(text_lexicographically_Previous));
// Both are not equal but other String lexicographically falls after text
// string in sorting order. So text is lesser.
System.out.println(text + " compareToIgnoreCase " + text_lexicographically_After + " = "
+ text.compareToIgnoreCase(text_lexicographically_After));
// Both string have similar first to char but other string has 4 extra
// character. This will compare & return difference in lengths.
System.out.println(text + " compareToIgnoreCase " + text_lexicographically_Similar_but_4CharLonger + " = "
+ text.compareToIgnoreCase(text_lexicographically_Similar_but_4CharLonger));
// compareToIgnoreCase null. Not null safe so causes NullPointerException. Make
// sure to do null checks.
text.compareToIgnoreCase(null);
Output: AD compareToIgnoreCase AD = 0 AD compareToIgnoreCase ad = 0 AD compareToIgnoreCase aA = 3 AD compareToIgnoreCase Ae = -1 AD compareToIgnoreCase AdAAAA = -4 java.lang.NullPointerException at java.base/java.lang.String$CaseInsensitiveComparator.compare(String.java:1225) at java.base/java.lang.String$CaseInsensitiveComparator.compare(String.java:1218) at java.base/java.lang.String.compareToIgnoreCase(String.java:1258) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_compareToIgnoreCase(StringExamples.java:246)
Tag: Example for compareToIgnoreCase method of class java.lang.String., String compareToIgnoreCase function example with arguments java.lang.String arg0, How to use compareToIgnoreCase method of String?, Usage of String.compareToIgnoreCase, String.compareToIgnoreCase() examples
String itsAll = "Its All";
String binary = " Binary";
String fun = "Fun";
System.out.println(itsAll.concat(binary));
// Chaining string concat method. Will create multiple intermidiate string
// objects so might not be good for performance.
System.out.println(itsAll.concat(binary).concat(" ").concat(fun).concat("!"));
// If concat with empty string, then same string object returned back.
String concatItsAll = itsAll.concat("");
System.out.println("concatItsAll == itsAll --> " + (concatItsAll == itsAll));
// Concat null. Not null safe so causes NullPointerException. Make
// sure to do null checks.
System.out.println(itsAll.concat(null));
Output: Its All Binary Its All Binary Fun! concatItsAll == itsAll --> true java.lang.NullPointerException at java.base/java.lang.String.concat(String.java:1937) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_concat(StringExamples.java:267)
Tag: Example for concat method of class java.lang.String., String concat function example with arguments java.lang.String arg0, How to use concat method of String?, Usage of String.concat, String.concat() examples
String string = "Its All Binary";
// Contains binray, should give true
boolean containsBinary = string.contains("Binary");
System.out.println("containsBinary = " + containsBinary);
// Contains XYZ. Should give false.
boolean containsXYZ = string.contains("XYZ");
System.out.println("containsXYZ = " + containsXYZ);
// Contains with empty string. Gives true.
boolean containsEmptyString = string.contains("");
System.out.println("containsEmptyString = " + containsEmptyString);
// Contains check of String to StringBuffer. StringBuffer is also CharSequence.
StringBuffer bufferBinary = new StringBuffer("Binary");
boolean containsBinaryBuf = string.contains(bufferBinary);
System.out.println("containsBinaryBuf = " + containsBinaryBuf);
// Contains check of String to StringBuilder. StringBuilder is also
// CharSequence.
StringBuilder builderBinary = new StringBuilder("Binary");
boolean containsBinaryBuild = string.contains(builderBinary);
System.out.println("containsBinaryBuild = " + containsBinaryBuild);
// contains null. Not null safe so causes NullPointerException. Make
// sure to do null checks.
string.contains(null);
Output: containsBinary = true containsXYZ = false containsEmptyString = true containsBinaryBuf = true containsBinaryBuild = true java.lang.NullPointerException at java.base/java.lang.String.contains(String.java:2036) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_contains(StringExamples.java:300)
Tag: Example for contains method of class java.lang.String., String contains function example with arguments java.lang.CharSequence otherString, How to use contains method of String?, Usage of String.contains, String.contains() examples
String string = "Its All Binary";
// equals() works only for String. So use contentEquals to check String equality
// against StringBuffer
StringBuffer sameStringBuf = new StringBuffer("Its All Binary");
boolean isContentBufEquals = string.contentEquals(sameStringBuf);
System.out.println("isContentBufEquals = " + isContentBufEquals);
// Not null safe so causes NullPointerException. Make
// sure to do null checks.
string.contentEquals(null);
Output: isContentBufEquals = true java.lang.NullPointerException at java.base/java.lang.String.contentEquals(String.java:1096) at java.base/java.lang.String.contentEquals(String.java:1035) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_contentEquals_StringBuffer(StringExamples.java:318)
Tag: Example for contentEquals method of class java.lang.String., String contentEquals function example with arguments java.lang.StringBuffer sb, How to use contentEquals method of String?, Usage of String.contentEquals, String.contentEquals() examples, String equals StringBuffer, Check equality of String and StringBuffer
String string = "Its All Binary";
String sameString = "Its All Binary";
boolean isContentEquals = string.contentEquals(sameString);
System.out.println("isContentEquals = " + isContentEquals);
// equals() works only for String. So use contentEquals to check String equality
// against StringBuffer
StringBuffer sameStringBuf = new StringBuffer("Its All Binary");
boolean isContentBufEquals = string.contentEquals(sameStringBuf);
System.out.println("isContentBufEquals = " + isContentBufEquals);
// equals() works only for String. So use contentEquals to check String equality
// against StringBuilder
StringBuilder sameStringBldr = new StringBuilder("Its All Binary");
boolean isContentBldrEquals = string.contentEquals(sameStringBldr);
System.out.println("isContentBldrEquals = " + isContentBldrEquals);
// Not null safe so causes NullPointerException. Make
// sure to do null checks.
string.contentEquals(null);
Output: isContentEquals = true isContentBufEquals = true isContentBldrEquals = true java.lang.NullPointerException at java.base/java.lang.String.contentEquals(String.java:1096) at java.base/java.lang.String.contentEquals(String.java:1035) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_contentEquals_CharSequence(StringExamples.java:346)
Tag: Example for contentEquals method of class java.lang.String., String contentEquals function example with arguments java.lang.CharSequence cs, How to use contentEquals method of String?, Usage of String.contentEquals, String.contentEquals() examples, String equals StringBuffer, String equals StringBuilder, Check equality of String and StringBuffer or StringBuilder
char[] chars = { 'I', 't', 's', ' ', 'A', 'l', 'l', ' ', 'B', 'i', 'n', 'a', 'r', 'y' };
// Create string of character starting at index 0 i.e. 'I'. Then count 3
// characters after that which is till 's'
String its = String.copyValueOf(chars, 0, 3);
System.out.println(its);
// Create string of character starting at index 4 i.e. 'A'. Then count 3
// characters after that which is till last 'l'.
String all = String.copyValueOf(chars, 4, 3);
System.out.println(all);
// Create string of character starting at index 8 i.e. 'B'. Then count 6
// characters after that which is till end.
String binary = String.copyValueOf(chars, 8, 6);
System.out.println(binary);
// Give count that goes beyond string length. Causes exception.
String.copyValueOf(chars, 8, 6);
Output: Its All Binary
Tag: Example for copyValueOf method of class java.lang.String., String copyValueOf function example with arguments char[] data, int offset, int count, How to use copyValueOf method of String?, Usage of String.copyValueOf, String.copyValueOf() examples
char[] chars = { 'I', 't', 's', ' ', 'A', 'l', 'l', ' ', 'B', 'i', 'n', 'a', 'r', 'y' };
String string = String.copyValueOf(chars);
System.out.println(string);
// Try empty character array. Creates empty string object.
char[] emptyCharsArray = {};
String empty = String.copyValueOf(emptyCharsArray);
System.out.println("Empty char array to string ='" + empty + "'" + " equals empty = " + "".equals(empty));
// Try null character array. Causes exception.
char[] nullCharsArray = null;
String nullString = String.copyValueOf(nullCharsArray);
System.out.println("Null char array to string ='" + nullString + "'");
Output: Its All Binary Empty char array to string ='' equals empty = true java.lang.NullPointerException at java.base/java.lang.String.<init>(String.java:251) at java.base/java.lang.String.copyValueOf(String.java:3017) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_copyValueOf_charArray(StringExamples.java:386)
Tag: Example for copyValueOf method of class java.lang.String., String copyValueOf function example with arguments char[] data, How to use copyValueOf method of String?, Usage of String.copyValueOf, String.copyValueOf() examples
String string = "Its All Binary";
boolean endsWithY = string.endsWith("y");
System.out.println("endsWithY = " + endsWithY);
boolean endsWithAry = string.endsWith("ary");
System.out.println("endsWithAry = " + endsWithAry);
boolean endsWithItsAllBinary = string.endsWith("Its All Binary");
System.out.println("endsWithItsAllBinary = " + endsWithItsAllBinary);
boolean endsWithAll = string.endsWith("All");
System.out.println("endsWithAll = " + endsWithAll);
Output: endsWithY = true endsWithAry = true endsWithItsAllBinary = true endsWithAll = false
Tag: Example for endsWith method of class java.lang.String., String endsWith function example with arguments java.lang.String suffix, How to use endsWith method of String?, Usage of String.endsWith, String.endsWith() examples
String string = "Its All Binary";
// equals is symmetric
System.out.println("string.equals(\"Its All Binary\") = " + string.equals("Its All Binary"));
System.out.println("\"Its All Binary\".equals(string) = " + "Its All Binary".equals(string));
System.out.println("string.equals(\"Binary\") = " + string.equals("Binary"));
System.out.println("string.equals(\"XYZ\") = " + string.equals("XYZ"));
System.out.println("string.equals(\"\") = " + string.equals(""));
// String equals is null safe. In case of null returns false.
System.out.println("string.equals(null) = " + string.equals(null));
// String equals does not work with StringBuffer or StringBuilder even if
// content is exactly same. Use contentEquals() instead.
StringBuffer sameStringBuf = new StringBuffer("Its All Binary");
System.out.println("string.equals(sameStringBuf) = " + string.equals(sameStringBuf));
StringBuilder sameStringBldr = new StringBuilder("Its All Binary");
System.out.println("string.equals(sameStringBldr) = " + string.equals(sameStringBldr));
Output: string.equals("Its All Binary") = true "Its All Binary".equals(string) = true string.equals("Binary") = false string.equals("XYZ") = false string.equals("") = false string.equals(null) = false string.equals(sameStringBuf) = false string.equals(sameStringBldr) = false
Tag: Example for equals method of class java.lang.String., String equals function example with arguments java.lang.Object anObject, How to use equals method of String?, Usage of String.equals, String.equals() examples
String string = "Its All Binary";
// equalsIgnoreCase is symmetric
System.out
.println("string.equalsIgnoreCase(\"ITS all biNArY\") = " + string.equalsIgnoreCase("ITS all biNArY"));
System.out
.println("\"ITS all biNArY\".equalsIgnoreCase(string) = " + "ITS all biNArY".equalsIgnoreCase(string));
System.out.println("string.equalsIgnoreCase(\"Binary\") = " + string.equalsIgnoreCase("Binary"));
System.out.println("string.equalsIgnoreCase(\"XYZ\") = " + string.equalsIgnoreCase("XYZ"));
System.out.println("string.equalsIgnoreCase(\"\") = " + string.equalsIgnoreCase(""));
// String equalsIgnoreCase is null safe. In case of null returns false.
System.out.println("string.equalsIgnoreCase(null) = " + string.equalsIgnoreCase(null));
// String equalsIgnoreCase does not work with StringBuffer or StringBuilder as
// method argument is of type String.
Output: string.equalsIgnoreCase("ITS all biNArY") = true "ITS all biNArY".equalsIgnoreCase(string) = true string.equalsIgnoreCase("Binary") = false string.equalsIgnoreCase("XYZ") = false string.equalsIgnoreCase("") = false string.equalsIgnoreCase(null) = false
Tag: Example for equalsIgnoreCase method of class java.lang.String., String equalsIgnoreCase function example with arguments java.lang.String other, How to use equalsIgnoreCase method of String?, Usage of String.equalsIgnoreCase, String.equalsIgnoreCase() examples
/*
* String format with argument index format.
*
* Format %1$s means '%'<1st argument>'$'<String type>
*/
String string = String.format("Its %1$s %2$s", "All", "Binary");
System.out.println(string);
// Reuse format. Use string %s & digit %d format.
String format = "Hello %s, price of product is USD%d";
System.out.println(String.format(format, "James", 100));
System.out.println(String.format(format, "Ravi", 200));
/*
* String format with LocalDate
*
* Format %1$tm means '%'<1st argument><month>
*/
String today = String.format("Today's date is : %1$tm / %1$te / %1$tY", LocalDate.now());
System.out.println(today);
// String format with width zero filling
String zeroFilledDigits = String.format("%d%05d", 1, 9);
System.out.println(zeroFilledDigits);
// Console Tabular format using String format width strings & system out
String tabelFormatWithWidth = "|%4s |%8s |%12s |";
String header = String.format(tabelFormatWithWidth, "Id", "Name", "Department", "Salary");
System.out.println(header);
String row1 = String.format(tabelFormatWithWidth, "1", "James", "IT", "80000");
System.out.println(row1);
// String format date with width
String dateWithWidth = String.format("%1$10tm %1$20te %1$40tY", LocalDate.now());
System.out.println("Today = " + dateWithWidth);
// Wrong format. Causes exception.
String.format("%T", "Hi");
Output: Its All Binary Hello James, price of product is USD100 Hello Ravi, price of product is USD200 Today's date is : 11 / 2 / 2019 100009 | Id | Name | Department | | 1 | James | IT | Today = 11 2 2019 java.util.UnknownFormatConversionException: Conversion = 'T' at java.base/java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2839) at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2865) at java.base/java.util.Formatter.parse(Formatter.java:2713) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2897) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_format_String_ObjectArray(StringExamples.java:494)
Tag: Example for format method of class java.lang.String., String format function example with arguments java.lang.String format, java.lang.Object[] args, How to use format method of String?, Usage of String.format, String.format() examples
/*
* String format with argument index format.
*
* Format %1$s means '%'<1st argument>'$'<String type>
*/
String string = String.format(Locale.FRANCE, "Its %1$s %2$s", "All", "Binary");
System.out.println(string);
// Reuse format. Use string %s & digit %d format.
String format = "Hello %s, price of product is USD%d";
System.out.println(String.format(Locale.FRANCE, format, "James", 100));
System.out.println(String.format(Locale.FRANCE, format, "Ravi", 200));
/*
* String format with LocalDate
*
* Format %1$tm means '%'<1st argument><month>
*/
String today = String.format(Locale.CHINA, "Today's date is : %1$tm / %1$te / %1$tY", LocalDate.now());
System.out.println(today);
// String format with width zero filling
String zeroFilledDigits = String.format(Locale.CANADA, "%d%05d", 1, 9);
System.out.println(zeroFilledDigits);
// Console Tabular format using String format width strings & system out
String tabelFormatWithWidth = "|%4s |%8s |%12s |";
String header = String.format(Locale.ITALY, tabelFormatWithWidth, "Id", "Name", "Department", "Salary");
System.out.println(header);
String row1 = String.format(Locale.JAPAN, tabelFormatWithWidth, "1", "James", "IT", "80000");
System.out.println(row1);
// String format date with width
String dateWithWidth = String.format(Locale.CHINA, "%1$10tm %1$20te %1$40tY", LocalDate.now());
System.out.println("Today = " + dateWithWidth);
// Wrong format. Causes exception.
String.format(Locale.CHINA, "%T", "Hi");
Output: Its All Binary Hello James, price of product is USD100 Hello Ravi, price of product is USD200 Today's date is : 11 / 2 / 2019 100009 | Id | Name | Department | | 1 | James | IT | Today = 11 2 2019 java.util.UnknownFormatConversionException: Conversion = 'T' at java.base/java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2839) at java.base/java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2865) at java.base/java.util.Formatter.parse(Formatter.java:2713) at java.base/java.util.Formatter.format(Formatter.java:2655) at java.base/java.util.Formatter.format(Formatter.java:2609) at java.base/java.lang.String.format(String.java:2938) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_format_Locale_String_ObjectArray(StringExamples.java:538)
Tag: Example for format method of class java.lang.String., String format function example with arguments java.util.Locale arg0, java.lang.String arg1, java.lang.Object[] arg2, How to use format method of String?, Usage of String.format, String.format() examples
String string = "öäü 123 Its All Binary ® é \u0080";
// Except '123 Its All Binary' everything else is non-ascii so not mappable
// using "US-ASCII". All other characters will be replaced by default
// replacement char.
byte[] bytes = string.getBytes(Charset.forName("US-ASCII"));
System.out.println(new String(bytes));
byte[] bytesUtf8 = string.getBytes(Charset.forName("UTF-8"));
System.out.println(new String(bytesUtf8, Charset.forName("UTF-8")));
Output: ??? 123 Its All Binary ? ? ? öäü 123 Its All Binary ® é ?
Tag: Example for getBytes method of class java.lang.String., String getBytes function example with arguments java.nio.charset.Charset arg0, How to use getBytes method of String?, Usage of String.getBytes, String.getBytes() examples
String string = "öäü 123 Its All Binary ® é \u0080";
// Except '123 Its All Binary' everything else is non-ascii so not mappable
// using "US-ASCII". All other characters will be replaced by default
// replacement char.
try {
byte[] bytes = string.getBytes("US-ASCII");
System.out.println(new String(bytes));
byte[] bytesUtf8 = string.getBytes("UTF-8");
System.out.println(new String(bytesUtf8, Charset.forName("UTF-8")));
// Wrong encoding. WIll throw exception.
string.getBytes("INCORRECT-ENCODING");
} catch (UnsupportedEncodingException e) { // Need to catch or throw UnsupportedEncodingException
e.printStackTrace();
}
Output: ??? 123 Its All Binary ? ? ? öäü 123 Its All Binary ® é ? java.io.UnsupportedEncodingException: INCORRECT-ENCODING at java.base/java.lang.StringCoding.encode(StringCoding.java:427) at java.base/java.lang.String.getBytes(String.java:941) at com.itsallbinary.javadocexamples.examples.java_lang.StringExamples.test_getBytes_String(StringExamples.java:578) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at com.itsallbinary.javadocexamples.core.CompilerAndExecutor.executeJavaMethod(CompilerAndExecutor.java:106) at com.itsallbinary.javadocexamples.core.Main.generateJavadocExamplesForJavaSourceFile(Main.java:74) at com.itsallbinary.javadocexamples.core.Main.generateJavadocExamples(Main.java:42) at com.itsallbinary.javadocexamples.core.Main.main(Main.java:33)
Tag: Example for getBytes method of class java.lang.String., String getBytes function example with arguments java.lang.String arg0, How to use getBytes method of String?, Usage of String.getBytes, String.getBytes() examples
String string = "öäü 123 Its All Binary ® é \u0080";
// Except '123 Its All Binary' everything else is non-ascii so not mappable
// using "US-ASCII".
byte[] bytes = string.getBytes();
System.out.println(new String(bytes));
Output: öäü 123 Its All Binary ® é ?
Tag: Example for getBytes method of class java.lang.String., String getBytes function example , How to use getBytes method of String?, Usage of String.getBytes, String.getBytes() examples
Import statements used in examples.
java.util.Arrays
java.util.Locale
java.util.stream.Collectors
java.util.stream.IntStream
org.apache.commons.lang3.CharSet
java.io.UnsupportedEncodingException
java.nio.charset.Charset
java.time.LocalDate
Tag: Simple working examples of methods / functions of class java.lang.String along with their console output, java.lang.String tutorial., Guide to java.lang.String & its methods., Understanding java.lang.String with examples.