&& vs & , || vs |


package com.me.date;

public class DoubleSingaleANDO {
public static void main(String[] args) {
int a=123,b=0;

//Exception in thread "main" java.lang.ArithmeticException: / by zero
//at com.me.date.DoubleSingaleANDO.main(DoubleSingaleANDO.java:9)
/*if((a< 100) & (a/b==0)){
System.out.println(a/b);
}else{
System.out.println("Hey");
}*/

//Hey
//if first one is false then it ignores rest
if((a100) || (a/b==0)){
System.out.println("True");
}else{
System.out.println("Hey");
}

//Exception in thread "main" java.lang.ArithmeticException: / by zero
//at com.me.date.DoubleSingaleANDO.main(DoubleSingaleANDO.java:35)
if((a>100) | (a/b==0)){
System.out.println("True");
}else{
System.out.println("Hey");
}

}
}

boolean a, b;

Operation Meaning Note
——— ——- —-
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT

short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE

up vote
185
down vote
accepted
& <– verifies both operands
&& 1) 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) 1) so if you have x=0 then this is perfectly safe and won’t throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <– this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <– this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

https://stackoverflow.com/questions/5564410/difference-between-and

Advertisements


#perl 5.22.1

print "Hello World\n";

my $a="ghj";
my $b="gjg";

if($a==$b){
print "true";
}
else{
print "false";
}

my @array=(A..Z);
foreach my $value(@array){
print "$value";
}

my $size=scalar(@array);
#trueABCDEFGHIJKLMNOPQRSTUVWXYZ$size =>'$size'
#26 => $size
print $size;

my @array=(A..Z);
foreach(@array){
print "$_";
}

my %hash=('a' => 123, 'b' => 124 , 'f'=> 256, '12' => 144);
print "\n";
#order can't be guaranteed 12144b124a123f256
print %hash;

foreach my $key(keys %hash){
print "\n";
print "$key";
}

foreach my $i(values %hash){
print "\n";
print "$i";
}

Error(s), warning(s):
"my" variable @array masks earlier declaration in same scope at source_file.pl line 25.
Argument "gjg" isn't numeric in numeric eq (==) at source_file.pl line 8.
Argument "ghj" isn't numeric in numeric eq (==) at source_file.pl line 8.
Hello World
trueABCDEFGHIJKLMNOPQRSTUVWXYZ26ABCDEFGHIJKLMNOPQRSTUVWXYZ
b12412144a123f256
b
12
a
f
124
144
123
256

my @list=qw("John","Messi","Pichai","Tcs");
print @list;

Error(s), warning(s):
Possible attempt to separate words with commas at source_file.pl line 3.
"John","Messi","Pichai","Tcs"

my @list=("John","Messi","Pichai","Tcs");
print @list;
JohnMessiPichaiTcs

#perl 5.22.1

my @list=("John","Messi","Pichai","Zodiac","Tcs");

foreach my $i(@list){

if($i eq "John") {
print "John-Found\n";
}
if($i ne "404_Error"){
print "404_Error not found";
}
if($i lt "Tcs"){
print " $i";
}
}

John-Found
404_Error not found John404_Error not found Messi404_Error not found Pichai404_Error not found404_Error not found

#1000*3434000$c*3434000
my $a =10;
my $b=3;
my $c= $a**$b;
print "$c*34";
print $c*34;
print '$c*34';
print $c*34;

Perl – Copy files to directory if doesn’t exits

#!/usr/bin/perl

use strict;
use warnings;
use File::Copy;

// source and dest file directories
my $dir = '/tmp';
my $dir2 = '/tmp2';

//open directory
opendir(DIR, $dir) or die $!;

///read directory
while (my $file = readdir(DIR)) {

# We only want files
next unless (-f "$dir/$file");

# Use a regular expression to find files ending in .txt
//here it will give all files
next unless ($file =~ m/\.*$/);

print "$file\n";
if (-e $dir2/$file)
{
print "the file exists\n";
}
else
{
print "the file does not exist!\n";
move($dir/$file, $dir2/$file) or die "The move operation failed: $!";
}
}

closedir(DIR);
exit 0;

java.lang.String methods


package com.me.strings;

import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.regex.Pattern;

