Java program to toggle each character in a string

Toggle each character in a String

 

In this java program we’re going to make a program to toggle each character in a String , First we will take String input from user  .  After that we will store String in variable ‘s’ (in this case) . Take another String s1 variable  , Take a for loop i start from i=0 to i<s.length

Take if part get one by one character from String using charAt() method and and check whether is it upper case using isUpperCase() and change upper case character to lower case and store it in s . In else part change the variable from lower case to upper case and store it in s variable 

Java program to toggle each character in a string

Algorithm

  • Take String input from user and store in the variable “s” (in this case)
  • Take another String variable s1 (in this case)
  • Take a for loop i start from i=0 to i<s.length
  • Take if part get one by one character from String using charAt() method and and check whether is it upper case using isUpperCase() and change upper case character to lower case and store it in s
  • In else part change the variable from lower case to upper case and store it in s variable

Code in Java

import java.util.Scanner;

public class ToggleEachCharacterInAString {

	public static void main(String[] args) {
	 Scanner sc = new Scanner(System.in); 
	 System.out.print("Enter a String : ");
	 String s = sc.nextLine();
	 String s1 = "";
	 for (int i = 0; i < s.length(); i++) {
		if(Character.isUpperCase(s.charAt(i))) 
			 s1=s1+Character.toLowerCase(s.charAt(i));
		else 
			 s1=s1+Character.toUpperCase(s.charAt(i));
	}
	System.out.println("Toggle String is : "+s1);
	 
  }
	
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter a String : PrePInsTa
Toggle String is : pREpiNStA

One comment on “Java program to toggle each character in a string”