0% found this document useful (0 votes)
104 views

Java Pgms

The document provides examples of how to perform common date manipulation tasks in Java, including adding weeks, months, or years to a date; checking if a date is before or after today; formatting dates in different formats; and finding the day of the week for a given date. The examples demonstrate using the GregorianCalendar and SimpleDateFormat classes from the Java date/time API to perform these operations in a straightforward way.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Java Pgms

The document provides examples of how to perform common date manipulation tasks in Java, including adding weeks, months, or years to a date; checking if a date is before or after today; formatting dates in different formats; and finding the day of the week for a given date. The examples demonstrate using the GregorianCalendar and SimpleDateFormat classes from the Java date/time API to perform these operations in a straightforward way.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

How do I add weeks to a date?

This example shows you how to add weeks to a date. package net.javaiq.examples.date; import java.util.Calendar; import java.util.GregorianCalendar;

/** * This class demonstrates on how to add weeks to a date. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class AddWeeksToDate { /** * Adds the required number of weeks to the date */ public static java.sql.Date addWeeks(final java.util.Date date, final int weeks) { java.sql.Date derivedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE, weeks * 7); derivedDate = new java.sql.Date(calendar.getTime().getTime()); } return derivedDate; } /** * Tests add weeks to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); final int weeksToAdd = 10; final java.sql.Date calculatedDate = addWeeks(currentDate, weeksToAdd); System.out.println("Date after adding weeks : " + calculatedDate); } }

2. How do I add months to a date?


This example shows you how to add months to a date. package net.javaiq.examples.date; import java.util.Calendar; import java.util.GregorianCalendar;

/** * This class demonstrates on how to add months to a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class AddMonthsToDate { /**

* Adds the required number of months to the date */ public static java.sql.Date addMonths(final java.util.Date date, final int months) { java.sql.Date calculatedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.MONTH, months); calculatedDate = new java.sql.Date(calendar.getTime().getTime()); } return calculatedDate; }

/** * Tests add months to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); final int monthsToAdd = 5; final java.sql.Date calculatedDate = addMonths(currentDate, monthsToAdd); System.out.println("Date after adding months : " + calculatedDate); } }

3. How do I add years to a date?


This example shows you how to add years to a date. package net.javaiq.examples.date; import java.util.Calendar; import java.util.GregorianCalendar;

/** * This class demonstrates on how to add years to a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class AddYearsToDate { /** * Adds the specified number of years to the given date */ public static java.sql.Date addYears(final java.util.Date date, final int years) { java.sql.Date calculatedDate = null; if (date != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.YEAR, years); calculatedDate = new java.sql.Date(calendar.getTime().getTime()); } return calculatedDate; }

/** * Tests add years to a date method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date currentDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Current Date : " + currentDate); //Note: the input is a negative number, hence substracts the num of years from the input date final int yearsToAdd = -5; final java.sql.Date calculatedDate = addYears(currentDate, yearsToAdd); System.out.println("Date after adding years : " + calculatedDate); } }

4. How do I check if a given date is after today ?


This example shows you how to check if a given date is after today. package net.javaiq.examples.date; /** * This class demonstrates on how to check if a given date is after today * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class AfterDateChecker { /** * checks if the given date is after today */ public static boolean afterToday(final java.util.Date date) { boolean isAfterToday = false; if (date != null) { final java.util.Date today = new java.util.Date(); isAfterToday = date.after(today); } return isAfterToday; } /** * Tests after today method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date inputDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Input Date : " + inputDate); boolean isInputDateAfterToday = afterToday(inputDate); System.out.println("isInputDateAfterToday : " + isInputDateAfterToday); } }

How do I check if a given date is before today?


This example shows you how to check if a given date is before today. package net.javaiq.examples.date; /** * This class demonstrates on how to check if a given date is before today * @author JavaIQ.net * Creation Date Dec 3, 2010

*/ public class BeforeDateChecker { /** * checks if the given date is before today */ public static boolean beforeToday(final java.util.Date date) { boolean isBeforeToday = false; if (date != null) { final java.util.Date today = new java.util.Date(); isBeforeToday = date.before(today); } return isBeforeToday; }

/** * Tests before today method with sample inputs * @param args */ public static void main(String[] args) { final java.util.Date inputDate = new java.util.Date(System.currentTimeMillis()); System.out.println("Input Date : " + inputDate); final boolean isInputDateBeforeToday = beforeToday(inputDate); System.out.println("isInputDateBeforeToday : " + isInputDateBeforeToday); } }

6. How do I format a date?


This example shows you how to format a date. package net.javaiq.examples.date; import java.sql.Date; import java.text.SimpleDateFormat;