public class StringMethods {
public static void main(String[] args) throws UnsupportedEncodingException {

//Unlike StringBuffer and StringBuilder String class doesn't have methods like
//reverse(), insert(), append(),delete() etc.

//Passing null as paramter to any constructor or method will
//leads to Exception in thread "main" java.lang.NullPointerException

//toUpper or toLower with Locale only
//Since case mappings are not always 1:1 char mappings, the resulting String may be a
//different length than the original String.

//Regex is applicable for replaceAll,replaceFirst,regionMatches,matches but not fore
//replace

// //converts to int interanally
//index=stringReplaceble.indexOf('w');
//System.out.println(index);
//
//index=stringReplaceble.indexOf(97);
// System.out.println(index);

//a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

String stringWithWhiteSpaces = "\t ";
String stringWithWhiteSpacesOnly = "\t ";
String stringWithWhiteSpacesNull = null;
String stringWithUpperLower = "ThIS is ABsuREd ..YoU KnoW!!";
String stringTempUpper;
String stringTempLower;
String stringsubStrings="physiology";
String stringSplittable= " Then now we are what we are ,"
+ ""
+ "PatternSyntaxException - if the regular "
+ "expression's syntax is invalid";
String stringReplaceble=" We are what we are then now forever...";
//CE
//String stringCENull=new String(null);

//Exception in thread "main" java.lang.NullPointerException
//at java.lang.String.(Unknown Source)
///at com.me.strings.StringMethods.main(StringMethods.java:16)
String stringRENull=null;
//String stringRENullResult=new String(stringRENull);

//valueOf --> Gives to you String object from other primitive or respective Wrapper objects
//Creating empty string and adding reminig using "+" operator.
String string=new String();

//boolean
string+=string.valueOf(new Boolean(true));
//"False" -> new Boolean("1"),new Boolean("JHJ"),new Boolean("Falsegf"),new Boolean("156ye")
// all wrong values it will give you false as value

//true -> new Boolean("true"), new Boolean("True")
string+=string.valueOf(new Boolean("1"));

//char
string+=string.valueOf('a');
string+=string.valueOf(new Character('M'));
string+=string.valueOf(new Character((char)101));

//short
string+=string.valueOf(new Short("10"));

//int
string+=string.valueOf(123);
string+=string.valueOf(new Integer(26526));
string+=string.valueOf(new Integer("5365"));
string+=string.valueOf(new Integer((int)'M'));

//float
string+=string.valueOf(23326.4554f);
string+=string.valueOf(new Float(0.23));
string+=string.valueOf(new Float("4576.22"));
string+=string.valueOf(new Float(new Double("23623")));

//Double
string+=string.valueOf(new Double(0.23D));
string+=string.valueOf(new Double("52345530.23"));

//long
string+=string.valueOf(new Long(2515145l));
string+=string.valueOf(new Long("146546545"));

//object
string+=string.valueOf(new Object());
Object object=new String(" Child of Object");

//char array
char[] cs={'W','O','R','L','D'};
string+=string.valueOf(cs);
string+=string.valueOf(cs,2,2);

//truefalseaMe101232652653657723326.4550.234576.2223623.00.235.234553023E72515145146546545java.lang.Object@15db9742WORLDRL
System.out.println(string);

System.out.println("=======================trim()====================");

//Adding white space characters at last , middle and start
//It has tab value and now we adding content and more tabs
stringWithWhiteSpaces+=" This is paragraph and it contains spaces tooo."
+ ""
+ ""
+ "Plese Ignore";
stringWithWhiteSpaces+="\n \t ";
System.out.println(stringWithWhiteSpaces);
System.out.println(stringWithWhiteSpaces.length());

//It will remove preceding and leading whitespaces only and it
//is not responsble for removing whitespaces in the middle of any non-whitepsace characters
stringWithWhiteSpaces.trim();
////This still gives you old result i.e before trim() call but trim() has applied successfully.
//So here you need make point on String class like it is immutable so calling trim() wont affect orginal
//reference instead Returns a copy of the string, with leading and trailing whitespace omitted.
System.out.println(stringWithWhiteSpaces);
System.out.println(stringWithWhiteSpaces.length());

//self-referencing after trim()
stringWithWhiteSpaces=stringWithWhiteSpaces.trim();
System.out.println(stringWithWhiteSpaces);
System.out.println(stringWithWhiteSpaces.length());

/* This is paragraph and it contains spaces tooo.Plese Ignore

83
This is paragraph and it contains spaces tooo.Plese Ignore

83
This is paragraph and it contains spaces tooo.Plese Ignore
63
*/
stringWithWhiteSpacesOnly=stringWithWhiteSpacesOnly.trim();
System.out.println(stringWithWhiteSpacesOnly);
System.out.println(stringWithWhiteSpacesOnly.length());

//gives you NullPointerException as reference is null
//stringWithWhiteSpacesNull=stringWithWhiteSpacesNull.trim();
//System.out.println(stringWithWhiteSpacesNull);

System.out.println("=======================toUpper() , toLower() , toString() and toCharArray()====================");

//Since case mappings are not always 1:1 char mappings, the resulting String may be a different
//length than the original String.

Locale locale = Locale.getDefault();
String[] locale2=Locale.getISOLanguages();
for(String str:locale2){
System.out.print(" "+str);
}
System.out.println();
System.out.println("Default locale :"+locale);
System.out.println(stringWithUpperLower);

stringTempLower=stringWithUpperLower.toLowerCase();
System.out.println(stringTempLower);

stringTempLower=stringWithUpperLower.toLowerCase(new Locale("tr"));
System.out.println(stringTempLower);

stringTempUpper=stringWithUpperLower.toUpperCase();
System.out.println(stringTempUpper);

stringTempUpper=stringWithUpperLower.toUpperCase(new Locale("tr"));
System.out.println(stringTempUpper);

//toString()
//string retuns itself..!
System.out.println(stringWithUpperLower.toString());

//converts string to char[]
//length of the char[] array is equal to length of string
char[] charArrayFromString = stringWithUpperLower.toCharArray();
System.out.println(charArrayFromString.length+"=="+stringWithUpperLower.length()+ " lengths are equal"
+ " if you convert string to char[] ");
for(char c:charArrayFromString){
System.out.print(" "+c);
}
System.out.println();

System.out.println("=======================subString() and split()====================");

String temp=null;
/*
* //Returns a new string that is a substring of this string. The
* substring begins with the character at the specified index and
* extends to the end of this string. Examples:
*
* "unhappy".substring(2) returns "happy" "Harbison".substring(3)
* returns "bison" "emptiness".substring(9) returns "" (an empty string)
*/

/* public String More ...substring(int beginIndex, int endIndex) {
1947 if (beginIndex value.length) {
1951 throw new StringIndexOutOfBoundsException(endIndex);
1952 }
1953 int subLen = endIndex - beginIndex;
1954 if (subLen siol
System.out.println(temp);

//It returns CharSequance object
temp=stringsubStrings.subSequence(3, 7).toString();
System.out.println(temp);

boolean b=stringsubStrings.startsWith("phy");
System.out.println(b);

// this.substring(toffset).startsWith(prefix)
//prefix - the prefix.
//toffset - where to begin looking in this string.
b=stringsubStrings.startsWith("olo",5);
System.out.println(b);

/*he string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }*/
//splits with space as delimeter
String[] splits=stringSplittable.trim().split("\\s+");
for(String strT:splits){
System.out.print(" "+strT);
}
System.out.println();
System.out.println(splits.length);

//--boo--and--foo
//--b----:and:f

String split2="boo:and:foo";
splits=split2.split(":");
for(String strT:splits){
System.out.print("--"+strT);
}
System.out.println();

splits=split2.split("o");
for(String strT:splits){
System.out.print("--"+strT);
}
System.out.println();

//The limit parameter controls the number of times the pattern is applied and therefore affects the
//length of the resulting array. If the limit n is greater than zero then the pattern will be applied at
//most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain
//all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as
//many times as possible and the array can have any length. If n is zero then the pattern will be applied
//as many times as possible, the array can have any length, and trailing empty strings will be discarded.

//Limiting the results
//ACTUAL -> Then now we are what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
//16

//NOW -> Thennowweare what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
//1,2,3,4 REMAING IS 5
splits=stringSplittable.split("\\s+",5);
for(String strT:splits){
System.out.print(strT);
}
System.out.println();
System.out.println(splits.length);

//0,-2 , -322
// Then now we are what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
//17
// It only limits the number of iterations if the size is zero or less than zero or greater than length of the string
splits=stringSplittable.split("\\s+",-32);
for(String strT:splits){
System.out.print(" "+strT);
}
System.out.println();
System.out.println(splits.length);

System.out.println("=======================replace() and regionMatches()====================");

//no regex support for replace() method
//Leght can be varied after replacing
System.out.println(stringReplaceble);
temp= stringReplaceble.replace('e', 'E');
System.out.println(temp);

temp= stringReplaceble.replace(new StringBuffer("we"), new StringBuffer("LOL"));
System.out.println(temp);

/* 39
&&&&&We&&&&&are&&&&&what&&&&&we&&&&&are&&&&&then&&&&&now&&&&&forever...
71
39
_ _ _ _ _ _ _ _...
19
39
&&&&&We are what we are then now forever...
43
*
*
*/

System.out.println(stringReplaceble.length());
temp= stringReplaceble.replaceAll("\\s+","&&&&&");
System.out.println(temp);
System.out.println(temp.length());

System.out.println(stringReplaceble.length());
temp= stringReplaceble.replaceAll("\\w+","_");
System.out.println(temp);
System.out.println(temp.length());

System.out.println(stringReplaceble.length());
temp= stringReplaceble.replaceFirst("\\s+","&&&&&");
System.out.println(temp);
System.out.println(temp.length());

//" We are what we are then now forever..."
b=stringReplaceble.regionMatches(4, "are", 0, 3);
System.out.println(b);

b=stringReplaceble.regionMatches(true, 4, "ARE", 0, 3);
System.out.println(b);
b=stringReplaceble.regionMatches(false, 4, "ARE", 0, 3);
System.out.println(b);

System.out.println("=======================matches()====================");

b= stringReplaceble.matches("^.*are.*$");
System.out.println(b);

b= stringReplaceble.matches("are");
System.out.println(b);

//The above matches has same effect as Pattern.matches
b=Pattern.matches("^.*are.*$", stringReplaceble);
System.out.println(b);

System.out.println("=======================indexdOf(),lastIndexOf(),isEmpty(),intern() and length()====================");

////" We are what we are then now forever..."
// -1
// 5
// 8

//If not found -1
//If found equavalent Unicode character in the string object then first occuranc index eis returned.
int index=stringReplaceble.indexOf('Q');
System.out.println(index);
//returns index
//converts to int interanally
index=stringReplaceble.indexOf('r');
System.out.println(index);
//converts to int interanally
index=stringReplaceble.indexOf('w');
System.out.println(index);
//accepts int as arg
index=stringReplaceble.indexOf(97);
System.out.println(index);

//-1 bcz though 'W' has in string ,It starts searching from 12th index
// (this.charAt(k) == ch) && (k >= fromIndex)
index=stringReplaceble.indexOf('W',12);
System.out.println(index);

// this.startsWith(str, k)
index=stringReplaceble.indexOf("waste");
System.out.println(index);
index=stringReplaceble.indexOf("now");
System.out.println(index);

// k >= fromIndex && this.startsWith(str, k)
index=stringReplaceble.indexOf("now",12);
System.out.println(index);
index=stringReplaceble.indexOf("now",162);
System.out.println(index);

//The String is searched backwards starting at the last character.
//The String is searched backwards starting at the last character.
// fromIndex is the limit here so it will givew the results <= to that index
//from right to left side.
index=stringReplaceble.lastIndexOf('e');
System.out.println(index);
//////" We are what we are then now forever..."
//Here search will
/* 34
6
34
2
1
-1
16
4*/

index=stringReplaceble.lastIndexOf('e',12);
System.out.println(index);
index=stringReplaceble.lastIndexOf('e',stringReplaceble.length());
System.out.println(index);
index=stringReplaceble.lastIndexOf('e',3);
System.out.println(index);
index=stringReplaceble.lastIndexOf('W',12);
System.out.println(index);
index=stringReplaceble.lastIndexOf(107);
System.out.println(index);

index=stringReplaceble.lastIndexOf("are");
System.out.println(index);

index=stringReplaceble.lastIndexOf("are",12);
System.out.println(index);

//int not long
//no if unicdoe chars
System.out.println(stringReplaceble.length());

//Returns true if, and only if, length() is 0.
System.out.println(stringReplaceble.isEmpty());

/* public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.*/
System.out.println(stringReplaceble.hashCode());
// public native String More ...intern();
// }
stringReplaceble.intern();
System.out.println(stringReplaceble.hashCode());

System.out.println("=======================hashCode()====================");
int hashcode=stringReplaceble.hashCode();
System.out.println(hashcode);
//for empty it will give zero
hashcode="".hashCode();
System.out.println(hashcode);
//Exception in thread "main" java.lang.NullPointerException
//at com.me.strings.StringMethods.main(StringMethods.java:490)
String stringHash=null;
//hashcode=stringHash.hashCode();
System.out.println(hashcode);

System.out.println("=======================getBytes() and getChars()====================");
/* public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination character array.
The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

dstbegin + (srcEnd-srcBegin) - 1

Parameters:
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.
dst - the destination array.
dstBegin - the start offset in the destination array.
Throws:
IndexOutOfBoundsException - If any of the following is true:
srcBegin is negative.
srcBegin is greater than srcEnd
srcEnd is greater than the length of this string
dstBegin is negative*/

//" We are what we are then now forever..."
char[] cArray={'R','P','A','H','Y'};
stringReplaceble.getChars(1, 3, cArray, 2);
for(char c:cArray){
System.out.println(c);
}

// Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
// The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
System.out.println();
byte[] bytes=stringReplaceble.getBytes();
for(byte c:bytes){
System.out.println(c);
}

//throws checked exception
//UnsupportedEncodingException
//public byte[] getBytes(Charset charset)
System.out.println();
bytes=stringReplaceble.getBytes("US-ASCII");
for(byte c:bytes){
System.out.println(c);
}

//public byte[] getBytes(String charsetName)
// throws UnsupportedEncodingException
//Encodes this String into a sequence of bytes using the named charset, s
System.out.println();
bytes=stringReplaceble.getBytes("US-ASCII");
for(byte c:bytes){
System.out.println(c);
}

System.out.println("=======================format()====================");

String stringFormat =String.format(" Concatinatging this using another string : %s", stringReplaceble);
System.out.println(stringFormat);

stringFormat =String.format(" Concatinatging this using another string : %.7f", 45645.44);
System.out.println(stringFormat);

// Concatinatging this using another string : We are what we are then now forever...
// Concatinatging this using another string : 45645.4400000

//If more no of args are there then it ignores the remining ones.
//Below "NO-4" got ignored.
stringFormat =String.format(" Concatinatging this using another strings are : %1$s ,%2$s and %3$s",
"NO-1","No-2","NO-3","No-4");
System.out.println(stringFormat);

stringFormat=String.format("|%30s|", "Hello World");
System.out.println(stringFormat);

stringFormat=String.format("|%-350s|", "Hello World");
System.out.println(stringFormat);
// Concatinatging this using another string : We are what we are then now forever...
//Concatinatging this using another string : 45645.4400000
// Concatinatging this using another strings are : NO-1 ,No-2 and NO-3
//| Hello World|
//|Hello World |

//With Locale
stringFormat=String.format(Locale.CANADA_FRENCH,"|%-350s|", "Hello World");
System.out.println(stringFormat);

System.out.println("=======================equals(), contentEquals()====================");

String stringFirst="Hypothesys";
String stringSecond="hypothesys";
String stringThird="HyPothEsys";

//Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object
//that represents the same sequence of characters as this object.

System.out.println("Hypothesys".equals(stringFirst));
System.out.println(stringSecond.equals(stringFirst));

/* //true
true
true
false
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.endsWith(Unknown Source)
at com.me.strings.StringMethods.main(StringMethods.java:615)*/

//The sequance of characters should be match not references.
b= stringFirst.endsWith("sys");
System.out.println(b);

b= stringFirst.endsWith("");
System.out.println(b);

b= stringFirst.endsWith("Hypothesys");
System.out.println(b);

b= stringFirst.endsWith("Hsys");
System.out.println(b);

//b= stringFirst.endsWith(null);
System.out.println(b);

System.out.println("=======================concat(),compareTo(),contains(),contentEqauls()====================");

//0 to length()-1 only
char
//=stringFirst.charAt(stringFirst.length());
// System.out.println(c);
c=stringFirst.charAt(stringFirst.length()-3);
System.out.println(c);
c=stringFirst.charAt(stringFirst.length()-stringFirst.length());
System.out.println(c);

int a=stringFirst.codePointAt(0);
System.out.println(a);

a=stringFirst.codePointBefore(1);
System.out.println(a);
a=stringFirst.codePointBefore(stringFirst.length());
System.out.println(a);

a=stringFirst.codePointCount(0, 6);
System.out.println(a);

/* public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()*/

int res=stringFirst.compareTo("Hypothesys");
System.out.println(res);

res=stringFirst.compareTo("Hypothe");
System.out.println(res);

res=stringFirst.compareTo("Hypothesys hey");
System.out.println(res);

//if it is empty then it won't return new string
System.out.println(stringFirst.equals(stringFirst));
stringFirst.concat("");
System.out.println(stringFirst);
System.out.println(stringFirst.equals(stringFirst));

//It it is not empty then it returns a new string and won't affect orginal string
String stringTemp=stringFirst.concat("Hey");
System.out.println(stringFirst);
System.out.println(stringTemp);
System.out.println(stringFirst.equals(stringFirst));

b=stringTemp.contains(new StringBuffer("Hey"));
System.out.println(b);

char[] ds={'A','S','D','F','G'};
stringTemp= stringFirst.copyValueOf(ds);
System.out.println(stringTemp);
System.out.println(stringFirst);
stringTemp= stringFirst.copyValueOf(ds,2,3);
System.out.println(stringTemp);

}
}

