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

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

Order by , Group by in Java

This is one of the rare requirement like if you want sort some data and you wants to segregate the data by grouping some factor.

Here players are sorted by rank,remunation  and we are grouping them by gametype .

 
package com.java8.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

public class Collectors_reducing {
public static void main(String[] args) {
PersonPojo personPojo = new PersonPojo(1, "MESSI", 250f, "Football");
PersonPojo personPojo3 = new PersonPojo(3, "Ronaldhino", 150f, "Football");
PersonPojo personPojo2 = new PersonPojo(2, "Inesta", 100f, "Football");

PersonPojo personPojo4 = new PersonPojo(5, "Nadal", 140f, "Tennis");
PersonPojo personPojo5 = new PersonPojo(7, "Ivanovic", 55f, "Tennis");
PersonPojo personPojo6 = new PersonPojo(4, "Federer", 170f, "Tennis");

System.out.println("-------------Order By Rank, Group by GAMENAME-----------------------");

ArrayList arrayList = new ArrayList(
Arrays.asList(personPojo, personPojo2, personPojo3, personPojo4, personPojo6, personPojo5));
Comparator comparator = Comparator.comparing(PersonPojo::getPlayerRank);
Map<String, Optional> map = arrayList.stream().collect(
Collectors.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator))));
map.forEach((k,
v) -> System.out.println("---" + k + "----" + ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ +((Optional) v).get().getPlayerRemunation() + "---"
+ ((Optional) v).get().getGameName()));

System.out.println("---------------------------Order BY remunation, Group by GameName------------------");
Comparator comparator2 = Comparator.comparing(PersonPojo::getPlayerRemunation);
Map<String, Optional> map2 = arrayList.stream().collect(Collectors
.groupingBy(PersonPojo::getGameName, Collectors.reducing(BinaryOperator.minBy(comparator2))));

map2.forEach((k,
v) -> System.out.println("---" + k + "---" + ((Optional) v).get().getGameName() + "---"
+ ((Optional) v).get().getPlayerName() + "---"
+ ((Optional) v).get().getPlayerRank() + "---"
+ ((Optional) v).get().getPlayerRemunation()));

}
}

class PersonPojo {
private int playerRank;
private String playerName;
private float playerRemunation;
private String gameName;

public String getGameName() {
return gameName;
}

public void setGameName(String gameName) {
this.gameName = gameName;
}

public int getPlayerRank() {
return playerRank;
}

public void setPlayerRank(int playerRank) {
this.playerRank = playerRank;
}

public String getPlayerName() {
return playerName;
}

public void setPlayerName(String playerName) {
this.playerName = playerName;
}

public float getPlayerRemunation() {
return playerRemunation;
}

public void setPlayerRemunation(float playerRemunation) {
this.playerRemunation = playerRemunation;
}

public PersonPojo(int playerRank, String playerName, float playerRemunation, String gameName) {
this.playerRank = playerRank;
this.playerName = playerName;
this.playerRemunation = playerRemunation;
this.gameName = gameName;
}

@Override
public String toString() {
return "PersonPojo [playerRank=" + playerRank + ", playerName=" + playerName + ", playerRemunation="
+ playerRemunation + ", gameName=" + gameName + "]";
}

}

output:

————-Order By Rank, Group by GAMENAME———————–
—Tennis—-Federer—4—170.0—Tennis
—Football—-MESSI—1—250.0—Football
—————————Order BY remunation, Group by GameName——————
—Tennis—Tennis—Ivanovic—7—55.0
—Football—Football—Inesta—2—100.0
Picked up _JAVA_OPTIONS: -Xmx512M

sort by id , name -custom sorting

Student.java:

package com.me.pack;

import java.util.Comparator;

@SuppressWarnings(“rawtypes”)
public class Student implements Comparable {
private int id;
private String name;
private float sal;

public static final Comparator idComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.id – o2.id;
}
};

public static final Comparator nameComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.name.compareTo(o2.name);
}
};

public static final Comparator salComparator = new Comparator() {

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return (int) (o1.sal – o2.sal);
}
};

public static final Comparator comp=
(Student s1, Student s2) -> s1.getName().compareTo(s2.getName());

@Override
public int compareTo(Student arg0) {
// TODO Auto-generated method stub
return this.id – arg0.id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public float getSal() {
return sal;
}

public void setSal(float sal) {
this.sal = sal;
}

public Student(int id, String name, float sal) {
super();
this.id = id;
this.name = name;
this.sal = sal;
}

@Override
public String toString() {
return “Student [id=” + id + “, name=” + name + “, sal=” + sal + “]”;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(sal);
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Float.floatToIntBits(sal) != Float.floatToIntBits(other.sal))
return false;
return true;
}

}

 

Test.java:

package com.me.pack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorStudentLamda {
public static void main(String[] args) {
Student student = new Student(125, “bcv”, 546.09f);
Student student2 = new Student(123, “mno”, 123.09f);
Student student3 = new Student(130, “fgh”, 74357.09f);

List list = new ArrayList(Arrays.asList(student, student2, student3));
for (Student studenttemp : list) {
System.out.println(studenttemp);
}
System.out.println(“—————–“);
Collections.sort(list, Student.idComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.nameComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.salComparator);
for (Student studentR : list) {
System.out.println(studentR);
}
System.out.println(“—————–“);
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}
}
}

 

 

