JavaRush /Java Blog /Random EN /Java Syntax: A Brief Introduction to the Programming Lang...

Java Syntax: A Brief Introduction to the Programming Language

Published in the Random EN group

What is Java Syntax?

Java syntax (Java Syntax) is the basis of the language, all the basic rules, commands, and constructs for writing programs that are “understood” by the compiler and the computer. Every programming language has its own syntax, just like the natural languages ​​we use to communicate with each other. This article covers the basic syntax of the Java programming language and is aimed at those learning Java, aspiring developers, or those who know another programming language. Some aspects may not be clear to beginners. If this happens to you, we recommend skipping the difficult parts and focusing on the examples. As with everything else, it is better to learn a programming language cyclically, gradually coming to a deeper understanding of certain concepts. Every Java program is essentially a collection of objects that include data (variables) and behavior (functions or methods). Also, a Java program is a class or several classes. An object is an instance of a class. A class is a model, such as a cookie cutter, and objects are cookies. Or, let’s say, a class is an abstract “Java programmer”, and an object is “Java programmer Ivan” or “Java programmer Alice”.

Objects in Java

Objects in Java have states and behavior. Here's an example. The cat has a fortune: his name is Barsik, his color is red, his owner is Ivan. The cat also has behavior: now Barsik is sleeping. He can also purr, walk and so on. An object is an instance of a class.

Class in Java

A class is a model, template, or blueprint of an object. It describes the behavior and states what an object of its type supports. For example, the Cat class has its own name, color, owner; The cat also has behavior: eating, purring, walking, sleeping.

Methods in Java

Methods are intended to describe logic, work with data and perform all actions. Each method defines a behavior. A class can contain many methods. For example, we can write a sleep() method for the Cat class (to sleep) or a purr() method for purring.

Instance Variables in Java

Each object has a unique set of instance variables. The state of an object is typically formed by the values ​​that are assigned to these instance variables. For example, the cat's name or age can be variable. Let's start with the simplest Java program. In this example, we will understand the basic components of Java syntax and then look at them in more detail.

A simple program in Java: Hello, Java!

