Welcome to the Parameters and Return Values exercises! This topic focuses on understanding how methods receive input through parameters and provide output through return values, building on your knowledge of classes, objects, and instance methods.
- Understanding different parameter types and how to use them effectively
- Working with multiple parameters and parameter validation
- Understanding return types and when to use different return strategies
- Method overloading with different parameter signatures
- Best practices for designing method interfaces
- Handling edge cases and error conditions through return values
These exercises focus specifically on the input/output aspects of methods, exploring different ways to pass data in and get results out. You'll work with various parameter patterns and return value strategies.
Class: DataValidator
Create a class that validates different types of data with detailed feedback.
Requirements:
- Methods that take parameters and return different types of validation results
- Methods:
validateEmail(String email)- ReturnStringwith validation message ("Valid" or specific error)validatePassword(String password, int minLength, boolean requireSpecial)- ReturnbooleanvalidateAge(int age, int minAge, int maxAge)- Returnintstatus code (-1: too young, 0: valid, 1: too old)validatePhoneNumber(String phone, String countryCode)- ReturnStringformatted number or "INVALID"validateCreditCard(String cardNumber, String expiryDate)- Returnboolean[]array [isValidNumber, isNotExpired]getValidationSummary(String email, String password, int age)- ReturnStringsummary of all validations
Class: MathEngine
Create a mathematical calculator that handles different types of calculations with various parameter combinations.
Requirements:
- Methods with different parameter counts and types
- Methods:
calculate(double a, double b, String operation)- Returndoubleresult of operation (+, -, *, /, %)findRange(double[] numbers)- Returndouble[]with [min, max]statisticalSummary(double[] values)- ReturnStringwith "Mean: X, Median: Y, Mode: Z"compound(double principal, double rate, int years, boolean isAnnual)- Returndoublecompound interestdistance(double x1, double y1, double x2, double y2)- Returndoubledistance between pointsquadraticRoots(double a, double b, double c)- ReturnString[]with solutions or ["NO_REAL_ROOTS"]isPrime(long number)- Returnbooleanwith prime check for large numbers
Class: TextAnalyzer
Create a text analysis tool that processes strings with various parameter options.
Requirements:
- Methods with optional behavior through parameters
- Methods:
extractWords(String text, boolean removePunctuation, boolean toLowerCase)- ReturnString[]findPattern(String text, String pattern, boolean ignoreCase)- Returnint[]positions of matchesreplaceText(String original, String find, String replace, int maxReplacements)- ReturnStringsummarizeText(String text, int maxSentences, boolean preserveOrder)- ReturnStringcompareTexts(String text1, String text2, boolean ignoreCase, boolean ignoreSpaces)- Returndoublesimilarity (0.0-1.0)formatText(String text, int lineLength, String alignment, boolean addNumbers)- ReturnString[]formatted linesextractEmails(String text, String domain)- ReturnArrayList<String>emails (empty domain = all domains)
Class: CollectionProcessor
Create a utility class for processing collections with various parameter configurations.
Requirements:
- Methods that work with collections and return processed collections
- Methods:
filterNumbers(ArrayList<Integer> numbers, int min, int max, boolean inclusive)- ReturnArrayList<Integer>sortStrings(ArrayList<String> strings, boolean ascending, boolean ignoreCase)- ReturnArrayList<String>mergeLists(ArrayList<Integer> list1, ArrayList<Integer> list2, boolean removeDuplicates)- ReturnArrayList<Integer>groupByLength(ArrayList<String> words, int targetLength, String comparison)- ReturnHashMap<String, ArrayList<String>>findCommonElements(ArrayList<String> list1, ArrayList<String> list2, boolean caseSensitive)- ReturnSet<String>processNumbers(ArrayList<Double> numbers, String operation, Double operand)- ReturnArrayList<Double>partitionData(ArrayList<Integer> data, int partitionSize, boolean allowPartial)- ReturnArrayList<ArrayList<Integer>>
Class: PersonFactory
Create a factory class that creates Person objects with different parameter combinations and returns them.
Requirements:
- Methods that create objects with different parameter sets
- Inner class:
Personwith fields:String name, int age, String email, String city, boolean isEmployed - Methods:
createBasicPerson(String name, int age)- ReturnPersonwith basic infocreateDetailedPerson(String name, int age, String email, String city)- ReturnPersonwith full infocreateEmployedPerson(String name, int age, String email, String city, boolean isEmployed)- ReturnPersoncreatePersonFromCsv(String csvLine)- ReturnPersonparsed from "name,age,email,city,employed"createRandomPerson(String[] namePool, int minAge, int maxAge)- ReturnPersonwith random datavalidateAndCreatePerson(String name, Integer age, String email)- ReturnPersonornullif invalidbatchCreatePeople(String[] names, int[] ages, String[] emails)- ReturnArrayList<Person>
Class: ConfigManager
Create a configuration manager that handles different types of settings with flexible parameters.
Requirements:
- Methods that manage configuration with various parameter types
- Fields:
HashMap<String, Object> settings - Methods:
setSetting(String key, Object value, boolean overwrite)- ReturnbooleansuccessgetSetting(String key, Object defaultValue)- ReturnObjectsetting or defaultgetStringSetting(String key, String defaultValue, boolean trim)- ReturnStringgetIntSetting(String key, int defaultValue, int minValue, int maxValue)- Returnintclamped valuegetBooleanSetting(String key, boolean defaultValue)- ReturnbooleanexportSettings(String[] keys, String format)- ReturnStringin JSON or XML formatimportSettings(String data, String format, boolean replaceExisting)- Returnintcount of imported settings
Class: DatabaseQuery
Create a database query builder that demonstrates advanced parameter usage patterns.
Requirements:
- Methods with complex parameter combinations and conditional logic
- Methods:
select(String table, String[] columns, String whereClause, Object[] parameters)- ReturnStringSQLinsert(String table, HashMap<String, Object> data, boolean ignoreConflicts)- ReturnStringSQLupdate(String table, HashMap<String, Object> updates, String whereClause, Object[] whereParams)- ReturnStringSQLjoin(String leftTable, String rightTable, String joinType, String[] conditions)- ReturnStringSQLbuildQuery(String operation, String table, Object... parameters)- ReturnStringusing varargsexecuteQuery(String sql, Object[] parameters, boolean returnResults)- ReturnQueryResult(create simple result class)batchExecute(String[] queries, Object[][] allParameters, boolean stopOnError)- Returnint[]affected counts
- Open the
topic.jshfile - Start with Exercise 1 (
DataValidator) - Focus on understanding how each parameter affects the method's behavior
- Pay attention to return types and what they communicate to the caller
- Test each method with different parameter combinations
- Move through exercises progressively
- Parameter Types: Understand when to use different parameter types
- Parameter Order: Logical ordering of parameters for usability
- Return Types: Choose return types that best serve the method's purpose
- Null Handling: How to handle null parameters and return null appropriately
- Parameter Validation: Check parameters and return appropriate error indicators
- Method Overloading: Same method name with different parameter signatures
- Optional Parameters: Simulating optional parameters through method overloading
- Required vs Optional: Put required parameters first, optional ones last
- Logical Grouping: Group related parameters together
- Meaningful Names: Parameter names should clearly indicate their purpose
- Type Safety: Use specific types rather than generic Object when possible
- Validation: Always validate parameters, especially public method parameters
- Success/Failure: Use boolean for simple success/failure operations
- Status Codes: Use int for operations with multiple possible outcomes
- Null vs Exception: Decide when to return null vs throw exceptions
- Collection Returns: Return empty collections rather than null when no results
- Complex Results: Use custom classes or arrays for multiple return values
Each exercise has comprehensive tests that check:
- Different parameter combinations
- Edge cases (null, empty, extreme values)
- Return value correctness
- Parameter validation behavior
- Method overloading works correctly
Make sure all tests pass and understand why each parameter and return value choice was made!