/** * This class demonstrates on how to format a date * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class DateFormatter { private static char separator = '/'; private static String[] validDateFormats = new String[] { "DDMMYYYY", "MMDDYYYY", "YYYYMMDD", "YYYYDDMM", "MMYYYY", "YYYYM M", "MMMYYYY", "DD", "MMDDYY", "DDMMYY", "YYMMDD" };

/** * Returns the string representation in the corresponding format. * Valid date formats valid are DDMMYYYY, MMDDYYYY, YYYYMMDD, YYYYDDMM, MMYYYY, YYY YMM, MMMYYYY, DD,

* MMDDYY, YYMMDD, DDMMYY * @param date * @param format * @param dateSeparator * @return */ public static String format(Date date, String format, char dateSeparator) { String formattedDate = null; if (date != null) { String allowed = " -./"; String dateSeparatorString = String.valueOf(separator); if (allowed.indexOf(dateSeparator) >= 0) { dateSeparatorString = String.valueOf(dateSeparator); } else if (dateSeparator == '\u0000') { dateSeparatorString = ""; } if (format.trim().equalsIgnoreCase("DDMMYYYY")) { formattedDate = formatDate(date, "dd" + dateSeparatorString + "MM" + dateSeparatorString + " yyyy"); } else if (format.trim().equalsIgnoreCase("MMDDYYYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "dd" + dateSeparatorString + " yyyy"); } else if (format.trim().equalsIgnoreCase("YYYYDDMM")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "dd" + dateSeparatorString + "MM"); } else if (format.trim().equalsIgnoreCase("YYYYMMDD")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "MM" + dateSeparatorString + "dd"); } else if (format.trim().equalsIgnoreCase("MMYYYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "yyyy"); } else if (format.trim().equalsIgnoreCase("YYYYMM")) { formattedDate = formatDate(date, "yyyy" + dateSeparatorString + "MM"); } else if (format.trim().equalsIgnoreCase("DD")) { formattedDate = formatDate(date, "dd"); } else if (format.trim().equalsIgnoreCase("MMMYYYY")) { formattedDate = formatDate(date, "MMM" + dateSeparatorString + "yyyy"); } else if (format.trim().equalsIgnoreCase("DDMMYY")) { formattedDate = formatDate(date, "dd" + dateSeparatorString + "MM" + dateSeparatorString + " yy"); } else if (format.trim().equalsIgnoreCase("MMDDYY")) { formattedDate = formatDate(date, "MM" + dateSeparatorString + "dd" + dateSeparatorString + " yy"); } else if (format.trim().equalsIgnoreCase("YYMMDD")) { formattedDate = formatDate(date, "yy" + dateSeparatorString + "MM" + dateSeparatorString + " dd"); } } return formattedDate; }
/** * Formats the given date in the specified format

* @param date * @param format * @return formattedDate */ public static String format(Date date, String format) { return format(date, format, separator); }

/** * Formats the given date in the specified format without the separator * @param date * @param format * @return formattedDate */ public static String format(Date date, String format, boolean separatorRequired) { if (separatorRequired) { return format(date, format); } else { return format(date, format, '\u0000'); } } /** * Formats the given date in the specified format * @param date * @param format * @return formattedDate */ private static String formatDate(java.util.Date date, String format) { SimpleDateFormat df = new SimpleDateFormat(format); return df.format(date) + ""; } /** * Fetches the valid date formats * @return validDateFormats */ public static String[] getAvailableDateFormats() { return validDateFormats; } /** * Tests date formatting methods with sample inputs * @param args */ public static void main(String[] args) { final java.sql.Date inputDate = new java.sql.Date(System.currentTimeMillis()); System.out.println("Input Date : " + inputDate); String formattedDate = format(inputDate, "DDMMYYYY"); System.out.println("Formatted date : " + formattedDate); formattedDate = format(inputDate, "DDMMYYYY", false); System.out.println("Formatted date with no separator : " + formattedDate);

} } 7. How do I find day of the week for any given This example shows you how to find day of the week for any given date. package net.javaiq.examples.date; /** * This class demonstrates on how to find day of the week for any given date. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class DayOfTheWeekFinder { /** * This method returns the Day Of Week */ public static double findDayOfTheWeek(int day, int month, int year) { double a = Math.floor((14 - month) / 12); double y = year - a; double m = month + 12 * a - 2; double d = (day + y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor((31 * m) / 12)) % 7; return d + 1; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { //Here we want to find what day of the week it was on 15th July 1976 System.out.println(findDayOfTheWeek(15, 7, 1976)); } }

date?

How do I calculate days between 2 given dates?


This example shows you how to calculate days between 2 given dates. package net.javaiq.examples.date; import java.util.Calendar; import java.util.GregorianCalendar;

/** * This class demonstrates on how to calculate days between 2 given dates * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class DaysBetweenCalculator { /** * Calculates the total number of days between the two given dates */ public static int getDaysBetween(java.util.Date date1, java.util.Date date2) { if (date1 == null || date2 == null) {

return -1; } GregorianCalendar gc1 = new GregorianCalendar(); gc1.setTime(date1); GregorianCalendar gc2 = new GregorianCalendar(); gc2.setTime(date2);

if (gc1.get(Calendar.YEAR) == gc2.get(Calendar.YEAR)) { return Math.abs(gc1.get(Calendar.DAY_OF_YEAR) - gc2.get(Calendar.DAY_OF_YEAR)); } long time1 = date1.getTime(); long time2 = date2.getTime(); long days = (time1 - time2) / (1000 * 60 * 60 * 24); return Math.abs((int)days); } }

8. How do I find earliest date for a given set of dates?


This example shows you how to find earliest date for a given set of dates. package net.javaiq.examples.date; import java.util.Date; /** * This class demonstrates on how to find earliest date for a given set of dates. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class EarliestDateFinder { public EarliestDateFinder() { } public static Date findEarliestDate(Date date1, Date date2) { Date earliestDate = null; if (date1 != null && date2 != null) { earliestDate = date1.getTime() > date2.getTime() ? date1 : date2; } return earliestDate; } public static Date findEarliestDate(Date[] dates) { Date earliestDate = null; if ((dates != null) && (dates.length > 0)) { for (Date date: dates) { if (date != null) { if (earliestDate == null) { earliestDate = date;

} earliestDate = date.before(earliestDate) ? date : earliestDate; } } } return earliestDate; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { EarliestDateFinder earliestDateFinder = new EarliestDateFinder(); } }

9. How do I find the latest date for a given set of dates?


This example shows you how to find the latest date for a given set of dates. package net.javaiq.examples.date; import java.util.Date;

/** * This class demonstrates on how to find the latest date for a given set of dates. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class LatestDateFinder { public LatestDateFinder() { } public static Date findLatestDate(Date date1, Date date2) { Date latestDate = null; if (date1 != null && date2 != null) { latestDate = date1.getTime() > date2.getTime() ? date1 : date2; } return latestDate; } public static Date findLatestDate(Date[] dates) { Date latestDate = null; if ((dates != null) && (dates.length > 0)) { for (Date date: dates) { if (date != null) { if (latestDate == null) { latestDate = date; } latestDate = date.after(latestDate) ? date : latestDate; } } } return latestDate; }

/** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }

How do I check if a year is a leap year?


This example shows you how to check if a year is a leap year. package net.javaiq.examples.date; import java.util.GregorianCalendar;

/** * This class demonstrates on how to check if a year is a leap year * @author JavaIQ.net * Creation Date Dec 3, 2010 */ public class LeapYearChecker { /** * Returns whether it is a leap year or not */ public static boolean isLeapYear(int year) { GregorianCalendar gc = new GregorianCalendar(); return gc.isLeapYear(year); } /** * Tests leap year checker method with sample inputs * @param args */ public static void main(String[] args) { int year = 2076; final boolean isLeapYear = isLeapYear(year); if (isLeapYear) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } } }

