New course! Every coder should learn Generative AI!
Try a free lesson+ 2
How to get the last element of a String array
Here is an example of what I've tried String words = "Programming/is/fun"; String[] arr = words.split("/"); String lastElement = arr.length-1; System.out.print(lastElement); Expected output: fun Output : an error that says cannot convert from int to String
7 Answers
+ 6
String lastElement = arr[arr.length-1];
+ 3
System.out.print(arr[arr.length - 1]);
+ 3
khalid raji
arr.length - 1 will return integer value so you can't directly assign to a String variable.
+ 2
Change lastElement type to int and output arr[lastElement]
+ 2
Got it thank y'all 😊
+ 1
You hv to convert the words to charArray first