Java program to Get current date and time

  • By using date and calendar classes we can get current date and time in java.
  • By using SimpleDateFormat we can convert date into string format.
  • Create object of date.
  • Create object of SimpleDateFormat by passing required format to constructor
  • Format using object of SimpleDateFormat 




Using Date Object:


Java Program to get current date and time using Date object and SimpleDateFormat


  1. import java.text.DateFormat;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4.  
  5. public class GetDateTime {
  6.  
  7.     /**
  8.      * Get current date and time in java
  9.      * @author www.instanceofjava.com
  10.      */
  11.     public static void main(String[] args) {
  12.         
  13.         
  14.         DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  15.         Date date = new Date();
  16.         System.out.println(df.format(date));
  17.  
  18. }
  19. }

Output:


  1. 23-04-2017 19:43:23
Using Calendar Object:

Java Program to get current date and time using Calendar object and SimpleDateFormat


  1. import java.text.DateFormat;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Calendar;
  4.  
  5. public class GetDateTime {
  6.  
  7.     /**
  8.      * Get current date and time in java
  9.      * @author www.instanceofjava.com
  10.      */
  11.  public static void main(String[] args) {
  12.         
  13.         
  14.         DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
  15.         Calendar calendarobj = Calendar.getInstance();
  16.         System.out.println(df.format(calendarobj.getTime()));
  17.  }
  18.  
  19. }

Output:


  1. 23-04-2017 19:47:45
Java Program to get current date and time in mill seconds


get current date and time java

Java program to find maximum of two numbers using Math.max()

  • We can find maximum of two numbers by using if condition check.
  • In java.lang.Math class also having a method Math.max() which will take two numbers and returns maximum number.
  • We have separate methods for int , float , double and long.




  1.  public static double max(double a, double b)

Java program to find maximum of two double values using Math.max() method.


  1. package com.mathmax;
  2. public class MathMAx {
  3.     
  4.     /**
  5.      * Math.max() method in java
  6.      * @author www.instanceofjava.com
  7.      */
  8.  
  9.   public static void main(String[] args) {
  10.         
  11.         
  12.         double a = 234567;
  13.         double b =234557;
  14.      
  15.         double x = 764554;
  16.         double y =764464;
  17.         
  18.         System.out.println("Math.max(" + a + "," + b + ")=" + Math.max(a, b));
  19.         System.out.println("Math.max(" + x + "," + y + ")=" + Math.max(x, y));
  20.         
  21.     }
  22.  
  23. }
Output:

  1. Math.pow(3.0,4.0)=81.0
  2. Math.pow(4.0,3.0)=64.0
  3. Math.pow(4,2)=16.0

Java program to find maximum of two float values using Math.max() method.



math.max method in java float


Java program to find maximum of two int values using Math.max() method.
 
  1. package com.mathmax;
  2. public class MathMAx {
  3.     
  4.     /**
  5.      * Math.max() method in java
  6.      * @author www.instanceofjava.com
  7.      */
  8.  
  9. public static void main(String[] args) {
  10.         
  11.         System.out.println( Math.max(1, 1));
  12.         System.out.println( Math.max(1, 2));
  13.         System.out.println(Math.max(1.222f, 1.223f));
  14.         System.out.println(Math.max(1.222, 1.223));
  15.         
  16.     }
  17.  
  18. }

Output:

  1. 1
  2. 2
  3. 1.223
  4. 1.223

Find power using math.pow() in java

  • java.lang.Math.pow() method used to find the power of numbers.
  • It is a static method define in Math class so that we can call directly using classname.
  • Math.pow();
  • It takes two double arguments and return type is double.

  1. public final class Math extends Object
  1. public static double pow(double a, double b)



