Wednesday, 19 July 2017

Reflection in Java - Field

Reflection in Java class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class fields, constructors, methods.

Member Interface

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor. Thus Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

This post talks about Field class and the methods it provides in detail. Class fields have a type and a value, the java.lang.reflect.Field class provides methods for accessing type information, field’s modifier and setting and getting values of a field on a given object.

How to get Field object

There are 4 methods for getting fields of the class.

  • getField(String name) - Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
  • getFields() - Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
  • getDeclaredField(String name) - Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
  • getDeclaredFields() - Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

So getFields() methods will only return object for public fields where as getDeclaredField() methods will return all the fields.

Example code

In this example generic class ReflectField is used which has few fields with access modifier as public or private.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class ReflectField<T> {
     public String name = "Test";
     private int i = 10;
     public List<Integer> numList;
     public T val;
     
     public static void main(String arg[]){
      try {
       Class<?> c = Class.forName("org.netjs.prog.ReflectField");
       try {
        Field f = c.getField("name");
        System.out.println("Name field " + f.getName());
        
        Field[] fields = c.getFields();
        System.out.println("All Fields - " + Arrays.toString(fields));
        
        fields = c.getDeclaredFields();
        
        System.out.println("Declared Fields - " + Arrays.toString(fields));
       } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
       
      }catch (ClassNotFoundException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
    }
}

Output

Name field name

All Fields - [public java.lang.String org.netjs.prog.ReflectField.name, public java.util.List org.netjs.prog.ReflectField.numList, 
public java.lang.Object org.netjs.prog.ReflectField.val]

Declared Fields - [public java.lang.String org.netjs.prog.ReflectField.name, private int org.netjs.prog.ReflectField.i, 
public java.util.List org.netjs.prog.ReflectField.numList, public java.lang.Object org.netjs.prog.ReflectField.val]

You can see here getFields() return array of all public fields in the class where as getDeclaredFields() return all the fields (field i is having access modifier as private).

Getting the field type

If you want to know the types of fields in any class reflectively you can do it using the methods getType() and getGenericType() methods.

Example code

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){
    System.out.println("Field name - " + field.getName() + " has Field Type " + field.getType());
    System.out.println("Field name - " + field.getName() + " has Generic Field Type " + field.getGenericType());
}

Output

Field name - name has Field Type class java.lang.String
Field name - name has Generic Field Type class java.lang.String
Field name - i has Field Type int
Field name - i has Generic Field Type int
Field name - numList has Field Type interface java.util.List
Field name - numList has Generic Field Type java.util.List<java.lang.Integer>
Field name - val has Field Type class java.lang.Object
Field name - val has Generic Field Type T

Here notice that the type for the field val is displayed as java.lang.Object because generics are implemented via type erasure which removes all information regarding generic types during compilation. Thus T is replaced by the upper bound of the type variable, in this case, java.lang.Object.

Getting field modifiers

You can get the field modifiers by using the getModifiers() method. This method returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.

Example code

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){     
    System.out.println("Field name - " + field.getName() + " has modifier " + Modifier.toString(field.getModifiers()));
}

Output

Field name - name has modifier public
Field name - i has modifier private
Field name - numList has modifier public
Field name - val has modifier public

Getting and Setting Field Values

If you have an object of a class, using reflection you can set the values of fields in that class. This is typically done only in special circumstances when setting the values in the usual way is not possible. Because such access usually violates the design intentions of the class, it should be used with the utmost discretion.

Example code

Given a public field name which is of type String here the new value is set to the field name.

public String name = "Test";
Class<?> c = Class.forName("org.netjs.prog.ReflectField");
ReflectField rf = new ReflectField();
Field f = c.getField("name");
// getting the field value
System.out.println("Value of field name " + f.get(rf));
// setting the new field value
f.set(rf, "New Value");
System.out.println("Value of field name " + rf.name);

Output

Value of field name Test
Value of field name New Value

That's all for this topic Reflection in Java - Field. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reflection in Java
  2. Reflection in Java - Class
  3. Object cloning in java
  4. Serialization in Java

You may also like -

>>>Go to Java advance topics page

Monday, 17 July 2017

Reflection in Java - Class