How do I find end date of any given month in any year?


This example shows you how to find end date of any given month in a year. package net.javaiq.examples.date; import java.util.GregorianCalendar;

/** * This class demonstrates on how to find end date of any given month in a year * @author JavaIQ.net

* Creation Date Dec 3, 2010 */ public class MonthEndDateCalculator { /** * calculates the last date of a month */ public static java.sql.Date calculateMonthEndDate(int month, int year) { int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day = daysInAMonth[month]; boolean isLeapYear = new GregorianCalendar().isLeapYear(year); if (isLeapYear && month == 2) { day++; } GregorianCalendar gc = new GregorianCalendar(year, month - 1, day); java.sql.Date monthEndDate = new java.sql.Date(gc.getTime().getTime()); return monthEndDate; } /** * Tests month end date calculation method with sample inputs * @param args */ public static void main(String[] args) { int month = 2; int year = 2076; final java.sql.Date calculatedDate = calculateMonthEndDate(month, year); System.out.println("Calculated month end date : " + calculatedDate); } }

How do I find if the month and year of 2 dates are equal?


This example shows you how to find if the month and year of 2 dates are equal.. package net.javaiq.examples.date; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * This class demonstrates on how to find if the month and year of 2 dates are equal. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class MonthYearEqualityChecker { /** * Checks whether the month and year of input dates are equal */ public static boolean checkIfMonthAndYearAreEqual(Date firstDate, Date secondDate) { boolean isEqual = false; if (firstDate != null && secondDate != null) { Calendar firstCal = Calendar.getInstance();

firstCal.setTime(firstDate); Calendar secondCal = Calendar.getInstance(); secondCal.setTime(secondDate); isEqual = firstCal.get(Calendar.YEAR) == secondCal.get(Calendar.YEAR) && firstCal.get(Calendar.MONTH) == secondCal.get(Calendar.MONTH); } return isEqual; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) throws Exception { Date firstDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-10-2010"); Date secondDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-18-2010"); boolean isEqual = checkIfMonthAndYearAreEqual(firstDate, secondDate); if (isEqual) { System.out.println("Month and year of the passed dates are equal."); } else { System.out.println("Month and year of the passed dates are not equal."); } secondDate = new SimpleDateFormat("MM-dd-yyyy").parse("12-18-2011"); isEqual = checkIfMonthAndYearAreEqual(firstDate, secondDate); if (isEqual) { System.out.println("Month and year of the passed dates are equal."); } else { System.out.println("Month and year of the passed dates are not equal."); } } }

How do I find a particular occurence of a week day in a month?


