Java: Why does this function always return null? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java: Why does this function always return null?

Hi, I'm trying to get this to work. It's supposed to send name1 and name2 into the function randomName and than get a name from the nameList returned. It always prints "null" and I need the value within main. What am I doing wrong here?! public class Funktionen { public static void main(String[] args) { String name1=null; randomName(name1); String name2=null; randomName(name2); System.out.println(name1); System.out.println(name2); } static String randomName(String a) { String [] nameList = { "Hans", "Paula", "Emma", "Florian" }; a = nameList[(byte)(Math.random()*nameList.length)]; return a; } }

22nd Oct 2018, 4:16 PM
Ole
3 Answers
+ 3
First, randomName method returns a String but you only invoke the method without assigning the return value to any variable, this is why your name1 and name2 variable are still null following the method invocation. String name1 = null; name1 = randomName(name1); This way you'll get your random name. Second, array index are commonly referred by int, I guess you better use int rather than byte for referring a certain array element, in your call to Math.random method. Hth, cmiiw
22nd Oct 2018, 4:34 PM
Ipang
+ 1
Thank you very much! This works. :-) (Using byte instead of int is not a problem btw..)
22nd Oct 2018, 4:40 PM
Ole
+ 1
You're welcome, glad if it helps : ) Yes, no problem for small arrays, for arrays with many elements (more than 127) int or long will be more suitable.
22nd Oct 2018, 5:08 PM
Ipang