Pure Method in Java

Rumman Ansari   Software Engineer   2024-07-25 07:53:18   237  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Pure Method

A pure method is a method that adheres to the following principles:

  1. No Side Effects: A pure method does not alter any external state or variables. It only operates on its input parameters and returns a result based solely on those inputs.

  2. Deterministic: For the same set of input values, a pure method always produces the same output. The output is predictable and consistent.

  3. No External Dependencies: It does not rely on or affect any external state, class variables, or other methods. The behavior of a pure method is entirely contained within itself.

Example:

<span class="pln">
</span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> </span><span class="kwd">add</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> a</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> b</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> a </span><span class="pun">+</span><span class="pln"> b</span><span class="pun">;</span><span class="pln"> </span><span class="com">// Only depends on input parameters</span><span class="pln">
</span><span class="pun">}</span><span class="pln">
</span>
  • No Side Effects: The method does not modify any variables outside of its scope.
  • Deterministic: For the same values of a and b, the method will always return the same result.
  • No External Dependencies: It only depends on its parameters.

MCQ Available

There are 1 MCQs available for this topic.

1 MCQ

No Questions Data Available.
No Program Data.

Stay Ahead of the Curve! Check out these trending topics and sharpen your skills.