Here the problem is that temp is a String and you try to assign one String into other. Remember s.getSobject('Owner').get('name') returns object and to convert into String user try to typecst into String that you did. So it is not possible to get the right answer until you use it as a String. Hope it clears you. You can use the below code List<sObject> a = [select owner.name, id from case limit 1]; String[] so = new String[]{'id','owner.name'}; for(sObject s :a) { for(String str : so) { string fieldvalue = str.replace(' ',''); if (str.contains('.')){ List<String> strList = new List<String>(str.split('\\.')); String first = ''; String second = ''; for(Integer i = 0; i < strList.size() -1; i++) { first = strList[i]; } second = strList[strList.size()-1]; //fieldValue = (string) obj; // getting correct string as expected but this not being evaluated to correct field value fieldValue = (String)s.getSObject(first).get(second); } else { fieldvalue = (string) s.get(fieldvalue); //This is working fine } system.debug(fieldvalue); } }