truefalseaMe101232652653657723326.4550.234576.2223623.00.235.234553023E72515145146546545java.lang.Object@15db9742WORLDRL
=======================trim()====================
This is paragraph and it contains spaces tooo.Plese Ignore

83
This is paragraph and it contains spaces tooo.Plese Ignore

83
This is paragraph and it contains spaces tooo.Plese Ignore
63

0
=======================toUpper() , toLower() , toString() and toCharArray()====================
aa ab ae af ak am an ar as av ay az ba be bg bh bi bm bn bo br bs ca ce ch co cr cs cu cv cy da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu hy hz ia id ie ig ii ik in io is it iu iw ja ji jv ka kg ki kj kk kl km kn ko kr ks ku kv kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mo mr ms mt my na nb nd ne ng nl nn no nr nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi yo za zh zu
Default locale :en_IN
ThIS is ABsuREd ..YoU KnoW!!
this is absured ..you know!!
th?s is absured ..you know!!
THIS IS ABSURED ..YOU KNOW!!
THIS ?S ABSURED ..YOU KNOW!!
ThIS is ABsuREd ..YoU KnoW!!
28==28 lengths are equal if you convert string to char[]
T h I S i s A B s u R E d . . Y o U K n o W ! !
=======================subString() and split()====================
null
physiology
siology