For every type of object JVM creates an immutable instance of java.lang.Class which provides methods to examine the runtime properties of the object including its members and type information. Class also provides the ability to create new classes and objects.

With the exception of java.lang.reflect.ReflectPermission, none of the classes in java.lang.reflect have public constructors. To get to these classes, it is necessary to invoke appropriate methods on Class. So you can say that the entry point for all reflection operations is java.lang.Class.

How to get Class

There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class.

Object.getClass()

If you have an instance of the class available, then you can get Class by invoking Object.getClass() method. This method will only work with reference types.

For Example – If you have a class called ClassA and an object objA of that class then you can get instance of Class as follows –

ClassA objA = new ClassA();
Class<?> cls = objA.getClass();

Using .class Syntax

If instance of the class is not available but the type is known, then you can get object of Class by using .class syntax. You just need to add “.class” to the name of the type. Using .class you can also get the Class for a primitive type.

For Example – If you want class object for type Boolean.

boolean b;
Class cls = boolean.class;

Note here that type (Boolean) is used to get instance of Class.

Same way if you want Class object for ClassA.

ClassA objA;
Class<?> cls1 = ClassA.class;

Then if you want to instantiate class object objA you can do that using class.newInstance() method.

try {
 objA = (ClassA)cls1.newInstance();
 objA.setI(12);
 System.out.println("Value of i " + objA.getI());
} catch (InstantiationException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
} catch (IllegalAccessException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}

Using Class.forName()

You can also get the instance of the class using the static method Class.forName().Make sure that you pass the fully-qualified class name. Which means you will have to include package names too.

For example – If you want instance of Class for ClassA which is residing in package org.prgm then do it as follows –

Class<?> c = Class.forName("org.prgm.ClassA");

Using TYPE Field for Primitive Type Wrappers

Wrapper classes for the primitive types have a field named TYPE which is equal to the Class for the primitive type being wrapped.

For example –

Class cls1 = Integer.TYPE;

Methods provided by class Class

There are many methods provided by the class Class to get the metadata about the class. Let’s go through an example to see some of these methods in practice.

Example code

As a preparation for the example code let’s have a class called Parent.java which will be extended by the class ChildClass.java which is the class we are going to examine. There is also an interface IntTest.java which is implemented by ChildClass.java.

Parent class

public class Parent {
 String name;
 Parent(String name){
  this.name = name;
 }

 public void displayName(){
  System.out.println("Hello - " + name);
 }
 
 public String getName(){
  return name;
 }
}

IntTest interface

public interface IntTest {
   public void showValue();
}

ChildClass.java

public class ChildClass extends Parent implements IntTest{
 private int value;
 //Constructor
 public ChildClass(String name, int value) {
  super(name);
  this.value = value;
 }

 @Override
 public void showValue() {
  System.out.println("Value - " + value);
  
 }
}

Based on these classes let us see some of the methods provided by class Class.

To get the class name

If you want to get the class name using the instance of the Class.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("Class name " + c.getName());
System.out.println("Class name " + c.getSimpleName());

Output

Class name org.prgm.ChildClass
Class name ChildClass

As you can see using the method getName() gives you the fully qualified name whereas getSimpleName() method gives you only the class name.

Getting super class

getSuperClass() method can be used for getting Super class. Returns the Class representing the superclass of the entity represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("Super Class name " + c.getSuperclass());

Output

Super Class name - class org.prgm.Parent

Getting implemented or extended interfaces

getInterfaces() method can be used for getting the interfaces. If the object on which you are calling this method represents a class, the return value is an array containing objects representing all interfaces implemented by the class. If this object represents an interface, the array contains objects representing all interfaces extended by the interface.

Class<?> c = Class.forName("org.prgm.ChildClass");
System.out.println("interfaces - " + Arrays.toString(c.getInterfaces()));

Output

interfaces - [interface org.prgm.IntTest]

Getting class modifier

You can get the class modifier by using the getModifiers() method. Returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier.

Class<?> c = Class.forName("org.prgm.ChildClass");
   
int modifiers = c.getModifiers();
System.out.println("Modifier - " + Modifier.toString(modifiers));

