Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
import java.lang.*;
import java.util.Scanner;

class Casio
{
	String abc[];
	Scanner j = new Scanner(System.in);
	
	public Casio(int x)
	{
		System.out.println("IM IN DEFAULT CONSTRUCTOR");
		String abc[] = new String[x];
		
		for(int i=0;i<x;i++)
		{
			System.out.println("ENTER THE NAME OF FRIEND "+(i+1));
			abc[i]= j.nextLine();
		}
		
	}
	
	public void show(int q)
	{
		for(int ji=0;ji<q;ji++)
		{
			System.out.println("THE NAMES ARE : "+(abc[ji]));//<-- Error at Line number 27
		}
	}

}

public class mycode
{
	public static void main(String args [])
	{
		int n,q;
		Scanner s = new Scanner(System.in);
		System.out.println("ENTER INITIALIZATION VALUE");
		n = s.nextInt();
		q=n;
		Casio obj = new Casio(n); 
		obj.show(q);//<-- Error at  line number 43
	}
}


THE OUTPUT I GET IS:

Exception in thread "main" java.lang.NullPointerException
at clg.Casio.show(mycode.java:27)
at clg.mycode.main(mycode.java:43)

What I have tried:

When i execute the program . It takes input but it fails to show output. I am trying to take input from array and display output by method calling. please help me. Thank you
Posted
Updated 5-Jul-19 21:41pm
v4

1 solution

The Casio constructor creates a local array called "abc" which "hides" the class level version. As a result, the class level version never gets any values assigned to it, or indeed any space for elements.
Change this line:
String abc[] = new String[x];
To this:
abc = new String[x];
And try again.

Seriously, you would have found this very, very quickly if you had used the debugger ... it should be your first port of call when you have runtime problems.
 
Share this answer
 
v2
Comments
SAI TEJ99 6-Jul-19 4:25am    
When i changed it to abc[] = new String[x];
it is showing error that i have to insert ".class" to complete the expression, and The Left-hand side of the assignment must be a variable.
:/
OriginalGriff 6-Jul-19 4:39am    
My c**k up - I forgot to remove the square brackets - see revised code (but you should have been able to spot that yourself!)
SAI TEJ99 6-Jul-19 5:04am    
Thanks for your help:) It Worked . I just learnt C/C++/DBMS/Data Structures,Im new to java :/ . can u suggest me a good book to excel in java ?
OriginalGriff 6-Jul-19 5:11am    
Start with the "usual three": O'Reilly, Wrox, and Addison Wesley - they all do excellent technical books on languages that take you from beginner to advanced.

Or better, find a local course - being taught by a human being who knows the subject works better because that can try explaining in different ways when you don't understand - books can't!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900