Here is the simplest program in Java:
class HelloJava {
   public static void main(String[] args) {
       System.out.println("Hello, Java!");
   }
}
This program displays the string “Hello, Java!” in the console. I recommend you install JDK and IntelliJ IDEA and try to write the code from this example. Or for the first time, just find an online IDE to do it. Now we will analyze this program line by line, but we will omit some details that are not needed for a beginner.
class HelloJava
Every Java program is a class, or more often a set of classes. The class HelloJava line means that we are creating a new class called HelloJava . As stated above, a class is a kind of template or blueprint; it describes the behavior and states of objects of the class. This may be difficult for new programmers, but don't worry: you'll learn this concept a little later. For now, the HelloJava class is just the beginning of your program. You may have noticed the curly brace { on the same line and throughout the text. A pair of curly braces {} denotes a block, a group of programmable statements that are treated as a single unit. Where { means the beginning of the block, and } its end. Blocks can be nested within each other, or they can be sequential. There are two nested blocks in the above program. The outer one contains the body of the Hello class . The inner block contains the body of the main() method .
public static void main (String args []) {
Here is the beginning of the main method . A method is a behavior or sequence of commands that allows an operation to be performed in a program. For example, multiply two numbers or print a string. In other words, a method is a function. In some other programming languages, methods are often called "functions". Methods, like all elements of a Java program, are located inside a class. Each class can have one, several methods, or no methods at all. Java Syntax: A Brief Introduction to the Programming Language - 1public — access modifier. A variable, method, or class marked with the public modifier can be accessed from anywhere in the program. In Java there are four of them: public, private, protected and default - by default (empty). We'll talk about them a little later. To begin with, it is better to make all your methods public. void is the return type of the method. Void means that it does not return any value. main represents the starting point of the program. This is the name of the method. String[] args is the main argument of the method. For now, it's enough to know that almost every Java program has a main method : it runs the program and is declared as public static void main(String[] args) . Static methods (static) are designed to work with a class. Methods that use the static keyword in their declaration can only operate directly on local and static variables.
System.out.println("Hello, Java!");
Formally, this line executes the println method of the out object . The out object is declared in the OutputStream class and statically initialized in the System class . However, it may seem a little difficult for a beginner. If you're just learning, it's enough to know that this line prints the words "Hello, Java!" in the console. So if you run the program in your development environment (IDE), you will get output like this: Java Syntax: A Brief Introduction to the Programming Language - 2

Basic Java Syntax Rules

There are a few basic syntax rules to follow when programming in Java:
  • The file name must match the class name;
  • Most often, each class is in a separate file with a .java extension . Class files are usually grouped into folders. These folders are called packages;
  • characters are case sensitive. String is not equal to string ;
  • The start of processing a Java program always starts in the main method: public static void main (String [] args) . The main() method is a required part of any Java program;
  • A method (procedure, function) is a sequence of commands. Methods define behavior on an object;
  • The order of the methods in the program file does not matter;
  • Keep in mind that the first letter of the class name must be in uppercase. If you use multiple words, capitalize the first letter of each word (for example, "MyFirstJavaClass");
  • All method names in Java syntax begin with a lowercase letter. When using multiple words, subsequent letters are capitalized ( public void myFirstMethodName () );
  • Files are saved with the class name and extension .java ( MyFirstJavaClass.java );
  • Java syntax has delimiters {...} that denote a block of code and a new region of code;
  • Each code statement must end with a semicolon.

Java Variables and Data Types

Variables are special entities used to store data. Any data. In Java, all data is stored in variables. We can say that a variable is a reserved space or box for placing a variable. Each variable has its own data type, name (identifier) ​​and value. Data types can be primitive, non-primitive, or reference. Primitive data types can be:
  • Integers: byte , short , int , long
  • Fractional numbers: float and double
  • Boolean values: boolean
  • Character values ​​(to represent letters and numbers): char

Example of variables in Java:

int s;
s = 5;
char myChar = ‘a’;
In this code, we created an integer variable s (an empty container) and then put the value 5 into it. The same story with the myChar variable . We created it with the char data type and defined it as the letter a . In this case, we created a variable and assigned a value to it at the same time. Java syntax allows you to do it this way. Reference types are some objects that contain references to values ​​or other objects. They may also contain a reference to null. Null is a special value that means there is no value. Reference types include String , Arrays , and any Class you want. If you have a violin class ( Violin ), you can create a variable for that class. Example of reference type variables in Java:
String s = “my words”;
Violin myViolin;
You will learn more about them later. Remember that non-primitive variable types begin with capital letters, and primitive types begin with lowercase letters. Example:
int i = 25;
String s =Hello, Java!;

Arrays in Java

Arrays are objects that store multiple variables of the same type. However, the array itself is an object on the heap. We'll look at how to declare, construct, and initialize in later chapters. Array example:
int[] myArray = {1,7,5};
Here we have an array containing three integers (1,7 and 5).

Enums in Java (Java Enums)

In addition to primitive data types, Java has a type called enum, or enumeration. Enumerations are a collection of logically related constants. An enumeration is declared using the enum statement followed by the name of the enumeration. Then comes a list of enumeration elements, separated by commas:
enum DayOfWeek {
     MONDAY,
     TUESDAY,
     WEDNESDAY,
     THURSDAY,
     FRIDAY,
     SATURDAY,
     SUNDAY
}
An enumeration is actually a new type, so we can define a variable of that type and use it. Here is an example of using an enumeration.

An example of an enumeration in Java (Java Enum)

public class MyNum{
    public static void main(String[] args) {

        Day myDay = DayOfWeek.FRIDAY;
        System.out.println(myDay);	//напечатать день из enum
}
}
enum DayOfWeek{

    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
If you run the program, the console will display FRIDAY. You can put the code for the Enum and MyNum classes in one file, but it's better to create two separate files: one for the MyNum class and one for listing the days of the week (Day). IntelliJ IDEA allows you to select an enum when creating it. Java Syntax: A Brief Introduction to the Programming Language - 3

Declaring Variables in Java

In fact, we have declared some variables above and even identified them. Declaration is the process of allocating memory for a variable of a particular type and giving it a name. Something like this:
int i;
boolean boo;
We can also declare variable initialization using the assignment operator ( = ). This means that we put a specific value into the allocated memory. We can do this right at the time of the announcement or later.

Variable Declaration Example

String str;
int i = 5;
Str = “here is my string”;
If you declare a variable without initialization, it will still get some default value. For int this value is 0, for String or any other reference type this is the special identifier null .

Identifiers in Java

Identifiers are simply the names of Java components—classes, variables, and methods. All Java components must have names.
Class Violin {
int age;
String masterName;
}
Violin - class identifier. age and masterName are variable identifiers. Here are some Java identifier rules:
  • all identifiers begin with a Latin letter (A to Z or a to z), a currency symbol ($) or an underscore (_);
  • after the first character, identifiers can have any combination of characters;
  • a Java keyword cannot be an identifier (you'll learn about keywords a little later);
  • identifiers are case sensitive.

Examples of identifiers

Valid identifiers: java, $mySalary, _something Invalid identifiers: 1stPart, -one

Modifiers in Java

Modifiers are special words in the Java language that you can use to change elements (classes, methods, variables). There are two categories of modifiers in Java: access modifiers and other modifiers.

Examples of access modifiers

There are four access modifiers in Java:
  • public _ Open element. It can be accessed from inside the class, outside the class, inside and outside the package;
  • An element with the default modifier - default (empty) - can only be accessed within the package;
  • protected modifier - can be accessed inside and outside the package through a child class;
  • private - the element is accessible only within the class it declares.

Examples of other modifiers

There are seven other modifiers (for classes, fields, methods, interfaces, and so on):
  • static
  • final
  • abstract
  • synchronized
  • transient
  • volatile
  • native

Java Keywords

Java keywords are special words for use in Java that act as a key to the code. These are also known as reserved words: they cannot be used for identifiers of variables, methods, classes, etc. Here they are:
  • abstract : keyword for declaring an abstract class;
  • boolean : The boolean keyword in Java is needed to declare a variable of boolean type. Such variables can only be true or false;
  • break : The break keyword in Java is used to break a loop or switch statement ;
  • byte : The byte keyword in Java is needed to declare a one-byte integer variable;
  • case : used with switch statements to mark blocks of text;
  • catch : used to catch exceptions after a try block ;
  • char : The char keyword in Java is used for a character variable. Can contain unsigned 16-bit Unicode characters;
  • class : The class keyword in Java is needed to declare a class;
  • continue : Java keyword to continue a loop;
  • default : The default keyword in Java is used to specify a default block of code in a switch statement ;
  • do : used in a do-while loop construct ;
  • double : The double keyword in Java is needed to declare a numeric variable. Can contain 8-byte floating point numbers;
  • else : can be used in conditional else-if statements;
  • enum : used to define a fixed set of constants;
  • extends : The extends keyword in Java is used to indicate that a class extends another class (is a child class of another class);
  • final : keyword to indicate that the variable is a constant;
  • finally : marks a block of code that will be executed whether the exception is handled or not;
  • float : a variable that contains a 4-byte floating point number;
  • for : keyword to run a for loop . It is used to repeatedly execute a set of instructions as long as some conditions are met;
  • if : keyword to test the condition. It executes the block if the condition is true;
  • implements : keyword to implement the interface;
  • import : The import keyword in Java is used to import a package, class or interface;
  • instanceof : checks whether an object is an instance of a particular class or interface;
  • int : variable that can hold a 4-byte signed integer;
  • interface : The interface keyword in Java is used to declare an interface;
  • long : a variable that can hold an 8-byte signed integer;
  • native : indicates that the method is implemented in native code using JNI (Java Native Interface);
  • new : The new keyword is used in Java to create new objects;
  • package : declares a Java package (folder) for Java class files;
  • private : The access modifier specifies that the method or variable can only be seen by the class in which it is declared;
  • protected : an access modifier that specifies that a method or variable can be accessed inside and outside the package through a child class;
  • public : the access modifier indicates that the element is accessible anywhere;
  • return : returns the result of the method execution;
  • short : a variable that can hold a 2-byte signed integer;
  • static : indicates that the variable or method is a class rather than an object or method;
  • strictfp : limits floating point calculations;
  • super : refers to an object of the parent class;
  • switch : selects a block of code (or several of them) to execute;
  • synchronized : another type of modifier. It specifies that the method can only be accessed by one thread at a time;
  • this : refers to the current object in a method or constructor;
  • throw : used to explicitly throw an exception;
  • throws : declares an exception;
  • transient data fragment cannot be serialized;
  • try : runs a block of code that is checked for exceptions;
  • void : indicates that the method does not return a value;
  • volatile : indicates that the variable can be changed asynchronously;
  • while : starts a while loop . Repeats part of the program several times while the condition is true.

Comments in Java

Java supports single-line and multi-line comments. All characters are available inside any comment and are ignored by the Java compiler. Developers use them to explain code or remember something. Examples of comments:
//однострочный комментарий
/*а вот многострочный комментарий. Как видите, в нем используются слеши и звездочки в начале и в конце.*/

public class HelloJava {
   /* эта программа создана для демонстрации комментариев в Java. Это многострочный комментарий.
   Вы можете использовать такие комментарии в любом месте вашей программы*/
   public static void main(String[] args) {
       //а вот однострочный комментарий
       String j = "Java"; //Это моя строка
       int a = 15; //Здесь у меня целое число
       System.out.println("Hello, " + j + " " + a + "!");
       int[] myArray = {1,2,5};
       System.out.println(myArray.length);
   }
}

Literals in Java

Literals in Java are constant values ​​assigned to a variable. These could be numbers, texts, or anything else that represents meaning.
  • Integer literals
  • Floating point literals
  • Character literals
  • String literals
  • Boolean literals

Examples of literals in Java

int i = 100; //100 – целочисленный литерал
double d = 10.2;//10.2 – литерал с плавающей точкой
char c = ‘b’; //b – символьный литерал
String myString =Hello!;
boolean bool = true;
Please note: null is also a literal.

Basic Operators in Java

There are different types of operators: Arithmetic:
  • + (number addition and string concatenation)
  • (minus or subtraction)
  • * (multiplication)
  • / (division)
  • % (modulus or remainder)
Comparisons:
  • < (less than)
  • <= (less than or equal to)
  • > (more than)
  • >= (greater than or equal to)
  • == (equal)
  • != (Not equal)
Brain teaser:
  • && (AND)
  • || (OR)
  • ! (NOT)
  • ^ (XOR)
We have already learned about data types, variables, methods and operators. Let's look at a simple code example, but a little more complex than the very first Java program. Let's create a class called NumberOperations .
public class NumbersOperations {
   int a;
   int b;
   public static int add(int a,int b){
       return a+b;
   }
   public static int sub (int a, int b){
       return a-b;
   }
   public static double div (double a, int b){
       return a/b;
   }
}
Here we have a class with tree methods for working with two numbers. You can try to write a fourth method int mul(int a, int b) to multiply two numbers in this program. Let's also create a class to demonstrate how NumberOprations works :
public class NumberOperationsDemo {
   public static void main(String[] args) {
       int c = NumbersOperations.add(4,5);
       System.out.println(c);
       double d = NumbersOperations.div(1,2);
       System.out.println(d);
   }
}
If you run NumberOperationsDemo you will get output like this:
9 0.5

Results

This is just the basics of the Java language, and it can be confusing at first. You'll need a lot of programming practice to get the hang of it. And this is the best way to learn a programming language - through practice. Start programming right now: try the first quest of the JavaRush course . Have fun learning Java!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION