Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson 1. Programming on Java in Microsoft Visual ...

Lesson 1. Programming on Java in Microsoft Visual Code

Java Programming Fundamentals

Essential syntax, concepts, and practical labs for beginners.

Useful Keyboard Shortcuts

The following shortcuts are valuable when working in Visual Studio or similar IDEs:

  • ▶ [CTRL] + K + C — Comment a block of code.
  • ▶ [CTRL] + K + U — Uncomment a block of code.
  • ▶ [F5] — Execute the program (with debugging).
  • ▶ [CTRL] + F5 — Start the application without debugging.
  • ▶ [ALT] + [SHIFT] + F — Formatting code.

Theory: Java Syntax - Statements

In Java, a statement is considered a command. Statements perform actions in your code, such as calling a method or performing calculations. They are also used to declare variables and assign values to them.

Statements are formed from tokens. These tokens can be keywords, identifiers (variables), operators, and the statement terminator, which is the semicolon (;). All statements in Java must be terminated with a semicolon.

Example:


int myVariable = 2;

In this example, the tokens are: int, myVariable, =, 2, and ;.

int is the data type for the variable myVariable.

The = is an assignment operator used to set myVariable to 2.

The numeral 2 is a literal value. A literal is exactly what it represents; you cannot assign a value to 2, but you can assign it to a variable.

Finally, the statement ends with a semicolon.

Using Constants

A named constant is an identifier that represents a permanent (unchanging) value.

The value of a variable can change during program execution, whereas a named constant (or simply a constant) represents a fixed value that never changes. In Java, a constant is also known as a final variable.

Syntax for declaring a constant:


final DataType CONSTANT_NAME = value;

A constant must be declared and initialized in the same statement. In Java, the keyword final is used to declare a constant. By convention, constant names are written in uppercase letters.

Example:


// Using π constant in area calculation
final double PI = 3.14159;
double radius = 5.0;
double area = PI * radius * radius;

Theory: Java Syntax - Identifiers

In Java, an identifier is a name you assign to elements in your program. These elements include:

  • ▶ Classes — Blueprints for reference types. They define the structure of an object.
  • ▶ Methods — Discrete pieces of functionality, analogous to functions in non-OOP languages.
  • ▶ Variables — Identifiers that hold values or references to objects; essentially named memory locations.

When creating a variable, you must specify its data type. This informs the compiler about the kind of data to be stored, contributing to Java's type safety.

Examples of Variable Declarations

Here are several examples of declaring variables in Java:

int count;                // declares 'count' as an integer variable
double radius;            // declares 'radius' as a double-type variable
double interestRate;      // declares 'interestRate' (interest rate) as a double-type variable

In these examples, the data types int and double are used. Later, you will learn about other data types, such as byte, short, long, float, char, and boolean.

Declaring Multiple Variables of the Same Type

If variables are of the same type, they can be declared together in a single statement using the following syntax:


                
int i, j, k;  // declares i, j, and k as int-type variables

Variable Initialization

Variables often have initial values. You can declare a variable and initialize it (i.e., assign it an initial value) in one statement. For example:

int count = 0;                  // declares and initializes 'count' to 0
double radius = 5.0;            // declares and initializes 'radius' to 5.0
double interestRate = 0.05;     // declares and initializes 'interestRate' to 0.05 (5%)

This combined declaration‑and‑initialization approach is common and helps ensure variables have meaningful starting values right from the moment they are created.

Code Sample: Declaring and assigning a variable.


int myVar = 0;

Identifier Rules

  • ▶ Identifiers are case-sensitive (myVar and myvar are different).
  • ▶ Can contain letters, digits, and underscores (_).
  • ▶ Must start with a letter or underscore (not a digit). myVar and _myVar are legal; 2Vars is not.
  • ▶ Cannot be a Java reserved keyword (e.g., double, class).

Theory: Java Syntax - Operators

An operator is a token that performs operations on one or more operands within an expression. Not all operators are valid for all data types.

Examples:

3 + 4 — Adds two numbers.

counter++ — Increments the variable counter by one.

"Tom" + "Sawyer" — Concatenates strings, resulting in "TomSawyer".

"Tom"++ — Invalid! The increment operator cannot be applied to strings.

Common Java Operators by Type

Type Operators
Arithmetic +, -, *, /, %
Increment/Decrement ++, --
Comparison ==, !=, <, >, <=, >=
String Concatenation +
Logical &&, ||, !
Assignment =, +=, -=, *=, /=, %=
Conditional (Ternary) ?:

