Tuesday, 29 December 2015

TimeZone Ids In Java and Date Serialization with TimeZone using Jackson




1. There are total of 617 number  of  supported time zone IDs  available in the JDK version 1.8  and following is the list of all the IDs obtained from the java.util.TimeZone  :
--------------------
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
Africa/Blantyre
Africa/Brazzaville
Africa/Bujumbura
Africa/Cairo
Africa/Casablanca
Africa/Ceuta
Africa/Conakry
Africa/Dakar
Africa/Dar_es_Salaam
Africa/Djibouti
Africa/Douala
Africa/El_Aaiun
Africa/Freetown
Africa/Gaborone
Africa/Harare
Africa/Johannesburg
Africa/Juba
Africa/Kampala
Africa/Khartoum
Africa/Kigali
Africa/Kinshasa
Africa/Lagos
Africa/Libreville
Africa/Lome
Africa/Luanda
Africa/Lubumbashi
Africa/Lusaka
Africa/Malabo
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Mogadishu
Africa/Monrovia
Africa/Nairobi
Africa/Ndjamena
Africa/Niamey
Africa/Nouakchott
Africa/Ouagadougou
Africa/Porto-Novo
Africa/Sao_Tome
Africa/Timbuktu
Africa/Tripoli
Africa/Tunis
Africa/Windhoek
America/Adak
America/Anchorage
America/Anguilla
America/Antigua
America/Araguaina
America/Argentina/Buenos_Aires
America/Argentina/Catamarca
America/Argentina/ComodRivadavia
America/Argentina/Cordoba
America/Argentina/Jujuy
America/Argentina/La_Rioja
America/Argentina/Mendoza
America/Argentina/Rio_Gallegos
America/Argentina/Salta
America/Argentina/San_Juan
America/Argentina/San_Luis
America/Argentina/Tucuman
America/Argentina/Ushuaia
America/Aruba
America/Asuncion
America/Atikokan
America/Atka
America/Bahia
America/Bahia_Banderas
America/Barbados
America/Belem
America/Belize
America/Blanc-Sablon
America/Boa_Vista
America/Bogota
America/Boise
America/Buenos_Aires
America/Cambridge_Bay
America/Campo_Grande
America/Cancun
America/Caracas
America/Catamarca
America/Cayenne
America/Cayman
America/Chicago
America/Chihuahua
America/Coral_Harbour
America/Cordoba
America/Costa_Rica
America/Creston
America/Cuiaba
America/Curacao
America/Danmarkshavn
America/Dawson
America/Dawson_Creek
America/Denver
America/Detroit
America/Dominica
America/Edmonton
America/Eirunepe
America/El_Salvador
America/Ensenada
America/Fort_Wayne
America/Fortaleza
America/Glace_Bay
America/Godthab
America/Goose_Bay
America/Grand_Turk
America/Grenada
America/Guadeloupe
America/Guatemala
America/Guayaquil
America/Guyana
America/Halifax
America/Havana
America/Hermosillo
America/Indiana/Indianapolis
America/Indiana/Knox
America/Indiana/Marengo
America/Indiana/Petersburg
America/Indiana/Tell_City
America/Indiana/Vevay
America/Indiana/Vincennes
America/Indiana/Winamac
America/Indianapolis
America/Inuvik
America/Iqaluit
America/Jamaica
America/Jujuy
America/Juneau
America/Kentucky/Louisville
America/Kentucky/Monticello
America/Knox_IN
America/Kralendijk
America/La_Paz
America/Lima
America/Los_Angeles
America/Louisville
America/Lower_Princes
America/Maceio
America/Managua
America/Manaus
America/Marigot
America/Martinique
America/Matamoros
America/Mazatlan
America/Mendoza
America/Menominee
America/Merida
America/Metlakatla
America/Mexico_City
America/Miquelon
America/Moncton
America/Monterrey
America/Montevideo
America/Montreal
America/Montserrat
America/Nassau
America/New_York
America/Nipigon
America/Nome
America/Noronha
America/North_Dakota/Beulah
America/North_Dakota/Center
America/North_Dakota/New_Salem
America/Ojinaga
America/Panama
America/Pangnirtung
America/Paramaribo
America/Phoenix
America/Port-au-Prince
America/Port_of_Spain
America/Porto_Acre
America/Porto_Velho
America/Puerto_Rico
America/Rainy_River
America/Rankin_Inlet
America/Recife
America/Regina
America/Resolute
America/Rio_Branco
America/Rosario
America/Santa_Isabel
America/Santarem
America/Santiago
America/Santo_Domingo
America/Sao_Paulo
America/Scoresbysund
America/Shiprock
America/Sitka
America/St_Barthelemy
America/St_Johns
America/St_Kitts
America/St_Lucia
America/St_Thomas
America/St_Vincent
America/Swift_Current
America/Tegucigalpa
America/Thule
America/Thunder_Bay
America/Tijuana
America/Toronto
America/Tortola
America/Vancouver
America/Virgin
America/Whitehorse
America/Winnipeg
America/Yakutat
America/Yellowknife
Antarctica/Casey
Antarctica/Davis
Antarctica/DumontDUrville
Antarctica/Macquarie
Antarctica/Mawson
Antarctica/McMurdo
Antarctica/Palmer
Antarctica/Rothera
Antarctica/South_Pole
Antarctica/Syowa
Antarctica/Troll
Antarctica/Vostok
Arctic/Longyearbyen
Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau
Asia/Aqtobe
Asia/Ashgabat
Asia/Ashkhabad
Asia/Baghdad
Asia/Bahrain
Asia/Baku
Asia/Bangkok
Asia/Beirut
Asia/Bishkek
Asia/Brunei
Asia/Calcutta
Asia/Chita
Asia/Choibalsan
Asia/Chongqing
Asia/Chungking
Asia/Colombo
Asia/Dacca
Asia/Damascus
Asia/Dhaka
Asia/Dili
Asia/Dubai
Asia/Dushanbe
Asia/Gaza
Asia/Harbin
Asia/Hebron
Asia/Ho_Chi_Minh
Asia/Hong_Kong
Asia/Hovd
Asia/Irkutsk
Asia/Istanbul
Asia/Jakarta
Asia/Jayapura
Asia/Jerusalem
Asia/Kabul
Asia/Kamchatka
Asia/Karachi
Asia/Kashgar
Asia/Kathmandu
Asia/Katmandu
Asia/Khandyga
Asia/Kolkata
Asia/Krasnoyarsk
Asia/Kuala_Lumpur
Asia/Kuching
Asia/Kuwait
Asia/Macao
Asia/Macau
Asia/Magadan
Asia/Makassar
Asia/Manila
Asia/Muscat
Asia/Nicosia
Asia/Novokuznetsk
Asia/Novosibirsk
Asia/Omsk
Asia/Oral
Asia/Phnom_Penh
Asia/Pontianak
Asia/Pyongyang
Asia/Qatar
Asia/Qyzylorda
Asia/Rangoon
Asia/Riyadh
Asia/Saigon
Asia/Sakhalin
Asia/Samarkand
Asia/Seoul
Asia/Shanghai
Asia/Singapore
Asia/Srednekolymsk
Asia/Taipei
Asia/Tashkent
Asia/Tbilisi
Asia/Tehran
Asia/Tel_Aviv
Asia/Thimbu
Asia/Thimphu
Asia/Tokyo
Asia/Ujung_Pandang
Asia/Ulaanbaatar
Asia/Ulan_Bator
Asia/Urumqi
Asia/Ust-Nera
Asia/Vientiane
Asia/Vladivostok
Asia/Yakutsk
Asia/Yekaterinburg
Asia/Yerevan
Atlantic/Azores
Atlantic/Bermuda
Atlantic/Canary
Atlantic/Cape_Verde
Atlantic/Faeroe
Atlantic/Faroe
Atlantic/Jan_Mayen
Atlantic/Madeira
Atlantic/Reykjavik
Atlantic/South_Georgia
Atlantic/St_Helena
Atlantic/Stanley
Australia/ACT
Australia/Adelaide
Australia/Brisbane
Australia/Broken_Hill
Australia/Canberra
Australia/Currie
Australia/Darwin
Australia/Eucla
Australia/Hobart
Australia/LHI
Australia/Lindeman
Australia/Lord_Howe
Australia/Melbourne
Australia/NSW
Australia/North
Australia/Perth
Australia/Queensland
Australia/South
Australia/Sydney
Australia/Tasmania
Australia/Victoria
Australia/West
Australia/Yancowinna
Brazil/Acre
Brazil/DeNoronha
Brazil/East
Brazil/West
CET
CST6CDT
Canada/Atlantic
Canada/Central
Canada/East-Saskatchewan
Canada/Eastern
Canada/Mountain
Canada/Newfoundland
Canada/Pacific
Canada/Saskatchewan
Canada/Yukon
Chile/Continental
Chile/EasterIsland
Cuba
EET
EST5EDT
Egypt
Eire
Etc/GMT
Etc/GMT+0
Etc/GMT+1
Etc/GMT+10
Etc/GMT+11
Etc/GMT+12
Etc/GMT+2
Etc/GMT+3
Etc/GMT+4
Etc/GMT+5
Etc/GMT+6
Etc/GMT+7
Etc/GMT+8
Etc/GMT+9
Etc/GMT-0
Etc/GMT-1
Etc/GMT-10
Etc/GMT-11
Etc/GMT-12
Etc/GMT-13
Etc/GMT-14
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
Etc/GMT-8
Etc/GMT-9
Etc/GMT0
Etc/Greenwich
Etc/UCT
Etc/UTC
Etc/Universal
Etc/Zulu
Europe/Amsterdam
Europe/Andorra
Europe/Athens
Europe/Belfast
Europe/Belgrade
Europe/Berlin
Europe/Bratislava
Europe/Brussels
Europe/Bucharest
Europe/Budapest
Europe/Busingen
Europe/Chisinau
Europe/Copenhagen
Europe/Dublin
Europe/Gibraltar
Europe/Guernsey
Europe/Helsinki
Europe/Isle_of_Man
Europe/Istanbul
Europe/Jersey
Europe/Kaliningrad
Europe/Kiev
Europe/Lisbon
Europe/Ljubljana
Europe/London
Europe/Luxembourg
Europe/Madrid
Europe/Malta
Europe/Mariehamn
Europe/Minsk
Europe/Monaco
Europe/Moscow
Europe/Nicosia
Europe/Oslo
Europe/Paris
Europe/Podgorica
Europe/Prague
Europe/Riga
Europe/Rome
Europe/Samara
Europe/San_Marino
Europe/Sarajevo
Europe/Simferopol
Europe/Skopje
Europe/Sofia
Europe/Stockholm
Europe/Tallinn
Europe/Tirane
Europe/Tiraspol
Europe/Uzhgorod
Europe/Vaduz
Europe/Vatican
Europe/Vienna
Europe/Vilnius
Europe/Volgograd
Europe/Warsaw
Europe/Zagreb
Europe/Zaporozhye
Europe/Zurich
GB
GB-Eire
GMT
GMT0
Greenwich
Hongkong
Iceland
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
Indian/Cocos
Indian/Comoro
Indian/Kerguelen
Indian/Mahe
Indian/Maldives
Indian/Mauritius
Indian/Mayotte
Indian/Reunion
Iran
Israel
Jamaica
Japan
Kwajalein
Libya
MET
MST7MDT
Mexico/BajaNorte
Mexico/BajaSur
Mexico/General
NZ
NZ-CHAT
Navajo
PRC
PST8PDT
Pacific/Apia
Pacific/Auckland
Pacific/Bougainville
Pacific/Chatham
Pacific/Chuuk
Pacific/Easter
Pacific/Efate
Pacific/Enderbury
Pacific/Fakaofo
Pacific/Fiji
Pacific/Funafuti
Pacific/Galapagos
Pacific/Gambier
Pacific/Guadalcanal
Pacific/Guam
Pacific/Honolulu
Pacific/Johnston
Pacific/Kiritimati
Pacific/Kosrae
Pacific/Kwajalein
Pacific/Majuro
Pacific/Marquesas
Pacific/Midway
Pacific/Nauru
Pacific/Niue
Pacific/Norfolk
Pacific/Noumea
Pacific/Pago_Pago
Pacific/Palau
Pacific/Pitcairn
Pacific/Pohnpei
Pacific/Ponape
Pacific/Port_Moresby
Pacific/Rarotonga
Pacific/Saipan
Pacific/Samoa
Pacific/Tahiti
Pacific/Tarawa
Pacific/Tongatapu
Pacific/Truk
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
ROK
Singapore
SystemV/AST4
SystemV/AST4ADT
SystemV/CST6
SystemV/CST6CDT
SystemV/EST5
SystemV/EST5EDT
SystemV/HST10
SystemV/MST7
SystemV/MST7MDT
SystemV/PST8
SystemV/PST8PDT
SystemV/YST9
SystemV/YST9YDT
Turkey
UCT
US/Alaska
US/Aleutian
US/Arizona
US/Central
US/East-Indiana
US/Eastern
US/Hawaii
US/Indiana-Starke
US/Michigan
US/Mountain
US/Pacific
US/Pacific-New
US/Samoa
UTC
Universal
W-SU
WET
Zulu
EST
HST
MST
ACT
AET
AGT
ART
AST
BET
BST
CAT
CNT
CST
CTT
EAT
ECT
IET
IST
JST
MIT
NET
NST
PLT
PNT
PRT
PST
SST