Output

Modifier – public

Getting fields of the class

There are 4 methods for getting fields of the class. If you want Field object for any specific field then you can use getDeclaredField(String name) or getField(String name) method. To get information for all the fields of the class you can following two methods.

  • getFields() - Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
  • getDeclaredFields() - Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.
Class<?> c = Class.forName("org.prgm.ChildClass");

// Getting fields of the class
Field[] allFields = c.getFields();
System.out.println("All Fields - " + Arrays.toString(allFields));

// Getting fields of the class
Field[] fields = c.getDeclaredFields();
System.out.println("Fields - " + Arrays.toString(fields));

Output

All Fields - []
Fields - [private int org.prgm.ChildClass.value]

Since ChildClass.java doesn’t have any accessible public field (inherited or its own) so no value is returned for getFields() method.

There is one private field in ChildClass.java, getDeclaredFields() method shows that field.

Getting constructors of the class

There are four methods for getting the constructors of the class. If you want Constructor object for any specific constructor, then you can use getConstructor(Class<?>... parameterTypes) or getDeclaredConstructor(Class<?>... parameterTypes) method. To get all the constructors of the class you can use following two methods.

  • getDeclaredConstructors() - Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors.
  • getConstructors()- Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.
Class<?> c = Class.forName("org.prgm.ChildClass");

Constructor<?>[] constructors = c.getConstructors();
System.out.println("Constructors - " + Arrays.toString(constructors));
   
Constructor<?>[] Decconstructors = c.getDeclaredConstructors();
System.out.println("Declared constructors - " + Arrays.toString(Decconstructors));

Output

Constructors - [public org.prgm.ChildClass(java.lang.String,int)]
Declared constructors - [public org.prgm.ChildClass(java.lang.String,int)]

Since class ChildClass has only one public constructor so both methods are returning the same array of Constructor objects.

Getting methods of the class

There are four methods for getting the methods of the class. If you want Method object for any specific constructor, then you can use getMethod(String name, Class<?>... parameterTypes) or getDeclaredMethod(String name, Class<?>... parameterTypes) method. To get all the methods of the class you can use following two methods.

  • getDeclaredMethods() - Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.
  • getMethods() - Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.
Class<?> c = Class.forName("org.prgm.ChildClass");

// Getting all methods (even inherited) of the class
Method[] methods = c.getMethods();
System.out.println("All Methods - " + Arrays.toString(methods));
   
// Getting methods of the class
methods = c.getDeclaredMethods();
System.out.println("Class Methods - " + Arrays.toString(methods));

Output

All Methods - [public void org.prgm.ChildClass.showValue(), public java.lang.String org.prgm.Parent.getName(), 
public void org.prgm.Parent.displayName(), public final void java.lang.Object.wait() throws java.lang.InterruptedException, 
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, 
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, 
public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), 
public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), 
public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]

Class Methods - [public void org.prgm.ChildClass.showValue()]

Here you can see how getMethods() shows all the methods even inherited one.

Getting annotations

You can use following two methods to get information about the annotations.

  • getAnnotations() - Returns annotations that are present on this element. If there are no annotations present on this element, the return value is an array of length 0.
  • getDeclaredAnnotations() - Returns annotations that are directly present on this element. This method ignores inherited annotations. If there are no annotations directly present on this element, the return value is an array of length 0.
Class<?> c = Class.forName("org.prgm.ChildClass");
   
Annotation[] annotations = c.getAnnotations();
System.out.println("Annotations - " + Arrays.toString(annotations));
   
Annotation[] Decannotations = c.getDeclaredAnnotations();
System.out.println("Annotations - " + Arrays.toString(Decannotations));

Output

Annotations - []
Annotations - []

Since there are no annotations present on the class so array length is zero for both methods. Note that these methods can be used in the same way with the object of Method or Field class to get annotations present on a method or a field.

That's all for this topic Reflection in Java-class. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reflection in Java
  2. Reflection in Java - Field
  3. Nested class and Inner class in Java
  4. Object cloning in java
  5. Serialization in Java

You may also like -

>>>Go to Java advance topics page

Wednesday, 12 July 2017

Reflection in Java

As per Wikipedia; in computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime.

