Course Content
Java Basics
Java Basics
Java's Syntax
The Syntax We'll Use
Java syntax might seem intimidating at first, especially when you're writing a basic main class with phrases like public static void
. But it's not as complicated as it appears. This syntax is just the starting point for your program, and the Java compiler looks for it to run your code.
You can easily remember how it should look, but here's a quick breakdown of what each part does:
Main
public class Main { public static void main(String[] args) { } }
public class Main
introduces a class, which serves as the foundation for our work. Since Java is an Object-Oriented Programming (OOP) language, classes play a crucial role. You will learn what a class is and how to work with it in a separate course;- The
public static void main
line is what you'll frequently interact with. Let's break down each word:public
is an access modifier that allows themain
method to be accessed from anywhere in the program;static
means that themain
method belongs to the class itself and can be invoked without creating an instance of the class;void
indicates that themain
method doesn't return any value;String[] args
is an array of strings used to pass command-line arguments to the program.
- Java code is always enclosed within curly braces
{ }
, which represent the body of our code; - A semicolon
;
must be placed at the end of each line of code, except when defining classes and methods. This helps structure the code.
Output operation
We can print a message to the console using the command System.out.println()
.
Keep in mind that we need to place this command inside the curly braces of the main
method. Here's an example:
Main
package com.example; public class Main { public static void main(String[] args) { System.out.println("Message for you"); } }
The package com.example
is used to group related classes together in a Java project. It helps keep things organized and avoids issues when different classes have the same name. Think of it like putting files into different folders on your computer to stay organized.
As we can see, this code prints a message for us. Using the System.out.println()
command, we can annotate relevant code snippets and output information that the user will see in the console. We can print any information to the console; the text we want to display should be enclosed in double quotation marks (""
).
Remember that text is displayed using double quotation marks (" "
). Single quotation marks (' '
) represent a completely different data type, which we'll cover later.
Here's an example of how any custom text will be displayed:
Main
package com.example; public class Main { public static void main(String[] args) { System.out.println("Custom message for you"); } }
Thanks for your feedback!