Given the string variables name1, name2, and name3, write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).

2
Given the string variables name1, name2, and name3, write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).

LANGUAGE: JAVA

CHALLENGE:

Given the string variables name1, name2, and name3, write a fragment of code that assigns the largest value to the variable max (assume all three have already been declared and have been assigned values).

SOLUTION:

if (name1.compareTo(name2)>0)max = name1;
else
   max = name2;
   if (name3.compareTo(max)>0)max = name3;

2 comments

  • Shyam Pandey says:

    I do not understand how this is correct (but this is what is correct :). what if name3 is the largest one? then, the code assigns name1 to the max before comparing the value of name3, doesn’t it?

Add comment