This example shows you how to find a particular occurence of a week day in a month. package net.javaiq.examples.date; /** * This class demonstrates on how to find a particular occurence of a week day in a month. * For example how to find second saturday or first monday or last tuesday in a month * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class NthWeekDayOfTheMonthFinder { /** * This method returns the date of the nth week day of the month(ex. 2nd Sunday ) * @param nth - the occurence. say for third monday of the month, the value should be 3. * @param weekDay - the day of the week. Sunday value is 0 and saturday is 7. * @param month - month of the year. Jan is 1 and Dec is 12 * @param year - year. * @return nthDayOfTheMonth - indicates the day of the month of the occurence */ public static double findNthWeekDayOfTheMonth(int nth, int weekDay, int month, int year) { int[] daysOfMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int[] daysOfMonthLeapYear = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (nth > 0)

return (nth - 1) * 7 + 1 + (7 + weekDay - findDayOfTheWeek((nth - 1) * 7 + 1, month, year)) % 7; int days = 0; if (leapYear(year)) { days = daysOfMonthLeapYear[month - 1]; } else { days = daysOfMonth[month - 1]; } return (days - (findDayOfTheWeek(days, month, year) - weekDay + 7) % 7); } /** * This method returns true if the given year is Leap Year */ public static boolean leapYear(int year) { if ((year / 4) != Math.floor(year / 4)) return false; if ((year / 100) != Math.floor(year / 100)) return true; if ((year / 400) != Math.floor(year / 400)) return false; return true; } /** * This method returns the Day Of the Week */ public static double findDayOfTheWeek(int day, int month, int year) { double a = Math.floor((14 - month) / 12); double y = year - a; double m = month + 12 * a - 2; double d = (day + y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) + Math.floor((31 * m) / 12)) % 7; return d + 1; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { //Here we want to find when the second saturday falls in the month of July 2020 int nth = 2; // indicating to find second occurence int weekDay = 7; // indicates to find saturday. Note sunday value is 0 and saturday value is 7 int month = 7; // indicates july month int year = 2020; // obvious! // The day of the month on which second saturday occurs in July 2020 double nthDay = findNthWeekDayOfTheMonth(nth, weekDay, month, year); System.out.println(" The day of the month : " + nthDay); } }

How do I convert String date to a Calendar?


This example shows you how to convert String date to a Calendar. package net.javaiq.examples.date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;

/** * This class demonstrates on how to convert String date to a Calendar. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringDateToCalendarConverter { public static Calendar convertStringDateToCalender(String strDate) { Calendar cal = null; if (strDate != null) { try { DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy"); Date date = formatter.parse(strDate); cal = Calendar.getInstance(); cal.setTime(date); } catch (Exception e) { e.printStackTrace(); } } return cal; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String date = "12-10-2010"; Calendar calender = convertStringDateToCalender(date); System.out.println("Converted Calendar : " + calender); } }

How do I format time to AM/PM. This example shows you how to format time to AM/PM.
package net.javaiq.examples.date; import java.sql.Time; /** * This class demonstrates on how to format time to AM/PM. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class TimeFormatter { /** * Method to change the given time in to AM PM format like hh:mm:ss AM */ public static String getFormattedTime(Time inputTime) { String formattedTime = ""; if (inputTime != null) { java.util.StringTokenizer st = new java.util.StringTokenizer(String.valueOf(inputTime), ":"); int hrs = Integer.parseInt((String)st.nextToken()); String mins = st.nextToken(); String secs = st.nextToken();

String meridian = ""; if (hrs > 12) { hrs = hrs - 12; meridian = "PM"; } else if (hrs == 12) { meridian = "PM"; } else { meridian = "AM"; } formattedTime = hrs + ":" + mins + ":" + secs + " " + meridian; } return formattedTime; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { Time currentTime = new Time(System.currentTimeMillis()); System.out.println("currentTime :: " + currentTime); String formattedTime = getFormattedTime(currentTime); System.out.println("formattedTime :: " + formattedTime); } }

How do I extend or copy contents of one array into another array?


This example shows you how to extend or copy contents of one array into another array. If you have situation like copying arrays, it is better to use to ArrayList than arrays. package net.javaiq.examples.collections;

/** * This class demonstrates on how to copy/extend/increase an existing array to accomodate * new elements * @author JavaIQ.net * Creation Date Oct 11, 2010 */ public class ArrayExtender { /** * Demonstrates copying elements from one array to another */ public void demonstrateArrayCopy() { //initial array with 3 employees String[] employees = new String[] { "Chris", "Kara", "Amanda" }; //Create the extended array to accomodate 2 more employees String[] extendedEmployees = new String[5]; //Add more names to the extended array extendedEmployees[3] = "Francis"; extendedEmployees[4] = "Ian"; //System class has arraycopy method which copies elements from one array to another

//arraycopy(Object src, int srcPos,Object dest, int destPos, int length); System.arraycopy(employees, 0, extendedEmployees, 0, employees.length); // Printing the contents of the array to console for (int i = 0; i < extendedEmployees.length; i++) { System.out.println(extendedEmployees[i]); } } /** * Tests array copy method * @param args - command line arguments */ public static void main(String[] args) { // Create arrayExtender object ArrayExtender arrayExtender = new ArrayExtender(); // calling the method which shows how to copy arrays elements in Java arrayExtender.demonstrateArrayCopy(); } }

How do I find the count the number of a particular value object in a collection?
This example shows you how to find the count the number of a particular value object in a collection. package net.javaiq.examples.collections; import java.util.ArrayList; import java.util.Collection; import java.util.List;

/** * This class demonstrates on how to find the count the number of a particular * value object in a collection * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class CollectionValueObjectSizeFinder { /** * Method to count the number of value objects in a given collection * @param coll -- the Collection to find the values. * @param val -- the value to compare each of the elements to. * @return size -- the number of value objects in the passed Collection */ public static int getNumberOfValueObjectsInCollection(Collection<Object> coll, Object val) { int numOfValueObjectsInColl = 0; if (coll != null) { for (Object collObj: coll) { if (collObj != null) { if (collObj.equals(val)) numOfValueObjectsInColl++; } else { if (val == null) numOfValueObjectsInColl++; } }

} return numOfValueObjectsInColl; } /** * Tests getNumberOfValueObjectsInCollection method with sample inputs * @param args */ public static void main(String[] args) { List list = new ArrayList(); list.add("Google"); list.add("Yahoo"); list.add("Bing"); list.add("Google"); int num = getNumberOfValueObjectsInCollection(list, "Google"); System.out.println("Value object count in the collection :: " + num); } }

How do I convert a tokenized string to an array?


This example shows you how to convert a tokenized string to an array. package net.javaiq.examples.collections; import java.util.StringTokenizer;

/** * This class demonstrates on how to convert a tokenized string to an array * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayConverter { /** * Method to convert a tokenized string to a string array * @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return stringArray -- the converted string array */ public static String[] convertTokenizedStringToStringArray(String tokenizedString, String token) { String stringArray[] = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); int i = 0; stringArray = new String[st.countTokens()]; while (st.hasMoreElements()) { stringArray[i] = st.nextToken(); i++; } } return stringArray; } /** * Method to convert a tokenized string to an int array

* @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return stringArray -- the converted int array */ public static int[] convertTokenizedStringToIntArray(String tokenizedString, String token) { int intArray[] = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); int i = 0; intArray = new int[st.countTokens()]; while (st.hasMoreElements()) { intArray[i] = Integer.parseInt(st.nextToken()); i++; } } return intArray; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { String token = ","; String stringCsv = "Red,Green,Blue"; String[] convertedStringArray = convertTokenizedStringToStringArray(stringCsv, token); for (String str: convertedStringArray) { System.out.println(str); }

String intCsv = "007,786,555,143"; int[] convertedIntArray = convertTokenizedStringToIntArray(intCsv, token); for (int num: convertedIntArray) { System.out.println(num); } } }