Thus the Reflection API in Java provides the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.

Using reflection API we can inspect a class and get information about the fields, methods, constructors, implemented interfaces, super classes at run time. We can invoke a method at run time. Using reflection we can also dynamically create and access Java arrays, examine the Enums. Using reflection we can even access a private field and invoke a private method from another class!

Where is it used?

Though you may not have a need to use reflection API in your application but you may be seeing its usage in many tools or applications you are using.

  1. The IDE like Eclipse giving you the list of methods in a class, auto completing the field or method name.
  2. Your persistence framework matching the fields in your objects with the fields in the DB table at runtime.
  3. Junit getting the information about the methods to be invoked.
  4. Spring framework getting the class information using the bean definition and also getting the setters and getters or constructor of the class. So you can say dependency injection in Spring depends heavily on reflection.

Drawbacks of Reflection

Reflection provides a lot of power so it should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. Some of the drawbacks of Reflection are –

  1. Performance Overhead – Since reflection resolves types dynamically certain JVM optimizations can’t be performed. Thus the reflective operations have slower performance than their non-reflective counterparts. That means use of reflection in the sections of code which are called frequently in performance-sensitive applications should be avoided.
  2. Security Restrictions - Reflection requires a runtime permission which may not be present when running under a security manager. Thus the code which has to run in a restricted security context should avoid reflection.
  3. Against Object oriented principles - Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

Reflection API

Some of the main classes and interfaces which you will use while using reflection are as follows –

  • Class - For every type of object, JVM instantiates an immutable instance of java.lang.Class (Note that Class itself is not part of Reflection API) which provides methods to examine the runtime properties of the object including its members and type information. Class also provides the ability to create new classes and objects. Most importantly, it is the entry point for all of the Reflection APIs.
  • Member - Reflection defines an interface java.lang.reflect.Member which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor which can be used to get information about class members.
  • Field - Field class provides methods for accessing type information and setting and getting values of a field on a given object.
  • Method - Method class provides methods for obtaining the type information for the parameters and return value. It may also be used to invoke methods on a given object.
  • Constructor - Constructor class provides methods for obtaining the information about the constructors of the class. If you reflectively invoke a constructor it will create a new instance of an object for a given class.
  • Array - The Array class provides static methods to dynamically create and access Java arrays. Reflection provides methods for accessing array types and array component types, creating new arrays, and retrieving and setting array component values.

Example code

Though we’ll go into more details about the Reflection API in posts about refelction API for class and refelction API for member but here also let’s see an example of Reflection API to get an idea about how to use it.

Here we have a class ClassA which has a constructor, private fields and getters and setters.

package org.prgm;

public class ClassA {
 private int i;
 private int j;
 // Constructor
 public ClassA(int i, int j){
  this.i = i;
  this.j = j;
 }
 public void setI(int i) {
  this.i = i;
 }
 public void setJ(int j) {
  this.j = j;
 }
 public int getI() {
  return i;
 }
 public int getJ() {
  return j;
 }
}

