I need class name for public static void main method. Eg for my class name is GetClassName so output statement was not printed GetClassName
public class GetClassName {
public static void main(String[] args)
{
System.out.println(getClass().getName().toString());
}
}
You can get it from static context, unless explicitly specifying the class. For example:
System.out.println(GetClassName.class.getName());
should be
System.out.println(GetClassName.class.getName());
No need for .toString() method, method already return String
You can try like this:
GetClassName.class.getName();
This will give you class name with package as well. OR
GetClassName.class.getSimpleName();
This will give you only class name.
IDEONE DEMO
Just use GetClassName.class.getName(). The whole point of a static method is that the class it's on will never change.
Related
Is it possible to create object of class in which main method resides.I have been searching for this answer but I have been told that it depends on compiler some compiler will allow while others will not.Is that true?
Yes? The main method is just an entry point. The class is like any other, except it has an additional public static method. The main method is static and therefore not part of the instance of the object, but you shouldn't be using the main method anyway except for starting the program.
public class Scratchpad {
public static void main(String[] args) {
Scratchpad scratchpad = new Scratchpad();
scratchpad.someMethod();
}
public Scratchpad() {
}
private void someMethod() {
System.out.println("Non-static method prints");
}
}
Yes, you can create object for the class which has main method. There is no difference in this class and a class which don't have main method with respect to creating objects and using.
I created a static method which returns a static int in class NewTriangle. But when I try to call it from the main it won't print. It asks to create a method with the same name inside the main.
public class NewTriangle{
public static in numberOfTriangles;
public static int getnumberOfTriangles(){
return numberOfTriangles;
}
}
The code works up until this point. But When I call getnumberOfTriangles() from the main I get an error.
public static void main(String args[]){
System.out.println(getnumberOfTriangles());
}
If your main method is in a different class, then you need to specify the classname while calling the static method, i.e., NewTriangle.getnumberOfTriangles()
Assuming the typos in your code are copy and paste errors, you need to either
Use the class name before the method name, you may need to add the class to your import statements (you need to if it is in a different package)
System.out.println(NewTriangle.getnumberOfTriangles());
Add a static import of the getnumberOfTriangles method to your main class
import static NewTriangle.getnumberOfTriangles;
However, note the caution given in the link:
So when should you use static import? Very sparingly!
You have to write the name of the class before :
NewTriangle.getnumberOfTriangles()
You can do something like this:
Example using :
I have created a package name stackoverflow
Two class callerClass and NewTriangle in package stackoverflow.
Make an import of class NewTriangle in callerClass.
using the Static function by NewTriangle.getnumberOfTriangles()
NewTriangle.getnumberOfTriangles() // className.StaticfunctionName()
Working Code:
Class 1 :
package stackoverflow;
public class NewTriangle {
public static int numberOfTriangles;
public static int getnumberOfTriangles() {
return numberOfTriangles;
}
}
Class 2 :
package stackoverflow;
import stackoverflow.NewTriangle;
public class callerClass {
public static void main(String args[]) {
System.out.println(NewTriangle.getnumberOfTriangles());
}
}
Java static method :
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
I hope I was helpful :)
I have a class Employee
import javax.swing.*;
public abstract class Employee {
public static void searchEmp(int id) {
JOptionPane.showMessageDialog(null, "done");
}
}
Now I have another class test:
public class `test` {
public static void main(String args[]) {
searchEmp(2);// here my programme give error
}
}
I want to call the searchEmp() which is part of Employee from a class test but it gives an error. Please suggest any solution without inheritance.
You have to call Employee.searchEmp().
The static method searchEmp() is still a member of the class Employee and you must make a static call via its class.
Also the class Employee must be visible to the class test, otherwise you have to import it. I assume the two classes reside in the same package so this will not be a problem in your case.
Static methods and properties are bound to class. So you need to use ClassName.methodName or ClassName.propertyName.
Employee.searchEmp();
Your Test class doesnt have a static searchEmp(int) method, thus the error:
searchEmp(2);// here my programme give error
should be
Employee.searchEmp(2);
static methods are called using ClassName.staticMethod()
can a static method be invoked before even a single instances of the class is constructed?
absolutely, this is the purpose of static methods:
class ClassName {
public static void staticMethod() {
}
}
In order to invoke a static method you must import the class:
import ClassName;
// ...
ClassName.staticMethod();
or using static imports (Java 5 or above):
import static ClassName.staticMethod;
// ...
staticMethod();
As others have already suggested, it is definitely possible to call a static method on a class without (previously) creating an instance--this is how Singletons work. For example:
import java.util.Calendar;
public class MyClass
{
// the static method Calendar.getInstance() is used to create
// [Calendar]s--note that [Calendar]'s constructor is private
private Calendar now = Calendar.getInstance();
}
If you mean, "is it possible to automatically call a specific static method before the first object is initialized?", see below:
public class MyClass
{
// the static block is garanteed to be executed before the
// first [MyClass] object is created.
static {
MyClass.init();
}
private static void init() {
// do something ...
}
}
Yes, that is exactly what static methods are for.
ClassName.staticMethodName();
Yes, because static methods cannot access instance variables, so all the JVM has to do is run the code.
Static methods are meant to be called without instantiating the class.
Yes, you can access it by writing ClassName.methodName before creating any instance.
Not only can you do that, but you should do it.
In fact, there are a lot of "utility classes", like Math, Collections, Arrays, and System, which are classes that cannot be instantiated, but whose whole purpose is to provide static methods for people to use.
Yes, that's definitely possible. For example, consider the following example...
class test {
public static void main(String arg[]) {
System.out.println("hello");
}
}
...if then we run it, it does execute, we never created a instance of the class test. In short, the statement public static void main(String arg[]) means execute the main method without instantiating the class test.
Currently I'm trying to invoke it like this:
class Test {
public static void test() {
System.out.println("hi");
}
public static void main(String[] args) {
Test t = null;
t.test();
}
}
The output of the code is hi
Try Test.test() with the class name before the dot.
Static methods are called on the class itself not instances of the class.
You don't need to instantiate Test for calling a static method. Your main could be look like this:
public static void main(String[] args) {
Test.test();
}
Static methiods should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args);
or
methodName(args); // from other static methods of the same class.
You can also refer to static methods with an object reference like
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.
So in your case:
Test.test();
or
test();
from the main method will do.
Try:
Test.test();
You are in the same class, you can simply call test() from main().
for (Method m : Class.forName ("Test").getDeclaredMethods ()) {
if (Modifier.isStatic (m.getModifiers ()) {
m.invoke (null);
}
}
just for lulz
The good thing about static methods and static variables is that you do not need an instance of the class to use it.
Normally you would create an instance and call the method
Test myClass = new Text();
myClass.test();
However with static methods the first line is not necessary, You just need to write the Class name at the start
Test.test();
However, in static methods you are not able to access any instance variables inside the Test class - unless they are also static!
By the way. The code works fine without any nullpointerexception
This code prints hi
I wanted to know what happens internally when a reference is used to invoke a static method.
It works because when invoking a static method using a reference, the reference is not used. The compiler looks at the declared/static/compile-time type of the expression the method is being called on, and uses that type to find the static method.
You gain nothing by calling a static method on a variable, and you can confuse people who think a polymorphic call is occurring.
Call Test.test(). As the main method is static and in the same class so you can also directly call test() too.
class Test {
public static void test() {
System.out.println("hi");
}
public static void main(String[] args) {
Test.test();
}
}