Arraylist with iterator

Iterator with ArrayList:
========================

alist.iterator();
while iteration add/remove will gives exception i.e concurrentmodificationException
update wont give any exception.
package com.me.collections;

import java.util.ArrayList;
public class ExceptionDemo {
public static void main(String args[]){
ArrayList books = new ArrayList();
books.add(“C”);
books.add(“Java”);
books.add(“Cobol”);

for(String obj : books) {
System.out.println(obj);
//We are adding element while iterating list
// books.add(“C++”);
// //Exception in thread “main” java.util.ConcurrentModificationException
// at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
// at java.util.ArrayList$Itr.next(Unknown Source)
// at com.me.collections.ExceptionDemo.main(ExceptionDemo.java:11)
// C

books.set(2, “fdsngfds”);

//error
// books.add(“C++”);
//error
// books.remove(“Java”);
}
}
}

Use CopyOnWriteArrayList
and if you want to remove it, do the following:

for (Iterator it = userList.iterator(); it.hasNext() 😉
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}

Advertisements

&& 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


#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
??
??