Using the following class you can get information about the constructor of the class, fields of the class and class methods.

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class ReflectionDemo {

 public static void main(String[] args) {
  try {
   Class<?> c = Class.forName("org.prgm.ClassA");
   // Getting constructors of the class
   Constructor<?>[] constructors = c.getConstructors();
   System.out.println("Constructors - " + Arrays.toString(constructors));
   
   // Getting all methods (even inherited) of the class
   Method[] methods = c.getMethods();
   System.out.println("All Methods - " + Arrays.toString(methods));
   
   // Getting methods of the class
   methods = c.getDeclaredMethods();
   System.out.println("Class Methods - " + Arrays.toString(methods));
   
   // Getting fields of the class
   Field[] fields = c.getDeclaredFields();
   System.out.println("Fields - " + Arrays.toString(fields));
   
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  

 }

}

Output

Constructors - [public org.prgm.ClassA(int,int)]

All Methods - [public int org.prgm.ClassA.getI(), public void org.prgm.ClassA.setI(int), public void org.prgm.ClassA.setJ(int), 
public int org.prgm.ClassA.getJ(), public final void java.lang.Object.wait() throws java.lang.InterruptedException, 
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException, 
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException, 
public boolean java.lang.Object.equals(java.lang.Object), public java.lang.String java.lang.Object.toString(), 
public native int java.lang.Object.hashCode(), public final native java.lang.Class java.lang.Object.getClass(), 
public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll()]

Class Methods - [public int org.prgm.ClassA.getI(), public void org.prgm.ClassA.setI(int), public void org.prgm.ClassA.setJ(int), 
public int org.prgm.ClassA.getJ()]

Fields - [private int org.prgm.ClassA.i, private int org.prgm.ClassA.j]

Reference - https://docs.oracle.com/javase/tutorial/reflect/index.html

That's all for this topic Reflection in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reflection in Java - Class
  2. Reflection in Java - Field
  3. Object cloning in java
  4. Serialization in Java

You may also like -

>>>Go to Java advance topics page

Monday, 10 July 2017

How to remove elements from an array - Java Program

Removing element from an array may look like a simple task but it comes with its own set of problems. Those problems stem from the fact that array in Java is fixed in length. Which means you can't just remove an element from the given index in an array. You will need to shift, all the elements that are after the element that has to be removed, left by one element.

Also the array size will still not reduce and the element that is at the end will be repeated to fill the empty space.

Let's try to clarify it with an example -

Here the array removal is done without using any third party tool (like Apache common utils) or any data structure provided by the Java language (Like Collection classes).

So the steps to remove the elements, followed in the code are -

  1. Ask the user to enter the element to be removed.
  2. Search in the array for the given element.
  3. If found shift all the element after that index to the left by one element. As example if element to be deleted is at index i then remove all the elements from index i+1 to array.length by one element which means element at i+1 will come at index i.

Java program to remove element from an array

 
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
        int elem = in.nextInt();
        
        for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }
      
        System.out.println("Elements -- " );
        for(int i = 0; i < intArr.length; i++){
            System.out.print(" " + intArr[i]);
        }                
    }
}

Output

Enter Element to be deleted : 5
Elements -- 
 1 2 12 7 3 8 8

If you notice last element 8 is repeated to fill the space that is left after shifting the elements.

Alternatives

You can fill the empty space with 0, space or null depending on whether it is primitive array, string array or an Object array.

Other alternative is to create a new array and copy the elements in that array. New array should have size of old array’s size – 1.

Let’s see an example where new array is used -

 
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        int[] newArr = null;
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
        
        /*for(int i = 0; i < intArr.length; i++){
            if(intArr[i] == elem){
                
                for(int j = i; j < intArr.length - 1; j++){
                    intArr[j] = intArr[j+1];
                }
                break;
            }
        }*/
        
         for(int i = 0; i < intArr.length; i++){
             if(intArr[i] == elem){
                newArr = new int[intArr.length - 1];
                for(int index = 0; index < i; index++){
                    newArr[index] = intArr[index];
                }
                for(int j = i; j < intArr.length - 1; j++){
                    newArr[j] = intArr[j+1];
                }
                break;
             }
         }
         System.out.println("Elements -- " );      
         for(int i = 0; i < newArr.length; i++){
             System.out.print(" " + newArr[i]);
         }                
    }

}

Output

Enter Element to be deleted : 
5
Elements -- 
 1 2 12 7 3 8

Enter Element to be deleted : 8
Elements -- 
 1 2 5 12 7 3

With copying the element to the new array problem of empty space is solved.

Using ArrayUtils to remove element from an array

If you can use Apache commons in your application then there is a utility class ArrayUtils that can be used to remove elements from an array.

Example code

 
import java.util.Scanner;
import org.apache.commons.lang3.ArrayUtils;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        System.out.print("Enter Element to be deleted : ");
            int elem = in.nextInt();
            for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                // Using ArrayUtils
                intArr = ArrayUtils.remove(intArr, i);
                break;
              }
          }
        
          System.out.println("Elements -- " );
          for(int i = 0; i < intArr.length; i++){
              System.out.print(" " + intArr[i]);
          }
    }
}

Output

Enter Element to be deleted : 2
Elements -- 
 1 5 12 7 3 8

