How to write Hello World in Java. What is a Statement. How to write Comments in Java

Today we will go over the basic elements of Java:

  • Statement (instructions)
  • Code blocks
  • We will create a simple program Hello World!
  • We will analyze each word in the code
  • We will learn to write comments that are not executed

What is a Statement

Any code in Java consists of statements, which is translated as instruction. An instruction is a command to perform some action: calling a method, initializing a variable, performing an operation, etc.

Each statement ends with a semicolon ;, which signals the compiler that the command is complete.

System.out.println("Hello World!");

{ 
    System.out.println("Hello World!"); 
    System.out.println("Hello Java!"); 
}
Here System.out.println — is a method that prints text to the console.
"Hello World!" — is the message that will be printed.
; — is the end of the statement.

Code Block

Instructions can be combined into code blocks, which are enclosed in curly braces { }:

{
    System.out.println("Hello World!");
    System.out.println("Hello Java!");
}
This block contains two instructions, each of which will output a message to the console.
The more functionality the program has, the more instructions it contains.

Hello World in Java

The simplest Java program looks like this:

public class JavaStart {
    public static void main(String args[]) {
        System.out.println("Hello World!");
    }
}

Breakdown by parts:

1. Class definition:

public class JavaStart { ... }
  • public — access modifier, the class is accessible to everyone.
  • class — keyword for defining a class.
  • JavaStart — the name of the class.

2. The main method — the entry point of the program:

public static void main(String args[]) { ... }
  • public — the method is accessible to everyone.
  • static — the method is static, called without creating an object.
  • void — the method does not return a value.
  • main — the name of the method.
  • (String args[]) — command-line arguments (an array of strings).
All instructions that you place inside { ... } of the main method will be executed when the program runs.

Comments in Java

Comments are lines of code that are not executed by the compiler. They help the developer understand the logic of the program.

1. Single-line comment

// This is a single-line comment
System.out.println("Hello World!"); // Comment after the code

2. Block comment

/*
   This is a block comment,
   which can span multiple lines
*/
System.out.println("Hello Java!");
It is recommended to leave comments on strategically important logic of the program to facilitate work for yourself and other developers.

Homework

  1. Create a new class (come up with a name on your own).
  2. Write code that prints a message to the console (come up with the text on your own).
  3. Try to comment your code in two ways: single-line and block.

Test — How well did you understand the lesson?


🌐 in English
Всего лайков:0

Оставить комментарий

Мой канал в социальных сетях
Отправляя email, вы принимаете условия политики конфиденциальности

Полезные статьи:

Когда HashMap начинает убивать продакшн: инженерная история ConcurrentHashMap
Представьте обычный продакшн-сервис. 32 CPU сотни потоков кэш конфигурации / сессий / rate limits десятки тысяч операций в секунду И где-то внутри — обычный Map. Сначала всё выглядит безобидно. Map&...
Error handling и defer в Go (Параллельность и синхронизация) | Паттерны, идиомы и лучшие практики Go
Обработка ошибок в Go сильно отличается от привычного Java-подхода с исключениями. Вместо try/catch Go использует возврат ошибки как отдельного значения, а `defer` помогает безопасно освобождать ресур...
Понимаем многопоточность в Java через коллекции и атомики
1️⃣ HashMap / TreeMap / TreeSet (не потокобезопасные) HashMap: Структура: массив бакетов + связные списки / деревья (для коллизий). Под капотом: при put/remove происходит модификация массива бакетов ...

Новые статьи:

Конкурентность — это не про «запустить много потоков». Это про договорённости между ними. Представь кухню ресторана: — повара (потоки / горутины) — заказы (задачи) — и главный вопрос: как они коорди...
История начинается не с академической теории, а с типичной production-проблемы. Представьте сервис: 48 CPU 300+ потоков нагрузка 200k операций в секунду много shared state Команда использует обы...
Когда HashMap начинает убивать продакшн: инженерная история ConcurrentHashMap
Представьте обычный продакшн-сервис. 32 CPU сотни потоков кэш конфигурации / сессий / rate limits десятки тысяч операций в секунду И где-то внутри — обычный Map. Сначала всё выглядит безобидно. Map&...
Fullscreen image