Invoke from java8:
Collections.sort(list, Student.comp);
for (Student studentR : list) {
System.out.println(studentR);
}

 

output:

Student [id=125, name=bcv, sal=546.09]
Student [id=123, name=mno, sal=123.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
—————–
Student [id=123, name=mno, sal=123.09]
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
—————–
Student [id=125, name=bcv, sal=546.09]
Student [id=130, name=fgh, sal=74357.09]
Student [id=123, name=mno, sal=123.09]
Picked up _JAVA_OPTIONS: -Xmx512M

refer : http://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-examplehttp://www.concretepage.com/java/jdk-8/lambda-expressions-java-8-
example

http://javarevisited.blogspot.in/2014/01/java-comparator-example-for-custom.html

Hidden features of JAVA-7

Here are some stuff  that I came across so far.

 1.NumberFormatException
int value = 123_8934758;
System.out.println(value);

2.String as argument in Switch condition.

String key1 = "HYD", key2 = "BLR";

Scanner scanner = new Scanner(new InputStreamReader(System.in));
String input = scanner.nextLine();

switch (input) {
case key1:
System.out.println("HYD HERE");
break;
case key1:
System.out.println("BLR HERE");
break;

default:
System.out.println("DEFAULT HERE");
break;
}

3. Diamond operator
When we doesn’t place both sides then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we doesn’t place at left side then no issues and it accepts specified any
type of object like Integer,String,Object etc because by default it will take
Object as generic type.

When we place both sides then no issues and it accepts only specified Generic type.

When we place at left side then issues and it accepts only specified any type.

List list = new ArrayList();
List list2 = new ArrayList();
List list3 = new ArrayList();
List list4 = new ArrayList();

List list5 = new ArrayList();
List list6 = new ArrayList();

list5.add(new Long(123));
list5.add(new Integer(548));

list.add("ABC");
list.add(new Object());
list.add(new String("Hey"));
list.add(new Integer(125));

list2.add(new Object());
list2.add(new String("Hey"));
list2.add(new Integer(125));

list3.add(new Object());
list3.add(new String("Hey"));
list3.add(new Integer(125));

list4.add(new Object());
list4.add(new String("Hey"));
list4.add(new Integer(125));

4. Parallel catching of Exceptions:

When all are placed in different exception hierarchies then we can place as this.
NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex

If they fall under same hierarchy then use the base Exception. The below will gives you the CE.

catch (NullPointerException | IOException | ArithmeticException | FileNotFoundException ex) {
ex.printStackTrace();
}

If you are using Checked Exception then it should be thrown.
IOException etc.

try {
File file = new File("C://Demos//me.txt");
FileInputStream fileInputStream = new FileInputStream(file);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
while (bufferedReader.readLine() != null) {
System.out.println(new SimpleDateFormat("DD/MM/YYYY"));
}
throw new ArithmeticException();
} catch (NullPointerException | IOException | ArithmeticException | IndexOutOfBoundsException ex) {
ex.printStackTrace();
}

5. Try with resource
Internally it uses implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println(“hey java-7 closable”);
}

try (BufferedReader bufferedReader = new BufferedReader(
new FileReader("C:\\Users\\n0290635\\Desktop\\het.txt"))) {
while (bufferedReader.readLine() != null) {
System.out.println(bufferedReader.readLine());
}
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}

try (CustomClass customClass = new CustomClass()) {
customClass.methodNene(123);
} catch (Exception exception) {
exception.printStackTrace();
}

class CustomClass implements AutoCloseable {

@Override
public void close() throws Exception {
// TODO Auto-generated method stub
System.out.println("hey java-7 closable");
}

public void methodNene(int a) {
System.out.println("result:" + a * a * 120);
}

}

6. Rethrow error -Throwing the exception in catch block too.
private static void rethrowErrorJAVA7() throws IOException, Exception {

try {
new SimpleDateFormat("yyyyMMdd").parse("foo");
new FileReader("file.txt").read();
} catch (ArithmeticException arithmeticException) {

} catch (Exception exception) {
throw exception;
}
}

StringBuffer capacity vs ensureCapacity and trimtoSize()

package com.me.practice;

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

//By default it’s 0
StringBuffer stringBuffer=new StringBuffer();

//By default it’s 16
System.out.println(stringBuffer.capacity());

//Now appending “xxxx”
stringBuffer.append(“madhu”);

//Capacity won’t change if length < default capacity
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if length > default capacity
stringBuffer.append(“madhugggggggggggggggggggggggg”);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity won’t change if ensureCapacity < current capacity
stringBuffer.ensureCapacity(23);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will change if ensureCapacity > current capacity
stringBuffer.ensureCapacity(123);
System.out.println(stringBuffer.capacity());
System.out.println(stringBuffer.length());

//Capacity will reduce to actual size
stringBuffer.trimToSize();
System.out.println(stringBuffer.capacity());

}
}

 

16
16
5
34
34
34
34
123
34
34