Home>

I'm new to java development.
I study by myself.

Please let me ask a question about the following source code.

public class Test {
    String name;
        // add the specified code
    public static void main (String [] args) {
        // TODO Automatically generated method stub
        Test b = new Test ();
        if (b.name == "")
            b.name = "abc";
        System.out.println (b.name);
    }
}

In the part of "Add // specified source code"
"System.out.println (name);"
I want to put in, but I get an error.
I think there is a syntax error, but I don't know why.
I would appreciate it if you could tell me why.

  • Answer # 1

    The location is in the class, not the method
    There, you can only describe methods, static {}, {}, etc. except for declaration and allocation of variables
    Writing a description such as System.out.println (name);directly in the part outside the method in the class will only result in an error

    public static void main (String [] args) written in {} or

    If you really want to be in that position,

    public static void prn () {
    System.out.println (name);
    }
    Describe each method in the method as shown.

  • Answer # 2

    Is it better to understand the difference between fields and methods?

    In the beginning, classes are easy to understand if you think they are made up of fields and methods.

    "System.out.println (name);" is a method call and is wrong in the method definition. So, compile errors are natural.

    class

    Field int a = 1;etc.

    Method int methodA (int a) {return a} etc.


    public static void main (String [] args) Let's also take {} as the main method.
    The main method is a special method, only those listed here are
    Processing takes place at runtime.

    ※ If you do not read in the main class, it will not be called.

    Appendix

    System.out.println This specifies a static variable of type PrintStream called out in the field of the System class.
    That
    Reading the method println of the PrintStream class.
    http://docs.oracle.com/javase/jp/6/api/java/lang/System.html#out

  • Answer # 3

    Must be described in the method.
    I think that the part I am going to describe is one line above the main method, but this is used for class field declarations and so on.

    If you want to write, it is in the main method.
    Then it will move.

  • Answer # 4

    If you want to call it at instantiation time, implement a constructor.

    From here, it will be a speculative speculation. Does the questioner want to check the initial value of name?
    If so, name is a String type, that is, a reference type field, so the initial value is null. But there is no need to have null, so
    String name;

    String name ="" ;;
    It is better to initialize it yourself.
    As an aside, I don't recommend that you use == to determine the reference type. Use the equals method. Or I think that the Objects.equals method is also acceptable.