Java Program to explain the usage of Math.pow() method in java

  1. public class MathPow {
  2.  
  3.     /**
  4.      * Math.pow() method in java
  5.      * @author www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {
  8.     
  9.     
  10.     double a = 3.0;
  11.     double b = 4.0;
  12.  
  13.     
  14.     System.out.println("Math.pow(" + a + "," + b + ")=" + Math.pow(a, b));
  15.     System.out.println("Math.pow(" + b + "," + a + ")=" + Math.pow(b, a));
  16.    
  17.     System.out.println("Math.pow(4,2)="+Math.pow(4,2));
  18. }
  19.  
  20. }

Output:


  1. Math.pow(3.0,4.0)=81.0
  2. Math.pow(4.0,3.0)=64.0
  3. Math.pow(4,2)=16.0
math pow method in java

Math.round() method in java

  • By using java.lang.math.round in java we will get crossest numbers.
  • If we pass double number with some decimal points it will returns closest integer or long  number. 
  • If we pass float number with some decimal points it will return closest integer or long number.
  • Lets see an example program on how to use math.random() method.
  • Math.random() method will returns closest int or long numbers.



Java program to round double number using math.random() method in java


  1. package com.mathrandommethod;
  2.  
  3. public class MathRandom {
  4.         /**
  5.          * Math.random() in java
  6.          * @author www.instanceofjava.com
  7.          */
  8.     public static void main(String[] args) {
  9.         
  10.           float float1 = 23.34f;
  11.           float float2 = 23.623f;
  12.           double double1 = 234.433;
  13.          double double2 = 234.654;
  14.  
  15.           System.out.println(Math.round(float1));
  16.           System.out.println(Math.round(float2)); 
  17.           System.out.println(Math.round(double1)); 
  18.           System.out.println(Math.round(double2));
  19.  }
  20.  
  21. }
Output:

  1. 23
  2. 24
  3. 234
  4. 235
java math random

Java example program to round double to 2 decimal places

  • To round the decimal number in java we have DecimalFormat class in java.
  • By using DecimalFormat class format() method we can round double or float number to N decimal places.
  • Lets see a java program on how to round double to 2 decimal places.



 Java Program to round double number to 2 / 3 decimal places.


  1. package com.javarounddecimal;
  2. import java.text.DecimalFormat;
  3.  
  4. public class RoundDecimal {
  5.     /**
  6.      * java round double to 2 decimal places
  7.      * @author www.instanceofjava.com
  8.      */
  9.     public static void main(String[] args) {
  10.         
  11.         double number = 12.3712377;
  12.         DecimalFormat df1 = new DecimalFormat("#.##");
  13.         System.out.println(number + " is rounded to: " + df1.format(number));
  14.          
  15.         DecimalFormat df2 = new DecimalFormat("#.###");
  16.         System.out.println(number + " is rounded to: " + df2.format(number));
  17.          
  18.         number = 12.388654;
  19.         
  20.         DecimalFormat df3 = new DecimalFormat("#.##");
  21.         System.out.println(number + " is rounded to: " + df3.format(number));
  22.        
  23.         
  24.         DecimalFormat df4 = new DecimalFormat("#.###");
  25.         System.out.println(number + " is rounded to: " + df4.format(number));
  26.  
  27.     }
  28.  
  29. }
 Output:


  1. 12.3712377 is rounded to: 12.37
  2. 12.3712377 is rounded to: 12.371
  3. 12.388654 is rounded to: 12.39
  4. 12.388654 is rounded to: 12.389

  Java Program to round float number to 2 / 3 decimal places.


java round float to 2 decimal places




Output:

  1. 12.371238 is rounded to: 12.37
  2. 12.371238 is rounded to: 12.371
  3. 12.388654 is rounded to: 12.39
  4. 12.388654 is rounded to: 12.389

How to Sort list of objects by multiple fields in java

  • In order to compare objects we have comparable and comparator in java.
  • If you want to do custom sorting we will use comparator in java
  • We need to use different comparators for sorting objects by different fields.
  • And using Collections.sort(List, Comparator).
  • We can sort list of class objects by using cmparator.
  • By this we can compare two objects field by field. actually many.
  • Lets see an example program to sort list of student objects by name rollno and marks using comparator. Here comparator means we need to develop sorting logic in separate class which implements comparator interface and overrides compare() method.  
Program 1: Write a java example program to sort list of objects 

