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

5 Different ways to print arrays in java

  •  Arrays in java are used to hold similar data types values.
  • System.out.print() method does not print values of array.
  • In order to print array values we have different ways.
  • Normally we use for loop and by using index we will print each element inside array.
  • let us see how many ways we can able to print values of array. 


1.Print array in java using for loop
  • How to print array in java using for loop?
  • Yes we can print arrays elements using for loop.
  • Find the length of the array using array.length and take initial value as 0 and repeat until  array.length-1. 
  • Then access each index values of an array then print.
#1. Write a program to print array in java using for loop

  1. package arraysinterview;
  2.  
  3. public class PrintArray {
  4.  
  5.     /**
  6.      * How to print java array using for loop
  7.      * @author www.instanceofjava.com
  8.      */
  9.     
  10. public static void main(String [] args){
  11.         
  12.         int[] array = { 12,13,8,34,2,7,9,43,54,21};
  13.         
  14.         for (int i = 0; i < array.length; i++) {
  15.             System.out.println(array[i]);
  16.         }
  17.         
  18. }
  19.  
  20. }

Output:

  1. 12
  2. 13
  3. 8
  4. 34
  5. 2
  6. 7
  7. 9
  8. 43
  9. 54
  10. 21

2. Print string array in java using Enhanced for loop

  • From java 1.5 using enhanced for loop also we can print array values.

#2.   How to print string array in java using for each loop



3. Using Arrays.toString(array) method
  • By  using Arrays.toString(array) method we can print array values.

#3 Write a program to print array in java using Arrays.toString(array)

  1. package arraysinterview;
  2. import java.util.Arrays;
  3.  
  4. public class PrintArray {
  5.     /**
  6.      * How to print java array using Arrays.toString(array)
  7.      * @author www.instanceofjava.com     */
  8.  
  9.   public static void main(String [] args){
  10.         
  11.         String[] array = { "hi", "hello", "java"};
  12.         
  13.         
  14.    System.out.println(Arrays.toString(array));
  15.                
  16.   }
  17. }

Output:

  1. [hi, hello, java]
4.Using Arrays.deepToString(array) Method

  • Arrays,deepToString(array) method added in java 5 with generics and varargs.

#4 Write a program to print array in java using  Arrays.deepToString(array)

  1. package arraysinterview;
  2. import java.util.Arrays;
  3.  
  4. public class PrintArray {
  5.     /**
  6.      * How to print java array using Arrays.deepToString(array)
  7.      * @author www.instanceofjava.com     */
  8.  
  9.   public static void main(String [] args){
  10.         
  11.         int[][] array = new int[][]{
  12.                 {1,2,3},
  13.                 {11,12,13},
  14.                 {4 ,5,6},
  15.                 };
  16.         
  17.   System.out.println(Arrays.deepToString(array));
  18.       
  19.                
  20.   }
  21. }

Output:
  1. [[1, 2, 3], [11, 12, 13], [4, 5, 6]]

5.Using Arrays.asList(array) Method

  • Arrays,asList(array) method we can print array elements

#5 Write a program to print array in java using  Arrays.asList(array)

  1. package arraysinterview;
  2. import java.util.Arrays;
  3.  
  4. public class PrintArray {
  5.     /**
  6.      * How to print java array using Arrays.asList(array)
  7.      * @author www.instanceofjava.com     */
  8.  
  9.   public static void main(String [] args){
  10.         
  11.       int[] array ={1,2,3,4,5,6};        
  12.      System.out.println(Arrays.asList(array));
  13.  
  14.      String[] strarray ={"hi","array","print"};
  15.       System.out.println(Arrays.asList(strarray));
  16.                
  17.   }
  18. }

Output:
  1. [[I@2a139a55]
  2. [hi, array, print]

Exception handling multiple choice interview questions and answers in java

Select Menu