Programming lesson
Java Methods Lab Tutorial: Building Reusable Code with multiConcat and Dog Class
Learn how to implement and invoke methods in Java with this step-by-step tutorial. Based on ICS 141 Lab 4, we cover method headers, loops, and testing with user input.
Introduction to Java Methods in Lab 4
In this tutorial, we'll walk through the key concepts of Java methods as required in the ICS 141 Lab 4 assignment. You'll learn how to declare static methods, use loops for string concatenation, and test your methods with user input. We'll also explore adding methods to a Dog class and invoking them from a driver class. By the end, you'll be able to create reusable code blocks that make your programs more modular and easier to maintain.
Think of methods like the special moves in a fighting game: each move has a specific input and output, and you can call them whenever needed. Just as a pro gamer chains combos, you'll chain method calls to build powerful programs.
Understanding Method Structure
Before diving into code, let's break down the parts of a method header. For example, consider the method multiConcat from Part 1 of the lab:
public static String multiConcat(String str, int times)- Access modifier:
public— visible to other classes. - Static modifier:
static— belongs to the class, not an instance. - Return type:
String— the method outputs a string. - Method name:
multiConcat— descriptive of what it does. - Parameters:
String strandint times— inputs the method expects.
In your Method class, you'll also declare a private static int count variable. This variable can track how many times a method is called, which is useful for debugging or analytics—similar to tracking API calls in a web app.
Implementing the multiConcat Method
Follow these steps to implement the method body:
- Declare a local
String result = "";to hold the output. - Use a
forloop that runstimesiterations. - Inside the loop, append
strtoresultusingresult += str;. - Return
result.
Here's the complete method:
public static String multiConcat(String str, int times) {
String result = "";
for (int i = 0; i < times; i++) {
result += str;
}
return result;
}Testing this method with inputs "hi" and 4 should return "hihihihi". This kind of string repetition is used in many real-world applications, from generating placeholder text to creating AI training data patterns.
Testing with User Input in Main
In your DogDriver class (or any main class), prompt the user for a string and a number of repetitions. Use a Scanner to read input, then call Method.multiConcat and print the result.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputStr = scanner.nextLine();
System.out.print("Enter number of repetitions: ");
int reps = scanner.nextInt();
String output = Method.multiConcat(inputStr, reps);
System.out.println("Result: " + output);This interactive testing is similar to how finance apps ask for user input to calculate compound interest or loan payments.
Adding Methods to the Dog Class
Part 2 of the lab asks you to add four methods to the Dog class. Let's implement each one:
1. price method
public double price(int quantity, double price) {
return quantity * price;
}This method calculates total cost—useful for e-commerce or gaming microtransactions where you buy multiple items.
2. greetings method
public String greetings(String greet) {
return "Hello, " + greet + "!";
}Personalized greetings are common in AI chatbots and school portals.
3. makeSound method (void)
public void makeSound() {
System.out.println("Woof!");
}Void methods perform an action without returning a value. This is like a notification sound on your phone.
4. eat method (void with parameter)
public void eat(String brand) {
System.out.println("The dog eats " + brand + " food.");
}Methods that take parameters allow customization—similar to AI image generators that accept prompts.
Invoking Methods in DogDriver
In your DogDriver main method, create a Dog object and call each method:
Dog myDog = new Dog();
double totalPrice = myDog.price(3, 25.99);
System.out.println("Total price: " + totalPrice);
String greeting = myDog.greetings("Buddy");
System.out.println(greeting);
myDog.makeSound();
myDog.eat("Pedigree");Notice how you call instance methods on an object, while multiConcat was called on the class itself (static). This distinction is crucial in Java OOP.
Checkpoint and Submission
After testing, show your output to your lab instructor. Then export your project as a ZIP file (e.g., DillonLab04.zip) and upload it to D2L under the Lab4 dropbox. Remember to use your last name in the filename for easy identification.
Real-World Analogy: Methods as Game Abilities
Imagine you're playing a battle royale game like Fortnite. Each character has abilities (methods) like buildWall(), shoot(), or heal(). These abilities take parameters (e.g., shoot(int damage)) and return results (e.g., boolean hitTarget). By designing your code with methods, you make it easier to update and reuse—just like game developers patch abilities without rewriting everything.
Similarly, in AI apps like ChatGPT, functions like generateResponse(prompt) take a string and return a string. The same principle applies: encapsulate logic in methods for clarity and reusability.
Common Mistakes to Avoid
- Forgetting the
statickeyword when calling a static method from a static context (main). - Mismatched parameter types or order when invoking methods.
- Not initializing local variables before use.
- Using
voidwhen you need to return a value.
Conclusion
By completing this lab, you've practiced writing and invoking both static and instance methods in Java. These skills are foundational for building larger applications, whether you're developing school projects, finance calculators, or AI-driven tools. Keep experimenting with different method signatures and see how they improve your code's organization.
For more Java tutorials, check out our other guides on loops, arrays, and object-oriented programming.