How do I convert a tokenized string to an array list ?


This example shows you how to convert a tokenized string to an array list . package net.javaiq.examples.collections; import java.util.ArrayList; import java.util.StringTokenizer;

/** * This class demonstrates on how to convert a tokenized string to an array list * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayListConverter {

/** * Method to convert a tokenized string to an array list of string type * @param tokenizedString -- the tokenized string which needs to be converted * @param token -- the token which separates the values in the input string. * @return list -- the converted string array list */ public static ArrayList<String> convertTokenizedStringToList(String tokenizedString, String token) { ArrayList<String> list = null; if ((tokenizedString != null) && (token != null)) { StringTokenizer st = new StringTokenizer(tokenizedString, token); list = new ArrayList<String>(); while (st.hasMoreElements()) { list.add(st.nextToken()); } } return list; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { // Comma separated values String csv = "Red,Green,Blue"; String token = ","; ArrayList<String> list = convertTokenizedStringToList(csv, token); for (String item: list) { System.out.println(item); } } }

How do I validate a email address in Java?


This example shows you how to validate a email address in Java. package net.javaiq.examples.string; import java.util.regex.Matcher; import java.util.regex.Pattern;

/** * This class demonstrates on how to convert a tokenized string to an array list * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class EmailValidator { /** * This method validates if a given email Id is a valid email address. * @param emailId -- The EmailId which needs to be validated * @return isEmailIdValid -- true if email address is valid, false otherwise. */ public static boolean isEmailIdValid(String emailId) { boolean isEmailIdValid = false; if (emailId != null && emailId.length() > 0) {

String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(emailId); if (matcher.matches()) { isEmailIdValid = true; } } return isEmailIdValid; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }

How do I validate if a given phone number is valid?


This example shows you how to validate if a given phone number is valid.. package net.javaiq.examples.string; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class demonstrates on how to validate if a given phone number is valid. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class PhoneNumberValidator { /** isPhoneNumberValid: Validate phone number using Java reg ex. * This method checks if the input string is a valid phone number. * @param phoneNumber String. Phone number to validate * @return boolean: true if phone number is valid, false otherwise. */ public static boolean isPhoneNumberValid(String phoneNumber) { boolean isValid = false; /* Phone Number formats: (nnn)nnn-nnnn; nnnnnnnnnn; nnn-nnn-nnnn ^\\(?</STRONG> : May start with an option "(" . (\\d{3})</STRONG>: Followed by 3 digits. \\)?</STRONG> : May have an optional ")" [- ]?</STRONG> : May have an optional "-" after the first 3 digits or after optional ) character. (\\d{3})</STRONG> : Followed by 3 digits. [- ]? </STRONG>: May have another optional "-" after numeric digits. (\\d{4})$</STRONG> : ends with four digits. Examples: Matches following <A href="http://mylife.com">phone numbers</A>: (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890 */ String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$"; CharSequence inputStr = phoneNumber; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid;

} /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { System.out.println("1. Phone Number is " + isPhoneNumberValid("123-456-7890")); System.out.println("2. Phone Number is " + isPhoneNumberValid("(234) 456-7890")); System.out.println("3. Phone Number is " + isPhoneNumberValid("1234567890")); System.out.println("4. Phone Number is " + isPhoneNumberValid("234567-789")); } }

How do I validate a SSN (Social Security Number) in Java?


This example shows you how to validate a SSN (Social Security Number) in Java. package net.javaiq.examples.string; import java.util.regex.Matcher; import java.util.regex.Pattern;

/** * This class demonstrates on how to validate a SSN (Social Security Number) in Java * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class SsnValidator { /** isSSNValid: Validate Social Security number (SSN) using Java reg ex. * This method checks if the input string is a valid SSN. * @param ssn String. Social Security number to validate * @return boolean: true if social security number is valid, false otherwise. */ public static boolean isSsnValid(String ssn) { boolean isValid = false; /*SSN format xxx-xx-xxxx, xxxxxxxxx, xxx-xxxxxx; xxxxx-xxxx: ^\\d{3}: Starts with three numeric digits. [- ]?: Followed by an optional "-" \\d{2}: Two numeric digits after the optional "-" [- ]?: May contain an optional second "-" character. \\d{4}: ends with four numeric digits. Examples: 879-89-8989; 869878789 etc. */ //Initialize reg ex for SSN. </CODECOMMENTS> String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$"; CharSequence inputStr = ssn; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid; }

/** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { System.out.println("1. SSN is " + isSsnValid("234-56-7890")); System.out.println("2. SSN is " + isSsnValid("234-56-78900")); System.out.println("3. SSN is " + isSsnValid("234567890")); System.out.println("4. SSN is " + isSsnValid("234567-789")); } }

How do I validate if a string contains only letters(alphabets)?


This example shows you how to validate if a string contains only letters(alphabets). package net.javaiq.examples.string; /** * This class demonstrates on how to validate if a string contains only letters(alphabets) * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringLetterValidator { /** * This method checks if a given contains only letters * @param arg -- the input string to be validated * @return isLetterString -- the return value */ public static boolean isLetterString(String arg) { boolean isLetterString = true; for (int i = 0; i < arg.length(); i++) { if (Character.isLetter(arg.charAt(i))) { continue; } else { isLetterString = false; break; } } return isLetterString; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { System.out.println(isLetterString("JustLetters")); System.out.println(isLetterString("Just Letters")); System.out.println(isLetterString("Hi 007")); }

How do I convert a tokenized string to an array?


This example shows you how to convert a tokenized string to an array.

package net.javaiq.examples.string; import java.util.StringTokenizer; /** * This class demonstrates on how to convert a tokenized string to an array * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class StringToArrayConverter { /** * This method converts a tokenized string into a string array using string tokenizer class * @param str : String -- the tokenized string which needs to be converted * @param token : String -- the token which separates the strings * @return strArr : String[] -- converted String array */ public static String[] getArrayFromTokenizedStringOldWay(String str, String token) { String strArr[] = null; if (str != null && token != null) { StringTokenizer st = new StringTokenizer(str.trim(), token.trim()); int i = 0; strArr = new String[st.countTokens()]; while (st.hasMoreElements()) { strArr[i] = st.nextToken(); i++; } } return strArr; } /** * This method converts a tokenized string into a string array using the split method in String class * @param str : String -- the tokenized string which needs to be converted * @param token : String -- the token which separates the strings * @return strArr : String[] -- converted String array */ public static String[] getArrayFromTokenizedString(String str, String token) { String strArr[] = null; if (str != null && token != null) { strArr = str.split(token); } return strArr; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String tokenizedString = "Clinton,Bush,Obama"; String[] strArr = getArrayFromTokenizedStringOldWay(tokenizedString, ","); for (String str: strArr) { System.out.println(str); } strArr = getArrayFromTokenizedString(tokenizedString, ",");

for (String str: strArr) { System.out.println(str); } } }

How do I write data to a file?


This example shows you how to write data to a file. package net.javaiq.examples.files; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; /** * This class demonstrates on how to write data to a file. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class DataToFileWriter { public static void writeDataToFile(String fileName, String data) { try { BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, false)); writer.write(data); writer.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String fileName = "C:\\data.txt"; String data = "Welcome to the world of Java!!"; writeDataToFile(fileName, data); } }

How do I create a sequentially numbered date based directory.?


This example shows you how to create a sequentially numbered date based directory. package net.javaiq.examples.files; import java.io.File; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * This class demonstrates on how to create a sequentially numbered date based directory. * If a directory directory exists for the date the sequence will be increased. * This code is useful when you wanted to create directories for automated backups.

* This has been tested only windows but can be adapted for *nix * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class DateBasedDirectoryCreator { public static String createDateBasedDirectory(String baseDirectory, Date argDate) { String newDir = null; if (baseDirectory != null && argDate != null) { try { String format = "yyyy-MM-dd"; DateFormat dateFormatter = new SimpleDateFormat(format); String date = dateFormatter.format(argDate); File f = new File(baseDirectory); File files[] = f.listFiles(); String dir = null; int baseDirLength = baseDirectory.length(); int checkingLength = baseDirLength + format.length() + 3; int maxSeqNo = 0; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { dir = files[i].toString(); if (dir.length() == checkingLength) { String existingDirDate = dir.substring(baseDirLength, baseDirLength + 10); if (date.equalsIgnoreCase(existingDirDate)) { int dirSeqNo = Integer.parseInt(dir.substring(baseDirLength + 11, baseDirLength + 10 + 3)); if (dirSeqNo > maxSeqNo) { maxSeqNo = dirSeqNo; } } } } } String currSeq = "" + (maxSeqNo + 1); if (currSeq.length() == 1) { currSeq = "0" + currSeq; } newDir = baseDirectory + date + "-" + currSeq; new File(newDir).mkdir(); } catch (Exception e) { e.printStackTrace(); } } return newDir; } /** * Method to test other methods in the class with sample inputs * In this example 2 directories are created for current date and 1 directory for a previous date. * Make sure the base directory in the file system with proper access. * @param args */ public static void main(String[] args) throws ParseException { Date currentDate = new java.util.Date(System.currentTimeMillis());

String baseDir = "C:/Admin/Backup/"; String newDir = createDateBasedDirectory(baseDir, currentDate); System.out.println("New Directory 1 :: " + newDir); newDir = createDateBasedDirectory(baseDir, currentDate); System.out.println("New Directory 2 :: " + newDir); Date oldDate = new SimpleDateFormat("yyyy-MM-dd").parse("2010-12-09"); newDir = createDateBasedDirectory(baseDir, oldDate); System.out.println("New Directory 3:: " + newDir); } }

How do I find/search for a file in a given directory and its subdirectories?


This example shows you how to find/search for a file in a given directory and its sub-directories. package net.javaiq.examples.files; import java.io.File; /** * This class demonstrates on how to find/search for a file in a given directory and its sub-directories. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class FileSearcher { boolean fileFound = false; String fileSeparator = "\\"; String filePath; String lastModifiedBy; String lastModifiedDate;

public void searchFile(String dirName, String fileName) { File f = new File(dirName); File files[] = f.listFiles(); for (int i = 0; (i < files.length) && !fileFound; i++) { if (files[i].isDirectory()) { String newDir = dirName + fileSeparator + files[i].getName(); searchFile(newDir, fileName); } else { if (files[i].getName().equalsIgnoreCase(fileName)) { filePath = files[i].getAbsolutePath(); lastModifiedDate = new java.util.Date(files[i].lastModified()).toString(); fileFound = true; break; } } } } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { FileSearcher fileFinder = new FileSearcher(); String fileName = "FileUtility.java"; String searchDirectory = "D:\\APPS\\eRASU"; fileFinder.searchFile(searchDirectory, fileName);

if (fileFinder.fileFound) { System.out.println("File Name : " + fileName); System.out.println("File Directory : " + fileFinder.filePath); System.out.println("Last Modified Date : " + fileFinder.lastModifiedDate); } else { System.out.println("File " + fileName + " not found in " + searchDirectory + " or in any of its sub-folders."); } } }

How do I convert an input stream to text?


This example shows you how to convert an input stream to text. package net.javaiq.examples.files; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * This class demonstrates on how to convert an input to text. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class InputStreamToTextConverter { public static String convertInputStreamToText(InputStream stream) { StringBuilder sb = new StringBuilder(); String line = null; if (stream != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(stream)); while ((line = br.readLine()) != null) { //apending the content sb.append(line); //appending new line sb.append("\n"); } br.close(); } catch (IOException ioEx) { ioEx.printStackTrace(); } } return sb.toString(); } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { FileInputStream inputStream; try {

inputStream = new FileInputStream("C:\\Sample.txt"); String streamText = convertInputStreamToText(inputStream); System.out.println(streamText); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

How do I find greatest or highest in a given set of numbers?


This example shows you how to find greatest or highest in a given set of numbers. package net.javaiq.examples.math; /** * This class demonstrates on how to find greatest or highest in a given set of numbers. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class GreatestNumberFinder { public static double findGreatestNumber(Number numA, Number numB) { double greatestNumber = 0; if (numA != null && numB == null) { greatestNumber = numA.doubleValue(); } else if (numA == null && numB != null) { greatestNumber = numB.doubleValue(); } else { greatestNumber = numA.doubleValue() > numB.doubleValue() ? numA.doubleValue() : numB.dou bleValue(); } return greatestNumber; } public static double findGreatestNumber(Double[] numbers) { double greatestNumber = 0; if ((numbers != null) && (numbers.length > 0)) { for (Number number: numbers) { if (number != null) { greatestNumber = number.doubleValue() > greatestNumber ? number.doubleValue() : greate stNumber; } } } return greatestNumber; } /** * Method to test other methods in the class with sample inputs * @param args */

public static void main(String[] args) { } }

How do I find lowest or least number in a given set of numbers?


This example shows you how to find lowest or least number in a given set of numbers. package net.javaiq.examples.math; /** * This class demonstrates on how to find lowest or least number in a given set of numbers * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class LeastNumberFinder { /** * Method to find the least of the two numbers * @param numA * @param numB * @return leastNumber */ public static double findLeastNumber(Number numA, Number numB) { double leastNumber = 0; if (numA != null && numB == null) { leastNumber = numA.doubleValue(); } else if (numA == null && numB != null) { leastNumber = numB.doubleValue(); } else { leastNumber = numA.doubleValue() < numB.doubleValue() ? numA.doubleValue() : numB.doubleValue(); } return leastNumber; } /** * Method to find the least number from a given set of numbers * @param numbers * @return leastNumber */ public static double findLeastNumber(Double[] numbers) { double leastNumber = 0; if ((numbers != null) && (numbers.length > 0)) { for (Number number: numbers) { if (number != null) { leastNumber = number.doubleValue() < leastNumber ? number.doubleValue() : leastNumber; } } } return leastNumber; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) {

} }