Using System.arraycopy() method to remove element from an array

Description of the System.arraycopy method

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length) - Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by src to the destination array referenced by dest. The number of components copied is equal to the length argument. The components at positions srcPos through srcPos+length-1 in the source array are copied into positions destPos through destPos+length-1, respectively, of the destination array.

If you use the same array as source and destination you will have the same issue of repeating element as discussed in the first program as the array length is fixed. In the example code new array is used as destination.

Example code

 
import java.util.Arrays;
import java.util.Scanner;


public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] intArr = {1, 2, 5, 12, 7, 3, 8};
        
        
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
          for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                removeElement(intArr, i);
                break;
              }
          }
        
    }
    
    public static void removeElement( int [] arr, int index ){
        // Destination array
        int[] arrOut = new int[arr.length - 1];
        int remainingElements = arr.length - ( index + 1 );
        // copying elements that come before the index that has to be removed
        System.arraycopy(arr, 0, arrOut, 0, index);
        // copying elements that come after the index that has to be removed
        System.arraycopy(arr, index + 1, arrOut, index,         remainingElements);
        System.out.println("Elements -- "  + Arrays.toString(arrOut));
    }

}

Output

Enter Element to be deleted : 5
Elements -- [1, 2, 12, 7, 3, 8]

Using Collection classes

If you want to remove element from an array using Collection API provided by the Java language then you can convert array to an ArrayList and then remove element from the ArrayList. Shuffling and all would be taken care of by the ArrayList itself. Once the element is removed you can again convert the ArrayList to an array.

 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class ElemRemoval {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Integer[] intArr = {1, 2, 5, 12, 7, 3, 8};            
        System.out.print("Enter Element to be deleted : ");
          int elem = in.nextInt();
        
          System.out.println("Original Array " + Arrays.toString(intArr));
        
          for(int i = 0; i < intArr.length; i++){
              if(intArr[i] == elem){
                intArr = removeElementUsingCollection(intArr, i);
                break;
              }
          }
          System.out.println("Array after removal of Element -- " );
          for(int i = 0; i < intArr.length; i++){
              System.out.print(" " + intArr[i]);
          }
        
    public static Integer[] removeElementUsingCollection( Integer[] arr, int index ){
        List<Integer> tempList = new ArrayList<Integer>(Arrays.asList(arr));
        tempList.remove(index);
        return tempList.toArray(new Integer[0]);
    }
}

Output

Enter Element to be deleted : 2
Original Array [1, 2, 5, 12, 7, 3, 8]
Array after removal of Element -- 
 1 5 12 7 3 8

That's all for this topic How to remove elements from an array. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Finding duplicate elements in an array - Java Program
  2. How to remove duplicate elements from an array - Java Program
  3. Matrix Subtraction - Java Program
  4. Difference between Array and ArrayList in Java
  5. How ArrayList works internally in Java

You may also like -

>>>Go to Java Programs page

Wednesday, 5 July 2017

PermGen Space Removal in Java 8

Though Java 8 introduced many new features to the Java language which are tangible in a way that you can see and use them like lambda expression and stream API. But there are other changes too which you won’t use day to day but are equally important. One of these changes is to remove PermGen space and replace it with Metaspace.

Knowledge about the memory management in Java will definitely help you in improving the performance of your application so in this post we’ll see what is PermGen space, why it is replaced with Metaspace and what options are there when using Metaspace.

What is PermGen space

Let’s have a brief introduction of PermGen space first in order to understand this post better.

PermGen (Permanent generation) space stores the meta-data about the class. That involves information about the class hierarchy, information about the class like its name, fields, methods, bytecode. Run time constant pool that stores immutable fields that are pooled in order to save space like String are also kept in PermGen.

Problem with PermGen space

PermGen space is contiguous to heap space and the information stored in PermGen is relatively permanent in nature (not garbage collected as swiftly as in young generation like Eden).

The space allocated to PermGen is controlled by the argument -XX:MaxPermSize and the default is 64M (30% higher in 64 bit JVM which means around 83M in a 64 bit JVM).

