Class forName() method in Java with Examples

Class forName() Method :-

  • This make JVM to load given class or interface into application from memory dynamically at runtime. if they are not available to load this method then its throws checked exception as ClassNotFoundException
  • This method does not create object of the loader class.it returns the Class object associated with the class or interface with the given name in the parameter as String.
  • It is a static method,no need to create object.
  • This is available in java.lang.Class package.

           Syntax :-  public static Class forName(String name) throws ClassNotFoundException

				
					public class AppMain {
	public static void main(String[] args) {
		try {
			Class cname = Class.forName("java.lang.ClassLoader");
			System.out.println("Name of Class :- " + cname.getName());

			Class ctype = Class.forName("java.lang.String");
			System.out.print("Class type represented as :- " + ctype.toString());
			
		} catch (ClassNotFoundException ex) {
			System.out.println(ex.toString());
		}
	}
}
				
			

Output :-
Name of Class :- java.lang.ClassLoader
Class type represented as :- class java.lang.String