Student class:

  • Define a class as student add variables.
  • Define a constructor to assign values to variables.
  • Define a toString() method to print each variable value inside object values when we print object.

  1. package com.sortobjects;
  2. /**
  3.  * How to sort list of class objects
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class Student {
  8.     
  9.     String name;
  10.     int Rollno;
  11.     float marks;
  12.  
  13. Student(String name, int Rollno, float marks){
  14.         
  15.         this.name=name;
  16.         this.marks=marks;
  17.         this.Rollno=Rollno;
  18. }
  19.  
  20.     public String getName() {
  21.         return name;
  22.     }
  23.     public void setName(String name) {
  24.         this.name = name;
  25.     }
  26.     public int getRollno() {
  27.         return Rollno;
  28.     }
  29.     public void setRollno(int rollno) {
  30.         Rollno = rollno;
  31.     }
  32.     public float getMarks() {
  33.         return marks;
  34.     }
  35.     public void setMarks(float marks) {
  36.         this.marks = marks;
  37.     }
  38.     
  39. public String toString() {
  40.         return ("Name:"+name+"\tRollNo:"+Rollno+"\tMarks"+marks);
  41.     }
  42.  
  43. }

 NameComparator:

  • This class sort list of student class objects by name.

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class NameComparator implements Comparator<Student>{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return obj1.getName().compareTo(obj2.getName());
  13.     }
  14.    
  15.  
  16. }

 RollNoComparator :
  • This class sort list of student class objects by Rollno.


  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class RollNoComparator implements Comparator<Student>{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return ((Integer)obj1.getRollno()).compareTo((Integer)obj2.getRollno());
  13.     }
  14.    
  15.  
  16. }

MarksComparator:
  • This class will compare list of student class objects by marks

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3. public class MarksComparator implements Comparator<Student>{
  4.     /**
  5.      * How to sort list of class objects
  6.      * @author www.instanceofjava.com
  7.      */
  8.     @Override
  9.     public int compare(Student obj1, Student obj2) {
  10.          return ((Float)obj1.getMarks()).compareTo((Float)obj2.getMarks());
  11.     }
  12.  
  13. }

SortListObjects:
  •  Take a test class 
  • Create arraylist object and add Student objects with different values into list.
  • Using Collections.Sort(List,FiledComparator) pass corresponding comparator class in order to sort multiple fields of a class.


  1. package com.sortobjects;
  2. mport java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5.  
  6. /**
  7.  * How to sort list of class objects
  8.  * @author www.instanceofjava.com
  9.  */
  10.  
  11. public class SortListObjects {
  12.  
  13.      public static void main(String[] args){
  14.         
  15.         
  16.         List<Student> studentlst= new ArrayList<Student>();
  17.         
  18.         studentlst.add(new Student("Saisesh",1,80));
  19.         studentlst.add(new Student("Vinod",2,90));
  20.         studentlst.add(new Student("Ajay",3,95));
  21.         
  22.         System.out.println("** Before sorting **:");
  23.          
  24.         for (Student student : studentlst) {
  25.             System.out.println(student);
  26.         }
  27.         Collections.sort(studentlst,new NameComparator());
  28.         
  29.         System.out.println("** After sorting **");
  30.          
  31.         for (Student student : studentlst) {
  32.             System.out.println(student);
  33.         }
  34.     }
  35.  
  36. }
 Output:



sort list of objects java


  •  Like this we can compare list of objects by Rollno, and marks aslo. Please practice this example by sorting rollno and marks and check output. if you have any doubts then leave a comment.

 Chained comparator:
  • We can use chained comparator to sort list of class objects by multiple fields by passing multiple comparators.
  • java collections sort multiple comparators
  • The below program is example of chained comparator java


  1. package com.sortobjects;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Comparator;
  5. import java.util.List;
  6.  
  7. public class StudentChainedComparator implements Comparator<Student> {
  8.     
  9.      private List<Comparator<Student>> listComparators;
  10.      
  11.     
  12.         public StudentChainedComparator(Comparator<Student>... comparators) {
  13.             this.listComparators = Arrays.asList(comparators);
  14.         }
  15.      
  16.         @Override
  17.         public int compare(Student student1, Student student2) {
  18.             for (Comparator<Student> comparator : listComparators) {
  19.                 int result = comparator.compare(student1, student2);
  20.                 if (result != 0) {
  21.                     return result;
  22.                 }
  23.             }
  24.             return 0;
  25.         }
  26.  
  27.        
  28.  
  29. }
 
Java comparator multiple fields example:


  • Lets see an example of java comparatorchain in java


java comparator multiple fields example

Select Menu