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,
import java.util.Date;
/**
* Convert number of milliseconds elapsed since 1st January 1970 to a java.util.Date
*/
public class MilliSecsToDate {
public static void main(String[] args) {
MilliSecsToDate md = new MilliSecsToDate();
// The long value returned represents number of milliseconds elapsed
// since 1st January 1970.
long millis = System.currentTimeMillis();
Date currentDate = new Date(millis);
System.out.println("Current Date is "+currentDate);
}
}
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 | Comments Off on Converting Milliseconds to Date in Java
If you are an experienced Android developer, here are 5 must watch videos to improve your Android skills. These videos cover not only advanced Android programming techniques but also stuff such as best practices in development, use of various frameworks, handling user expectation when you app becomes a Play Store success, etc. What makes these videos special is that these are from hardcore developers who have worked on the platform for a number of years building successful applications for Android.
Following videos are from well known Android developers such as Jake Wharton, Donn Felker and Michael Bailey. These videos also gives us a glimpse on how Android development is done in companies such as Twitter and Dropbox.
1. Android From Trenches by Donn Felker (Myfitnesspal, Groupon)
Donn Felker is one of the key developers behind Myfitnesspal app and Groupon app. This video is a collection of lessons learned from having these two apps in the top 100 on Google Play for 3 years. This video is packed with practical advice on developing Android apps, managing them on the Google Play Store and handling user expectations. Some of the key Android topics covered in this video are,
How to handle users when your app becomes a success on the Google Play Store?
Importance of unit testing and automation (Roboelectric, Expresso etc.)
Defensive coding
Use of frameworks such as Dagger, EventBus, Otto and Hugo
Jake Wharton is one of the superheroes in the world of Android developers. Jake starts off the video with a number of well known optimization techniques in Android to minimize memory, CPU and I/O usage. He calls these optimizations as “macro” optimizations and then points out that there are a number of micro optimizations that can have large impact on application performance and battery usage. Check out the video for these micro optimizations that you can apply while programming Android applications.
3. How the Main Thread Works by Michael Bailey (American Express)
In Android, the user interface operations run on a single thread known as the main thread. This thread uses queuing to schedule multiple UI events. It is very critical to keep this main thread responsive. Hence in Android, every large operation must be executed on a separate thread.
In this video, Michael Bailey gives an under the hood look at the Android main thread queuing system. A solid understanding of how main thread works is important for Android programmers.
4. Android At Dropbox by Aakash Kambuj (Dropbox)
This talk starts with the history of Dropbox and then Aakash proceeds to give a overview of Android development at Dropbox. The talk contains high level view of Dropbox architecture, specifically the photo loading process and onboarding flow in Dropbox app. The most interesting bit is the details of the product development process and how development teams are structured at Dropbox.
5. Android Programming - Pushing the Limits, Eric Hellmann (Spotify)
Eric Hellmann is the author of the book, Android Programming – Pushing the Limits and this talk explains the Android development tips contained in the book. Eric takes us through the efficient memory management and multi-threading techniques and correct use of Android components.
One 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 files and directories. This enables us to handle them in identical fashion, but using a simple check, we can differentiate them in the code.
The following sample Java program lists all the files in a directory. For each entry found, we print its name indicating whether 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.
import java.io.File;
/**
* Lists all files and directories under a directory. Subdirectory entries are not listed.
*/
public class FileLister {
public static void main(String[] args) {
FileLister fl = new FileLister();
String pathToDirectory = "/Users/jj/temp"; // replace this
fl.listFilesInDirectory(pathToDirectory);
}
/**
*
* @param pathToDirectory list all files/directories under this directory
*/
private void listFilesInDirectory(String pathToDirectory) {
File dir = new File(pathToDirectory);
File[] files = dir.listFiles();
for (File file:files) {
if(file.isFile()) {
System.out.println("FILE: "+file.getName());
}
else if(file.isDirectory()) {
System.out.println("DIR: "+file.getName());
}
}
}
}
The following Java program lists all the files in a directory and also recursively traverses through subdirectories listing every file and directory. For large directory structures, this can take a lot of time and memory. We have also added logic to print the entries indicating its position in the overall directory hierarchy,
import java.io.File;
/**
* List all files and directories under a directory recursively.
*/
public class FileListerRecursive {
public static void main(String[] args) {
FileListerRecursive fl = new FileListerRecursive();
String pathToDirectory = "/Users/jj/temp";
fl.listFilesInDirectoryAndDescendents(pathToDirectory,"");
}
/**
* @param pathToDirectory
* @param prefix This is appended with a dash every time this method is recursively called
*/
private void listFilesInDirectoryAndDescendents(String pathToDirectory,String prefix) {
File dir = new File(pathToDirectory);
File[] files = dir.listFiles();
for (File file:files) {
if(file.isFile()) {
System.out.println(prefix+"FILE: "+file.getName());
}
else if(file.isDirectory()) {
System.out.println(prefix+"DIR: "+file.getName());
listFilesInDirectoryAndDescendents(file.getAbsolutePath(),prefix+"-");
}
}
}
}
Posted in Java | Comments Off on Java Listing All Files In a Directory
Java has a dedicated class for representing and manipulating dates. This full package name of this class is java.util.Date. However when we receive date from external sources such as web services, we receive them as a String. The format of this date string depends on the source of the data. Hence we require conversion from String to Date depending on how date is encoded in a String. Java has a utility class called SimpleDateFormat for 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” (26 September 2015). The pattern for SimpleDateFormat in this case is “d MMMMM yyyy”. Please see this link for the full set of pattern characters available.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Converting a string to a Java date variable
* @author jj
*/
public class DateConvertor {
//See http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
//This pattern string is dependent on how date is represented in String
private static final String DATE_STRING_FORMAT="d MMMMM yyyy"; //26 September 2015
public static void main(String[] args) {
DateConvertor dc = new DateConvertor();
String dateString = "26 September 2015";
Date date = dc.convert(dateString);
System.out.println("Date is "+date);
}
/**
*
* @param dateString date in string form
* @return date in java.util.Date class
*/
private Date convert(String dateString) {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_STRING_FORMAT);
try {
date = sdf.parse(dateString);
}catch(ParseException px){
System.out.println("Unable to parse date");
}
return date;
}
}
Posted in Java | Comments Off on Convert String to Date in Java
One of the common numerical needs in programs is to calculate the average of a list of numbers. This involves taking the sum of the numbers and then dividing the result with the count of numbers.The following example illustrates 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 use the Java inline syntax to initialize an array of numbers. We have also provided a utility function if you want to read the numbers from command line. If you are using the utility function, invoke the program using the following command line,
java CalcAverage 12 45 98 33 54
/**
* Calculate average of a list of numbers using array
*/
public class CalcAverage {
public static void main(String[] args) {
CalcAverage ca = new CalcAverage();
int[] numbers = new int[]{12, 45, 98, 33, 54};
// Uncomment following line for inputting numbers from command line
//numbers = ca.getNumbersFromCommandLine(args);
ca.findAndPrintAverage(numbers);
}
private void findAndPrintAverage(int[] numbers) {
// Use float for fractional results
float sum=0.0f;
for(int i=0;i<numbers.length;i++){
sum += numbers[i];
}
System.out.println("Average is "+sum/numbers.length);
}
/**
* Return an integer array of strings passed to command line
* @param commandLine array of strings from command line
* @return integer array
*/
private int[] getNumbersFromCommandLine(String[] commandLine) {
int[] result = new int[commandLine.length];
for (int i =0;i<commandLine.length;i++){
result[i] = Integer.parseInt(commandLine[i]);
}
return result;
}
}
Posted in Java | Comments Off on Java program to find average of numbers in an array