I get the feeling once someone answers this question, I will feel a little stupid.
Regardless, I just downloaded Java 7.5 and I am immediately a encountering problem that did not exist before the download.
I was about to write a quick program to do something. To do what is, for once definitely, irrelevant. I set about starting this by initiating the console.
Literally all I had written was:
public static void main(String[] args)
{
Console console = new Console();
}
I encountered this error
The constructor Console() is not visible
Before I updated Java, I had only encountered this due to my own error.
Has the Console constructor's modifier been changed in this update? I'm assuming not.
If the Console class has been changed, what is the correct syntax now?
Read the javadoc for this kind of information. It will tell you there is in fact no visible constructor, and that an instance "can be obtained by invoking the System.console() method".
You need to invoke System.console() to retreive the object:
You should use: Console con = System.console();
public final class Console
extends Object
implements Flushable
http://docs.oracle.com/javase/7/docs/api/index.html?java/io/Console.html
Related
This question already has answers here:
What is System.out exactly?
(3 answers)
Closed 2 years ago.
What are System.in and System.out in java a java program ? I know how to use them but the way '.' Operator is used seems like object in/out is static in nature even though I didn't get it .
Structure of System.out.println:
public final class System {
static PrintStream out;
static PrintStream err;
static InputStream in;
...
}
public class PrintStream extends FilterOutputStream {
//out object is inherited from FilterOutputStream class
public void println() {
...
}
The following explanation of System.out.println(); given below:
System is a final class in java.lang package.
out is a static member field of System class and is of PrintStream type.
println is a method of PrintStream class.
Note: System.out.println(); is used to print on console. Similarly System.in is a standard InputStream which is connected to the keyboard input of console programs.
They are, effectively, flukes of history. Nothing else in the entire java language is quite like them; for learning java it is best to just accept that they are like this, and aren't like any other things, and it doesn't quite matter.
Beware - if you must know
out, err and in are all public static fields in the java.lang.System class. They are marked final, so System.out = null; isn't legal, but they aren't actually final (in that they can be changed). The support for changing them is a hack that is applied by System.setOut. This method calls into native code (that's a java method which is implemented in C/assembler, i.e. an implementation straight for the platform your VM is running on, every architecture java on has its own implementation of these).
This is, in a word, a preposterous way to do it, but that's how it was done.
So why is that legal java?
The syntax itself is nothing special, although not advised and therefore, you rarely see it. Imagine you have this:
public class Example {
public static final List<String> foo = new ArrayList<String>();
}
class MyCode {
void whatever() {
Example.foo.add("Hello!");
}
}
This compiles and runs fine; Example refers to the Example class, Example.foo refers to the public field named foo inside it, and Example.foo.add is dereferencing that field to find the arraylist that this field is pointing at, and invoking that list's add method.
The problem with this is that public fields are 'icky' - they are not idiomatic (most java code doesn't work this way; making public fields therefore makes your code look weird), fields do not participate in inheritance (you cannot declare via an interface that any classes that implement it expose some field. fields cannot be overridden), and you cannot mock them or otherwise virtualize or abstract their nature.
So why is System.out done this way?
History. If java had 'fixed' this error, then any code written that reads from sysin or writes to sysout or syserr would no longer compile in whatever version of java 'fixed' this. Some language do this. Java is institutionally very hesitant to do this ('breaking backwards compatibility'). Doing so leads to projects sticking to old versions and fracturing the community. Imagine you wrote a popular java library. You'd have to publish it for 18 separate java versions, it'd be quite the mess.
Good that you are learning JAVA.
I hope these links helps you to understand more about your question.
Static Methods
System Class
About System.in and System.out
This question already has answers here:
Java Understanding Java main method on logic
(4 answers)
Closed 9 years ago.
I'm new to java (today was my first lesson). I tried to read and do a small exercise but I don't understand exactly what the main method is.
Our teacher told us to just focus on the main method and not more, but he did not explain what it is. He just said it is the start of a program in Java. I would like to understand more, but it's difficult because every time i encountered difficulties. Example:
public static void main(String[] args) {
}
Why does this method exist? Why can't I choose another name?
Welcome to java :)
i try to use the most simple word. to reply at your question:
the main method is called by the system when you run your program, for this reason you have to use this name (main), because when your app start there is someone that call by default the method main. if you choose another name... you cannot run your program because when the system (i call it system because i think you need to read a little bit) call the main method, if it cannot find it you cannot start your program.
try to think:
have to someone that have to start your program right? but how it can know from where your program have to start ? for this reason java (but also other language) decide that the begin is the method main.
Because from main method the program starts .As many you have main() mehtods as many you have programs.This is the starting point of any program
http://docs.oracle.com/javase/tutorial/getStarted/application/
http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html
http://journals.ecs.soton.ac.uk/java/tutorial/getStarted/application/main.html
Within Java (and many other languages) the main function is special, because it is the Entry point. I suggest you read this document, with a focus on the section beginning with "The main Method".
The main method is your entrance to the program, that's it. It's where you start from.
You don't have to know the specifics of what each keyword does yet, the only important thing for you is to realize it has a parameter called args of type String[]. This is what allows your program to take arguments when executed.
A java program is a set of method containing at least one method. This is the method by which the program begins to run. Method Main.
It must be declared as :
public static void main(String[] args) {
// Your code
}
I was strucked in a place that i cannot create new instance for Console class. So i took the source code of jdk and then look into it. Then i got cleared that it was declared as "public final class Console........"... So i understood that the final class cannot be instantiated. But that is not my actual doubt. Here in the SCJP Book, i came across a line of code that tells me as Console c = System.console()
Here we cannot create new instance for console class, so creating a reference variable c. Then What is that System.console actually is?? In the book it is told as
Keep in mind that it's possible for your Java program to be running in an environment that doesn't have access to a console object, so be sure that your invocation of System.console() actually returns a valid console reference and not null.
So then i entered to look up source code for System.console().
There i happen to see System as final class and console() as static method inside that.
So how can a Console reference object refer to that console method in system class..
What is the link between these two. I thought of a polymorphic reference.
But that is not because it doesn't pass IS-A Test. So please explain me in detail about this.
Hope my question is clear. Thanks in advance. !
the final class cannot be instantiated
That is wrong , final class cannot be subclassed. It can be instantiated using the new operator if its constructor is visible . I guess Console class has private constructor. Abstract classes cannot be instantited. See the JLS 8.1.1.2:
A class can be declared final if its definition is complete and no subclasses are desired or required.
It is a compile-time error if the name of a final class appears in the extends clause (§8.1.4) of another class declaration; this implies that a final class cannot have any subclasses.
System.console()
Returns the unique Console object associated with the current Java virtual machine, if any.
Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method.
If no console device is available then an invocation of that method will return null.
console() is some sort of a factory method which gives you back an object of Console associated with the current JVM . The System class has knowledge of the JVM in which it is running and it is the perfect candidate to give you back the Console object.
Console c = System.console();
System.console() gives us back a reference to the Console object and you are assigning the object reference to variable c. This way you can use that reference variable c to access the properties or methods of Console object.
I believe the mistake in your understanding is here:
So i understood that the final class cannot be instantiated
Final classes cannot be extended but can be instantiated. FYI it is the abstract class than cannot be instantiated.
I am trying to create an object of Console class, but could not succeed. I am getting this error "The constructor Console() is not visible". I also could not find any constructor in the document. Can anybody explain this?
Jon Skeet's answer is correct: you should use System.console() to get hold of the one instance of Console.
The reason for this is that Console is an implementation of the Singleton design pattern, which is used when the author of an API wants to ensure that one and only one instance of a class is ever created.
You're not meant to create instances directly. Instead, use the System.console() method:
Console console = System.console();
You cannot create a Console object, the constructor is private.
But you can obtain a Console object in this way:
Console console = System.console();
Look at the javadoc for more info.
You dont need to create the object of the Console class. It is not required. Please read below from documentation :
If this virtual machine has a console then it is represented by a
unique instance of this class which can be obtained by invoking the
System.console() method. If no console device is available then an
invocation of that method will return null.
So, you will get the console by System.console() if any console device is available with Virtual Machine.
A Console can't be instantiated explicitely while it's constructor is private. You can access the console associated with the JVM the following way:
Console console = System.console();
See the documentation here.
New Java programmers often encounter messages like the following when they attempt to run a Java program. (Different Java tools, IDEs and so on give a variety of diagnostics for this problem.)
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Error: Main method not found in the file, please define the main method as:
public static void main(String[] args)
Error: Main method is not static in class MyClass, please define the main method as:
public static void main(String[] args)
Error: Main method must return a value of type void in class MyClass, please
define the main method as:
public static void main(String[] args)
java.lang.NoSuchMethodError: main
Exception in thread "main"
What does this mean, what can cause it, and what should one do to fix it?
When you use the java command to run a Java application from the command line, e.g.,
java some.AppName arg1 arg2 ...
the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:
package some;
public class AppName {
...
public static void main(final String[] args) {
// body of main method follows
...
}
}
The specific requirements for the entry point method are:
The method must be in the nominated class.
The name of the method must be "main" with exactly that capitalization1.
The method must be public.
The method must be static 2.
The method's return type must be void.
The method must have exactly one argument and argument's type must be String[] 3.
(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)
If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Or, if you are running an extremely old version of Java:
java.lang.NoSuchMethodError: main
Exception in thread "main"
If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.
1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 - Here is an explanation of why the method is required to be static.
3 - String must be the standard java.lang.String class and not to a custom class named String that is hiding the standard class.
The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.
It
must be static
must have exactly one String array argument (which may be named anything)
must be spelled m-a-i-n in lowercase.
Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.
Other answers are doing a good job of summarizing the requirements of main. I want to gather references to where those requirements are documented.
The most authoritative source is the VM spec (second edition cited). As main is not a language feature, it is not considered in the Java Language Specification.
2.17.1 Execution - Virtual Machine Start-up
5.2 Virtual Machine Start-up
Another good resource is the documentation for the application launcher itself:
java - the Java application launcher
If you are running the correct class and the main is properly defined, also check if you have a class called String defined in the same package. This definition of String class will be considered and since it doesn't confirm to main(java.lang.String[] args), you will get the same exception.
It's not a compile time error since compiler just assumes you are defining a custom main method.
Suggestion is to never hide library java classes in your package.
The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main method, though it would help if you posted the code that caused the error and the context in which the code was run.
This might have happened if the user tried to run a .class file or a .jar file that has no main method - in Java, the main method is the entry point to begin executing the program.
Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.
To fix this problem, a new programmer must either add the midding method (assuming still that it's main that's missing) or change the method call to the name of a method that does exist.
Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html
Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main method:
For example, in the file Foo.java
public class Foo {
public static void main(final String args[]) {
System.out.println("hello");
}
}
This program should compile and run no problem - if main was called something else, or was not static, it would generate the error you experienced.
Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main, which is passed the parameter args[] containing the command line arguments. This method is equivalent to int main(int argc, char** argv) in C language.
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
If you are using VSCode:
Choose: Clean Workspace
Choose: Restart and delete
Keep coding :-)
For those who encountered this problem in Kotlin Project.
You can try deleting .idea folder and running the project again - for me it solved the issue. (better close IntelliJ first)
Seems like sometimes IntelliJ gets all confused about the main method signature and expecting the java signature instead of the Kotlin one.
Few min back i was facing " main method not defined".Now its resolved.I tried all above thing but nothing was working.There was not compilation error in my java file.
I followed below things
simply did maven update in all dependent project (alt+F5).
Now problem solved.Getting required result.