VST
-----------------------

2. In the Jackson setting the Timezone can help in the serialization of the Date data correct with the given timezone , there are two ways of setting the timezone for Jackson frequently used in the Spring framework : 
a) Using Object wrapper : 

         ObjectMapper mapper = new ObjectMapper();
         DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss.SSSZ");
         dateFormat.setTimeZone(TimeZone.getTimeZone("IST"));
         mapper.setDateFormat(dateFormat);

b)  In the  Jackson 2.x version using the  annotation : 

@JsonFormat(shape=JsonFormat.Shape.STRING,pattern="dd-MM-yyyy'T'HH:mm:ss.SSSZ", timezone="IST")
private Date date;



Tuesday, 8 December 2015

Anagram


An anagram is a type of wordplay, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

Example is "silent" which can be rearranged to "listen"

Question arises to find out whether two given strings are Anagram or not??

There can be multiple ways of solving the problems and most optimal solution would be using least time complexity and space. O(1) is the best and  denotes constant  time complexity , O(n) can be better etc..

Couple of solution is given as follows : 

**
 * @author sachin
 *
 */
public class Anagram {
public static void main(String[] args) {
String firstString = "silent";
String secondString = "listen";
System.out.println(isAnagram1(firstString, secondString));
System.out.println(isAnagram2(firstString, secondString));
//isAnagram1()  method gives solution in time complexity of O(nlogn)
//isAnagram2()  method gives solution in time complexity of O(n)
     
}
public static boolean isAnagram1(String s1, String s2) {
if (s1 == null || s2 == null )
return false;
int len = s1.length();
if (len != s2.length() || len < 2)
return false;
char[] s1CharArr = s1.toLowerCase().toCharArray();
char[] s2CharArr = s2.toLowerCase().toCharArray();
Arrays.sort(s1CharArr);
Arrays.sort(s2CharArr);
return new String(s1CharArr).equals(new String(s2CharArr));

}
public static boolean isAnagram2(String s1, String s2) {
if (s1 == null || s2 == null )
return false;
int len = s1.length();
if (len != s2.length() || len < 2)
return false;

final int LETTERS_LEN = 256;
int[] letters = new int[LETTERS_LEN];

for (int i = 0; i < len; i++) {
letters[s1.charAt(i)]++;//incrementing the character count
letters[s2.charAt(i)]--;//decrementing the character count
}
for (int i = 0; i < LETTERS_LEN; i++) {
if (letters[i] != 0) {
return false; //returning from first non zero element finding means count mismatch
}
}
return true;
}
}

