Function Fundamentals Revision
Java Functions
Welcome to the first course in the "Functional Programming in Java" path! Get ready to revisit the basics of functions, and then dive into exciting topics like functional interfaces, the powerful Streams API, and more—it's going to be a great journey toward mastering functional programming in Java!
Functions, or methods, are the building blocks of any Java program. They encapsulate code, making it reusable, modular, and easier to manage. In this section, we'll revisit the foundational concepts of functions in Java, including their syntax, arguments, and return types. We'll also delve into the details of essential keywords used in function declarations.
The Entry Point of a Java Program: main Method
Every Java application must have a main method, which serves as the entry point for the program. It is where the program starts executing.
Let’s break down the main method:
public: This keyword specifies that the method is accessible from outside its defining class. It is the most open access level in Java.static: Indicates that the method belongs to the class, not instances of the class. This means you can call the method without creating an object of the class.void: The return type, indicating that the method does not return any value. If the function were to return something, this keyword would be replaced with the appropriate type (e.g.,int,String).main: This is the name of the method, and it is a special method recognized by the Java runtime as the entry point of the application.String[] args: This is an array ofStringarguments passed to themainmethod. It allows for command-line arguments to be passed to the program.
Function Syntax and Structure
In Java, a function is defined by specifying its return type, name, and any parameters it may take. Let’s break down the sayHello function:
- Return Type: The type of value the function returns.
voidmeans the function does not return any value. - Function Name: The name of the function, which in this example is
sayHello. - Parameters: Input values the function can accept. This function doesn't take any parameters.
- Function Body: The block of code that runs when the function is called. Here, it prints "Hello, world!" to the console.
