Self-Review Questions

  1. Given the following local variable declarations:
    String a = "abc";
    String s = a;
    String t;
    
    What is the value of the following statements?
     
    1. ___true___ 'b' + 2 == 'd'
       
    2. ____5_____ (char)('5' - 0)
       
    3. _compile error_ t.length()
       
    4. ___true___ s == a
       
    5. ___5abc___ 5 + a
       
    6. ___ABC____ a.toUpperCase()
       
    7. ___false__ (a.length() + a).startsWith("a")
       
    8. ____4_____ "Algorithm".indexOf("r")
       
    9. ____Algo__ "Algorithm".substring(0,4)
       
    10. ___true___ "Algorithm".substring(2).startsWith("go")
       
    11. ___false__ a.substring(1) == "bc"
       
    12. ____-1____ "ab".compareTo("ac")
       

     

  2. Consider the following code fragment
    String n = new String("Make OOP Fun");
    foobar(n);
    System.out.println(n);
    
    What will this code print? Does it depend on actual implementation of the foobar() method? Explain your answer.

    "Make OOP Fun". It does not depend on the actual implementation of the foobar() method. Strings cannot be changed.

  3. Write a method that prints the ASCII values of uppercase letters of the English alphabet.

    
    public void printASCII(){
    	for(char letter='A'; letter <= 'Z'; letter++){
    		System.out.println(letter + " " + (int)(letter));
    	}
    }
    
    
    
  4. Write a method that counts vowels in a string.

        public int countVowels(String s){
            int count = 0;
            String vowels = "aeiou";
            String lower = s.toLowerCase();
            for(int i=0; i<s.length(); i++){
                if(vowels.indexOf(lower.charAt(i))> -1)
                    count++;
            }
            return count;
        }