siol
siol
true
true
Then now we are what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
16
--boo--and--foo
--b----:and:f
Thennowweare what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
5
Then now we are what we are ,PatternSyntaxException - if the regular expression's syntax is invalid
17
=======================replace() and regionMatches()====================
We are what we are then now forever...
WE arE what wE arE thEn now forEvEr...
We are what LOL are then now forever...
39
&&&&&We&&&&&are&&&&&what&&&&&we&&&&&are&&&&&then&&&&&now&&&&&forever...
71
39
_ _ _ _ _ _ _ _...
19
39
&&&&&We are what we are then now forever...
43
true
true
false
=======================matches()====================
true
false
true
=======================indexdOf(),lastIndexOf(),isEmpty(),intern() and length()====================
-1
5
8
4
-1
-1
25
25
-1
34
6
34
2
1
-1
16
4
39
false
-93419148
-93419148
=======================hashCode()====================
-93419148
0
0
=======================getBytes() and getChars()====================
R
P
W
e
Y

32
87
101
32
97
114
101
32
119
104
97
116
32
119
101
32
97
114
101
32
116
104
101
110
32
110
111
119
32
102
111
114
101
118
101
114
46
46
46

32
87
101
32
97
114
101
32
119
104
97
116
32
119
101
32
97
114
101
32
116
104
101
110
32
110
111
119
32
102
111
114
101
118
101
114
46
46
46

