RP. ← All Chapters
Hands-on practice By Salesforce makes sense

Apex Practice Questions

Master the fundamentals of Salesforce development with these targeted exercises. These questions cover everything from Variables to Advanced Collections.

Scenario: Password Attempt Counter

Write a method that checks a list of password attempts against a correctPassword string. If the attempt fails, increment an attemptCounter. If failed attempts reach 3, throw an error and lock the account.

Apex Class Solution

public class PracticeQ1 {
    public static String correctPassword = 'Jun3040';
    public static Integer attemptCounter = 0;

    public static void handlePasswordWithLoop(List<String> tries) {
        for(String s : tries) {
            if(s != correctPassword) {
                attemptCounter++;
                System.debug('failure');
            } else {
                System.debug('Success');
            }

            if(attemptCounter == 3) {
                System.debug('Account Locked');
                break; // Stop processing once locked
            }
        }
    }
}

Execute in Anonymous Window

// 1. Create a list of sample password attempts
List<String> myTries = new List<String>();
myTries.add('password123'); // Fails
myTries.add('wrongPass');    // Fails
myTries.add('Jun3040');      // Success!

// 2. Execute the logic
PracticeQ1.handlePasswordWithLoop(myTries);

// 3. Check logs to see the 'Success' or 'failure' messages

Scenario: Learning Counter

Write a method that display a log of the number of days you learned something new from Salesforce Make Sense.

Apex Class Solution

public class PracticeQ1 {
    // Note: Changed 'weekLog' type to match the requirement (Map)
    public static Integer checkNewLearning(Map<String, Boolean> weekLog){
        Integer numberOfDaysILearnentSomeThingNew = 0;
        
        // Iterate over the map keys (the days of the week)
        for(String weekDay : weekLog.keySet()){
            Boolean currentDayStatus = weekLog.get(weekDay);

            // If status is true, increment counter
            if(currentDayStatus){
                numberOfDaysILearnentSomeThingNew++;
            }
        }
        return numberOfDaysILearnentSomeThingNew;
    }
}

Execute in Anonymous Window

// 1. Prepare the data sample (Map of Day -> Learned Status)
Map<String, Boolean> myWeekLog = new Map<String, Boolean>();
myWeekLog.put('Monday', true);
myWeekLog.put('Tuesday', false);
myWeekLog.put('Wednesday', true);
myWeekLog.put('Thursday', true);
myWeekLog.put('Friday', false);

// 2. Call the static method and store result
Integer daysLearned = PracticeQ1.checkNewLearning(myWeekLog);

// 3. Verify the result in Debug Logs
System.debug('--- Results ---');
System.debug('Total days I learned something new: ' + daysLearned);

// Expected Debug Output: 3

Scenario: Counter

Write a method that tracks the number of times '“makes Sense” is used in List of String.

Apex Class Solution

public class PracticeQ1 {
    public static Integer checkForMakesSenseKeyword(List<String>statements){
        Integer makesSenseCounter = 0;
        for(String statement : statements){
            if(statement.contains('Makes Sense')){
                makesSenseCounter++;
            }
        }
        return makesSenseCounter;
    }
}

Execute in Anonymous Window

List<String> statements = new List<String>();
statements.add('Ram Prasad, Makes Sense');
statements.add('salesforce Makes Sense');
statements.add('no one is make this type of thing sense');
statements.add('ok thats make sense');
Integer result = PracticeQ1.checkForMakesSenseKeyword(statements);
System.debug(result);

Scenario: Highest & Lowest

Write a method that check the marks on individual subjects and displays the highest and lowest marks as result.

Apex Class Solution

public class PracticeQ1 {
    public static void checkHighAndLow(Map<String, Integer>myReport){
        List<Integer>allMarks = myReport.values();
        allMarks.sort();
        
        System.debug('Max Mark is: '+ allMarks[allMarks.size() - 1]);
        System.debug('Min Mark is: '+ allMarks[0]); 
    }
}

Execute in Anonymous Window

Map myReportCard = new Map<String, Integer>();
myReportCard.put('Science', 88);
myReportCard.put('Physics', 68);
myReportCard.put('Math', 54);
myReportCard.put('Biology', 78);
myReportCard.put('History', 96);

practiceQ2.checkHighAndLow(myReportCard);

Scenario: TO-DO List

Create methods to manage your to do list you can add and remove what you need to do and what you have done

Apex Class Solution