Output : 

true
true
                 

Thursday, 26 November 2015

Pythagorean Triplets


A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5). If (a, b, c) is a Pythagorean triple, then so is (ka, kb, kc) for any positive integer k. A primitive Pythagorean triple is one in which a, b and c are coprime. A right triangle whose sides form a Pythagorean triple is called a Pythagorean triangle.


Finding all the triplets  for c2<= n :

public class PythagoreanTriplet {
        static int count = 0;
public static void main(String[] args) {
Long start = System.currentTimeMillis();
                //time comparison for various number of inputs 
//int n = 100000000;//total time in ms=1118847
//int n = 10000000;//total time in ms=36031
//int n = 1000000;//total time in ms=2122
//int n = 100000;//total time in ms=66
//int n = 10000;//total time in ms=20
//int n = 1000;//total time in ms=2
//int n = 100;//total time in ms=1

int n = 1000;
List<Integer> listOfSquraes = new ArrayList<>();
for (int i = 1;; i++) {
int sqr = i*i;
if(sqr > n){
break;
} else {
listOfSquraes.add(sqr);
}
}
int  k =listOfSquraes.size();
for (int i = 0; i<k; i++) {
findPythagoreanTriplet(listOfSquraes.get(i), listOfSquraes,k);
}
Long end = System.currentTimeMillis();
System.out.println("total triplets found=" + count + " and total time in ms=" + (end-start));
}

public static void findPythagoreanTriplet(int sumRequired,List<Integer> list, int size){
for (int i = 1; i < size; i++) {
for (int j = i+1; j < size; j++) {
int sum  = list.get(i) + list.get(j);
int diff = sumRequired-sum;
if(diff == 0){
count++;
System.out.println("("+(int)Math.sqrt(list.get(i)) + "," + (int)Math.sqrt(list.get(j)) + "," + (int)Math.sqrt(sumRequired)+")");
}
}
}
}
}