How do I check if a given number is a valid number?


This example shows you how to check if a given number is a valid number. package net.javaiq.examples.math; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * This class demonstrates on how to check if a given number is a valid number. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class NumberValidator { public NumberValidator() { } /** isNumeric: Validate a number using Java regex. * This method checks if the input string contains all numeric characters. * @param number String. Number to validate * @return boolean: true if the input is all numeric, false otherwise. */ public static boolean isNumeric(String number) { boolean isValid = false; /*Number: A numeric value will have following format: ^[-+]?: Starts with an optional "+" or "-" sign. [0-9]*: May have one or more digits. \\.?</STRONG> : May contain an optional "." (decimal point) character. [0-9]+$</STRONG> : ends with numeric digit. */ String expression = "^[-+]?[0-9]*\\.?[0-9]+$"; CharSequence inputStr = number; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }

How do I generate a range of tokenized numeric values?


This example shows you how to generate a range of tokenized numeric values.

package net.javaiq.examples.math;

/** * This class demonstrates on how to generate a range of tokenized numeric values. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class RangeValuesGenerator { /** * @param low : Double -- the starting number * @param high : Double -- the ending number * @param token : String -- the token which separates the numbers * @return tokenizedRange : String -- the generated range */ public static String generateRangeValuesAsString(Double low, Double high, String token) { StringBuffer tokenizedRange = new StringBuffer(""); if (low != null && high != null && token != null && high > low) { for (; low <= high; low++) { tokenizedRange.append(low); if (low != high) { tokenizedRange.append(token); } } } return tokenizedRange.toString(); } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { String rangeValuesCsv = generateRangeValuesAsString(1.0, 7.0, ","); System.out.println(rangeValuesCsv); } }

