πŸ“š

Β >Β 

πŸ’»Β 

Β >Β 

βš™οΈ

5.6 Writing Methods

4 min readβ€’june 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang


AP Computer Science AΒ πŸ’»

130Β resources
See Units

Now, it’s time to write most of the rest of our methods. But first, a quick reminder about pass-by-value from Unit 2. When we put a primitive variable in as a parameter, we are giving the method a copy of that value so if you change the value of that variable, it does not get carried over to outside that method.
Meanwhile, if you put a reference variable or object as a parameter, it passes a copy of the reference to the method. Changing the value of the variable has the same effect as a primitive variable, but changing information about the variable (such as using a getter method) will carry over outside the method as well. Normally we do not want to modify mutable objects that are passed in as parameters.

Writing Methods

Now, we will write some of the methods for our two classes (others will require information from future topics). Take note of the Javadoc comments and also new instance variables that we have added in order for these methods to work. Any changes we have made to the class will be bolded as in previous topics.

Java Example

/** Represents an assignment that a student will complete */ public class Assignment { private boolean correctAnswer; // represents the answer to an assignment, either T/F /** Makes a new assignment with one True/False question and sets the correct answer */ public Assignment(boolean answer) { correctAnswer = answer; } /** Prints details about the assignment */ @Override public String toString() { return "This is an assignment with correct answer " + answer; } /** Grades an assignment, returns true if correct, false if incorrect */ public boolean gradeAssignment(boolean studentAnswer) { return studentAnswer == correctAnswer; } } /** Represents a high school student */ public class Student { private int gradeLevel; // a grade between 9-12 private String name; // the students name in the form "FirstName LastName" private int age; // the student's age, must be positive private Assignment assignment; // the current assignment the student is working on private int assignmentsComplete; // number of assignments completed private int correctAssignments; // number of correct assignments /** Makes a new student with grade gradeLev, name fullName, and age ageNum */ public Student(int gradeLev, String fullName, int ageNum) { gradeLevel = gradeLev; name = fullName; age = ageNum; assignment = null; // There is no active assignment at the moment assignmentsComplete = 0; // no assignments complete yet correctAssignments = 0; } /** Returns the student's grade level */ public int getGradeLevel() { return gradeLevel; } /** Returns the student's name */ public String getName() { return name; } /** Returns the current assignment the student is working on */ public Assignment returnCurrentAssignment() { return assignment; } /** Prints details about the student */ @Override public String toString() { return name + ", a " + gradeLevel + "th grade high school student has an average grade of " + averageGrade + "."; } /** Changes the student's name */ public void setName(String fullName) { name = fullName; } /** Changes the student's grade level */ public void setGradeLevel(int gradeLev) { gradeLevel = gradeLev; } /** Submits an assignment */ public void submitAssignment() { boolean grade = assignment.gradeAssignment(); assignmentsComplete++; if grade { correctAssignments++ } } /** Calculates the student's grade as a decimal */ public double getGradeDecimal() { return (double) correctAssignments / assignmentsComplete; } }

Format

The typical format of a method header is <access modifier> <return type> <method name> (<parameters>).
  • Access modifiers for Java methods can be: public, private, or protected. One of these three can be followed by static, which we will discuss in the next topic. We will talk more about access modifiers in Topic 5.8.
  • Return type can be: void, String, boolean, int, double, float, char, etc.
  • Method name can be anything, but usually something descriptive that allows you to infer what the method does.
  • You can have any number of parameters or no parameters.
Here are some examples of method headers:
public static void main (String args[])
private String sayHello ()
protected static int addNums (int a, int b)
public void printSum (double a, double b, int c, boolean flag, String text)

Browse Study Guides By Unit
βž•Unit 1 – Primitive Types
πŸ“±Unit 2 – Using Objects
πŸ–₯Unit 3 – Boolean Expressions & if Statements
πŸ•ΉUnit 4 – Iteration
βš™οΈUnit 5 – Writing Classes
⌚️Unit 6 – Array
πŸ’ΎUnit 7 – ArrayList
πŸ’»Unit 8 – 2D Array
πŸ–²Unit 9 – Inheritance
πŸ–±Unit 10 – Recursion
🧐Exam Skills

Fiveable
Fiveable
Home
Stay Connected

Β© 2024 Fiveable Inc. All rights reserved.


Β© 2024 Fiveable Inc. All rights reserved.