Null Pointer Exception in Java when using String Arrays - java

I have a piece of code where the program compares the value of two arrays of strings. I am getting a java.lang.NullPointerException, even though I initialized both arrays. Here is the relevant code:
String[] functions=new String [inputs+1];
int funCounter=0;
for (int a=0;a<2;a++)
{
for (int b=0;b<2;b++)
{
if (tokenizedString[b].equals(keywords[a])&&keywords[a].equals("add"))
{
System.out.println("Yay");
functions[funCounter]="add";
funCounter++;
}
}
}
This is where I inialize tokenizedString:
String[] tokenizedString;
tokenizedString=new String[2];
tokenizedString is added to a Scanner in stream here:
StringTokenizer st = new StringTokenizer(input," ");
And here is where I initialize keywords:
String[] keywords;
keywords=new String[2];
Any ideas? Thanks!

While you are accessing tokenizedString[n], the string array will give you the nth element. If the nth element is not initialized, for object arrays it will be defaulted to null.
A better way to avoid null checks in this case will be to switch places of the string values if you are sure that the other one will never be null. So instead of:
tokenizedString[b].equals(keywords[a])
use:
keywords[a].equals(tokenizedString[b])

Related

Accessing an array java

for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
}
I used this code to store the strings from a dictionary array into an array containing strings with a shorter word length. I now want to pass this array alongside a random number to the following method(to create a randomly generated word):
randomWord(smallWordDictionary, outcome);
When I use the following method:
static void randomWord(String [] array, int number){
System.out.println(array[number]);
}
The console prints out null and I'm not sure why. How can I get the console to print out a string that corresponds to its element within the smallWordDictionary array?
You're not storing anything in smallWordDictionary[i] when the length is more than maxWordlength.
The default value for your array members is null, not empty string. (The default value for any array members of reference type is null.)
Consequently, some of your random indices will point to an array member that is still null.
Solutions include:
Build a smaller array, that includes only the words that passed. No nulls will be present.
Place empty string in each member that does not pass.
Check for null when printing.
Build a smaller array
The easiest way to do this is with a List.
List<String> smallWordList = new ArrayList<>;
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordList.add( dictionary.words[i] );
}
}
smallWordDictionary = smallWordList.toArray( new String[] );
Note that count is the sames as smallerWords.size() or smallerWordDictionary.length.
Place empty string in each member that does not pass
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
else {
smallWordDictionary[i]="";
}
}
Check for null when printing
static void randomWord(String [] array, int number){
String member = array[number];
System.out.println( (null == member) ? "" : member);
}

Why is there no difference between returning an object with assignment operator and without

I hope this is not a re-post. I couldn't find anything that answered my question so I decided to make this.
Say for example I have a
String [] arrayS = new String [2];
I assign the String arrays with words
arrayS[0] = Hello;
arrayS[1] = World;
Now I have a String [] method.
public static String [] change(String [] sArray, String newWord){
//Do Stuff
return sArray;
}
So when I return the method, with or without the assignment operator, I still get the same result.
Example...
//This result
String newWord = Hi;
arrayS = change(arrayS, newWord); // With assignment operator.
for(String word:arrayS)
System.out.println(word);
//Is the same as this result
String newWord = Hi;
change(arrayS, newWord); // No assignment operator.
for(String word:arrayS)
System.out.println(word);
Is there any reason why it is like this? I always thought you must have an assignment operator to something when you return. But when I print out the arrayS, it gave me the same thing doing both method.
You are not actually returning an object, you are returning a reference to an object.
public static String [] change(String [] sArray...
means that the method accepts a reference to a String[] and return a reference to a String[]. This also means that, even if these references are passed by value, any modification you do to sArray locally to change method it's reflected to the object itself.
There is no direct correlation between assignment operator and what you need to do. If the method returns a String[] then it means that it could return something different from the sArray passed, otherwise there's no reason to return anything at all, it just makes code less readable.
For example, returning a value could make sense when doing something like
String[] foo = new String[] {"foo"}
String[] bar = new String[] {"bar"};
String[] chosen = choose(foo, bar); // this method could return foo or bar
But doesn't make any sense in your situation, in which you reassign a value with itself making everything just more confusing.
It's is worth noting that these considerations doesn't apply to primitive types, which are values passed by value.

Difference between two dimensional different flavours type array ? Advantages of these of two type

I am trying to study array in depth. I tried so many multidimensional array but didn't understand
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
String [][] obj1 = new String [10][5];
String [][] obj2 = new String [10][];
System.out.println(obj1[1].length);
System.out.println(obj2[1].length);
}
}
In this example , I have tried two double dimensional array.
String [][] obj1 = new String [10][5]; and String [][] obj2 = new String [10][];.
Now
System.out.println(obj1[1].length); gives the length 5 as a Output. Totally Cleared.
In Second sysout statement throws NullPointerException
System.out.println(obj2[1].length); Totally UnCleared. because i am not trying to access the member variables only want to get the length.
So, why NullPointerException Here ? Is there really any advantage of Second type of array declaration ??
Please explain in details, found several Sources but still Confused.
Thanks
In String [][] obj2 = new String [10][]; you are initializing obj2 to refer to an array of 10 String[] elements. The elements of the array are initialized to null, which is why obj2[1].length throws a NullPointerException.
This type of declaration allows you to assign arrays of different lengths in the 2D array.
For example :
obj2[0] = new String[5];
obj2[1] = new String[10];
while in
String [][] obj1 = new String [10][5];
all the inner arrays have the same length of 5, since here you are initializing obj1 to refer to an array of 10 String[] elements, each of which is initialized to refer to an array of 5 String elements.
In Second sysout statement throws NullPointerException
Which you would expect as it hasn't been initialise.
i am not trying to access the member variables only want to get the length.
You didn't create any such array or give it a length so this doesn't make sense.
Is there really any advantage of Second type of array declaration ??
You might not want all the arrays to have the same length in which case you can set each one to whatever length you want.

