Here you can find the source of difference(String str1, String str2)
public static String difference(String str1, String str2)
//package com.java2s; //License from project: Mozilla Public License public class Main { public static final String EMPTY = ""; public static String difference(String str1, String str2) { if (str1 == null) { return str2; }//w w w. j a v a 2 s. c o m if (str2 == null) { return str1; } int at = indexOfDifference(str1, str2); if (at == -1) { return EMPTY; } return str2.substring(at); } public static int indexOfDifference(String str1, String str2) { if (str1.equals(str2)) { return -1; } if (str1 == null || str2 == null) { return 0; } int i; for (i = 0; i < str1.length() && i < str2.length(); ++i) { if (str1.charAt(i) != str2.charAt(i)) { break; } } if (i < str2.length() || i < str1.length()) { return i; } return -1; } public static int indexOfDifference(String[] strs) { if (strs == null || strs.length <= 1) { return -1; } boolean anyStringNull = false; boolean allStringsNull = true; int arrayLen = strs.length; int shortestStrLen = Integer.MAX_VALUE; int longestStrLen = 0; for (int i = 0; i < arrayLen; i++) { if (strs[i] == null) { anyStringNull = true; shortestStrLen = 0; } else { allStringsNull = false; shortestStrLen = Math.min(strs[i].length(), shortestStrLen); longestStrLen = Math.max(strs[i].length(), longestStrLen); } } if (allStringsNull || (longestStrLen == 0 && !anyStringNull)) { return -1; } if (shortestStrLen == 0) { return 0; } int firstDiff = -1; for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) { char comparisonChar = strs[0].charAt(stringPos); for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) { if (strs[arrayPos].charAt(stringPos) != comparisonChar) { firstDiff = stringPos; break; } } if (firstDiff != -1) { break; } } if (firstDiff == -1 && shortestStrLen != longestStrLen) { return shortestStrLen; } return firstDiff; } public static String substring(String str, int start) { if (str == null) { return null; } if (start < 0) { start = str.length() + start; } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY; } return str.substring(start); } public static String substring(String str, int start, int end) { if (str == null) { return null; } if (end < 0) { end = str.length() + end; } if (start < 0) { start = str.length() + start; } if (end > str.length()) { end = str.length(); } if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } public static boolean equals(String str1, String str2) { return str1 == null ? str2 == null : str1.equals(str2); } public static int length(String str) { return str == null ? 0 : str.length(); } }