java programming tips

33
Quick Programming Tips A collection of programming wisdom! Home Privacy Policy Contact Converting Milliseconds to Date in Java Many Web Service specifications represent dates as number of milliseconds elapsed since 1st January 1970. This representation also enables us to store and transfer date values as long values. However when want to manipulate dates such as adding days or months, this long value is cumbersome to process. In such cases we want to work with java.util.Date. The following program shows how we can easily convert number of milliseconds after 1970 to a Java Date, If you need to get the number of milliseconds elapsed since 1st January 1970, you can use the method getTime() on java.util.Date. This is useful when you want to store or transfer date values. Posted in Java category | No Comments Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us . Leave a Reply Name (required) 1 import java.util.Date; 2 3 /** 4 5 * Convert number of milliseconds elapsed since 1st January 1970 to a java.util.Date 6 7 */ 8 9 public class MilliSecsToDate { 10 public static void main(String[] args) { 11 MilliSecsToDate md = new MilliSecsToDate(); 12 // The long value returned represents number of milliseconds elapsed 13 // since 1st January 1970. 14 long millis = System.currentTimeMillis(); 15 Date currentDate = new Date(millis); 16 System.out.println("Current Date is "+currentDate); 17 } 18 }

Upload: prabhu-kumar-chintamaneni

Post on 07-Apr-2017

283 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Converting Milliseconds to Date in JavaMany Web Service specifications represent dates as number of milliseconds elapsed since 1st January 1970.This representation also enables us to store and transfer date values as long values. However when want tomanipulate dates such as adding days or months, this long value is cumbersome to process. In such cases wewant to work with java.util.Date.

The following program shows how we can easily convert number of milliseconds after 1970 to a Java Date,

If you need to get the number of milliseconds elapsed since 1st January 1970, you can use the methodgetTime() on java.util.Date. This is useful when you want to store or transfer date values.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

1 import java.util.Date;2 3 /**4 5 * Convert number of milliseconds elapsed since 1st January 1970 to a

java.util.Date6 7 */8 9 public class MilliSecsToDate 10 public static void main(String[] args) 11 MilliSecsToDate md = new MilliSecsToDate();12 // The long value returned represents number of milliseconds

elapsed13 // since 1st January 1970.14 long millis = System.currentTimeMillis();15 Date currentDate = new Date(millis);16 System.out.println("Current Date is "+currentDate);17 18

Page 2: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Date Manipulation Techniques in JavaManipulating dates is a common requirement in Java programs. Usually you want to add or subtract a fixednumber of days, months or years to a given date. In Java, this can be easily achieved using thejava.util.Calendar class. Calendar class can also work with java.util.Date.

The following program shows how date manipulation can be done in Java using the Calendar class. Please notethat the following examples uses the system time zone,

1 import java.util.Calendar;2 import java.util.Date;3 4 /**5 * This program demonstrates various date manipulation techniques in Java6 */7 public class DateManipulator 8 public static void main(String[] args) 9 DateManipulator dm = new DateManipulator();10 Date curDate = new Date();11 System.out.println("Current date is "+curDate);12 13 Date after5Days = dm.addDays(curDate,5);14 System.out.println("Date after 5 days is "+after5Days);15 16 Date before5Days = dm.addDays(curDate,‐5);17 System.out.println("Date before 5 days is "+before5Days);18 19 Date after5Months = dm.addMonths(curDate,5);20 System.out.println("Date after 5 months is "+after5Months);21 22 Date after5Years = dm.addYears(curDate,5);23 System.out.println("Date after 5 years is "+after5Years);24 25 26 // Add days to a date in Java27 public Date addDays(Date date, int days) 28 Calendar cal = Calendar.getInstance();29 cal.setTime(date);30 cal.add(Calendar.DATE, days);31 return cal.getTime();32 33 34 // Add months to a date in Java35 public Date addMonths(Date date, int months) 36 Calendar cal = Calendar.getInstance();37 cal.setTime(date);

38 cal.add(Calendar.MONTH, months);

Page 3: Java programming tips

There are a number of third party libraries which provides these data manipulation methods and much more.For advanced date processing in Java, please use Apache Commons Lang library or Joda­Time.

If you are using Java 8, use the classes in java.time for date manipulation. The following code demonstratesdate manipulation in Java 8 using java.time classes,

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

38 cal.add(Calendar.MONTH, months);39 return cal.getTime();40 41 42 // Add years to a date in Java43 public Date addYears(Date date, int years) 44 Calendar cal = Calendar.getInstance();45 cal.setTime(date);46 cal.add(Calendar.YEAR, years);47 return cal.getTime();48 49

1 import java.time.LocalDate;2 /**3 * This program demonstrates various date manipulation techniques in Java

8 using java.time.LocalDate4 */5 public class DateManipulator8 6 // This program works only in Java87 public static void main(String[] args) 8 DateManipulator dm = new DateManipulator();9 LocalDate curDate = LocalDate.now();10 System.out.println("Current date is "+curDate);11 12 System.out.println("Date after 5 days is "+curDate.plusDays(5));13 System.out.println("Date before 5 days is "+curDate.plusDays(5));14 System.out.println("Date after 5 months is

"+curDate.plusMonths(5));15 System.out.println("Date after 5 years is

"+curDate.plusYears(5));16 17

Page 4: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

How to Find Method Execution Time in JavaPerformance is an important technical feature to focus on when you write Java programs. One of the easiestways to measure performance is to check the time taken by each method. Java provides a utility class Systemwhich is capable of returning the number of milliseconds elapsed since 1st January 1970. Using this we canmeasure the value before the method call and after the method call. The difference will give us the time takenby the method.

Following Java program shows how we can measure method execution time,

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

1 /**2 * Java program to measure method execution time3 */4 public class MethodExecutionTime 5 public static void main(String[] args) 6 MethodExecutionTime me = new MethodExecutionTime();7 long startTime = System.currentTimeMillis();8 float v = me.callSlowMethod();9 long endTime = System.currentTimeMillis();10 System.out.println("Seconds take for execution is:"+(endTime‐

startTime)/1000);11 12 /* Simulates a time consuming method */13 private float callSlowMethod() 14 float j=0;15 for(long i=0;i<5000000000L;i++) 16 j = i*i;17 18 return j;19 20

Page 5: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

How to Take Input From User in JavaWhether you are writing console programs or solving problems in Java, one of the common needs is to takeinput from the user. For console programs, you need to have access to the command line. Java has a utilityclass named Scanner which is capable of getting typed input from user. This class can directly convert userinput to basic types such as int, float and String.

The following example program demonstrates the use of java.util.Scanner for getting user input from commandline. It asks for user’s name and age and then prints it back. Note the automatic conversion of age to the intvariable. This is what makes Scanner so useful.

Please note that the scanner methods throw InputMismatchException exception if it doesn’t receive theexpected input. For example, if you try to enter alphabets when you called nextInt() method.

Scanner has methods such as nextInt, nextFloat, nextByte, nextDouble, nextBigDecimal, etc. to directly readtyped data from command line. To read a line of String, use nextLine method. Scanner also has a generic nextmethod to process an input which can be defined using a regular expression. If the input doesn’t match theregular expression, InputMismatchException is thrown.

The following code demonstrates the use of restricting the user input to a regular expression pattern,

1 import java.util.Scanner;2 3 /** This example program demonstrates how to get user input from

commandline in Java */4 public class UserInput 5 public static void main(String[] args) 6 UserInput ui = new UserInput();7 ui.getInputAndPrint();8 9 10 /** Takes a number of inputs from user and then prints it back */11 private void getInputAndPrint() 12 Scanner scn = new Scanner(System.in);13 System.out.print("Please enter your name: ");14 String name = scn.nextLine();15 System.out.print("Please enter your age: ");16 int age = scn.nextInt();17 System.out.println("Hello "+name+"! "+ "You are "+age+" years

old.");18 19

1 private void get4DigitNumber() 2 Scanner scn = new Scanner(System.in);3 String s = "";

4 Pattern p = Pattern.compile("\\d\\d\\d\\d");//get 4 digit number

Page 6: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code LibrariesStruts2

Mobile Platforms

4 Pattern p = Pattern.compile("\\d\\d\\d\\d");//get 4 digit number5 System.out.print("Please enter a 4 digit number: ");6 try 7 s = scn.next(p);8 System.out.println("4digit number is: "+s);9 catch(InputMismatchException ex) 10 System.out.println("Error! Doesn't match the pattern");11 12 13

Page 7: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

How To Reverse a String in JavaThere are a multiple ways to solve a programming problem. There may be library classes that may be veryuseful in solving programming problems. If you don’t know these classes and methods, you will end up spending time writing your own methods and wasting time. We would use the programming problem ofreversing a given String to illustrate this.

If you have a String such as "Hello", the reverse would be "olleH". The logic is easy to find, start from the endof the given string and then take each character till the beginning. Append all these characters to create thereversed String. The following program implements this logic to reverse a given String,

However there is a much easier way to reverse Strings. The StringBuilder class of Java has a built­in reversemethod! The following program demonstrates the usage of this library method. This is much better since wecan implement it faster and can be sure that the library method is well tested reducing the amount of bugs in

1 import java.util.Scanner;2 /**3 * Reverse a String given by user. Write our own reversing logic4 */5 public class ReverseString1 6 7 public static void main(String[] args) 8 ReverseString1 rs = new ReverseString1();9 System.out.print("Please enter String to reverse:");10 11 Scanner sn = new Scanner(System.in);12 String input = sn.nextLine();13 String output = rs.reverseString(input);14 System.out.println("The reverse form of "+input+" is "+output);15 16 17 /**18 * Our custom method to reverse a string.19 * @param input20 * @return21 */22 private String reverseString(String input) 23 String reversedString = "";24 char[] characters = input.toCharArray();25 for(int i=characters.length‐1;i>=0;i‐‐) 26 reversedString+=characters[i];27 28 return reversedString;29 30

Page 8: Java programming tips

your code. This is the approach you should follow when writing Java programs. Always make use of Javalibrary classes or reliable third party libraries to solve your problem.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

1 import java.util.Scanner;2 /**3 * Reverse a String given by user using Java library methods4 */5 public class ReverseString2 6 7 public static void main(String[] args) 8 ReverseString1 rs = new ReverseString1();9 System.out.print("Please enter String to reverse:");10 11 Scanner sn = new Scanner(System.in);12 String input = sn.nextLine();13 StringBuffer sb = new StringBuffer(input);14 String output = sb.reverse().toString();15 System.out.println("The reverse form of "+input+" is "+output);16 17

Page 9: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

How to do Linear Search in JavaLinear search is one of the simplest algorithms for searching data. In linear search, the entire data set issearched in a linear fashion for an input data. It is a kind of brute­force search and in the worst case scenario,the entire data set will have to be searched. Hence worst case cost is proportional to the number of elements indata set. The good thing about linear search is that the data set need not be ordered.

The following sample Java program demonstrates how linear search is performed to search a specific color in alist of colors. We sequentially take each color from the color list and compare with the color entered by theuser. On finding the color, we immediately stop the iteration and print the results.

1 import java.util.Scanner;2 3 /**4 * Example program in Java demonstrating linear search5 * @author6 */7 public class LinearSearchExample 8 private static final String[] COLOR_LIST = new String[] 9 "blue","red","green","yellow",

"blue","white","black","orange","pink"10 ;11 12 public static void main(String[] args) 13 System.out.println("Please enter a color to search for:");14 Scanner sn = new Scanner(System.in);15 String colorToSearch = sn.nextLine();16 17 LinearSearchExample ls = new LinearSearchExample();18 int position = ls.findColor(colorToSearch);19 if(position <0) 20 System.out.println("Sorry, the color is not found in the

list");21 else 22 System.out.println("Found color "+colorToSearch+" at position

"+position);23 24 25 26 /**27 * Demonstrates linear search in Java28 * Using linear search, looks up the color in a fixed list of colors29 * If color is found, the position is returned, else returns ‐130 * Since linear search goes through entire list of elements in the

worst case,31 * its cost is proportional to number of elements

32 * @param colorToSearch

Page 10: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code Libraries

32 * @param colorToSearch33 * @return34 */35 private int findColor(String colorToSearch) 36 int foundAt = ‐1;37 for(int i=0;i<COLOR_LIST.length;i++) 38 if(COLOR_LIST[i].equalsIgnoreCase(colorToSearch)) 39 foundAt = i;40 break;// found the color! no need to loop further!41 42 43 return foundAt;44 45

Page 11: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Splitting Strings in JavaOne of the common string processing requirements in computer programs is to split a string into sub stringsbased on a delimiter. This can be easily achieved in Java using its rich String API. The split function in Stringclass takes the delimiter as a parameter expressed in regular expression form.

The following Java program demonstrates the use of split function for splitting strings. Note that characterswhich has special meaning in regular expressions must be escaped using a slash (\) when passed as parameterto split function. Also note that an additional slash is required to escape slash in a Java string.

Please see this page on regular expressions for more details.

1 /**2 * Sample program to split strings in Java. The Java String API has a

built‐in3 * split function which uses regular expressions for splitting strings.4 *5 *6 */7 public class SplitString 8 9 public static void main(String[] args) 10 11 // Demo1 ‐ splitting comma separated string12 String commaSeparatedCountries = "India,USA,Canada,Germany";13 String[]countries = commaSeparatedCountries.split(",");14 // print each country!15 for(int i=0;i<countries.length;i++) 16 System.out.println(countries[i]);17 18 19 // Demo2 ‐ Splitting a domain name into its subdomains20 // The character dot (.) has special meaning in regular

expressions and21 // hence must be escaped. Double slash is required to escape

slash in Java22 // string.23 String fullDomain = "www.blog.quickprogrammingtips.com";24 String[] domainParts = fullDomain.split("\\.");25 26 for(int i=0;i<domainParts.length;i++) 27 System.out.println(domainParts[i]);28 29 30 31 // Demo3 ‐ Splitting a string using regular expressions

32 // In this example we want splitting on characters such as

Page 12: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code LibrariesStruts2

32 // In this example we want splitting on characters such ascomma,dot or

33 // pipe. We use the bracket expression defined in regularexpressions.

34 // Only dot(.) requires escaping.35 String delimtedText = "data1,data2|data3.data4";36 String[] components = delimtedText.split("[,|\\.]");37 38 for(int i=0;i<components.length;i++) 39 System.out.println(components[i]);40 41 42

Page 13: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Array to Map Conversion in JavaConverting an array of strings to a map of strings with the same string as key and value is required in many usecases. Conversion to map enables quick and easy evaluation as to whether a string exists in the list of strings.Conversion to map also enables removal of duplicate strings. The following Java program demonstratesconversion of an array of strings to its corresponding map.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

1 import java.util.HashMap;2 import java.util.Map;3 4 /**5 * Converts an array of strings to a map. Each string becomes the key and

the corresponding value.6 * Useful for removal of duplicates and quick check on existence of a

string in the list.7 * @author jj8 */9 public class ArrayToMap 10 11 public static void main(String[] args) 12 String[] colors = new String[]"blue","green","red";13 Map<String,String> colorMap = new HashMap<String,String>();14 for(String color:colors) 15 colorMap.put(color, color);16 17 18 19

Page 14: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Accessing Outer Class Local Variables from InnerClass MethodsWhen you try to compile the following Java code, you will get this error,

local variable a is accessed from within inner class; needs to be declared final

The simplest solution to fix this error is to declare the outer class local variable as final. The fixed code isgiven below,

Why outer class local variables cannot be accessed from inner classmethods?

Java language doesn’t support full fledged closures. So whenever an outer class local variable is accessed frominner class methods, Java passes a copy of the variable via auto generated inner class constructors. However ifthe variable is modified later in the outer class, it can create subtle errors in the program because effectivelythere are two copies of the variable which the programmer assumes to be the same instance. In order to removesuch subtle errors, Java mandates that only final local variables from the outer class method can be accessed in

1 public class Outer 2 3 public void test() 4 int a = 10;5 Runnable i = new Runnable() 6 7 @Override8 public void run() 9 int j = a * a;10 11 ;12 13

1 public class Outer 2 public void test() 3 final int a = 10;4 new Object() 5 public void test2() 6 int j = a * a;7 8 ;9 10

Page 15: Java programming tips

the inner class methods. Since final variables cannot be modified, even though a copy is made for inner class,effectively both instance values remain the same.

However in the case of outer class member variables, this is not an issue. This is because during the entire lifetime of inner class, an active instance of the outer class is available. Hence the same outer class instancevariable is shared by the inner class.

So there are basically two options to pass data from outer class to inner class,

Use final local variables in the outer class methodUse member variables in outer class

This means that passed local variables cannot be modified from the inner class method. However thisrestriction can be easily bypassed by using an array or a wrapper class. The following example showsmodifying the passed in local variable from the inner class by using an array wrapper,

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

1 public class Outer 2 public void test() 3 final int a[] = 10;4 Runnable i = new Runnable() 5 @Override6 public void run() 7 a[0] = a[0] * a[0];8 9 ;10 i.run();11 System.out.println(a[0]);12 13 14 public static void main(String[] args) 15 new Outer().test();16 17

Page 16: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Creating an Inline Array in JavaThe usual way of creating an array in Java is given below. In this example, we create a String array containingprimary color names,

The problem with this approach is that it is unnecessarily verbose. Also there is no need to create a temporaryarray variable to pass a constant list of values.

Java also provides an inline form of array creation which doesn’t need a temporary variable to be created. Youcan use the inline array form directly as a parameter to a method. Here is the above code example written usinginline Java arrays,

Still the above usage is not as concise as we want it to be. Alternatively you can also use the Varargs featureintroduced in Java 5. Whenever Varargs is used, the successive arguments to the method is automaticallyconverted to array members. This is the most concise way of creating an array inline! The above code examplecan be written as follows,

1 public class InlineArrays 2 3 public static void main(String[] args) 4 String[] colors = "red","green","blue";5 printColors(colors);6 7 public static void printColors(String[] colors) 8 for (String c : colors) 9 System.out.println(c);10 11 12 13

1 public class InlineArrays 2 3 public static void main(String[] args) 4 printColors(new String[]"red","green","blue" );5 6 public static void printColors(String[] colors) 7 for (String c : colors) 8 System.out.println(c);9 10 11 12

1 public class InlineArrays 2

3 public static void main(String[] args)

Page 17: Java programming tips

Note the use of … immediately after the String type in printColors() method definition. This instructs thecompiler to automatically convert one or more String arguments into array members of the variable colors.Inside the method you can treat colors as an array.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code LibrariesStruts2

3 public static void main(String[] args) 4 printColors("red","green","blue");5 6 public static void printColors(String... colors) 7 for (String c : colors) 8 System.out.println(c);9 10 11

Page 18: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Using BigInteger in JavaFor handling numbers, Java provides built­in types such as int and long. However these types are not useful forvery large numbers. When you do mathematical operations with int or long types and if the resulting values arevery large, the type variables will overflow causing errors in the program.

Java provides a custom class named BigInteger for handling very large integers (which is bigger than 64 bitvalues). This class can handle very large integers and the size of the integer is only limited by the availablememory of the JVM. However BigInteger should only be used if it is absolutely necessary as using BigIntegeris less intuitive compared to built­in types (since Java doesn’t support operator overloading) and there isalways a performance hit associated with its use. BigInteger operations are substantially slower than built­ininteger types. Also the memory space taken per BigInteger is substantially high (averages about 80 bytes on a64­bit JVM) compared to built­in types.

Another important aspect of BigInteger class is that it is immutable. This means that you cannot change thestored value of a BigInteger object, instead you need to assign the changed value to a new variable.

Java BigInteger Example

The following BigInteger example shows how a Java BigInteger can be created and how various arithmeticoperations can be performed on it,

Computing Factorial Using BigInteger

1 import java.math.BigInteger;2 3 public class BigIntegerDemo 4 5 public static void main(String[] args) 6 7 BigInteger b1 = new BigInteger("987654321987654321000000000");8 BigInteger b2 = new BigInteger("987654321987654321000000000");9 10 BigInteger product = b1.multiply(b2);11 BigInteger division = b1.divide(b2);12 13 System.out.println("product = " + product);14 System.out.println("division = " + division); // prints 115 16 17

Page 19: Java programming tips

Computation of factorial is a good example of numbers getting very large even for small inputs. We can useBigInteger to calculate factorial even for large numbers!

The factorial output for an input value of 50 is,

50! = 30414093201713378043612608166064768844377641568960512000000000000

Posted in Java category | 1 Comment

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

One Response to “Using BigInteger in Java”

1. kamals1986 on May 17th, 2015 at 5:18 am

Recursive version is cleaner:

BigInteger fatFactorial(int b) if (BigInteger.ONE.equals(BigInteger.valueOf(b))) return BigInteger.ONE; else return BigInteger.valueOf(b).multiply(fatFactorial(b – 1));

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

1 import java.math.BigInteger;2 public class BigIntegerFactorial 3 4 public static void main(String[] args) 5 calculateFactorial(50);6 7 public static void calculateFactorial(int n) 8 9 BigInteger result = BigInteger.ONE;10 for (int i=1; i<=n; i++) 11 result = result.multiply(BigInteger.valueOf(i));12 13 System.out.println(n + "! = " + result);14 15 16

Page 20: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Reading a Text File in JavaJava has an extensive API for file handling. The following code illustrates how Java File API can be used toread text files. This example shows line by line reading of the file content. This example also assumes that atext file with the name input.txt is present in the C:\ drive. If you are using a Linux system, replace the pathwith something like \home\tom\input.txt.

The above example reads lines from c:\input.txt file and outputs the lines on the console. Note the followingimportant points illustrated by this file reading program in Java,

File operations can throw checked IOException. Hence you need to explicitly handle them.When you use forward slash in path names, you need to escape its special meaning using an additionalforward slash.The class FileReader enables character by character reading of text files. However it has no facilities forreading lines.Java uses decorator pattern extensively in File API. In this example we use the BufferedReader decoratorclass over FileReader. The BufferedReader internally buffers the reading of characters and is also awareof line breaks. Even when a single character is read, BufferedReader internally reads a block ofcharacters from the file system. Hence whenever you request the next character, it is served from theinternal buffer not from file system. This makes BufferedReader very efficient compared to FileReader.The readLine() method returns null if BufferedReader encounters end of the file stream.

Posted in Java category | No Comments

1 import java.io.BufferedReader;2 import java.io.FileReader;3 import java.io.IOException;4 5 public class FileReaderDemo 6 7 public static void main(String[] args) 8 9 try 10 FileReader fr = new FileReader("c:\\input.txt");11 BufferedReader reader = new BufferedReader(fr);12 String line;13 while((line=reader.readLine())!=null) 14 System.out.println(line);15 16 catch(IOException ex) 17 ex.printStackTrace();18 19 20 21

Page 21: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Recursively Listing Files in a Directory in JavaUsing the File class in Java IO package (java.io.File) you can recursively list all files and directories under aspecific directory. There is no specific recursive search API in File class, however writing a recursive methodis trivial.

Recursively Listing Files in a Directory

The following method uses a recursive method to list all files under a specific directory tree. The isFile()method is used to filter out all the directories from the list. We iterate through all folders, however we will onlyprint the files encountered. If you are running this example on a Linux system, replace the value of the variablerootFolder with a path similar to /home/user/.

1 import java.io.File;2 3 public class FileFinder 4 5 public void listAllFiles(String path) 6 7 File root = new File(path);8 File[] list = root.listFiles();9 10 if (list != null) // In case of access error, list is null11 for (File f : list) 12 if (f.isDirectory()) 13 System.out.println(f.getAbsoluteFile());14 listAllFiles(f.getAbsolutePath());15 else 16 System.out.println(f.getAbsoluteFile());17 18 19 20 21 22 23 public static void main(String[] args) 24 FileFinder ff = new FileFinder();25 String rootFolder = "c:\\windows";26 System.out.println("List of all files under " + rootFolder);27 System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");28 ff.listAllFiles(rootFolder); // this will take a while to run!29 30

Page 22: Java programming tips

The return value of listFiles() will be null if the directory cannot be accessed by the Java program (for examplewhen a folder access requires administrative privileges). If you run it on the root folder in your file system, thisprogram will take a while to run!

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code Libraries

Struts2

Mobile PlatformsAndroid

Page 23: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Finding Number of Digits in a NumberThe following Java program finds the number of digits in a number. This program converts the number to astring and then prints its length,

The following is an alternate Java implementation which finds number of digits in a number withoutconverting it into a string. This program divides the number by 10 until the number becomes 0. The number ofiterations is equal to the number of digits.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

1 public class DigitsInNumber 2 3 public static void main(String[] args ) 4 int number = 94487;5 String s = String.valueOf(number);6 System.out.println(number + " has "+ s.length()+" digits");7 8

1 public class DigitsInNumber 2 3 public static void main(String[] args ) 4 int original_number = 1119;5 int n = original_number;6 int digits = 0;7 while(n > 0 ) 8 digits ++;9 n = n / 10;10 11 System.out.println(original_number + " has "+ digits+" digits");12 13

Page 24: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Removing a String from a String in JavaOne of the common text processing requirements is to remove a specific substring from a given string. Forexample, let us assume we have string "1,2,3,4,5" and we want to remove "3," from it to get the new string"1,2,4,5". The following Java program demonstrates how this can be achieved.

Java Program to Remove a Substring from a String

The key method here is replace(). This can be called on a string to replace the first parameter with the secondparameter. When the second parameter is a blank string, it effectively deletes the substring from the mainstring.

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

1 // Java program to remove a substring from a string2 public class RemoveSubString 3 4 public static void main(String[] args) 5 String master = "1,2,3,4,5";6 String to_remove="3,";7 8 String new_string = master.replace(to_remove, "");9 // the above line replaces the t_remove string with blank string

in master10 11 System.out.println(master);12 System.out.println(new_string);13 14 15

Page 25: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Find Number of Words in a String in JavaFinding number of a words in a String is a common problem in text processing. The Java string API andregular expression support in Java makes it a trivial problem.

Finding Word Count of a String in Java

The following Java program uses split() method and regular expressions to find the number of words in astring. Split() method can split a string into an array of strings. The splitting is done at substrings whichmatches the regular expression passed to the split() method. Here we pass a regular expression to match one ormore spaces. We also print the individual words after printing the word count.

The above examples works even with strings which contain multiple consecutive spaces. For example, thestring "This is a test" returns a count of 4. That is the beauty of regular expressions!

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

1 // Java program to find word count of a string2 import java.io.BufferedReader;3 import java.io.IOException;4 import java.io.InputStreamReader;5 6 public class WordCount 7 8 public static void main(String[] args) throws IOException 9 System.out.print("Please enter a string: ");10 BufferedReader reader = new BufferedReader(new

InputStreamReader(System.in));11 String string = reader.readLine();12 13 String[] words = string.split("\\s+"); // match one or more

spaces14 15 System.out.println("\""+string+"\""+" has "+words.length+"

words");16 System.out.println("The words are, ");17 for(int i =0;i<words.length;i++) 18 System.out.println(words[i]);19 20 21

Page 26: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Find Largest Number in an Array Using JavaThe following Java program finds the largest number in a given array. Initially the largest variable value is setas the smallest integer value (Integer.MIN_VALUE) and whenever a bigger number is found in array, it isoverwritten with the new value. We iterate through the entire array with the above logic to find the largestnumber.

Print the Largest Number in an Array Using Java

Posted in Java category | 1 Comment

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

One Response to “Find Largest Number in an Array Using Java”

1. Gary Lampley on December 5th, 2014 at 8:52 pm

I cannot get my program to run. im trying to find the maximum number from my array where I accept 10numbers from the keyboard but it’s not working.

Int number [] = 32, 42, 53, 54, 32, 65, 63, 98, 43, 23;int highest = Integer.MIN_VALUE;Scanner keyboard = new Scanner(System.in);

1 // Java program to find largest number in an array2 public class FindLargest 3 4 public static void main(String[] args) 5 int[] numbers = 88,33,55,23,64,123;6 int largest = Integer.MIN_VALUE;7 8 for(int i =0;i<numbers.length;i++) 9 if(numbers[i] > largest) 10 largest = numbers[i];11 12 13 14 System.out.println("Largest number in array is : " +largest);15 16

Page 27: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Find Smallest Number in an Array Using JavaThe following Java program prints the smallest number in a given array. This example uses an inline array,however it can be easily changed to a method taking an array as parameter. We loop through the arraycomparing whether the current smallest number is bigger than the array value. If yes, we replace the currentsmallest number with the array value. The initial value of the smallest number is set as Integer.MAX_VALUEwhich is the largest value an integer variable can have!

Find Smallest Number in an Array Using Java

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

1 // Java program to find smallest number in an array2 public class FindSmallest 3 4 public static void main(String[] args) 5 int[] numbers = 88,33,55,23,64,123;6 int smallest = Integer.MAX_VALUE;7 8 for(int i =0;i<numbers.length;i++) 9 if(smallest > numbers[i]) 10 smallest = numbers[i];11 12 13 14 System.out.println("Smallest number in array is : " +smallest);15 16

Page 28: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Java program to find average of numbers in anarrayOne of the common numerical needs in programs is to calculate the average of a list of numbers. This involvestaking the sum of the numbers and then dividing the result with the count of numbers.The following exampleillustrates the algorithm of finding average of a list of numbers,

Numbers are 12, 45, 98, 33 and 54 Sum = 12 + 45 + 98 + 33 + 54 = 242 Count of Numbers = 5 Average = Sum/Count = 242/5 = 48.4

Following is a sample Java program to calculate the average of numbers using an array. In this example, we usethe Java inline syntax to initialize an array of numbers. We have also provided a utility function if you want toread the numbers from command line. If you are using the utility function, invoke the program using thefollowing command line,

java CalcAverage 12 45 98 33 54

1 /**2 * Calculate average of a list of numbers using array3 */4 public class CalcAverage 5 public static void main(String[] args) 6 CalcAverage ca = new CalcAverage();7 int[] numbers = new int[]12, 45, 98, 33, 54;8 // Uncomment following line for inputting numbers from command

line9 //numbers = ca.getNumbersFromCommandLine(args);10 ca.findAndPrintAverage(numbers);11 12 13 private void findAndPrintAverage(int[] numbers) 14 // Use float for fractional results15 float sum=0.0f;16 for(int i=0;i<numbers.length;i++)17 sum += numbers[i];18 19 System.out.println("Average is "+sum/numbers.length);20 21 22 /**23 * Return an integer array of strings passed to command line24 * @param commandLine array of strings from command line25 * @return integer array26 */

Page 29: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code LibrariesStruts2

Mobile Platforms

26 */27 private int[] getNumbersFromCommandLine(String[] commandLine) 28 int[] result = new int[commandLine.length];29 for (int i =0;i<commandLine.length;i++)30 result[i] = Integer.parseInt(commandLine[i]);31 32 return result;33 34

Page 30: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Convert String to Date in JavaJava has a dedicated class for representing and manipulating dates. This full package name of this class isjava.util.Date. However when we receive date from external sources such as web services, we receive them asa String. The format of this date string depends on the source of the data. Hence we require conversion fromString to Date depending on how date is encoded in a String. Java has a utility class called SimpleDateFormatfor String to Date conversion.

The following program demonstrates how a String can be converted to a Date class. Note that in this example,the string is assumed to be in the form of “day of the month, full name of the month and full year” (26September 2015). The pattern for SimpleDateFormat in this case is “d MMMMM yyyy”. Please see this linkfor the full set of pattern characters available.

1 import java.text.ParseException;2 import java.text.SimpleDateFormat;3 import java.util.Date;4 5 /**6 * Converting a string to a Java date variable7 * @author jj8 */9 public class DateConvertor 10 11 //See

http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html12 //This pattern string is dependent on how date is represented in

String13 private static final String DATE_STRING_FORMAT="d MMMMM yyyy"; //26

September 201514 15 public static void main(String[] args) 16 DateConvertor dc = new DateConvertor();17 String dateString = "26 September 2015";18 Date date = dc.convert(dateString);19 System.out.println("Date is "+date);20 21 22 23 /**24 *25 * @param dateString date in string form26 * @return date in java.util.Date class27 */28 private Date convert(String dateString) 29 Date date = null;30 SimpleDateFormat sdf = new SimpleDateFormat(DATE_STRING_FORMAT);

31 try

Page 31: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish thesolution on this site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

JavaObjective­C

Web Programming

Java EE

Code LibrariesStruts2

Mobile Platforms

Android

31 try 32 date = sdf.parse(dateString);33 catch(ParseException px)34 System.out.println("Unable to parse date");35 36 return date;37 38

Page 32: Java programming tips

Quick Programming TipsA collection of programming wisdom!

HomePrivacy PolicyContact

Java Listing All Files In a DirectoryOne of the common file system needs during programming is to find all the files or subdirectories in a directory. In Java,it is pretty easy since java.io.File has simple methods to achieve this. The File class is capable of representing both filesand directories. This enables us to handle them in identical fashion, but using a simple check, we can differentiate them inthe code.

The following sample Java program lists all the files in a directory. For each entry found, we print its name indicatingwhether it is a directory or file. Note that the following example uses a Mac OS directory path (if you are using Windows,replace it with a path of the form – c:/dir1.

The following Java program lists all the files in a directory and also recursively traverses through subdirectories listingevery file and directory. For large directory structures, this can take a lot of time and memory. We have also added logicto print the entries indicating its position in the overall directory hierarchy,

1 import java.io.File;2 3 /**4 * Lists all files and directories under a directory. Subdirectory entries are

not listed.5 */6 public class FileLister 7 8 public static void main(String[] args) 9 FileLister fl = new FileLister();

10 String pathToDirectory = "/Users/jj/temp"; // replace this11 fl.listFilesInDirectory(pathToDirectory);12 13 14 /**15 *16 * @param pathToDirectory list all files/directories under this directory17 */18 private void listFilesInDirectory(String pathToDirectory) 19 File dir = new File(pathToDirectory);20 File[] files = dir.listFiles();21 22 for (File file:files) 23 if(file.isFile()) 24 System.out.println("FILE: "+file.getName());25 26 else if(file.isDirectory()) 27 System.out.println("DIR: "+file.getName());28 29 30 31

1 import java.io.File;2 3 /**

Page 33: Java programming tips

Posted in Java category | No Comments

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution onthis site within 48 hours! Please email us.

Leave a Reply

Name (required)

Mail (will not be published) (required)

Website

Submit Comment

Search

Programming Languages

3 /**4 * List all files and directories under a directory recursively.5 */6 public class FileListerRecursive 7 public static void main(String[] args) 8 FileListerRecursive fl = new FileListerRecursive();9 String pathToDirectory = "/Users/jj/temp";

10 fl.listFilesInDirectoryAndDescendents(pathToDirectory,"");11 12 13 /**14 * @param pathToDirectory15 * @param prefix This is appended with a dash every time this method is

recursively called16 */17 private void listFilesInDirectoryAndDescendents(String pathToDirectory,String

prefix) 18 File dir = new File(pathToDirectory);19 File[] files = dir.listFiles();20 21 for (File file:files) 22 if(file.isFile()) 23 System.out.println(prefix+"FILE: "+file.getName());24 25 else if(file.isDirectory()) 26 System.out.println(prefix+"DIR: "+file.getName());27 listFilesInDirectoryAndDescendents(file.getAbsolutePath(),prefix+"‐

");28 29 30 31