Java
Java
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and
methods from the class.
Java Methods
A method is a block of code which only runs when it is called. You can pass data, known as parameters,
into a method. Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an
object of the Main class. You will learn more about objects and how to
access methods through objects later in this tutorial.
void means that this method does not have a return value. You will learn
more about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
A method can also be called multiple times:
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to print
"Hello World" to the screen:
Example explained
Every line of code that runs in Java must be inside a class. And the class name should always start with
an uppercase first letter. In our example, we named the class Main.
The name of the java file must match the class name. When saving the file, save it using the class name
and add ".java" to the end of the filename. To run the example above on your computer, make sure that
Java is properly installed: Go to the Get Started Chapter for how to install Java. The output should be:
The main() method is required and you will see it in every Java program:
Any code inside the main() method will be executed. Don't worry about the keywords before and after
it. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and
that every program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen: