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

Convert arraylist to array in java with example program

  • Inoder to convert arraylist to array normally we will try to iterate arraylist using loop and get each element and put it in an array.
  • But you know we have a predefined method in arraylist which convert list to array of elements in sequence order.
  • toArray() method inside arraylist class.



  1. public <T> T[] toArray(T[] a) {  }



  •  Lets see a java program on how to convert arraylist to array.

 Program #1: Java example program to covert arraylist to array using toArray() method


  1. package arraysinterview;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class ArrayListTOArray {
  6.  
  7.     public static void main(String[] args) {
  8.         List<String> list = new ArrayList<String>();
  9.         
  10.         list.add("array");
  11.         list.add("arraylist");
  12.         list.add("convertion");
  13.         list.add("javaprogram");
  14.         
  15.         String [] str = list.toArray(new String[list.size()]);
  16.         
  17.         for (int i = 0; i < str.length; i++) {
  18.             System.out.println(str[i]);
  19.         }
  20.  
  21.     }
  22.  
  23. }

Output:
  1. array
  2. arraylist
  3. convertion
  4. javaprogram

Program #2: Java example program to covert Integer arraylist to int array using toArray() method

  •  In this case toArray() method gives Integer array so we need to convert again Integer array to int array.



  1. package arraysinterview;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. public class ArrayListTOArray {
  6.  
  7.  public static void main(String[] args) {
  8.         List<Integer> list = new ArrayList<Integer>();
  9.         
  10.         list.add(10);
  11.         list.add(20);
  12.         list.add(30);
  13.         list.add(40);
  14.         list.add(50);
  15.         
  16.         Object[] integers = list.toArray();
  17.         
  18.         int[] intarray = new int[integers.length];
  19.         int i = 0;
  20.         for (Object n : integers) {
  21.             intarray[i++] = (Integer) n;
  22.             System.out.println(i);
  23.         }
  24.  
  25.     }
  26.  
  27. }



Output:
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5



Finalize() method in java with example program

  • finalize() method pre defined method which is present in java.lang.Object class.
  • finalize() method is protected  method defined in java.lang.Object class.
  • The finalize method is a method defined in the Object class in Java. It is called by the garbage collector before an object is garbage collected.
  • The finalize method can be overridden in a subclass to perform any cleanup that is required before the object is garbage collected. For example, if an object has opened a file, it may need to close that file in its finalize method.


  1. protected void finalize() throws Throwable{
  2.  
  3. }



1.What is purpose of overriding finalize() method?

  • The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

2.How many times does the garbage collector calls the finalize() method for an object? 

  • Only once.

3.What happens if an uncaught exception is thrown from during the execution of finalize() method of  an object?

  •  The exception will be ignored and the garbage collection (finalization) of that object terminates

  •  If we are overriding finalize() method then its our responsibility to call finalize() method explicitly.

  •  finalize() method never invoked more than once by JVM or any given object.
  • There is no guaranty that if we call finalize() method but we can force garbage collector by calling below two methods
  • System.gc();
  • Runtime.getRuntime().gc();

#1 : Java program to explain about finalize() method


  1. package inheritance
  2. public class B {
  3.  /**
  4.  * Finalize() method in java
  5.  * @author www.instanceofjava.com
  6.  */
  7.   @Override
  8.   protected void finalize() throws Throwable {
  9.             try{
  10.                 System.out.println("Inside Finalize() method of Sub Class : B");
  11.             }catch(Throwable t){
  12.                 throw t;
  13.             }finally{
  14.                 System.out.println("Calling finalize() method of Super Class:  Object");
  15.                 super.finalize();
  16.             }
  17.          
  18.  }
  19.  
  20. public static void main(String[] args) throws Throwable{
  21.         B obj= new B();
  22.         String str=new String("finalize method in java");
  23.         str=null;
  24.         obj.finalize();
  25.         
  26.         }
  27. }

finalize() method in java with example program
  • It is important to note that the finalize method is not guaranteed to be called, and it should not be relied upon for performing important tasks. It is generally better to use try-finally blocks to ensure that resources are properly cleaned up.
Here is an example of how the finalize method can be overridden in a subclass:

finalize method in java

Final method in java with example programs

  • If we declare any method as final by placing final keyword then that method becomes final method.
  • The main use of final method in java is they are not overridden.
  • We can not override final methods in sub classes.
  • If we are using inheritance and we need some methods not to overridden in sub classes then we need make it final so that those methods can not be overridden by sub classes. 
  • We can access final methods in sub class but we can not overridden final methods.



Defining a final method in java:

  • Add final keyword to the normal method then it will become final method.
  1. public final void method(){
  2. //code
  3.  }

What happens if we try to override final methods in sub classes?


#1 : Java program to explain about final method in java

  1. package inheritance;
  2. /**
  3.  * final methods in java with example program
  4.  * @author www.instanceofjava.com
  5.  */
  6. public class A {
  7.  
  8.     int a,b;
  9.     
  10.     public final void show(){
  11.         System.out.println("A class show method");
  12.     }
  13. }

final method in java with example program

Can we access final methods in sub classes?

  • Yes we can access final methods in sub classes.
  • As mentioned above we can access all super class final methods in sub class but we can not override super call final methods.

#2 : Java program to explain about final method in java

  1. package inheritance;
  2. /**
  3.  * final methods in java with example program
  4.  * @author www.instanceofjava.com
  5.  */
  6. public class A {
  7.  
  8.     int a,b;
  9.     
  10.     public final void show(){
  11.         System.out.println("A class show method");
  12.     }
  13. }

  1. package inheritance;
  2.  
  3. /**
  4.  * final methods in java with example program
  5.  * @author www.instanceofjava.com
  6.  */
  7.  
  8. public class B {
  9.     
  10.  public static void main(String[] args){
  11.         
  12.         B obj = new B();
  13.         obj.show();
  14.        
  15.     }
  16. }

Output:
  1. A class show method

Top 10 Java interview questions on final keyword 

Static method vs final static method in java with example programs  

Final static string vs Static string in java  

Format text using printf() method in java

printf method in java:

  • Print() and println() methods are used to print text and object values or format data.
  • In order to format text we also have printf() method in java
  • Formatting data means displaying corresponding data type value. 
  • For example when print float ot double value if we want to specify upto 2 decimal numbers we user.
  • System.out.printf("%.2f", variable); 
  • Also alignment of string data. when we are printing string data in java using print() and pintf() 



#1. Write a program to print string using print() and printf() methods


  1. package printfinjava;
  2. /**
  3.  * How to format text using java printf() method
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class PrintfMethod {
  8.  
  9.     public static void main(String[] args) {
  10.         String str="java printf double";
  11.         
  12.         System.out.println ("String is "+str);
  13.         System.out.printf ("String is %s", str);
  14.  
  15.     }
  16.  
  17. }
Output:

  1. String is java printf double
  2. String is java printf double

java printf table



printf in java double int string


Format double using printf():
  • We can format double using printf() method in java
  • format double to 2 decimal places in java possible by using system.out.printf() method.

#2. Write a program to print double to 2 decimal places in java

  1. package printfinjava;
  2. /**
  3.  * How to format text using java printf() method
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class PrintfMethod {
  8.  
  9. public static void main(String[] args) {
  10.  
  11.      double value=12.239344;
  12.      System.out.printf("%.2f", value);
  13.  
  14. }
  15.  
  16. }
Output:

  1. 12.24

#3. Write a program to format text using printf() method in java


printf in java double
Select Menu