Let us directly jump into the puzzle. Following code is a Java puzzle, read and guess the output. Then run, see the result and try to reason it.
public class StringClass { public static void main(String[] args) { int a = 10 + 20; System.out.println(a); } } class String { private final String str; public String(String str) { this.str = str; } }
If you run the code, you will get the following error:
Error: Main method not found in class StringClass, please define the main method as: public static void main(String[] args) ...
So as per the error message, there is no main method and we have to define it. But what is strange here is we have got a main method already defined. You might have sensed that the “String” class should not be defined as it is already present in the core classes. The error message is not pointing that.
Actually what happens is that the error message is right. We do not have a main method with the expected signature. “main” method should have a String array as argument, but in our code the String array is compiled to be our custom String class and not the “java.lang.String” class. Therefore we get the error as main method missing.
What can we do to make this code run without error. Change the main method signature as public static void main(java.lang.String[] args)
. Now we make sure that the argument is the String class from standard package instead of our custom class.
What is the right thing to do? Do not declare your custom classes in the name of classes from the standard package. It will result in unexpected behaviour and also it will become a nightmare to other programmers who will work on your code.
Comments are closed for "Java Puzzle: Class Name".
Nice one… Thanks for the information..
Hi Joe,
Thank you for the information.
I was not even aware that we can define the java’s classes in our code without any error.
Good one Joe.
nice
easy one
Joe is back!
NICE JOE…GOOD EXPLANATION…
Nice one…I would be happy to see more like this.
Thanku you sir for your valueble information.
I got it…
Thanks Joe
Little and Nice… When will we see your latest learned technology
Really nice information…!
Good one :) Thanks joe for such an interesting points…
Good post. Thank you.
Nice.
Nice trick Joe!!