/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		System.out.println(replaceSecondOccurrence("aaaa aa", "aa", "bb"));
	}
	
	public static String replaceSecondOccurrence(String haystack, String needle, String replacement) {
	    int occurenceToReplace = 2;
	    int pos = -1;
	    while (true) {
	        pos = haystack.indexOf(needle, pos + 1);
	        if (pos == -1) {
	            // There is no second occurence. Just return the haystack.
	            return haystack;
	        }
	        if (--occurenceToReplace == 0) return
	            haystack.substring(0, pos) +
	            replacement +
	            haystack.substring(pos + needle.length());
	    }
	}
}