Lab Letter Name CSE 110 Lab 3 Objects and Classes in Java La
Solution
Here is the code explained as comments after each statement:
import java.util.Scanner;
 public class StringManips
 {
 public static void main(String[] args)
 {
 String phrase = new String(\"Programming is fun.\");   //Initializes a string.
 int phraseLength;   //number of characters in the phrase String.
 int middleIndex;    //index of the middle character in the String
 String firstHalf;    //first half of the phrase String.
 String secondHalf;   //second half of the phrase String.
 String switchedPhrase;   //a new phrase with original halves switched.
   
 //compute the length and middle index of the phrase.
 phraseLength = phrase.length();   //Statement 1.
 //This assigns the length of the phrase to the variable phraseLength.
 //Therefore, after executing this block, phraseLength will be assigned a value of 19.
   
 middleIndex = phraseLength / 2;
   
 //get the substring for each half of the phrase.
 firstHalf = phrase.substring(0, middleIndex);   //Statement 2.
 //This assigns the first half of the phrase string to the variable firstHalf.
 //Note that middleIndex value is 19 / 2 = 9.
 //Starting from index 0,upto 9-1, i.e., till index 8.
 //And therefore, firstHalf is assigned the value: Programmi
   
 secondHalf = phrase.substring(middleIndex, phraseLength);   //Statement 3.
 //This assigns the second half of the phrase string to the variable secondHalf.
 //Starting from index 9, upto 19-1, i.e., till index 18.
 //As the middleIndex value is 9, the secondHalf is assigned a value: ng is fun.
   
 //concatenate the firstHalf at the end of the secondHalf
 switchedPhrase = secondHalf.concat(firstHalf);   //Statement 4.
 //This assigns the firstHalf concatenated(appended to the right of) to the firstHalf.
 //Therefore, switchedPhrase is assigned a value ng is fun.Programmi
   
 //print information about the phrase
 System.out.println();   //Leaves an empty line.
 System.out.println(\"Original phrase: \" + phrase);   //Prints the string in phrase, i.e., \"Programming is fun.\"
 System.out.println(\"Length of the phrase: \" + phraseLength + \" characters\");   //Prints the length of phrase, i.e., 19.
 System.out.println(\"Index of the middle: \" + middleIndex);   //Print the middleIndex value, i.e., 9.
 System.out.println(\"Character at the middle index: \" + phrase.charAt(middleIndex));   //Statement 5.
 //This prints the character at index middleIndex in the string phrase.
 //phrase holds \"Programming is fun.\", and the middleIndex holds the value of 9.
 //So, the output this statement is: Character at the middle index: n
   
 System.out.println(\"Switched phrase: \" + switchedPhrase); //Prints the string in switchedPhrase, i.e., ng is fun.Programmi
 System.out.println();
 }
 }