Here point to note is PermGen's size is Fixed at start-up and can't be changed dynamically which may lead to java.lang.OutOfMemoryError: PermGen error. As your application grows the classes that are loaded will grow and the size of class metadata may become more than what was the size of the PermGen space. Once the permanent generation space is full OutOfMemoryError: PermGen Space error occurs.

Introducing MetaSpace

In Java 8 PermGen space has been completely removed so using argument -XX:MaxPermSize won’t do anything.

For example, if I go to eclipse where compiler compliance level is Java 1.8 and set a VM argument for MaxPermSize, it will give me warning for this option.

“Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128m; support was removed in 8.0”

In place of PermGen a new space MetaSpace has been introduced. How it differs from PermGen is that it is not contiguous to Heap space, it is part of native memory instead. You can also opt to use default value for MetaSpace (Though there are some flags provided to limit the memory usage) which theoretically means total available native memory.

Options with Metaspace

There are some new flags added for Metaspace in JDK 8 two of them are analogous to the option provided with PermGen; PermSize and MaxPermSize. In Metaspace options are MetaspaceSize and MaxMetaspaceSize. Other two flags are MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio.

Before going into those options just a brief introduction about the class metadata and how it is garbage collected.

Metadata of the class is deallocated when the corresponding Java class is unloaded. Garbage collections may be induced in order to unload classes and deallocate class metadata. Garbage collection is induced when the space committed for class metadata reaches a certain level (a high-water mark). This level (a high-water mark) in metaspace is defined by MetaspaceSize (Default - 12Mbytes on the 32bit client VM and 16Mbytes on the 32bit server VM with larger sizes on the 64bit VMs). After the garbage collection, the high-water mark may be raised or lowered depending on the amount of space freed from class metadata.

-XX:MetaspaceSize=<M> Where <M> is the initial amount of space(the initial high-water-mark) allocated for class metadata (in bytes) that may induce a garbage collection to unload classes. It is raised or lowered based on the options MaxMetaspaceFreeRatio and MinMetaspaceFreeRatio. If the committed space available for class metadata as a percentage of the total committed space for class metadata is greater than MaxMetaspaceFreeRatio, then the high-water mark will be lowered. If it is less than MinMetaspaceFreeRatio, then the high-water mark will be raised.

-XX:MaxMetaspaceSize=<M> Where <M> is the maximum amount of space to be allocated for class metadata (in bytes). The amount of native memory that can be used for class metadata is by default unlimited. Use the option MaxMetaspaceSize to put an upper limit on the amount of native memory used for class metadata.

-XX:MinMetaspaceFreeRatio=<M> Where <M> is the figure in percentage (minimum percentage of class metadata capacity free after a GC). It is used in conjunction with the MetaspaceSize option to determine whether high-water mark should be raised so as not to induce another garbage collection too soon.

-XX:MaxMetaspaceFreeRatio=<M> Where <M> is the figure in percentage (maximum percentage of class metadata capacity free after a GC). It is used in conjunction with the MetaspaceSize option to determine whether high-water mark should be reduced.

Using default option

You may be tempted to use the default with the Metaspace so that more and more space is allocated for the class meta-data but in my opinion that may result in false sense of security that every thing is fine with your application where as in reality your application may have memory leak issues.

You should provide enough space for the Metaspace so that classes of your application and any third party libraries are loaded then you should monitor it for any memory leaks in case that space is not enough. There are instances when I had to increase PermGen space when application itself was big and using third party tools like reporting engines. But that was a genuine case where it had to be increased up to certain level. If it still gave “ OutOfMemoryError” that meant memory leaks which had to be addressed rather than increasing PermGen space even more.

That's all for this topic PermGen Space Removal in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reduction Operations in Java Stream API
  2. Spliterator in Java
  3. Method reference in Java 8
  4. Optional class in Java 8
  5. effectively final in Java 8

You may also like -

>>>Go to Java advance topics page

Monday, 3 July 2017

How to pass command line arguments in Eclipse

Eclipse is one of the most preferred IDE for Java/JEE development. Eclipse IDE provides various options like running the application from the IDE, providing arguments to your Java program, debugging your application.

In this post we’ll see how to pass program arguments to your Java program.

Passing arguments

Let’s take an example Java program where you have to add the two passed arguments and print the total.