Output

(3,4,5)
(6,8,10)
(5,12,13)
(9,12,15)
(8,15,17)
(12,16,20)
(7,24,25)
(15,20,25)
(10,24,26)
(20,21,29)
(18,24,30)

total triplets found=11 and total time in ms=2

Time complexity though O(n3) which we can reduce with the improving the search to O(nlogn) , so overall complexity would reduce to O(n2logn).

Sunday, 22 November 2015

Installing MongoDB on MacOS X



MongoDB Version : 3.0.7

Mac OS X Version : 10.10.4

Following are step by step installation of the mongodb on the Mac OS :

Start with the Terminal 1 :

1. Get the latest MongoDB from the downloads MongoDB

2. Go to Downloads folder  -- >  cd ~ Downloads/

3.  sudo mv mongodb-osx-x86_64-3.0.7.tgz  /Users/sachin/Documents/software/mongodb [cd ~ is /Users/sachin ]

4. cd ~ Documents/software/mongodb

5. tar xzf mongodb-osx-x86_64-3.0.7.tgz

6. By default MongoDB stores the data  in the /data/db folder , so  we require to create the data and to provide proper permission to it :

  a) sudo mkdir -p /data/db
  b) whoami
      sachin
  c) sudo chown sachin /data/db

7. Adding mongo db to $PATH  : 
  a)  cd ~
  b) pwd 
      /Users/sachin
 c)  vim .bash_profile
 d) export PATH=$PATH:/Users/sachin/Documents/software/mongodb/mongodb-osx-x86_64-3.0.7/bin

