When you call a function, the program follows a specific sequence: it passes your parameters to the function, executes the function's code, and returns a result back to where it was called. This process is shown in the diagram below:
graph TD
A[Program Execution] --> B[Function Call]
B --> C[Pass Parameters]
C --> D[Execute Function Body]
D --> E[Return Result]
E --> F[Continue Program]
G[Function Benefits] --> H[Code Reusability]
G --> I[Modularity]
G --> J[Easier Testing]
G --> K[Better Organization]
style B fill:#e3f2fd
style D fill:#fff3e0
style E fill:#c8e6c9
style H fill:#c8e6c9
style I fill:#c8e6c9
style J fill:#c8e6c9
style K fill:#c8e6c9
The diagram shows both the execution flow (top) and the benefits (bottom) of using functions in your programs.
Optional Parameters are parameters that can be omitted when calling a function. They can be implemented in different ways:
With Default Values: The parameter gets a specific default value when omitted
Nullable/Optional Types: The parameter can be null/undefined and must be checked
Default Values are specific values assigned to parameters that are used when no value is provided. This is the most common way to implement optional parameters.
Java doesn't support optional parameters directly. Use method overloading instead.
// Optional parameter with null checkingfunplayChord(root:String,type:String?=null){valchordType=type?:"major"println("Playing $root$chordType chord")}playChord("C")// Playing C major chordplayChord("G","minor")// Playing G minor chord
// Optional parameter with undefined checkingfunctionplayChord(root:string,type?:string){constchordType=type||"major";console.log(`Playing ${root}${chordType} chord`);}playChord("C");// Playing C major chordplayChord("G","minor");// Playing G minor chord
// Optional parameter with null checkingvoidplayChord(Stringroot,{String?type}){StringchordType=type??"major";print('Playing $root$chordType chord');}playChord("C");// Playing C major chordplayChord("G",type:"minor");// Playing G minor chord
// Optional parameter with nil checkingfuncplayChord(root:String,type:String?=nil){letchordType=type??"major"print("Playing \(root)\(chordType) chord")}playChord(root:"C")// Playing C major chordplayChord(root:"G",type:"minor")// Playing G minor chord
# Optional parameter with None checkingdefplay_chord(root:str,type:str=None):chord_type=typeiftypeisnotNoneelse"major"print(f"Playing {root}{chord_type} chord")play_chord("C")# Playing C major chordplay_chord("G","minor")# Playing G minor chord