When I try to call the lyrics function in this code, "invalid method declaration; return type required" occurs.
I'm learning java and very very new to it. I'm confused how to define the function and call the function so that code may run.
public class Main {
public static void main(String[] args) {
}
public void lyrics() {
System.out.println("some lyrics here");
}
lyrics();
}
Normally, one can't just invoke a method randomly in the body of the code. However, there is something called an initialization block (this gets run in the body of the constructors of the object). I think an example might clarify. Like,
public class Main {
public static void main(String[] args) {
new Main(); // <-- instantiate an instance of Main
}
public void lyrics() {
System.out.println("some lyrics here");
}
{ // <-- this is an initialization block
lyrics();
}
}
The above uses the default constructor, we can add an explicit one. Like,
public Main() {
super();
System.out.println("In Main constructor");
}
Note how the output changes.
They can also be static (and run when the class is first referenced). Like,
public class Main {
public static void main(String[] args) {
}
public static void lyrics() {
System.out.println("some lyrics here");
}
static {
lyrics();
}
}
Your code is nearly correct. Your lyrics() method must be static if you want to call it inside main method because main method is static. Non static members cannot be accessed from static method (without creating an instance to invoke it).
public class Main {
public static void main(String[] args) {
lyrics();
}
public static void lyrics() {
System.out.println("some lyrics here");
}
}
You can invoke non-static methods from static method by creating an instance of the class containing non-static method inside your main method as mentioned in comments by Elliott Frisch.
new Main().lyrics();
Since you're learning Java, you must remember that the only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
Or you can simply make your function static. Also, you need to call the function inside the main block.
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
Happy coding!
The method should be declared as static and function call should be within main method. The correct code should look like as follows:
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
You need to move the call to lyrics() into the main method where code is actually executed. Where you have it now, the compiler is expecting a new method defination.
public class Main {
public static void main(String[] args) {
// execution begins here.
new Main().lyrics();
}
public void lyrics() {
System.out.println("some lyrics here");
}
}
EDIT: created new class Main class to avoid errors.
Related
When calling out the function testFunc(), I am not using the syntax
Apples.testFunc(). Yet the code runs successfully. How so?
class Apples {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
Since, the static method is in the same class. So, you don't need to specify the class name.
If it is in different class, then you need to specify the class name.
Remember: Non-static methods can access both static and non-static members whereas static methods can access only static members.
For example :
Calling a static method present in different class, you need to do like this :
import com.example.Test;
public class Apples {
public static void main(String args[]) {
Test.testFunc();
}
}
package com.example;
public class Test {
public static void testFunc() {
System.out.println("Hello world!");
}
}
Your function testFunc() is in same class where the function main is. So you don't need to use class name before function testFunc().
When the memory is allocated for the class, Static method or static variable is assigned memory within a class. So we can access static member function or data variable using class name.
we can call static function as below
class Main1 {
public static void main(String args[] ) {
Main1.testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
or
class Main1 {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
the answer will be same, but when static function is in other class then we must use classname to call it
I have two java class file's in my project.
First one is main.Java
Second one is function.java
How to call function.java method from main.java
for Example.
main.Java
public class main {
//call function here
}
function.Java
public class function {
public void example(){
System.out.println("Function working");
}
}
How to call function.java example method from Main.Java?
Class name should be always start with Upper letter.
This is the way to call a function in another class in another .java
In Main.java
public class Main{
public static void main(String[] args){
SecondClass sc = new SecondClass();
sc.go();
}
}
In SecondClass.java
public class SecondClass{
public void go(){
System.out.println("Done");
}
}
If you want to call the method in the same class
public class Main{
public void go(){
System.out.println("Done");
}
public static void main(String[] args){
Main m = new Main();
m.go();
}
}
or this
public class Main{
public static void go(){
System.out.println("Done");
}
public static void main(String[] args){
go();
}
}
First make the example() method static
public static void example(){
System.out.println("Function working");
}
Then call
public class main {
//call function here
public static void main(String[] args) {
function.example();
}
}
if they are not in the same package you should import function.java in main.java like this
import function
then you should create an instance of function class like this where you want to use it
function func = new function();
then you can call the example method using func object you created like this
func.example();
Your method isn't static, so you need to instantiate object from this class(function) to obtain access to the example method. First of all read some java specific book, so you can understand what static keyword is and how you can use it.
The code below will work :
package main.Java; //this is from where you want to call.
public class function {
public void inFunction(){
function.Java.function function = new function.Java.function();
function.example();
}
}
Happy learning :)
Okay, so don't ask why, but I'm trying to make a universal public static void main() method. I've already tried to use these two methods;
public class Foo {
public static void main(String[] args){
try {
this.getClass().newInstance().check();
} catch(Exception e) {
e.printStackTrace();
}
}
public void check() {
System.out.println("Check succesful");
}
}
The error I get is that this "Cannot be used in a static context"
Okay, so I know I can't use this in a static context, but what I want to know is how I can replace it, without using Foo.check()
If possible, how should I do this? If not, I'd like to know why.
Looking at How to call getClass() from a static method in Java? and Getting the class name from a static method in Java something like
interface Checkable {
public void check();
}
public class Foo implements Checkable {
public static void main(String[] args){
try {
Class currentClass = new Object() { }.getClass().getEnclosingClass();
Checkable instance = (Checkable) currentClass.newInstance();
instance.check();
} catch(Exception e) {
e.printStackTrace();
}
}
public void check() {
System.out.println("Check succesful");
}
}
might do the trick, but I'm not sure I should recommend doing that...
this is the current instance. You don't have an instance in a static method. Please see I want to know the difference between static method and non-static method
Do this instead:
public class Foo {
public static void main(String[] args) {
new Foo().check();
}
public void check() {
System.out.println("Check succesful");
}
}
As an answer to the comment (I don't seem to be able to make comments yet): No. The only other way is to make check() static as well and call Foo.check(), but you didn't want to do that.
There's no this in a static context; that's exactly what static means. The approach you're trying will not work. You could perhaps supply the name of the class you're interested in on the command line.
As, I know in java instance variable cannot be accessed in static block util you don't have object of that class for which class you want to access instance variable and this in java is a instance variable. so you cannot access this variable in any static block or you required object reference for this.for further clarification check here.
why dont you try this ?
public class Foo
{
public static void main(String[] args){
try
{
Foo obj = new Foo();
// this.getClass().newInstance().check();
obj.check();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void check()
{
System.out.println("Check succesful");
}
}
I know this will probably be an easy fix, but i'm just starting out in java. I need to declare a method inside the main method that clears the screen. Line 5 is giving me an error called Illegal start of expression.
public class Project2
{
public static void main(String [] args)
{
public static void clearScreen()
{
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}// end clearScreen()
System.out.print("\nDid it work?");
}
}
Nested methods is not allowed in Java(as of yet). The closest you can get is
class Project2 {
public static void main(String [] args) {
class InnerClass {
void clearScreen() {
// Do something.
}
}
new InnerClass().clearScreen(); // Call it this way.
}
}
If the above solution doesn't suit, then just move that method outside your main and call it.
You can't put a method inside a method like that. You call methods from methods, like so:
public class Project2
{
public static void main(String [] args)
{
clearScreen();
System.out.print("\nDid it work?");
}
public static void clearScreen()
{
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}// end clearScreen()
}
I want to print "Hello" even before main() is executed in Java Program. Is there any way for doing this?
What you need is a static keyword. One of the options is to use static function as initializer to static variable.
class Main {
public static int value = printHello();
public static int printHello() {
System.out.println("Hello");
return 0;
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
value is a static variable so initialized before main function execution. This program prints:
Hello
Main started
Moreover, you can even simplify this by calling printHello() even without variable initialization like in the following:
static {
printHello();
}
public class Sample {
static {
System.out.println("Hello first statement executed first ");
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
Use a static block:
static {
System.out.println("hello");
}
public static void main(String[]args) {
System.out.println("After hello");
}
Output:
hello
after hello
public class Test {
static {
System.out.println("Hello");
}
public static void main(String[] args) {
System.out.println("Inside Main");
}
}
Outputs
Hello
Inside Main
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.
Apart from using static block, you can also try instrumentation and premain
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html
import java.io.*;
class ABCD {
public static int k= printit();
public static int printit(){
System.out.println("Hello it will be printed before MAIN");
return 0;
}
public static void main (String[] args) {
System.out.println("Main method is Executed");
}
}
Static variables are initialized in the start of execution of program . So to initialize it will call printit(); function which will be executed and "Hello it will be printed before MAIN" will be printed and in last function will return value '0' and finally after this main block will be executed.
Final Output :
Hello it willl be printed before MAIN
Main method is Executed
Here is another way:
class One{
public One() {
System.out.println("Before main");
}
}
class Two extends One{
public Two() {
super();
}
public static void main(String[] args) {
Object abj = new Two();
System.out.println("in the main");
}
}
Here in run configuration, class Two would be the main class.