8) Starting the MongoDB :

a) Go to new Terminal 2
b) mongod    (it starts the mongo service)

9) Go to Terminal 3 :
a) mongo

MongoDB shell version: 3.0.7

connecting to: test

An Alternate to manually starting the mongoDB using the background job as following : 

10 ) Auto starting the Mongodb  using job : 

a)  sudo vim /Library/LaunchDaemons/mongodb.plist

b)  insert the following text and save the file : 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>mongodb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/sachin/Documents/software/mongodb/mongodb-osx-x86_64-3.0.7/bin/mongod</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>WorkingDirectory</key>
  <string>/usr/local/mongodb</string>
  <key>StandardErrorPath</key>
  <string>/var/log/mongodb/error.log</string>
  <key>StandardOutPath</key>
  <string>/var/log/mongodb/output.log</string>
</dict>
</plist>

c) Load the above mentioned job in the background :

sudo launchctl load /Library/LaunchDaemons/mongodb.plist






Welcome and Enjoy the MongoDB world !!!!!

Saturday, 21 November 2015

Generating multiple log file using log4j

It is a good practise to separate out the application log and error log for your application. With a distinguish error logs , monitoring of the project becomes easy and debugging process becomes easy.

Usually in application log, we write many useful information depending upon what the default logging level is set. 

With the latest development in Log4J , the set of built-in levels includes TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. 