Example code

public class Add {

 public static void main(String[] args) {
  try{
   if(args.length != 2){
    throw new IllegalArgumentException("Argument length "
      + "should be 2 ");
   }
  }catch(IllegalArgumentException IAexp){
   System.out.println("Error in the code - " + IAexp.getMessage()); 
  }
  double total = Double.parseDouble(args[0]) + 
      Double.parseDouble(args[1]);
  System.out.println("Sum of " + args[0] + " and " 
      + args[1] + " is: " + total);

 }

}

How to provide arguments

You can select “Run Configuration” option by selecting the Run menu from the top menu.

Selecting Run Configuration option from Run menu

You can also select the same “Run Configuration” option by right clicking the program for which you have to provide args, from the package explorer.

command line arguments in eclipse
Selecting Run Configuration option from package explorer

That will open the “Run Configuration” screen.

Run Configuration screen

Make sure that the program where arguments are to be passed is selected.If you don’t find your program there search for it or add it by right clicking on “Java Application” and selecting New.

In the “Run Configuration” screen select the “Arguments” tab and provide required arguments in the “Program arguments” text area. Then select Apply and then Run to run you program.

That's all for this topic How to pass command line arguments in Eclipse. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Creating a Maven project in Eclipse
  2. Why file name and class name should be same in Java
  3. Why main method static in Java
  4. Java pass by value or pass by reference

You may also like -

Thursday, 29 June 2017

Matrix Subtraction - Java Program

When you subtract two matrices subtraction is done index wise you subtract the element at (0, 0) in the first matrix with the element at (0, 0) in the second matrix, element at (0, 1) in the first matrix with the element at (0, 1) in the second matrix and so on.

As example – If you are subtracting two matrices of order 3X3 -

matrix subtraction

Which results in -

Also remember these points when subtracting one matrix with another -

  1. Both of the matrix have to be of same size.
  2. Resultant matrix will also have the same order for the elements. Element at (0, 0) in the first matrix minus (0, 0) of the second matrix becomes the element at index (0, 0) in the resultant matrix too.

Matrix subtraction Java program

 
import java.util.Scanner;

public class MatrixSubtraction {

    public static void main(String[] args) {
        int rowM, colM;
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter Number of Rows and Columns of Matrix : ");
        rowM = in.nextInt();
        colM = in.nextInt();
        
        int M1[][] = new int[rowM][colM];
        int M2[][] = new int[rowM][colM];
        int resMatrix[][] = new int[rowM][colM];
        
        System.out.print("Enter elements of First Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M1[i][j] = in.nextInt();
            }
        }
        System.out.println("First Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M1[i][j]+"\t");
            }
            System.out.println();
        }
        
        System.out.print("Enter elements of Second Matrix : ");
        
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                M2[i][j] = in.nextInt();
            }
        }
        System.out.println("Second Matrix : " );
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +M2[i][j] + "\t");
            }
            System.out.println();
        }
        
        // Subtraction logic 
        for(int i = 0; i < rowM; i++){
            for(int j = 0; j < colM; j++){
                resMatrix[i][j] = M1[i][j] - M2[i][j];
            }
        }
        
        // Printing the result matrix 
        System.out.println("Result Matrix : " );
        for(int i = 0; i < resMatrix.length; i++){
            for(int j = 0; j < colM; j++){
                System.out.print(" " +resMatrix[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

Output

Enter Number of Rows and Columns of Matrix : 3 3

Enter elements of First Matrix : 1 3 4 2 5 6 4 3 2

First Matrix : 
 1  3  4 
 2  5  6 
 4  3  2
 
Enter elements of Second Matrix : 2 7 1 0 4 6 9 8 1

Second Matrix : 
 2  7  1 
 0  4  6 
 9  8  1
 
Result Matrix : 
 -1  -4  3 
 2  1  0 
 -5  -5  1 

That's all for this topic Matrix Subtraction - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Matrix Multiplication Java Program
  2. Matrix Addition - Java Program
  3. How to remove duplicate elements from an array - Java Program
  4. Factorial program in Java
  5. Fibonacci series program in Java

You may also like -

>>>Go to Java Programs page