Compound Assignment Operators

Arithmetic operators +, -, *, /, and % can be combined with the assignment operator to form compound assignment operators.

Example of standard increment:


count = count + 1;  // Traditional way
count += 1;         // Using compound assignment

Compound Assignment Operators Table

Operator Name Example Equivalent to
+= Addition assignment i += 8 i = i + 8
-= Subtraction assignment i -= 8 i = i - 8
*= Multiplication assignment i *= 8 i = i * 8
/= Division assignment i /= 8 i = i / 8
%= Modulo assignment i %= 8 i = i % 8

Evaluation Order: A compound assignment operator is executed last, after all other operators in the expression have been evaluated.


x /= 4 + 5.5 * 1.5;
// Equivalent to:
x = x / (4 + 5.5 * 1.5);

Important Notes:

  • ▶ No spaces are allowed within compound assignment operators. For instance, + = is invalid; it must be written as +=.
  • ▶ The right hand side of a compound assignment is fully evaluated before the assignment takes place.

Increment and Decrement Operators

The ++ (increment) and -- (decrement) operators are used to increase or decrease a variable's value by 1, respectively.

Operator Forms

The ++ and -- operators have two forms:

  • ▶ Postfix (post increment/post decrement): the operator is placed after the variable (i++, j--).
  • ▶ Prefix (pre increment/pre decrement): the operator is placed before the variable (++i, --j).

Usage Examples:


// Postfix form
int i = 3, j = 3;
System.out.print (i++); // output i = 3, but i becomes 4 after the line is compiled
System.out.print (i); // i = 4 j--; // j becomes 2 // Prefix form int i = 3, j = 3; System.out.print (++i); // i becomes 4 at once, and output i = 4 System.out.print(i); // i = 4 --j; // j becomes 2

Key Difference Between Prefix and Postfix Forms

The crucial distinction becomes apparent when using the operators in expressions:

  • ▶ Postfix operator (i++): First returns the current value of the variable, then increments it by 1.
  • ▶ Prefix operator (++i): First increments the variable by 1, then returns the new value.

Postfix Increment Example:


int i = 5;
int result = i++;
// result = 5, i = 6

Prefix Increment Example:


int i = 5;
int result = ++i;
// result = 6, i = 6

Restrictions:

  • ▶ The ++ and -- operators can only be applied to variables (not constants or expressions).
  • ▶ They cannot be used with literals (e.g., 5++ is an error).
  • ▶ No whitespace is allowed within the operator (i.e., i ++ or ++ i is invalid).

Java Input Methods Reference

In Java, System.out is used to refer to the standard output device, and System.in is used to refer to the standard input device. By default, the output device is the display monitor, and the input device is the keyboard.

To perform console input, you need to use the Scanner class to create an object for reading input data from System.in.

Using Scanner class for input:

Step 1: Import Scanner class


import java.util.Scanner;

Step 2: Create Scanner object


Scanner scanner = new Scanner(System.in);

The statement Scanner scanner = new Scanner(System.in);  creates a Scanner object and assigns its reference as the value of the variable scanner.

Step 3: Read different data types


int num = scanner.nextInt();      // Read integer
double d = scanner.nextDouble();  // Read double
String text = scanner.next();       // Read single word
String line = scanner.nextLine();    // Read entire line

Step 4: Close scanner when done


scanner.close();

The Scanner class is located in the java.util package. This package is imported into the program when java.util.Scanner is imported. Then, a Scanner-type object is created. Note that the import statement can be omitted if you replace Scanner with java.util.Scanner .

There are two types of import statements: single and group (also called wildcard).

  • Single import specifies one particular class from a package. For example, the following statement imports the Scanner class from the java.util package:

    import java.util.Scanner;
    
  • Group import brings in all classes from a package using the asterisk (*) as a wildcard. For instance, the following statement imports all classes from the java.util package:

    import java.util.*;
    

Important notes:

  1. Information about classes in an imported package is not loaded at compilation or runtime until those classes are actually used.

  2. The import statement merely tells the compiler where to locate the referenced classes.

  3. There is no performance difference between single and group import declarations — both are equally efficient in terms of program execution.

Laboratory Works and Tasks

Lab 0: Hello World

Objective: Create a simple console application that displays "Hello world!" in the console window.

[File name and class name: HelloWorld.java]

