Here's an example of a program in Java that swaps the first and last characters of each word in a sentence
import java.util.Scanner; public class SwapCharacters { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a sentence: "); String sentence = sc.nextLine(); String[] words = sentence.split(" "); for (int i = 0; i < words.length; i++) { char[] wordChars = words[i].toCharArray(); int length = wordChars.length; char first = wordChars[0]; char last = wordChars[length - 1]; wordChars[0] = last; wordChars[length - 1] = first; words[i] = new String(wordChars); } String result = String.join(" ", words); System.out.println("Result: " + result); } }
This program uses a Scanner
object to take an input sentence from the user. It then splits the sentence into words using the split()
method and stores the words in a String
array.
For each word in the array, the program converts it into a char
array and swaps the first and last characters. Finally, the program joins the words back into a sentence using the String.join()
method and prints the result