How do I get a database connection to a Oracle database?


This example shows you how to get a database connection to a Oracle database. package net.javaiq.examples.database; import java.sql.Connection; import java.sql.DriverManager; /** * This class demonstrates on how to get a database connection to a Oracle database. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ class OracleDatabaseConnector { public OracleDatabaseConnector() { } public static Connection getConnectionForOracleDatabase() { String hostName = "oradbsvr"; //The host where the database is installed String portNum = "1528"; // The port on the which the database is listening String dbName = "Sample"; // The name of the database //String url = "jdbc:oracle:thin:@10.255.169.55:1528:ATSPROD"; String url = "jdbc:oracle:thin:@" + hostName + ":" + portNum + ":" + dbName; System.out.println("db URL : " + url);

String driver = "oracle.jdbc.driver.OracleDriver"; // The driver class (classes12.jar) should be in the classpath String userName = "Test"; String password = "test@123"; Connection con = null; try { Class.forName(driver); con = DriverManager.getConnection(url, userName, password); } catch (Exception e) { e.printStackTrace(); } return con; } /** * Method to test the methods in the class with sample inputs * @param args */ public static void main(String[] args) { getConnectionForOracleDatabase(); } }

How do I execute a external command from Java?


This example shows you how to execute a external command from Java. package net.javaiq.examples.exec; import java.io.BufferedReader; import java.io.InputStreamReader;