public class PracticeQ2 {
    public static List<WorkItem>toDoList = new List();  
    public static void addNewWorkItem(WorkItem toDoItem){
        toDoList.add(toDoItem);      
    } 
    public static List<PracticeQ2.WorkItem> retriveToDoList(){
        return toDoList;
    } 
    //method to update the item that i have completed
    public static void updateWorkItem(Integer WorkItemId, String newStatus){
        //find the work item from my current list. if i find it, I will update the corresponding status
        for(PracticeQ2.WorkItem workItem : toDoList){
            if(workItem.toDoId == workItemId){
                workItem.toDoStatus = newStatus;
            }
        }
        System.debug(toDoList); 
    }
    public static void deleteWorkItem(Integer workItemId){
        Integer indexToRemove = -1;
        for(Integer i = 0;i < toDoList.size();i++){
            if(toDoList[i].toDoId == workItemId){
                indexToRemove = i;
                break; 
            }
        }
        if(indexToRemove != -1){
            toDoList.remove(indexToRemove);
        }
        System.debug('Update List after deletion: '+toDoList);
    }
    public static Integer totalToDoListItems(){
        return toDoList.size();     
    }
    public class WorkItem{
        public Integer toDoId;
        public String toDoName;
        public String toDoDescription;
        public String toDoStatus;     
    }
}

Execute in Anonymous Window

PracticeQ2.WorkItem wItem = new PracticeQ2.WorkItem();
wItem.toDoId = 1;
wItem.toDoName = 'Record SMS video';
wItem.toDoDescription = 'Record Practice Questions for my video';
wItem.toDoStatus = 'In Progress';

PracticeQ2.addNewWorkItem(wItem);

PracticeQ2.WorkItem wItem2 = new PracticeQ2.WorkItem();
wItem2.toDoId = 2;
wItem2.toDoName = 'Shop Shelling';
wItem2.toDoDescription = 'shop is not so crowed so we have to sell it';
wItem2.toDoStatus = 'Not Started';

PracticeQ2.addNewWorkItem(wItem2);

List<PracticeQ2.WorkItem> workItems = PracticeQ2.retriveToDoList();
for(PracticeQ2.WorkItem wItem : workItems){
    System.debug(wItem);
}

PracticeQ2.updateWorkItem(2, 'Completed');
PracticeQ2.deleteWorkItem(1);

Scenario: Certification Tracker

Create methods to store your certification along with the issue date create a method that shows the total number of certifications you hold

Apex Class Solution

public class CertificationTracker {
    public static Map<String, Date> myCertificationData = new Map<String,Date>();
    public static void addNewCertifications(String certificateName, Date issueDate){
        myCertificationData.put(certificateName, issueDate);  
    }
    public static List<Date> returnCertCount(){
        return myCertificationData.values();
    }
}

Execute in Anonymous Window


CertificationTracker.addNewCertifications('Platform Developer 1', System.today());
CertificationTracker.addNewCertifications('Platform Developer 2', System.today() - 60);
CertificationTracker.addNewCertifications('System Adminstrator', System.today()- 720);
CertificationTracker.addNewCertifications('Service Cloud Developer', System.today() - 1020);

List dateResult = CertificationTracker.returnCertCount();
System.debug(dateResult);

Scenario: Library Tracker

create method to store your book repository. Create method to track which user has borrowed a book and what is the book name .

Apex Class Solution

public class LibraryTracker {
    
    public static List<String> allMyBook = new List<String>();
    
    //Book Name vs person who borrowed it?
    
    public static Map<String, String>borrowerMapping = new Map<String, String>();
    
    public static void addBooksToLibrary(String bookName){
        allMyBook.add(bookName);
    } 

    public static void leanBooksToSomeone(String bookName, String personName){
        List<String>remainingBooks = new List<String>();    
        if(allMyBook.contains(bookName)){
            borrowerMapping.put(bookName, personName);
        	for(String eachBook : allMyBook){
            	if(eachBook != bookName){
                	remainingBooks.add(eachBook);
            	}
        	}
        	allMyBook = remainingBooks;
        }
    }  

    public static Map<String, String> displayBooksBorrowed(){
        System.debug(borrowerMapping);
        return borrowerMapping;
    }
    
    public static List<String> showMyCurrentRepository(){
        System.debug(allMyBook);
        return allMyBook;
    }

}

Execute in Anonymous Window

LIbraryTracker.addBooksToLibrary('Ikigai');
LibraryTracker.addBooksToLibrary('Rich Dad Poor Dad');
LibraryTracker.addBooksToLibrary('Too good to be True');
LIbraryTracker.addBooksToLibrary('Focus on What Matters');
LibraryTracker.addBooksToLibrary('The 5am Club');

