Jump to content

Java Doubt


nikhilboorla

Recommended Posts

public class PositionFinder {
 
public static void findPosition(String[] list, String term){
if (list==null || list.length==0)
System.out.print("Empty array");
else{ 
int position=-1;
for (String name: list){
if(name.compareTo(term)==0)
break;
position++;
}
System.out.print(position > 0 ? position: 0);
}
}
 
public static void main(String[] args){
String[] myArray = {"Hola","Kumusta", "Hello", "Ciao"};
findPosition(myArray, "Ciao");
}
}
 
1 - What is the output of the code? 
a.-1
b.0
c.1
d.2
e.3

2 - What would have been the output if instead of "Ciao" we had "Hola" at line 19 
a.-1
b.0
c.1
d.2
e.3

3 - What would have been the output if instead of "Ciao" we had an empty String (e.g.;"") at line 19 
a.-1
b.0
c.1
d.2
e.3

4 - What would have been the output if we had "String[] myArray = {};" at line 18 
a.Empty array
b.NullPointer exception
c.ArrayOutOfBounds exception
d.0

5 - What line of the program would have caused a NullPointer exception if we set myArray to {"Hola"; null} at line 18 
a.19
b.20
c.6
d.9
e.10
Link to comment
Share on other sites

evi answers otions chusko 

 

2
0
3
Empty
if(name.compareTo(term)==0)
 
Edited: 

 

public class PositionFinder {
 
public static void findPosition(String[] list, String term){
if (list==null || list.length==0)
System.out.print("Empty array");
else{ 
int position=-1;
for (String name: list){
if(name.compareTo(term)==0)
break;
position++;
}
System.out.print(position > 0 ? position: 0);
}
}
 
public static void main(String[] args){
String[] myArray = {"Hola","Kumusta", "Hello", "Ciao"};
findPosition(myArray, "Ciao");
}
}
 
1 - What is the output of the code? 
a.-1
b.0
c.1
d.2
e.3

2 - What would have been the output if instead of "Ciao" we had "Hola" at line 19 
a.-1
b.0
c.1
d.2
e.3

3 - What would have been the output if instead of "Ciao" we had an empty String (e.g.;"") at line 19 
a.-1
b.0
c.1
d.2
e.3

4 - What would have been the output if we had "String[] myArray = {};" at line 18 
a.Empty array
b.NullPointer exception
c.ArrayOutOfBounds exception
d.0

5 - What line of the program would have caused a NullPointer exception if we set myArray to {"Hola"; null} at line 18 
a.19
b.20
c.6
d.9
e.10

 

 

Link to comment
Share on other sites

×
×
  • Create New...