What does Class.forName(" ").newInstance() do?

The 'Class' class is located in the java.lang package, its forName() method returns the Class object for the parameter that was loaded by the class loader.

The newInstance() method then returns a new instance of the class.

Example:


class MyMath
{
  int sum(int a,int b)
 {
   return(a+b);
 }
}
class Main
{
  public static void main(String args[]) throws Exception
 {
  MyMath m = (MyMath)Class.forName("MyMath").newInstance();
  System.out.println("Sum is "+ m.sum(4, 5));
 }
}


Here,
Class.forName("MyMath") returns MyMath.class and call to newInstance() returns an instance of the Sum class. So basically, it is similar to calling new MyMath();


 Also See :-