Algorithm:

  1. Open Visual Studio Code.
  2. Create a new folder called 'java' to store comleted tasks.
  3. Within the created folder create a new file named HelloWorld.java.
  4. The code will include a class name (must be the same as the file name) and a main function (method).
  5. Inside the main method, add:
    public class HelloWorld{
    public static void main(String[] args) { System.out.println("Hello world!"); } }
  6. To run the project Java Platform Extension for Visual studio Code must be installed. Press F5 to run, VC will give you an advice to install extension. Install it.


  1. Press F5 to run again or select Run button on a special tool.
  2. Save the file. Upload the HelloWorld.java file to the learning management system.

How to Run Java files (even if there is no java extension) :

  1. Save the file as HelloWorld.java.
  2. Compile:

bash (terminal):

javac HelloWorld.java

  1. Run:

bash (terminal):

java HelloWorld


Lab 1: Variables and Data Types

Objective: Create variables of different data types, initialize them with default values, assign values, and output to console.

[File name and class name: L1Lab1.java]

  1. Create a new file named L1Lab1.java.
  2. Complete the code below.
  3. To run current file you should select Stop ([Shift] + F5) in the java tool.
  4. Press F5 to run again or select Run button on a java tool.
  5. Save the file and upload it to the learning management system.

How to Run Java files (even if there is no java extension) :

  1. Save the file (filename.java).
  2. Compile:

bash (terminal):

javac filename.java

  1. Run:

bash (terminal):

java filename


Complete the Code:


/* Lab 1: Create variables of different data types, initialize, assign values, output */
public class L1Lab1 { public static void main(String [] args){ // create variables of different data types // initialize them with the default values String firstname = ""; String lastname = ""; int
age = 0; String city = ""; String country = ""; // Assign some values firstname = "Alex"; lastname = "Ivanov"; age = 18; city = "anyTown"; country = "myCountry"; // use simple output with just variable name System.out.println(firstname); System.out.println(lastname); // use format output: %d - decimal integer, #n - new line System.out.printf("%d years old.%n", age); // use string concatenation System.out.println(city + ", " + country); } }

Lab 2: Increasing a Number by One

Objective: Ask user to input a number, increase it by one, output the result.

[File name and class name: L1Lab2.java]

  1. Create a new file named L1Lab2.java.
  2. To input data a special library must be imported.

Step 1: Import the Scanner Package

First, import the required class from the Java standard library:

import java.util.Scanner;

Step 2: Creating a Scanner Instance

Then create a Scanner type object by passing it an input stream (usually a standard input stream — System.in ):

Scanner scanner = new Scanner(System.in);

Step 3: Reading different types of data

Using the methods of the Scanner class, you can read different types of data:

For reading real numbers:

double n = scanner.nextDouble();

scanner.close();

...

  1. Complete the code.
  2. To run current file you should select Stop ([Shift] + F5) in the java tool.
  3. Press F5 to run again or select Run button on a java tool.
  4. Save the file and upload it to the learning management system.

How to Run Java files (even if there is no java extension) :
  1. Save the file (filename.java).
  2. Compile:

bash (terminal):

javac filename.java

  1. Run:

bash (terminal):

java filename


Complete the Code:


/* Lab 2: Ask user to input a number. Increase the inputted number by one. */
import java.util.Scanner;
public class L1Lab2
{
        public static void main(String[] args)
        {
            System.out.println("Input a number, please";)
            Scanner scanner = new Scanner(System.in);
            double n = scanner.nextDouble();
            n++;
            System.out.Printf("The result: %f", n);

        }
}

Task 1: Calculate Average

Objective: Create a console application that calculates and outputs the arithmetic mean of two given integers.

[File name and class name: L1Task1.java]

Expected Output:

Please, input two integers:
2  6
The average is 4

Note: To get a real-number result from division, ensure one operand is real, e.g., (a + b) / 2.0.

Task 2: Triangle Perimeter and Area

Objective: Ask user to enter a triangle side, calculate perimeter and area of equilateral triangle.

[File name and class name: L1Task2.java]

Expected Output:

Enter a side of triangle, please:
5
Perimeter of the triangle: 15,00 Area: 10,83

Note:  To calculate perimeter: 3 * side, to calculate area: (side² * √3) / 4

In the code you must use Math method: 
(Math.pow(side, 2) * Math.sqrt(3)) / 4;

© 2026 - some matherisals are taken from labs-org.ru

◄ +Lesson 0. Programming and Documentation Style
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

          • Methods (functions)

          • Arrays

          • Topic 4

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • ОИИ

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика