简体   繁体   中英

The local variable n may not have been initialized

import View.UI;
public class App {
UI m;    
public static void main(String [] args){
    System.out.println("Hello");
    UI n ;
    n.menu();
}}

The UI class is in View,the import is done but in the last expression I get the error The local variable n may not have been initialized .I'm a starter in Java and I don't get it why I'm not allowed to use it this way.

public static void main(String [] args){
    System.out.println("Hello");
    UI n =AssignUIOBjectHere ;
    n.menu();
}}

Method's local variables needs to be initialize, before they are using.

Compiler complaining that you are using a variable which is not yet initialized.

As per language specification

Every variable in a program must have a value before its value is used:

As it is, calling n.menu() will cause a NullPointerException since you never assign anything to it.

You will need to do something like so: UI n = new ... or UI n = someObject .

You have to create an instance of UI, such as; UI n = new UI();

If you are declaring variables/object inside the method in java you need to initialize it.

In most simple term,

In your case its an object which is accessing a method so if you do not initialize it like

UI n = new UI();

it would give you an NULL pointer exception.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM