Apex: Flip Your Sentence Backwards

Ever typed something and wanted to flip it backwards just for fun, testing, or logic puzzles? In this blog post, we’ll write a super simple Apex method that reverses any sentence or string you input.

This little utility is not just cool it’s also a great way to practice working with strings and built-in Apex methods. Whether you’re doing text transformations, validations, or just having fun with logic, this one’s for you!

Let’s jump in and see how it works. 🔄

🧠 What Are We Trying to Do?

 

The idea is simple:

  • We take a sentence like "Hello World"

  • Flip it to return "dlroW olleH"

It should work for any string, including:

  • Names

  • Paragraphs

  • Numbers or symbols

🔍 Code Explanation

 
public with sharing class ApexUseCaseFifteen {
    
    public static String reverseMySentence(String sentence){

We begin with a class called ApexUseCaseFifteen, and define a method called reverseMySentence that takes one input a String called sentence.

        String reversedString = sentence.reverse();

This line is the magic ✨.
Apex provides a built-in method called .reverse() which does exactly what it says: reverses the characters in a string.

So if your input is "apple", this returns "elppa".

        return reversedString;
    }
}

We then return the reversed string to whoever called the method.

Simple, efficient, and very readable!

✅ Why This Is Useful

 

You might be thinking — okay, reversing a string is cool, but when would I actually need this?

Here are some ideas:

  • Palindromes: Check if a word reads the same backward (like madam or racecar)

  • Fun UI tricks: Show text animations, flip inputs

  • Encryption or obfuscation: Not secure encryption, but useful for hiding values in demo apps

  • String manipulation practice: If you’re learning, this is a great start

And the best part? It’s just one line of code.

You can even extend this method to:

  • Reverse only words, not characters

  • Reverse individual words in a sentence

  • Add conditions (e.g., ignore spaces, numbers, etc.)

🧾 Final Code Snippet

 
public with sharing class ApexUseCaseFifteen {
    
    public static String reverseMySentence(String sentence){
        String reversedString = sentence.reverse();
        return reversedString;
    }
}

🎥 Watch It in Action!

Want to see this method live in action? I created a short video where I walk through the code and test a few examples using the Developer Console in Salesforce.

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)