Java > AP-1 > matchUp (CodingBat Solution)


Given 2 arrays that are the same length containing strings, compare the 1st string in one array to the 1st string in the other array, the 2nd to the 2nd and so on. Count the number of times that the 2 strings are non-empty and start with the same char. The strings may be any length, including 0.

matchUp({"aa", "bb", "cc"}, {"aaa", "xx", "bb"}) → 1
matchUp({"aa", "bb", "cc"}, {"aaa", "b", "bb"}) → 2
matchUp({"aa", "bb", "cc"}, {"", "", "ccc"}) → 1


public int matchUp(String[] a, String[] b) {
  int count = 0;
  for (int i = 0; i < a.length; i++) {
    String tmp1 = a[i];
    String tmp2 = b[i];
    if (!tmp1.equals("") && !tmp2.equals("")) {
      if (tmp1.charAt(0) == tmp2.charAt(0))
  return count;


  1. String tmp1 = a[i];
    String tmp2 = b[i];

    These string variables should be declared outside the for loop. Declare once, use over and over again.

  2. int count = 0;

    for(int i=0; i<a.length; i++){
    if(!b[i].isEmpty() && !a[i].isEmpty() && a[i].substring(0, 1).equals(b[i].substring(0, 1))) count++;

    return count;


Follow Me

If you like our content, feel free to follow me to stay updated.


Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?


Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact