Before writing any Java code, let’s understand some basic building blocks of Java.
Functions / Methods
Functions are the basic building blocks of a Java program. A function is a snippet of code that performs a specific task. Every function has a return type and a set of parameters which are optional. Every Java program must have a main method. Functions belonging to a class are called as methods.
Class
A class is a container for a set of related functions. No method can exists without a class. A class is more than that which will be discussed later
Package —
A package is a collection of related classes. The standard practice for the base package name is the domain name in reverse. We don’t actually need a domain on the internet. It is just a way to create a namespace for the project.
package io.rizwan; // <----- package name
public class Main { // <-------- class declaration
public static void main(String[] args) { // <------- method declaration
// print "Hello World" on the console
System.out.println("Hello World");
}
}
System.out.println("Hello World");
is used to print any string that is passed as an argument on the console.
Detailed Explanation —
System
is a class that has a field called out
which returns a reference, of type PrintStream
. The PrintStream
class has a method called println
which prints the text that is passed as an argument on the new line in the console or terminal.“Hello World”
is passed as an argument in the println
method//
(Double forward slashes). Comments don’t get executed. As a best practice we should comment about why we wrote the block of code instead of what and how.Naming Convention, for Classes — PascalNamingConvention
and for Methods — camelNamingConvention
. Also, Starting curly braces should be on the same line as the method declaration.
<aside> 👨💻
Every statement in Java ends with a semicolon. Java is a case-sensitive language i.e. println
and Println
will be treated differently. In fact the program won’t compile if we write Println
</aside>