LibraryTracker.showMyCurrentRepository();

LibraryTracker.leanBooksToSomeone('Ikigai', 'Den');
LibraryTracker.leanBooksToSomeone('Rich Dad Poor Dad', 'Riyan');

LibraryTracker.displayBooksBorrowed();
LibraryTracker.ShowMyCurrentRepository();

Scenario: Travel Tracker

Create methods to store your travel journey
Create methods to store your wishlist
Create methods that tells you which Countries You visited ia a particular Year
Create methods that stores the count of the number of times you have been to a specific country.

Apex Class Solution

public class TravelTracker {
    public static Map<Integer, List<String>>placeVisitedDirectory = new Map<Integer, List<String>>();
    public static ListmyWishList;
 
    public static Map<Integer,List<String>> captureLocations(String countryName, Integer yearOfVisit){
        if(placeVisitedDirectory.containsKey(yearOfVisit)){
            
            List<String> countriesVisited = placeVisitedDirectory.get(yearOfVisit);
            countriesVisited.add(countryName);
            
            placeVisitedDirectory.put(yearOfVisit, countriesVisited);
            
        }else{   
            placeVisitedDirectory.put(yearOfVisit, new List{countryName});
        }
        return placeVisitedDirectory;  
    }
    
    public static List<String> wishListTracker(String countryIWishToVisit){
        if(myWishList == null){
            myWishList = new List<String>{countryIWishToVisit};    
        }else{
            myWishList.add(countryIWishToVisit);
        }
 
        return myWishList;
    }
    public static List<String> showCountriesVisited(Integer yearOfVisit){
        return placeVisitedDirectory.get(yearOfVisit);
        
    }
    public static Integer retriveCountryCount(Integer yearOfVisit){
        return placeVisitedDirectory.get(yearOfVisit).size();
        
	}
    
    public static Integer countSpecificCountry(String countryVisited){
        Integer count = 0;
        for(Integer d : placeVisitedDirectory.keySet()){
            for(String str : placeVisitedDirectory.get(d)){
                if(countryVisited == str){
                    count++;
                }
            }
        }
         return count; 
    }   
}

Execute in Anonymous Window


TravelTracker.captureLocations('India', 2002);
TravelTracker.captureLocations('UK', 2027);
TravelTracker.captureLocations('USA', 2030);
TravelTracker.captureLocations('Japan', 2031);
TravelTracker.captureLocations('Egypt', 2033);
TravelTracker.captureLocations('Russia', 2033);
TravelTracker.captureLocations('German', 2036);
TravelTracker.captureLocations('Korea', 2037);
TravelTracker.captureLocations('Italy', 2038);
TravelTracker.captureLocations('Russia', 2040);
Map<Integer, List<String>> myPlaceVisited = TravelTracker.captureLocations('Singapore', 2039);
System.debug(myPlaceVisited);

List<String>resultViews = TravelTracker.showCountriesVisited(2033);
System.debug(resultViews);

System.debug(TravelTracker.retriveCountryCount(2033));

System.debug('This Country visited ' + TravelTracker.countSpecificCountry('Russia') + ' Times');

Scenario: Employee Bonus

The company has decided to give a minimum bonus of 25k to all their employees but there’s a catch

  • Regular employees will get 25k
  • Managerial employees will get 30k
  • Region Heads will get 35k.
  • SVPs will get 40k.
  • VPs will get 50k
  • CEO, COO, CTO will get 75k

So, write a method that accepts the employee type and declares the bonus amount.

Apex Class Solution

public class BonusTracker {
    
    public static Decimal fetchFinalBonusAmount(String employeeType){
        Decimal bonusAmount = 25000;
        
        if(employeeType == 'Manager'){
            bonusAmount += 5000 ;
        }else if(employeeType == 'Region Head'){
             bonusAmount += 10000 ;
            
        }else if(employeeType == 'SVP'){
             bonusAmount += 15000 ;
            
        }else if(employeeType == 'VP'){
             bonusAmount += 20000 ;
            
        }else if(employeeType == 'CEO' || employeeType == 'CTO' || employeeType == 'COO'){
             bonusAmount += 30000 ;
            
        }
        
        return bonusAmount;
        
    }
	
}

Execute in Anonymous Window

System.debug(BonusTracker.fetchFinalBonusAmount('CTO'));