Can someone tell me what a class CLASS does? I tried looking at the API but could not quite understand it. I actually used Class.forName("") once in my JDBC code and I thought it loads the JDBC driver.Can any one give me more information on this? Scanner class:
I wrote the following program and ran it in command prompt and it ran fine. I was just wondering how to run such programs from an IDE like Wsad etc? it's not asking me for an user input at all.
When one writes code in .java file and compiles (using javac), compiler creates .class file. This .class file is byte code representation of the source file and is collection of many compiled segments like static variables, instance variables, methods etc.
To execute this .class file, JVM needs to load it into the memory and it needs a way to access the many compiled segments easily and this is where java.lang.Class class comes into picture. java.lang.Class is a runtime inmemory representation of the .class file created by the javac compiler.
Every java object is created based on a .class file and so every object holds reference to object representation of its own .class file, which can be accessed by object.getClass() method.
Regd Scanner Class: Code is working fine and reading the first line, displays the first token from that line and exiting, as you have written the code as. Here is the output of your code.
Hi Santhosh thanks for ya answer. I kinda understood what ya said lil bit. I wrote the following program
Can you tell me why I cannot call sum() method using the Class.forName("CLASSTest") ? and why am gettin the same output for both Class.forName("CLASSTest") and obj.getClass()?
Regarding my second question, I just noticed that I can give the user input from the console. I was so stupid and wondering where to give the input till now.
As per javadocs, Class.forName() returns the Class object associated with the class or interface with the given string name.
To invoke sum() method, we need object of class CLASSTest, not the class Class. We can use Class.newInstance() to create new instance of actual class that is represented by this class object. I've modified your code to illustrate this-
Using object of class Class, we can get metadata about actual object, like list of methods, fields, superclasses, implemented interfaces, etc. which we can use for reflection. Hope this clears your doubt.
Um.. I have one question tho.. The Class.forName() method returns the .class object of the class CLASSTest? That means there are objects regularly created for a Java class and there are objects for .class files too? and they both are different right?