using split on Array Object in Java

Why do I get mssg with "cannot find symbol", when I use .split on the String Object?
public static void main(String[] args) {
String[] inputFile = StdIn.readAllLines().split("\\n");
//create Congress caracteristics
int states = Integer.parseInt(inputFile[0]); // read states value and save in the first
//position in the array
int totalSeats = Integer.parseInt(inputFile[1]); //read number of seats and save in the second
//position in the array
This is because you are trying to call the split method on an array. There is no such method on an array. readAllLines() already returns an array of the strings. Just remove the .split() call.
From the JavaDoc:
static String[] readAllLines()
Reads all remaining lines from standard input and returns them as an array of strings.
StdIn.readAllLines() does not return a String but a String[] (array of strings). You can't use split() on an array of strings.
Actually, you don't need to do that, because calling readAllLines() already gives you the array you are looking for.
You are most likely calling #split() in an Array/Collection of Strings, not a String. You should iterate though them and split one after the other.
We have fileName Object we itrate it a split it simple in this program i split my object with (.) so thats why i used this =split("\\.");
String[] fileName="we have a object here to we want to splite it ";
for(String obj:FileName)
{
String[] part1=obj.split("\\.");
}
System.out.println(part1);
check it its working fine

Put String[] in a String[][]?

Ok, soo what I'm trying to do, I have an oject with a attribut which looks like String[][], and I want to fill this one by calling a function and fill this String[][], one by one.
So here is what I tried but I get an error telling me :
"The type of the expression must be an array type but it resolved to String"
When I try to do
Produit[NbrProduit][0] = Produit[0];
My code :
public String[][] Produit = new String[MAX_Produit][2];
public void GetInfo1(String Client, String[] Produit,int NbrProduit){
Produit[NbrProduit][0] = Produit[0];
Produit[NbrProduit][1] = Produit[1];
Produit[NbrProduit][2] = Produit[2];
I don't understand why I get this because I'm filling a String field with an another String, right ? no ?
Sorry for my english.
Your parameter name (a 1D array) is the same as your instance variable name (a 2D array), so you're actually referring to your parameter only. Either use a different name (recommended), or use this.Produit when referring to your 2D array.
i.e.
public void GetInfo1(String Client, String[] produitParam,int NbrProduit){
Produit[NbrProduit][0] = produitParam[0];
Produit[NbrProduit][1] = produitParam[1];
Produit[NbrProduit][2] = produitParam[2];
Produit is a two dimensional String array, which means each of its element will be a string array. So you need to assign the element with the array of String and not just one String. Try this if it makes sense for your logic:
this.Produit[NbrProduit][0] = Produi;

Categories