Java variables not initialized error

北战南征 提交于 2019-11-28 02:28:17

Local variables don't get default values, you should initialize them before you use them , initialize nam and r with default values inside your main and you will be fine.

public static void main(String args[]) throws IOException{
String nam=null;
int r=0;

BTW, consider naming your class's and variables something meaningful.

Initialize your local variable before using it, like in above case it must be String nam = "" or it can be null also; int r = 0;

When we define any instance variables in class they are default initialized eg. int to 0 but local variable needs to be initialized before using it.

Thanks, Brijesh

It is always good practice to give your variables a value of null or zero depending on the data type you are working with. If you look over your code there you will see that you did not tell the variables their values for example you have a variable r; instead make your integer know that there is nothing inside it before you start using it like this int r = 0;. that way your java program will know that it is overriding the existing value when you use that variable. Telling your variable what they hold is what java calls initializing. Take it in the day to day activities and see it while you are coding.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!