32
87
101
32
97
114
101
32
119
104
97
116
32
119
101
32
97
114
101
32
116
104
101
110
32
110
111
119
32
102
111
114
101
118
101
114
46
46
46
=======================format()====================
Concatinatging this using another string : We are what we are then now forever...
Concatinatging this using another string : 45645.4400000
Concatinatging this using another strings are : NO-1 ,No-2 and NO-3
| Hello World|
|Hello World |
|Hello World |
=======================equals(), contentEquals()====================
true
false
true
true
true
false
false
=======================concat(),compareTo(),contains(),contentEqauls()====================
s
H
72
72
115
6
0
3
-4
true
Hypothesys
true
Hypothesys
HypothesysHey
true
true
ASDFG
Hypothesys
DFG

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
http://www.theasciicode.com.ar/ascii-printable-characters/space-ascii-code-32.html
https://www.tutorialspoint.com/java/lang/stringbuilder_capacity.htm
https://stackoverflow.com/questions/3184244/stringbuilder-capacity
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/lang/String.java#String.startsWith%28java.lang.String%2Cint%29
https://stackoverflow.com/questions/11063102/using-locales-with-javas-tolowercase-and-touppercase
https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space
https://stackoverflow.com/questions/4724095/check-if-word-contains-substring-in-java-regex

java.lang.String constructors

package com.me.strings;

import java.io.UnsupportedEncodingException;

public class StringConstructors {
public static void main(String[] args) throws UnsupportedEncodingException {

String string=new String();
String string2="Empty";

//empty
//"Empty"
System.out.println(string);
System.out.println(string2);

String stringString=new String(new String("Hey.."));
String stringString2=new String("Hey..");

//Hey..
//Hey...
System.out.println(stringString);
System.out.println(stringString2);

String stringStringBuffer=new String(new StringBuffer("Hey.."));
String stringStringBuilder=new String(new StringBuilder("Hey.."));

//Hey..
//Hey..
System.out.println(stringStringBuffer);
System.out.println(stringStringBuilder);

char[] cs={'L','e','g','a','c','y',' ','i','t'};
String stringCharArray=new String(cs);
String stringCharArray2=new String(cs,2,3);

//legacy it
//gac
System.out.println(stringCharArray);
System.out.println(stringCharArray2);

int[] codepoints=new int[cs.length];
for(int i=0;i<cs.length;i++){
Character temp = cs[i];
int tempint=temp.codePointAt(cs, i);
codepoints[i]=tempint;
}

String stringIntegerrArray=new String(codepoints,2,3);

//gac
System.out.println(stringIntegerrArray);

String stringByte="His name is Cena....";
byte[] bs=stringByte.getBytes();

String charSetName="UTF-16";
String stringByteArray=new String(bs);
String stringByteArray2=new String(bs,"UTF-8");
String stringByteArray3=new String(bs,2,3,"UTF-8");
String stringByteArray4=new String(bs,2,3);
String stringByteArray5=new String(bs,2,3,charSetName);
String stringByteArray6=new String(bs,2,3,charSetName);

//His name is Cena....
//His name is Cena....
//His name is Cena....
//s n
//s n
//s n
//s n
System.out.println(stringByte);
System.out.println(stringByteArray2);
System.out.println(stringByteArray);
System.out.println(stringByteArray3);
System.out.println(stringByteArray4);
System.out.println(stringByteArray5);
System.out.println(stringByteArray6);

}
}

Empty
Hey..
Hey..
Hey..
Hey..
Legacy it
gac
gac
His name is Cena....
His name is Cena....
His name is Cena....
s n
s n
??
??

StringBuffer


package com.me.strings;

