0
Java Programming - Arrays
Can someone explain in detail as to what is going on in this code? public class Longest { public String[] words = {"Hello", "Star", "Fish", "tennis", "telephone", "wardrobe", "lampost", "intensify", "ghost"}; public static void main(String args[]) { Longest l = new Longest(); int longIndex = 0; int shortIndex = 0; for (int i = 1; i < l.words.length; i++) { if (l.words[i].length() >= l.words[longIndex].length()) longIndex = i; if (l.words[i].length() <= l.words[shortIndex].length()) shortIndex = i; } System.out.println(l.words[longIndex].charAt(l.words[shortIndex].length())); } }
2 Answers
+ 2
it's just a random program don't know what's the motive behind this question. they are first storing the index of longest and shortest string present in the string array.
Then they are printing the character present in the longest string, at the position equal to the length of the shortest string .
This is an overview.Do you want a detail explanation also ?
+ 2
ok
1) A public class is created
2) A class variable of type string array is defined. Values that it will hold is also given there.
3) Now the main method is executed. This method is essential for any java program to run. As this will be the first method present in the call stack after any other method.
4) Now an instance(object) of this class is created. This is because , main function is a static method , and you can't access a non-static variable from a static method. In this case we are using words variable which is non-static , so that's why we are creating an instance of this class.
5) Now two variable are defined which will store the index of longest and shortest string
6) loop starts with index 1, comparing the string at 1 with the the string present at index value of longindex I.e 0. Star is matched with hello. hello is greater so longindex will not change. but short index will have new value I.e 1 as star is smaller than hello.
7) Loop continues
8) At the end longindex will have value 7 and short index will have value 2
9) Now they are printing. They chose the string(intensify) at 7th position because it's the longest and then printed the character at 4th position of 'intensify' because 4 is the length of the smallest string in the array at index 2(fish).
10 ) so 'n' will get printed.