Illegal Start of Expression : declaring a method inside another method - java

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()
}

Related

How a static method call works in Java?

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

Unable to call function in java

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.

How can I wrap main in an extendable class?

I want to make a test program that instead of specifying main method explicitly, extends a class/abstract class and overrides a method that gets called by that superclass eg init.
My attempt:
JavaApplication.java
public class JavaApplication {
public JavaApplication(){
this.init(null);
}
public JavaApplication(String[] args) {
this.init(args);
}
public void init(String[] args) {
/* override me */
}
public static void main(String[] args) {
new JavaApplication(args);
}
}
MyApp.java:
public class MyApp extends JavaApplication {
#Override
public void init(String[] args) {
System.out.println("Hello, World!");
}
}
The code compiles but my init method is not called(The string does not appear).
What is the proper way of formulating this behavior in Java?
Related Questions:
can-i-access-a-subclass-method-through-a-base-class-typed-reference
calling-a-method-of-subclass-through-reflection
whats-wrong-with-overridable-method-calls-in-constructors
calling-an-overridden-method-from-a-parent-class-ctor
You need to add a main method in MyApp that creates an instance of MyApp:
public static void main(String[] args) {
new MyApp(args);
}
Then, run MyApp instead of JavaApplication.

I want to print "Hello" even before main() is executed

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.

why can't I create a method in the main method [duplicate]

This question already has answers here:
Writing a function inside the main method - Java
(7 answers)
Closed 6 years ago.
Hello I am a want create method into main?
So this is code where i want crete method:
import java.io.*;
import java.util.Random;
class input{
public static void main (String args[]){
void Randomises() {
int writabledata;
Random a=new Random();
writabledata=a.nextInt();
}
}}
Java does not allow to create methods within a method. This is a general rule and NOT specific to main method.
Perhaps what you are looking for is to create additional static methods in your class:
public final class MyCommand {
private MyCommand() {
//
}
private static void releaseTheCatsOfWar() {
System.out.println("Meow!");
}
public static void main(String[] args) {
releaseTheCatsOfWar();
}
}
Of course, it would be better to do:
public final class MyCommand {
private MyCommand() {
//
}
private void releaseTheCatsOfWar() {
System.out.println("Meow!");
}
public static void main(String[] args) {
MyCommand that = new MyCommand();
that.releaseTheCatsOfWar();
}
}
you cannot create methods within methods in Java.
You can have it as an additional method of your class and call it form main.
public static void main is not a class, it's a method within class. And your class is input (by the way, you should start class name with an uppercase letter, like Input), in which you define method main, from which your program starts working.
Although it is entirely pointless, the closest way you would get to achieving your results is with the following:
public class Main {
private static interface MethodMaker{
void randomise();
}
public static void main(String[] args) {
MethodMaker methodMaker = new MethodMaker(){
#Override
public void randomise() {
// DO SOMETHING
}
};
methodMaker.randomise();
}
}
You have to put method outside main ,, and just call it in main ,, like this :-
import java.io.*;
import java.util.Random;
class input{
public static void main (String args[]){
Randomises();
}
public void Randomises() {
int writabledata;
Random a=new Random();
writabledata=a.nextInt();
}
}

Categories