If you want to create two different files , one for application and one for errors log, following configuration is required to add in the log4j.properties file kept in the classpath : 
----------------------------------------------------------
# Root logger option
log4j.rootLogger=INFO, app, error

# application log file
log4j.appender.app=org.apache.log4j.RollingFileAppender
log4j.appender.app.File=${catalina.home}/logs/application.log
log4j.appender.app.MaxFileSize=10MB
log4j.appender.app.MaxBackupIndex=10
log4j.appender.app.layout=org.apache.log4j.PatternLayout
log4j.appender.app.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n


#error logs
log4j.appender.error=org.apache.log4j.RollingFileAppender
log4j.appender.error.File=${catalina.home}/logs/error.log
log4j.appender.error.MaxFileSize=10MB
log4j.appender.error.MaxBackupIndex=10
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n
log4j.appender.error.Threshold=ERROR
-----------------------------------------------------

File path is used here is the default set value of the tomcat catalina home , if you are using some other application server , then you can use the ${SERVER_HOME} path  or whatever the path , you would like to add.

Above configuration generates two files : 

1 . application.log which contains all the logging information  of INFO and upper level  of logging levels.
2. error.log file only contains ERROR logging level information, so whatever you want keep in the error logs .

Java is Pass by Value or Pass by Reference !!!!


In the Java , there is no concept of pointers and objects are  stated to have passed by value. In case of primitives only values can be passed to a method and in case of java objects , it is said to be pass by reference value.

I think correct term should be termed as  Pass by reference value instead of Pass by Value.

Behind the scene its the passing of the value of the reference bit by bit in the method  so its not passing the reference. Following example would validate the  above facts  :


public class Name
{
String name;

Name(String name){
this.name = name;
}

public static void changeNameReference(Name oldname){
oldname = new Name("John");
}
public static void modifyNameReference(Name oldname){
oldname.name = "Brock";
}

public static void main (String[] args) throws java.lang.Exception
{
Name newname = new Name("Rock");
System.out.println("#1.Original name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
changeNameReference(newname);
System.out.println("#2.After changeNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
modifyNameReference(newname);
System.out.println("#3.After modifyNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));

}

}

Output : 
-----------------------------------------------------------------------
#1.Original name= Rock and system hashcode=582216281
#2.After changeNameReference method call name= Rock and system hashcode=582216281
#3.After modifyNameReference method call name= Brock and system hashcode=582216281

------------------------------------------------------------------------

Following points by points to keep understand the above example :

1. Note the Point#1 and # 2 having the same value of the object even though object is passed into the method changeNameReference   which assigning the new reference to the object but original object remain intact.

2. In the point#3 , when a new value is assigned to the  argument object to the method  modifyNameReference , its changed the value of the original object with the  new value "Brock"

3. Value of the object is being passed bit by bit but reference remain same in the Heap memory

4. Note the system hash code value  they are same, so object reference is same  in the heap memory.If reference would have passed then definitely the value system hashcode  would have changed.

Note that Class instance and Array  are the objects in java, so passing the reference value in any method would not affect the reference of the object.


Palindrome



palindrome is a word, phrasenumber, or other sequence of characters which reads the same backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and word dividers. Famous examples include "A man, a plan, a canal, Panama!", "Amor, Roma", "race car", "stack cats", "step on no pets", "taco cat", "put it up", "Was it a car or a cat I saw?" and "No 'x' in Nixon"


Java code to validate the Palindrome is as follow : 

/*
 * @sachin
 */
public class Palindrome {
public static boolean isPalindrome(String input) throws Exception{
if(input == null || input.isEmpty()) {
throw new Exception("Invalid input");
}
String str = input.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
boolean isPalindrome = true;
int i = 0;
int j = str.length();
for(i=0; i< j;i++){
if(str.charAt(i) == str.charAt(j-1)){
j--;
continue;
} else {
isPalindrome = false;
}
}
return isPalindrome;
}
public static void main(String[] args) {
try {
System.out.println("isValidPalindrome=" + isPalindrome("No 'x' in Nixon"));
                        System.out.println("isValidPalindrome=" + isPalindrome("12321"));
                        System.out.println("isValidPalindrome=" + isPalindrome("sachin"));
} catch (Exception e) {
e.printStackTrace();
}
}

}

Output

true
true
false