/** * This class demonstrates on how to execute a external command from Java. * For example how to execute a batch file from Java or a shell script from Java. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class ExternalCommandExecutor { public static String executeExternalCommand(String[] cmdArray) { StringBuffer commandOutput = new StringBuffer(""); try { Process process = Runtime.getRuntime().exec(cmdArray); BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = input.readLine()) != null) { commandOutput.append(line); commandOutput.append("\n"); } } catch (Exception e) { e.printStackTrace(); } return commandOutput.toString(); } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) {

String[] cmdArray = new String[1]; cmdArray[0] = "C:\\test.bat"; String commandResult = executeExternalCommand(cmdArray); System.out.println("Command Result :: " + commandResult); } }

How do I replace special characters with URL encoders.?


This example shows you how to replace special characters with URL encoders. package net.javaiq.examples.http; /** * This class demonstrates on how to replace special characters with URL encoders. * @author JavaIQ.net * Creation Date Dec 10, 2010 */ public class UrlEncoder { /** * method to give URL encoded characters for the given special characters */ public static String replaceSpecialCharactersWithUrlEncoders(String urlToEncode) { if (urlToEncode != null) { if ((urlToEncode).contains("\'")) { urlToEncode = urlToEncode.replace("\'", " "); } if ((urlToEncode).contains("\"")) { urlToEncode = urlToEncode.replace("\"", "%22"); } if ((urlToEncode).contains("#")) { urlToEncode = urlToEncode.replace("#", "%23"); } if ((urlToEncode).contains("$")) { urlToEncode = urlToEncode.replace("$", "%24"); } if ((urlToEncode).contains("%")) { urlToEncode = urlToEncode.replace("%", "%25"); } if ((urlToEncode).contains("&")) { urlToEncode = urlToEncode.replace("&", "%26"); } if ((urlToEncode).contains("@")) { urlToEncode = urlToEncode.replace("@", "%40"); } } return urlToEncode; } /** * Method to test other methods in the class with sample inputs * @param args */ public static void main(String[] args) { } }

You might also like