English
Follow Us Online
Twitter    YouTube(TM)
Declare constants
Define enum
Define a method
Exit program
Exit a for loop
Exit a method
Format date
Format double
Find current directory
Get current date
Get user input
Get Class name
Java How to A B C D E F G H I J K L M N O P Q R S T U V W Y W Z
Java How to format date
Related Links Format date Format double Find current directory Next Page >>>
Steps:
  1. Instantiate the Date class to fetch the current date.
  2. SimpleDateFormat class which extends Format class, is used to format date. Constructor of SimpleDateFormat class takes the pattern in which the date should be formatted.
  3. format(Object obj) method of Format class formats the given date to return a String of the specified pattern.
/**
 * Example showing how to format date
 * 
 * @author www.f5java.com
 * @return : void
 */
public void formatDateExample() {
	// 1. Instantiate the Date class to fetch the current date
	Date date = new Date();

	// 2. Pass the  date pattern in the constructor of SimpleDateFormat to which the date should be formatted
	Format sdFormat = new SimpleDateFormat("dd-MMM-yy");

	// 3. Invoke format() method passing the date argument to be formatted
	System.out.println("Date is :: " + sdFormat.format(date));
}
     
Java How to format double
Steps:
  1. DecimalFormat class which is a subclass of NumberFormat class, is used to format (or round) the double value.
  2. Specify the pattern in which the decimal number should be formatted as an argument in the DecimalFormat constructor.
  3. Invoke the format() method to return a String obtained after rounding up the given decimal value.
/**
 * Example showing how to format double
 * 
 * @author www.f5java.com
 * @return : void
 */
public void formatDoubleExample() {
	double value = 23;
	NumberFormat nf = new DecimalFormat("#00.00");
	// 3. Invoke format() to format the double value
	System.out.println(nf.format(value));
}
     
Java How to find current directory
Steps:
  1. Create a new File instance for the current directory "."; The constructor argument is converted to the abstract pathname.
  2. Invoke getCanonicalPath() method on this File instance. This method returns the absolute path of the abstract pathname which is "." in this case.
/**
 * Example showing how to find current directory
 * 
 * @author www.f5java.com
 * @return : void
 */
public void findCurrentDirectoryExample() {
	// 1. Create new File instance for the current directory
	File directory = new File(".");

	try {
		// 2. Invoke getCanonicalPath() method on the File instance to get the absolute path
		System.out.println("Current directory :: " + directory.getCanonicalPath());
	} catch (IOException e) { //getCanonicalPath() method throws IOException, so caller has to handle it.
		System.out.println("Exception in geting cuurent directory " + e.getMessage());
	}
}