public class SBMethods {
public static void main(String[] args) {

String string = "Never\t\t let somebody decide \r your life..123";
StringBuilder stringBuilder = new StringBuilder(string);

String tempString = null;
int tempLength = 0;

// Never let somebody decide your life..123
// start - The beginning index, inclusive.
// end - The ending index, exclusive.

// so 2 is countable and 7 is not so 7-1 6
// ver l
tempString = stringBuilder.substring(2, 7);
System.out.println(tempString);
System.out.println("==================================");

/*
* behaves in exactly the same way as the invocation sb.substring(begin,
* end) This method is provided so that this class can implement the
* CharSequence interface.
*/
// return type is CharSequence so toString has to call.
tempString = stringBuilder.subSequence(2, 7).toString();
System.out.println(tempString);

tempString = stringBuilder.subSequence(7, 15).toString();
System.out.println(tempString);
System.out.println("==================================");

/*
* Returns a new String that contains a subsequence of characters
* currently contained in this character sequence. The substring begins
* at the specified index and extends to the end of this sequence.
*/
// specified index to end of string
tempString = stringBuilder.substring(12);
System.out.println(tempString);
tempString = stringBuilder.substring(2);
System.out.println(tempString);
System.out.println("==================================");

/*
* The character at the specified index is set to ch. The index argument
* must be greater than or equal to 0, and less than the length of this
* sequence.
*/
// NEver let somebody decide your life..123
stringBuilder.setCharAt(1, 'E');
tempString = stringBuilder.toString();
System.out.println(tempString);
// Ncver let somebody decide your life..123
// ==================================
stringBuilder.setCharAt(1, (char) 99);
tempString = stringBuilder.toString();
System.out.println(tempString);
System.out.println("==================================");

/*
* //public void getChars(int srcBegin, int srcEnd, char[] dst, int
* dstBegin) Characters are copied from this sequence into the
* destination character array dst. The first character to be copied is
* at index srcBegin; the last character to be copied is at index
* srcEnd-1. The total number of characters to be copied is
* srcEnd-srcBegin. The characters are copied into the subarray of dst
* starting at index dstBegin and ending at index: dstbegin +
* (srcEnd-srcBegin) - 1
*
* Parameters: srcBegin - start copying at this offset. srcEnd - stop
* copying at this offset. dst - the array to copy the data into.
* dstBegin - offset into dst. Throws: NullPointerException - if dst is
* null. IndexOutOfBoundsException - if any of the following is true:
* srcBegin is negative dstBegin is negative the srcBegin argument is
* greater than the srcEnd argument. srcEnd is greater than
* this.length(). dstBegin+srcEnd-srcBegin is greater than dst.length
*/

char[] dest = new char[string.length()];
stringBuilder.getChars(2, 12, dest, 2);
for (int i = 0; i < dest.length; i++) {
System.out.print(dest[i]);
}
System.out.println();
System.out.println(stringBuilder);

char[] dest2 = { '2', '3', '7', '8', '4', '4', '3', '3', '9', '0' };
stringBuilder.getChars(2, 7, dest2, 5);
for (int i = 0; i 44 so null values would be added
/*
* ================================== 44 Ncver let somebody decide your
* life..123 44 Ncver let somebody decide your life..123 95 Ncver let
* somebody decide your life..123
*/
stringBuilder.setLength(95);
System.out.println(stringBuilder.length());
System.out.println(stringBuilder);
System.out.println("==================================");

// public void trimToSize()
// Attempts to reduce storage used for the character sequence. If the
// buffer is larger than necessary to hold its current sequence of
// characters, then it may be resized to become more space efficient.
// Calling this method may, but is not required to, affect the value
// returned by a subsequent call to the capacity() method.
System.out.println(stringBuilder.length());
System.out.println(stringBuilder);
System.out.println(stringBuilder.capacity());
stringBuilder.trimToSize();
System.out.println(stringBuilder.length());
System.out.println(stringBuilder);
System.out.println(stringBuilder.capacity());
System.out.println("==================================");

// The number of character sequance spaces that it can hold
System.out.println(stringBuilder);
System.out.println(stringBuilder.capacity());
System.out.println("==================================");

// The number of character sequance spaces that it can hold
/*
* Ncver let somebody decide your life..123
*/
System.out.println(stringBuilder);
/*
* ensureCapacity public void ensureCapacity(int minimumCapacity)
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new
* internal array is allocated with greater capacity. The new capacity
* is the larger of: The minimumCapacity argument. Twice the old
* capacity, plus 2. If the minimumCapacity argument is nonpositive,
* this method takes no action and simply returns. Parameters:
* minimumCapacity - the minimum desired capacity.
*/
stringBuilder.ensureCapacity(132);
System.out.println(stringBuilder.capacity());
System.out.println("==================================");

System.out.println(stringBuilder.length());
System.out.println("==================================");

System.out.println(stringBuilder.toString());
System.out.println("==================================");

/*
* public StringBuilder reverse() Causes this character sequence to be
* replaced by the reverse of the sequence. If there are any surrogate
* pairs included in the sequence, these are treated as single
* characters for the reverse operation. Thus, the order of the high-low
* surrogates is never reversed. Let n be the character length of this
* character sequence (not the length in char values) just prior to
* execution of the reverse method. Then the character at index k in the
* new character sequence is equal to the character at index n-k-1 in
* the old character sequence. Note that the reverse operation may
* result in producing surrogate pairs that were unpaired low-surrogates
* and high-surrogates before the operation. For example, reversing
* "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate
* pair.
*
* Returns:
*
* for(int i=0;i<cs.length;i++){ cs2[i]= cs[cs.length-1-i]; }
*
*
* a reference to this object.
*/
System.out.println(stringBuilder.reverse());
System.out.println("==================================");

System.out.println(stringBuilder.reverse());
// 16
System.out.println(stringBuilder.indexOf("body"));

System.out.println(stringBuilder.indexOf("body", 17));
// Ncver let somebody decide
// your life..123
// -1 bcz the string "body" not found after 17th index

System.out.println(stringBuilder.indexOf("e", 17));
// 22 first occuranc after 17th
System.out.println("==================================");

/*
* public int lastIndexOf(String str) Returns the index within this
* string of the rightmost occurrence of the specified substring. The
* rightmost empty string "" is considered to occur at the index value
* this.length(). The returned index is the largest value k such that
* this.toString().startsWith(str, k)
*/

// searches from Right most to LeftMost
System.out.println(stringBuilder.lastIndexOf("body"));
// 17 16 ......
System.out.println(stringBuilder.lastIndexOf("e", 17));
// 6 5 4 3............
System.out.println(stringBuilder.lastIndexOf("e", 6));
System.out.println("==================================");

/*
* public StringBuilder insert(int index, char[] str, int offset, int
* len) Inserts the string representation of a subarray of the str array
* argument into this sequence. The subarray begins at the specified
* offset and extends len chars. The characters of the subarray are
* inserted into this sequence at the position indicated by index. The
* length of this sequence increases by len chars. Parameters: index -
* position at which to insert subarray. str - A char array. offset -
* the index of the first char in subarray to be inserted. len - the
* number of chars in the subarray to be inserted.
*/

// starts from 5th position and inserts data
// the last to is for subarray elemts caluculation
char[] dest3 = { '2', '3', '7', '8', '4', '4', '3', '3', '9', '0' };
stringBuilder.insert(5, dest3, 1, 3);
System.out.println(stringBuilder);

//
stringBuilder.insert(5, dest3, 1, 9);
System.out.println(stringBuilder);

/*
* Ncver378 let somebody decide your life..123
*/
System.out.println("==================================");

/*
* public StringBuilder insert(int offset, Object obj) Inserts the
* string representation of the Object argument into this character
* sequence. The overall effect is exactly as if the second argument
* were converted to a string by the method String.valueOf(Object), and
* the characters of that string were then inserted into this character
* sequence at the indicated offset.
*
* The offset argument must be greater than or equal to 0, and less than
* or equal to the length of this sequence.
*/

Person person=new Person(123, "Messi");
stringBuilder.insert(5, person);
System.out.println(stringBuilder);
System.out.println("==================================");

String string2=new String( "Messi");
stringBuilder.insert(5, string2);
System.out.println(stringBuilder);
System.out.println("==================================");

/*
* All values converted to String.valueOf(......) internally.
*
insert(int offset, boolean b)
Inserts the string representation of the boolean argument into this sequence.
StringBuilder insert(int offset, char c)
Inserts the string representation of the char argument into this sequence.
StringBuilder insert(int offset, char[] str)
Inserts the string representation of the char array argument into this sequence.
StringBuilder insert(int index, char[] str, int offset, int len)
Inserts the string representation of a subarray of the str array argument into this sequence.
StringBuilder insert(int dstOffset, CharSequence s)
Inserts the specified CharSequence into this sequence.
StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
Inserts a subsequence of the specified CharSequence into this sequence.
StringBuilder insert(int offset, double d)
Inserts the string representation of the double argument into this sequence.
StringBuilder insert(int offset, float f)
Inserts the string representation of the float argument into this sequence.
StringBuilder insert(int offset, int i)
Inserts the string representation of the second int argument into this sequence.
StringBuilder insert(int offset, long l)
Inserts the string representation of the long argument into this sequence.
StringBuilder insert(int offset, Object obj)
Inserts the string representation of the Object argument into this character sequence.
StringBuilder insert(int offset, String str)
Inserts the string into this character sequence.*/

/* StringBuilder append(boolean b)
Appends the string representation of the boolean argument to the sequence.
StringBuilder append(char c)
Appends the string representation of the char argument to this sequence.
StringBuilder append(char[] str)
Appends the string representation of the char array argument to this sequence.
StringBuilder append(char[] str, int offset, int len)
Appends the string representation of a subarray of the char array argument to this sequence.
StringBuilder append(CharSequence s)
Appends the specified character sequence to this Appendable.
StringBuilder append(CharSequence s, int start, int end)
Appends a subsequence of the specified CharSequence to this sequence.
StringBuilder append(double d)
Appends the string representation of the double argument to this sequence.
StringBuilder append(float f)
Appends the string representation of the float argument to this sequence.
StringBuilder append(int i)
Appends the string representation of the int argument to this sequence.
StringBuilder append(long lng)
Appends the string representation of the long argument to this sequence.
StringBuilder append(Object obj)
Appends the string representation of the Object argument.
StringBuilder append(String str)
Appends the specified string to this character sequence.
StringBuilder append(StringBuffer sb)
Appends the specified StringBuffer to this sequence.
StringBuilder appendCodePoint(int codePoint)
Appends the string representation of the codePoint argument to this sequence.*/

}
}

class Person{
int no;
String name;
@Override
public String toString() {
return "Person [no=" + no + ", name=" + name + "]";
}
public Person(int no, String name) {
super();
this.no = no;
this.name = name;
}
}

ver
==================================
ver
let som
==================================
somebody decide
your life..123
ver let somebody decide
your life..123
==================================
NEver let somebody decide
your life..123
Ncver let somebody decide
your life..123
==================================


package com.me.strings;

public class ReverseFunction {
public static void main(String[] args) {
String string="My name is khan";
char[] cs=new char[string.length()];
char[] cs2=new char[string.length()];

for(int i=0;i<string.length();i++){
cs[i]=string.charAt(i);
}

for(int i=0;i<cs.length;i++){
System.out.print(cs[i]);
}

System.out.println( );

for(int i=0;i<cs.length;i++){
cs2[i]= cs[cs.length-1-i];
}

for(int i=0;i<cs2.length;i++){
System.out.print(cs2[i]);
}

System.out.println( );

StringBuilder stringBuilder=new StringBuilder(string);
System.out.println(stringBuilder.toString());
System.out.println(stringBuilder.reverse().toString());
}
}


package com.me.strings;

public class BuilderAppend {
public static void main(String[] args) {
StringBuilder stringBuilder=new StringBuilder("hey here we go there");

//hey here we go there2323323
//stringBuilder.append(new StringBuilder("2323323"));
System.out.println(stringBuilder);

String string="2324456gdfg4564366";
char[] cs=new char[string.length()];

for(int i=0;i<string.length();i++){
cs[i]=string.charAt(i);
}

for(int i=0;i<cs.length;i++){
//System.out.print(cs[i]);
}

stringBuilder.append(cs,3,13);
System.out.println(stringBuilder);

}
}


package com.me.strings;

public class StringBuilderDemo {
public static void main(String[] args) {

/*
* length() - the length of the character sequence in the builder since
* this stringbuilder doesn't contain any content, its length will be 0.
*
* capacity() - the number of character spaces that have been allocated.
* When you try to construct a stringbuilder with empty content, by
* default it takes the initialize size as length+16 which is 0+16. so
* capacity would return 16 here.
*
* Note: The capacity, which is returned by the capacity() method, is
* always greater than or equal to the length (usually greater than) and
* will automatically expand as necessary to accommodate additions to
* the string builder.
*
* The logic behind the capacity function:
*
* If you don't initialize stringbuilder with any content, default
* capacity will be taken as 16 characters capacity. If you initialize
* stringbuilder with any content, then capacity will be content
* length+16. When you add new content to stringbuilder object, if
* current capacity is not sufficient to take new value, then it will
* grow by (previous array capacity+1)*2. This analysis is take from
* actual StringBuilder.java code
*/

CharSequence sequence = new StringBuilder();
System.out.println(sequence.length());

StringBuilder stringBuilder = new StringBuilder("me");
System.out.println(stringBuilder.length());
System.out.println(stringBuilder.capacity());
// length =2 i.e no of characters
// capacity = default i. 16+2 =18

stringBuilder.append(true);
// added true i.e it will take as "true"so stringBuilder becomes
// "metrue"
// 2+ 4 =6
System.out.println(stringBuilder.length());
// 18 bcz we are not passing through constructor
// 6< 18 keep 18 as it is . ile length 16
//so length would become ""+characters count i.e characters count
//capacity would become 16+no of characters
StringBuilder stringBuilder2 = new StringBuilder("Be good AND DO GOOD ,EVERYTHING COMES BACK TO YOU");
System.out.println(stringBuilder2.length());
System.out.println(stringBuilder2.capacity());
System.out.println(stringBuilder2);

//Here I have given capacity as 5
StringBuilder stringBuilder3 = new StringBuilder(5);
//0 as no characters
System.out.println(stringBuilder3.length());
//5
System.out.println(stringBuilder3.capacity());
//empty
System.out.println(stringBuilder3);

//now adding "my name is khan"
stringBuilder3.append(string);
// 0+ "my name is khan" length i.e 0+15 =15
System.out.println(stringBuilder3.length());
//capacity shoudn't compare with 5 it should be compared with 16 i.e default only.
//as we mentioned intial capacity the capacity becomes length i.e 15
// now 15 16 i.e
// current array size is before insert 15
// so 15+1 * 2 =32
//so capacity is 32
System.out.println(stringBuilder3.capacity());
System.out.println(stringBuilder3);

StringBuilder stringBuilder4=new StringBuilder();
stringBuilder4.append("something");
System.out.println(stringBuilder4.length());
System.out.println(stringBuilder4);

stringBuilder4.setLength(3);
System.out.println(stringBuilder4.length());
System.out.println(stringBuilder4);

StringBuilder stringBuilder5=new StringBuilder();
stringBuilder5.append("something");
System.out.println(stringBuilder5.length());
System.out.println(stringBuilder5);

stringBuilder5.setLength(20);
System.out.println(stringBuilder5.length());
System.out.println(stringBuilder5);

System.out.println("===============");

//ensureCapacity
StringBuilder stringBuilder6=new StringBuilder();
stringBuilder6.append("something");
System.out.println(stringBuilder6.length());
System.out.println(stringBuilder6.capacity());

stringBuilder6.ensureCapacity(30);
System.out.println(stringBuilder6.capacity());

StringBuilder stringBuilder7=new StringBuilder();
stringBuilder7.append("something");
System.out.println(stringBuilder7.length());
System.out.println(stringBuilder7.capacity());

stringBuilder7.ensureCapacity(6);
System.out.println(stringBuilder7.capacity());
System.out.println(stringBuilder7.length());

System.out.println("---");

StringBuilder stringBuilder8=new StringBuilder();
stringBuilder8.append("something");
System.out.println(stringBuilder8.length());
System.out.println(stringBuilder8.capacity());

stringBuilder8.ensureCapacity(-609);
System.out.println(stringBuilder8.capacity());
System.out.println(stringBuilder8.length());

StringBuilder stringBuilder9=new StringBuilder(string);
System.out.println(stringBuilder9.toString());
stringBuilder9.delete(2, 6);
System.out.println(stringBuilder9.toString());

System.out.println(stringBuilder9.toString());
System.out.println(stringBuilder9.length());
stringBuilder9.deleteCharAt(5);
System.out.println(stringBuilder9.toString());
System.out.println(stringBuilder9.length());

/*
stringBuilder9.replace(15, 7, "235");
System.out.println(stringBuilder9.toString());
System.out.println(stringBuilder9.length());
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start > length()
at java.lang.AbstractStringBuilder.replace(Unknown Source)
at java.lang.StringBuilder.replace(Unknown Source)
at com.me.strings.StringBuilderDemo.main(StringBuilderDemo.java:178)*/

stringBuilder9.replace(5, 7, "23");
System.out.println(stringBuilder9.toString());
System.out.println(stringBuilder9.length());

StringBuilder stringBuilder10=new StringBuilder("sample");
stringBuilder10.replace(1, 3, "23");
System.out.println(stringBuilder10.toString());
System.out.println(stringBuilder10.length());

stringBuilder10.replace(1, 3, "55555");
System.out.println(stringBuilder10.toString());
System.out.println(stringBuilder10.length());

}
}

References:
https://docs.oracle.com/javase/tutorial/java/data/buffers.html
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.delete%28int%2Cint%29
https://stackoverflow.com/questions/3184244/stringbuilder-capacity
https://www.tutorialspoint.com/java/lang/stringbuilder_capacity.htm
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(boolean)
https://javabeat.net/ocajp/
https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-808
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(boolean)