How to set up smartphones and PCs. Informational portal
  • home
  • TVs (Smart TV)
  • Java programming language purpose and features. Java programming language (Java)

Java programming language purpose and features. Java programming language (Java)

A Java source file is a text file containing one or more class definitions. The Java translator assumes

that the source code of programs is stored in files with Java extensions. The code obtained during the translation process for each class is written in a separate output file, with a name that matches the class name and a class extension.

First of all, in this chapter we will write, broadcast, and run the canonical “Hello World” program. After that, we'll look at all the essential lexical elements accepted by the Java translator: whitespace, comments, keywords, identifiers, literals, operators, and delimiters. By the end of the chapter, you will have enough information to navigate a good Java program on your own.

So here is your first Java program

:

class HelloWorld(

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

In order to work with the examples given in the book, you need to obtain and install the Java Developers Kit over the network from Sun Microsystems - a package for developing Java applications (

http://java.sun.com/products/jdk ). Full description of the package utilities JDK - in Appendix 1 .

The Java language requires that all program code be contained within named classes. The above example text should be written to the HelloWorld.java file. Be sure to check that the capital letters in the file name match those in the name of the class it contains. In order to translate this example, you need to run the Java translator - javac, specifying the name of the file with the source text as a parameter:

\> javac HelloWorld.Java

The translator will create a file HelloWorld.class with the processor-independent bytecode of our example. In order to execute the resulting code, you must have a Java runtime environment (in our case, this is the java program), into which you need to load a new class for execution. We emphasize that the name of the class is indicated, and not the name of the file in which this class is contained.

>java HelloWorld

Not much useful work has been done, but we have verified that the installed Java translator and runtime environment work.

Step by step

HelloWorld is a trivial example. However, even such a simple program for a beginner in the languageJava can seem intimidatingly complex because it introduces you to a lot of new concepts and details of the language's syntax. Let's take a closer look at each line of our first example, analyzing the elements that make up a Java program.

class HelloWorld(

This line uses a reserved word

class. It tells the translator that we are going to define a new class.The full class definition appears between the opening curly brace on line 1 and the matching closing curly brace on line 5. The curly braces inJava is used in exactly the same way as in C and C languages++.

public static void main (String args) (

This seemingly overly complex example string is a consequence of an important requirement when the Java language was designed. The point is that in

Java lacks global functions. Since similar lines will appear in most of the examples in the first part of the book, let's take a closer look at each element of the second line.

Breaking this string into separate tokens, we immediately encounter the keyword

public. This - access modifier, which allows the programmer to control the visibility of any method and any variable. In this case, the access modifierpublic means the methodmain is visible and accessible to any class. There are 2 more access level indicators - private and protected, which we will get to know in more detail inchapter 8 .

The next keyword is

static. This word is used to declare class methods and variables used to work with the class as a whole. Methods that use the static keyword in their declaration can only work directly with local and static variables.

You will often need methods that return a value of one type or another: for example,

int for integer values, float - for real ones, or the class name for programmer-defined data types. In our case, we just need to display a string and return the value from the methodmain is not required. That is why the modifier was usedvoid. This issue is discussed in more detail inchapter 4 .

Finally we get to the method name

main. There is nothing unusual here, it’s just that all existing implementations of Java interpreters, having received the command to interpret a class, begin their work by calling the method main. A Java translator can translate a class that does not have a main method. But the Java interpreter runs classes without a method main can't.

All parameters that need to be passed to the method are specified inside a pair of parentheses as a list of elements separated by ";" characters. (semicolon). Each element of the parameter list consists of a type and identifier separated by a space. Even if a method has no parameters, you still need to put a pair of parentheses after its name. In the example we are now discussing, the method

main has only one parameter, albeit of a rather complex type. String args declares a parameter namedargs, which is an array of objects - representatives of the classString. Note the square brackets after the args identifier. They indicate that we are dealing with an array, and not with a single element of the specified type. We'll return to a discussion of arrays in the next chapter, but for now let's note that the type String - this is class. We'll talk about strings in more detail inChapter 9 .

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

This line executes the method

println of the out object. An object out is declared in the classOutputStream and is statically initialized in the System class. IN chapters 9 And 13 you will have a chance to get acquainted with the nuances of how classes work String and OutputStream.

The closing curly brace on line 4 ends the method declaration

main, and the same parenthesis on line 5 ends the HelloWorld class declaration.

Lexical Basics

Now that we've looked at the minimal Java class in detail, let's go back and look at the general syntax of the language. Programs for

Java - it is a collection of spaces, comments, keywords, identifiers, literal constants, operators and delimiters.a language that allows arbitrary formatting of program text. In order for the program to work properly, there is no need to align its text in a special way. For example, classHelloWorld could be written in two lines or any other way you like. And it will work exactly the same, provided that there is at least one space, tab character, or newline character between the individual tokens (between which there are no operators or separators).

Comments

Although comments have no effect on the executable code of the program,

when used correctly, they turn out to be a very significant part of the source text. There are three types of comments: single-line comments, multi-line comments, and finally documentation comments. Single-line comments begin with // characters and end at the end of the line. This commenting style is useful for providing short explanations of individual lines of code:

a = 42; // If

42 - the answer, then what was the question?

For more detailed explanations, you can use comments placed on several lines, starting the comment text with the characters /* and ending with the characters */. In this case, all text between these pairs of characters will be regarded as a comment and the translator will ignore it.

* This code is a bit complicated...

*I'll try to explain:

The third, special form of comments is intended for the service program

javadocwhich uses Java translator components to automatically generate documentation for class interfaces. The convention used for this type of comment is to place a documenting comment before the declaration of a public class, method, or variable., you need to start it with the characters /** (slash and two asterisks). Such a comment ends in the same way as a regular comment - with the symbols */. The javadoc program can recognize in documenting comments some special variables whose names begin with the @ symbol. Here is an example of such a comment:

* This class can do amazing things. We recommend it to anyone who

* wants to write an even more advanced class, take it as

* basic.

* @see Java. applet. Applet

* ©author Patrick Naughton

class CoolApplet extends Applet ( /**

* This method has two parameters:

key is the name of the parameter.is the value of the parameter namedkey.

*/ void put (String key, Object value) (

Reserved Keywords

Reserved keywords are special identifiers that the language

Java is used to identify built-in types, modifiers, and program execution controls. Today in the language J ava has 59 reserved words (see Table 2). These keywords, along with the syntax of operators and delimiters, are included in the language descriptionJava. They can only be used for their intended purpose and cannot be used as identifiers for variable, class or method names.

table 2

Java Reserved Words

Note that the words

byvalue, cast, const, future, generic, goto, inner, operator, outer, rest, varreserved in Java, but not yet used. In addition, in Java there are reserved method names (these methods are inherited by every class and cannot be used except in cases of explicit overriding of class methods Object).

Table 3

Reserved method names

Java

Identifiers

Identifiers are used to name classes, methods, and variables. The identifier can be any sequence of lowercase and uppercase letters, numbers, and the symbols _ (underscore) and $ (dollar). Identifiers should not begin with a number, so that the translator does not confuse them with numeric literal constants, which will be described below.

Java - case-sensitive language. This means that, for example, Value and VALUE - various identifiers.

Literals

Constants in

Java are given by their literal representation. Integers, floats, booleans, characters, and strings can be placed anywhere in the source code. The types will be discussed inchapter 4 .

Integer literals

Integers are the type most commonly used in regular programs. Any integer value, such as 1, 2, 3, 42, is an integer literal. This example shows decimal numbers, that is, numbers with a base of 10 - exactly those that we use every day outside the world of computers. In addition to decimal, numbers with base 8 and 16 - octal and hexadecimal - can also be used as integer literals. Java recognizes octal numbers by leading them with a leading zero. Normal decimal numbers cannot start with zero, so using the externally valid number 09 in a program will result in a translation error message because 9 is not in the range of 0..

7, valid for octal digits. Hexadecimal constants are distinguished by leading zero-x characters (0x or 0X). The range of hexadecimal digit values ​​is 0..15, and as numbers for the values ​​10..15 letters from A to are used F (or from a to f). With hexadecimal numbers you can express computer-friendly values ​​in a concise and clear way, for example by writing Oxffff instead of 65535.

Integer literals are values ​​of type

int, which is in Java is stored in a 32-bit word. If you require a value that is greater than approximately 2 billion, you must use a constant likelong. In this case, the number will be stored in a 64-bit word. For numbers with any of the bases mentioned above, you can assign a lowercase or uppercase letter to the rightL, thus indicating that the given number is of the typelong. For example, Ox7ffffffffffffffL or9223372036854775807L is the largest value for a number of type long.

Floating point literals

Floating point numbers represent decimal values ​​that have a fractional part. They can be written in either regular or exponential formats. In the usual format, a number consists of a number of decimal digits, followed by a decimal point, and the following decimal digits of the fractional part. For example, 2.0, 3.14159, and .6667 are valid values ​​for floating-point numbers written in standard format. In exponential format, after the listed elements, the decimal order is additionally indicated. The order is determined by the positive or negative decimal number following the symbol E or e. Examples of numbers in exponential format: 6.022e23, 314159E-05, 2e+100. IN

Java floats are treated as doubles by default. If you require a type constantfloat, the symbol F or f must be added to the right of the literal. If you are a fan of redundant definitions, you can add to literals like double character D or d. Default Type Valuesdouble are stored in a 64-bit word, less precise type values float - in 32-bit.

Boolean literals

A boolean variable can only have two values ​​-

true and false (false). Boolean values true and false are not converted to any numeric representation. Keyword true in Java is not equal to 1, and false is not equal to 0. In In Java, these values ​​can only be assigned to boolean variables or used in expressions with logical operators.

Character literals

Symbols in

Java - these are the indexes in the symbol tableUNICODE. They are 16-bit values ​​that can be converted to integers and to which integer arithmetic operators, such as addition and subtraction, can be applied. Character literals are placed inside a pair of apostrophes (" "). All visible table symbolsASCII can be directly inserted inside a pair of apostrophes: -"a", "z", "@". For characters that cannot be entered directly, several escape sequences are provided.

Table 3.

2. Escape sequences

Control sequence

Description

Octal character

(ddd)

Hexadecimal character

UNICODE (xxxx)

Apostrophe

Backslash

Carriage return

Line feed (line feed, new line)

Page translation

(form feed)

Horizontal tabulation

(tab)

Go back one step

(backspace)

String literals

String literals in

Java looks exactly the same as many other languages ​​- it is arbitrary text enclosed in a pair of double quotes (""). Although lowercase literals inJava are implemented in a very unique way(Java creates an object for each line), this does not appear externally. Examples of string literals:“Hello World!”; "two\strings; \And this is in quotes\"". All escape sequences and octal/hexadecimal notations that are defined for character literals work exactly the same in strings. String literals inJava codes must start and end on the same line of source code. In this language, unlike many others, there is no escape sequence for continuing a string literal on a new line.

Operators

An operator is something that performs some action on one or two arguments and produces a result. Syntactically, operators are most often placed between identifiers and literals. The operators will be discussed in detail in

chapter 5 , their list is given in Table 3. 3.

Table 3.

3. Language operators Java

Separators

Only a few groups of characters that can appear in a syntactically correct Java program still remain unnamed. These are simple separators that affect the appearance and functionality of program code.

Name

What are they used for?

round brackets

They highlight lists of parameters in a method declaration and call; they are also used to set the priority of operations in expressions, highlight expressions in program execution control statements, and in type casting operators.

braces

square brackets

Used in array declarations and when accessing individual array elements.

semicolon

Separates operators.

Separates identifiers in variable declarations, also used to link statements in a loop header

for.

Separates package names from subpackage and class names, and is also used to separate a variable or method name from a variable name.

Variables

A variable is the main element of storing information in a Java program. A variable is characterized by a combination of identifier, type, and scope. Depending on where you declare the variable, it may be local, such as to the code inside a for loop, or it may be an instance variable of the class that is available to all methods in that class. Local scopes are declared using curly braces.

Variable Declaration

The basic form of a variable declaration is:

type identifier [ = value] [, identifier [ = value

7...];

A type is either one of the built-in types, that is,

byte, short, int, long, char, float, double,boolean, or the name of a class or interface. We will discuss all these types in detail innext chapter . Below are some examples of declaring variables of various types. Note that some examples involve initializing an initial value. Variables for which no initial values ​​are specified are automatically initialized to zero.

The example below creates three variables corresponding to the sides of a right triangle and then

c Using the Pythagorean theorem, the length of the hypotenuse is calculated, in this case the number 5, the size of the hypotenuse of a classic right triangle with sides 3-4-5.

class Variables(

public static void main (String args) (

= Math.sqrt(a* a + b* b);

System.out.println("c = "+ c);

Your first step

We have already achieved a lot: first we wrote a small program in the language

Java and looked in detail at what it consists of (code blocks, comments). We have been introduced to a list of keywords and operators whose purpose will be explained in detail in subsequent chapters. Now you are able to independently distinguish the main parts of any Java program and are ready to start readingchapter 4 , which covers simple data types in detail.

Programming is writing the source code of a program in one of the programming languages. There are many different programming languages, thanks to which all kinds of programs are created that solve a certain range of problems. A programming language is a set of reserved words with which the source code of a program is written. Computer systems are not (yet) able to understand human language, much less human logic (especially female logic), so all programs are written in programming languages, which are subsequently translated into computer language or machine code. Systems that translate program source code into machine code are very complex and, as a rule, they are created over dozens of months and dozens of programmers. Such systems are called integrated application programming environments or tools.

A programming system is a huge, well-thought-out visual environment where you can write the source code of a program, translate it into machine code, test it, debug it, and much more. Additionally, there are programs that allow you to perform the above actions using the command line.

You have probably heard the term “a program is written for Windows or Linux or Unix” more than once. The fact is that programming environments when translating a programming language into machine code can be of two types - compilers and interpreters. Compiling or interpreting a program specifies how the program will continue to be executed on the device. Programs written in Java always work on the basis of interpretation, while programs written in C/C++ are compiled. What is the difference between these two methods?

The compiler, after writing the source code at the time of compilation, reads the entire source code of the program at once and translates it into machine code. After which the program exists as a single whole and can only be executed in the operating system in which it was written. Therefore, programs written for Windows cannot function in a Linux environment and vice versa. The interpreter executes the program step by step or line by line each time it is executed. During interpretation, not executable code is created, but virtual code, which is subsequently executed by the Java virtual machine. Therefore, on any platform - Windows or Linux, Java programs can be executed equally if there is a virtual Java machine in the system, which is also called the Runtime System.

Object-oriented programming

Object-oriented programming is built on the basis of objects, which is somewhat similar to our world. If you look around you, you can definitely find something that will help you more clearly understand the model of such programming. For example, I am now sitting at my desk and typing this chapter on a computer, which consists of a monitor, system unit, keyboard, mouse, speakers, and so on. All these parts are the objects that make up a computer. Knowing this, it is very easy to formulate some kind of generalized model of the operation of the entire computer. If you do not understand the intricacies of the software and hardware properties of a computer, then we can say that the System Unit object performs certain actions that are shown by the Monitor object. In turn, the Keyboard object can adjust or even set actions for the System Unit object, which affect the operation of the Monitor object. The presented process very well characterizes the entire object-oriented programming system.

Imagine some powerful software product containing hundreds of thousands of lines of code. The entire program is executed line by line, line by line, and in principle each of the subsequent lines of code will necessarily be connected to the previous line of code. If you do not use object-oriented programming, and when you need to change this program code, say, if you need to improve some elements, then you will have to do a lot of work with the entire source code of this program.

In object-oriented programming everything is much simpler, let's return to the example of a computer system. Let's say you are no longer satisfied with a seventeen-inch monitor. You can easily exchange it for a twenty-inch monitor, of course, if you have certain financial resources. The exchange process itself will not entail huge problems, unless you have to change the driver, wipe the dust from under the old monitor and that’s it. Object-oriented programming is based approximately on this operating principle, where a certain part of the code can represent a class of homogeneous objects that can be easily upgraded or replaced.

Object-oriented programming very easily and clearly reflects the essence of the problem being solved and, most importantly, makes it possible to remove unnecessary objects without damaging the entire program, replacing these objects with newer ones. Accordingly, the overall readability of the source code of the entire program becomes much easier. It is also important that the same code can be used in completely different programs.

Classes

The core of all Java programs are classes, on which object-oriented programming is based. You essentially already know what classes are, but you don’t realize it yet. In the previous section we talked about objects, using the structure of an entire computer as an example. Each object from which a computer is assembled is a representative of its class. For example, the Monitor class unites all monitors, regardless of their types, sizes and capabilities, and one specific monitor standing on your desk is an object of the monitor class.

This approach makes it very easy to model all kinds of programming processes, making it easier to solve problems. For example, there are four objects of four different classes: monitor, system unit, keyboard and speakers. To play a sound file, you need to give a command to the system unit using the keyboard; you will observe the very action of giving the command visually on the monitor and, as a result, the speakers will play the sound file. That is, any object is part of a certain class and contains all the tools and capabilities available to this class. There can be as many objects of one class as necessary to solve the problem.

Methods

When an example of playing a sound file was given, it was mentioned that a command or message was given, on the basis of which certain actions were performed. The task of performing actions is solved using the methods that each object has. Methods are a set of commands that can be used to perform certain actions with an object.

Each object has its own purpose and is designed to solve a certain range of problems using methods. What good would be a Keyboard object, for example, if you couldn’t press keys and still be able to issue commands? The Keyboard object has a certain number of keys with which the user gains control over the input device and can issue the necessary commands. Such commands are processed using methods.

For example, you press the Esc key to cancel any actions and thereby give a command to the method assigned to this key, which solves this task at the program level. The question immediately arises about the number of methods of the Keyboard object, but there can be a different implementation - from defining methods for each of the keys (which, in general, is unwise), and to creating a single method that will monitor the general state of the keyboard. That is, this method monitors whether a key has been pressed, and then, depending on which key is activated, decides what to do.

So, we see that each of the objects can have at its disposal a set of methods for solving various problems. And since each object is an object of a certain class, it turns out that the class contains a set of methods that are used by various objects of the same class. In Java, all methods you create must belong to or be part of a specific class.

Syntax and semantics of the Java language

In order to speak and read any foreign language, you need to learn the alphabet and grammar of that language. A similar condition is observed when studying programming languages, with the only difference, it seems to me, that this process is somewhat easier. But before you start writing the source code of the program, you must first solve the problem assigned to you in any form convenient for you.

Let's create a certain class responsible, for example, for a telephone, which will have only two methods: turning on and off this very phone. Since we currently do not know the syntax of the Java language, we will write the Phone class in an abstract language.

Class Phone
{
Enable() method
{
// operations to turn on the phone
}
Disable() method
{
// operations to turn off the phone
}
}

The Phone class might look something like this. Note that curly braces indicate the beginning and end of the body of a class, method, or any sequence of data, respectively. That is, parentheses indicate membership in a method or class. For every opening parenthesis there must be a closing parenthesis. To avoid confusion, they are usually placed at the same level in the code.

Now let's write the same class only in Java.

Class Telephone
{
void on()
{
// body of the on() method
}
void off()
{
// body of the off() method
}
}

The keyword class in the Java language declares a class, followed by the name of the class itself. In our case, this is Telefon. Just a few words about the recording register. In almost all programming languages, it is important to save names in the register in which they were written. If you wrote Telefon, then such a spelling as telefon or TELefoN will generate an error during compilation. As we wrote initially, this is how we should continue to write.

Reserved or keywords are written in their own specific case, and you cannot use them by naming them to methods, classes, objects, and so on. Spaces between words don't matter because the compiler simply ignores them, but they are important for code readability.

In the body of the Telefon class there are two methods: on() - turns on the phone and off() method - turns off the phone. Both methods have their own bodies and, in theory, they should contain some source code that describes the necessary actions of both methods. For us now it doesn’t matter how these methods are implemented, the main thing is the syntax of the Java language.

Both methods have on() parentheses within which parameters can be written, such as on(int time) or on(int time, int time1). With the help of parameters, there is a kind of connection between methods and the outside world. The on(int time) method is said to take a time parameter. What is it for? For example, you want your phone to turn on at a certain time. Then the integer value in the time parameter will be passed to the body of the method and, based on the received data, the phone will be turned on. If the parentheses are empty, then the method does not accept any parameters.

Comments

In the Telefon class, in the bodies of both methods there is an entry after two slashes: //. This entry denotes comments that will be ignored by the compiler, but are needed for code readability. The more information you comment on as you write the program, the more likely you will be to remember in a year what you have been working on all this time.

Comments in Java can be of three types:

//, /*…*/ And /**…*/

Comments written using the // operator must appear on one line:

// One line
!!! Error! You can't wrap it on the second line!
// First line
// Second line
// …
// Last line

Comments using the /*…*/ operators can span multiple lines. At the beginning of your comment, put /*, and at the end, when you finish commenting the code, put the operator */. The last type of comment /**…*/ is used when documenting code and can also be located on any number of lines.

Java Data Types

To set an arbitrary value, Java has data types. In the Telefon class we have created two methods. Both methods had no parameters, but when the example of the on(int time) method with a time parameter was given, they talked about passing a value to the method. This value indicated the time at which the phone supposedly should turn on. The int specifier determines the type of the time value. There are six data types in Java 2 ME.

Byte – small integer value from –128 to 128;
short – short integer value in the range from –32768 to 32767;
int – contains any integer value from –2147483648 to 2147483647;
long – very large integer value, from –922337203685475808 to 9223372036854775807;
char is a Unicode character constant. The range of this format is from 0 to 65536, which is equal to 256 characters. Any character of this type must be written in single quotes, for example: 'G';
boolean is a logical type that has only two values: false and true. This type is often used in loops, which will be discussed later. The meaning is very simple - if you have money in your pocket, it is supposed to be true, and if not, then it is false. Thus, if we have money, we go to the store for bread or beer (underline what is appropriate), if there is no money, we stay at home. That is, this is a logical value that contributes to the choice of further actions of your program.

To declare some necessary value, use the following entry:

Int time;
long BigTime;
char word;

The semicolon operator is required after entries and is placed at the end of the line. You can combine several declarations of the same type, separated by commas:

Mt time, time1, time2;

Now let's improve our Telefon class by adding some values ​​to it. We no longer need the on() and off() methods; let's add new methods that can actually solve certain problems.

Class Telephone
{
//S – display area
//w – display width
//h – display height
int w, h, S;
//method that calculates display area
vord Area()
{
S = w*h;
}
}

So, we have three variables S, w and h, which are responsible, respectively, for the area, width and height of the display in pixels. The Area() method calculates the area of ​​the phone's screen in pixels. The operation is useless, but very illustrative and easy to understand. The body of the Area() method has found itself and has the form S = w*h. In this method, we simply multiply the width by the height and assign or, as they say, store the result in the variable S. This variable will contain the values ​​​​of the display area of ​​\u200b\u200bthis phone.

Now we have come close to the operators of the Java language, with the help of which you can perform all kinds of operations. The operators of the Java language, as well as other programming languages, have their own purposes. So there are arithmetic operators, increment and decrement operators, logical operators and relational operators. Let's look at each of the above operators.

Arithmetic operators

All arithmetic operators are very simple and similar to the multiplication “*”, division “/”, addition “+” and subtraction “-” operators used in mathematics. There is a modulo division operator “%” and a slightly confusing at first glance situation with the equal operator “=”. The equals operator is called the assignment operator in programming languages:

Here you assign the value 3 to the variable x. And the “equal” operator in programming languages ​​corresponds to writing two consecutive “equal” operators: “==”. Let's look at an example of what various arithmetic operators can do.

Int x, y, z;
x = 5;
y = 3;
z = 0;
z = x + y;

In this case, z will have the value of the sum of x and y, that is, 8.

The variable x had the value 5, but after this recording the previous value is lost and the product z*x (8*5) is written, which is equal to 40. Now, if we continue our code further, the variables will look like this:

// x = 40;
// y = 3;
// z = 8;

The addition and subtraction operators have the same purposes as in mathematics. Negative numbers are also related.

The decrement “––” and increment “++” operators are very specific, but very simple. In programming, there are often times when you need to increase or decrease a value by one. This often occurs in cycles. The increment operation increases a variable by one.

Int x = 5;
x++;
// Here x is already equal to 6

The decrement operation decreases a variable by one.

Int x = 5;
x--;
// x equals 4

Increment and decrement operations can be post and prefix:

Int x = 5;
int y = 0;
y = x++;

In the last line of code, the value x is first assigned to y, which is the value 5, and only then the variable x is incremented by one. It turns out that:

The prefix increment has the form:

Int x = 3;
int y = 0;
y = ++x;

And in this case, first the variable x is increased by one, and then it assigns the already increased value to y.

Relational operators

Relational operators allow you to test whether both sides of an expression are equal. There is an equality operator "==", operators less than "<» и больше «>", less or equal "<=» и больше или равно «>=”, as well as the negation operator “!=”.
9 == 10;

This expression is not true, nine does not equal ten, so the value of this expression is false.

Here, on the contrary, the negation operator indicates the inequality of the expression, and the value will be true. The operators greater than, less than, greater than or equal to, and less than or equal to are similar to the corresponding operators from mathematics.

Logical operators

There are two logical operators. The “AND” operator, denoted by the symbols “&&” and the “OR” operator, denoted by two forward slashes “||”. For example, there is an expression:

A*B && B*C;

If only both parts of an expression are true, the value of the expression is considered true. If one of the parts is false, then the value of the entire expression will be false.
In contrast to the “&&” operator, there is the “||” operator, which is not without reason called “OR”.

A*B || B*C;

If any part of an expression is true, then the entire expression is true. Both operators can be combined in one expression, for example:

A*B || B*C && C*D || B*A;

With the help of this expression, I, it seems to me, have led you into difficulty, haven’t I? The fact is that in Java, as in mathematics, there is a priority or a so-called hierarchy of operators, with the help of which it is determined which of the operators is more important, and, therefore, is checked first. Let's consider using a list the priority of all available Java language operators:

, ., (),
!, ~, ++, – –, + (unary), – (unary), new,
*, /, %,
+, –,
<<, >>, >>>,
<, <=, >, >=,
= =, !=,
&, ^, |,
&&,
||,
?:,
=, +=, –=, *=, /=, %=, |=, ^=, <<=, >>=, >>>=.

The associativity of operators in the list follows from left to right and from top to bottom. That is, everything that is to the left and above is senior in rank and more important.

A Brief Course in the History of the Java Language

This section briefly describes the history of the Java language. This section is based on various published materials (mostly interviews with the creators of the Java language in the July 1995 issue of SunWorld).

Java's history goes back to 1991, when a group of engineers at Sun, led by Patrick Naughton and board member (and all-around computer wizard) James Gosling, set out to develop a small language that could be used to program everyday devices. devices, for example, controllers for switching cable television channels (cable TV switchboxes).

Since such devices do not consume much power and do not have large memory chips, I had to be small and generate very compact programs. Additionally, since different manufacturers may choose different Central Processor Units (CPUs), it was important not to get bogged down by any one computer architecture. The project was codenamed "Green".

In an effort to invent small, compact, and machine-independent code, the developers revived the model used to implement the first versions of the Pascal language at the dawn of the personal computer era. Niklaus Wirth, the creator of the Pascal language, once developed a machine-independent language that generates intermediate code for a certain hypothetical machine. This language became a commercial product under the name UCSD Pascal. (Such hypothetical machines are often called virtual machines—for example, the Java virtual machine, or JVM.)
This intermediate code can be executed on any machine that has an appropriate interpreter. The engineers working on Project Green also used a virtual machine, which solved their main problem.

However, most Sun employees had experience with the UNIX operating system, so the language they developed was based on C++, not Pascal. In particular, they made the language object-oriented rather than procedure-oriented.

As Gosling said in his interview: " Language is always a means, not an end"At first, Gosling decided to call it "Oak." (Perhaps because he liked to look at the oak tree growing right outside the windows of his office at Sun.) Then Sun employees learned that the word Oak was already used in as the name of a previously created programming language, and changed the name Java.

In 1992, the first products were released as part of the Green project, called
"*7". It was a means for extremely intelligent remote control. (It had the power of a SPARK workstation, but fit into a 6x4x4-inch box.) Unfortunately, no electronics companies were interested in this invention.

The group then began developing a cable television device that could provide new types of services, such as video on demand. And again they did not receive a single contract. (It’s funny that one of the companies that refused to sign a contract with them was led by Jim Clark, the founder of Netscape, which later did a lot for the success of the Java language.)

Throughout 1993 and half of 1994, an unsuccessful search for buyers of products developed within the framework of the Green project (under the new name “First Person, Inc.”) continued. (Patrick Naughton, one of the group's founders who later worked primarily in marketing, flew more than 300,000 miles in total trying to sell the technology.) First Person, Inc. was discontinued in 1994.

Meanwhile, the World Wide Web was growing within the Internet. The key to this network is the browser, which turns hypertext into an image on the screen.
In 1994, most people were using the Mosaic browser, a non-profit Web browser developed at the University of Illinois Supercomputing Center in 1993. (This browser was written in part by Mark Andreessen for $6.85 an hour. At the time, Mark was graduating from university and the browser was his thesis. He then became one of the founders and chief programmer of Netscape, and fame came to him and wealth.)

In an interview with Sun World magazine, Gosling said that in mid-1994, the language's developers realized: "We need to create a really cool browser. This browser should be one of the few applications of fancy client-server technology, where exactly what is vital would be what we did: architectural independence, real-time execution, reliability, security - issues that were not extremely important for workstations And we created such a browser."

In fact, the browser was developed by Patrick Naughton and Jonathan Payne. It later evolved into the modern HotJava browser. This browser was written in Java to demonstrate its full power. However, developers did not forget about the powerful tools now called applets, giving their browser the ability to execute code inside Web pages. The "technology demo" was presented at Sun World '95 on May 23, 1995, and sparked a Java craze that continues to this day.

Sun released the first version of the Java language in early 1996. A few months after it, Java version 1.02 appeared. People quickly realized that Java 1.02 was not suitable for developing serious applications. Of course, this version can be used to develop Web pages with dancing men, but in Java 1.02 you can't even print anything.

To be honest, Java 1.02 was still raw. Its successor, Java 1.1, filled in most of the gaping holes by greatly improving reflection capabilities and adding a new event model for GUI programming. Despite this, it was still quite limited.

The release of Java 1.2 was the main news at the JavaOne conference in 1998. The new version replaces weak tools for creating graphical user interfaces and graphical applications with complex and extensive tools. This was a step forward towards the implementation of the slogan "Write Once, Run Anywhere" ™, put forward during the development of previous versions.

In December 1998, three days (!) after its release, the name of the new version was changed to the cumbersome phrase Java 2 Standard Edition Software Development Kit Version 1.2 (Standard edition of a package of tools for software development in the Java 2 language, version 1.2).

In addition to the standard edition of the package ("Standard Edition"), two more options were offered: a "micro edition" ("Micro Edition") for portable devices, for example, for mobile phones, etc. "Industrial Edition" ("Enterprise Edition") for creating server-based applications. Our book focuses on the standard edition.

Versions 1.3 and 1.4 of the standard edition of the toolkit are much more advanced than the original release of the Java 2 language. They have new features and, of course, contain many fewer bugs. In table Figure 1 1 shows the rapid growth of the API library as new versions of the standard edition SDK become available.

Table 1.1. The growth of the API library from the Java Standard Edition package

Number of classes and interfaces

Number of methods and fields

Common Misconceptions About the Java Language

This section lists and comments on some of the common misconceptions about Java.

The Java language is an extension of the HTML language.

Java is a programming language, and HTML is a way of describing the structure of Web pages. There is nothing in common between them, with the exception of HTML language extensions that allow applets written in Java to be placed on Web pages.

I'm working in XML, so I don't need Java.

Java is a programming language, and XML is simply a way to describe data. Data described using XML can be processed by programs written in any programming language, but only the Java API library provides excellent support for processing such data. In addition, Java implements many of the features of XML. They are described in more detail in the second volume.

The Java language is easy to learn.

There is no programming language as powerful as Java that can be learned easily. It's easy to write toy programs, but doing serious work is always difficult. Also, note that this book only devotes four chapters to discussing the Java language itself. The remaining chapters explain how to work with its libraries, which contain thousands of classes and interfaces, as well as many thousands of functions. Fortunately, you don't need to know every one of them, but doing a real project requires a surprising amount of knowledge from the user.

Java is easy to program in.

The Java SDK is not easy to use for anyone except programmers accustomed to the command line. There are integrated programming environments that include text editors, compilers, and drag-and-drop form creation tools, but they seem too complex and intimidating for a beginner. In addition, they often generate programs consisting of hundreds of lines. It seems to us that starting to learn the Java language using long programs, automatically generated and filled with comments like “DO NOT TOUCH YOUR HANDS!” is not a very good idea. We believe that the best way to learn Java is to use your favorite text editor. This is exactly what we will do.

The Java language will eventually become a universal programming language for all platforms.

Theoretically this is possible. This is what all software manufacturers dream of, except Microsoft. However, there are many applications that work great on personal computers that will not work as well on other devices or browsers. In addition, these applications are written to take maximum advantage of the processors and machine-dependent libraries. In any case, they have already been ported to all important platforms. Such applications include text and graphic editors, as well as Web browsers. Typically these applications are written in C or C++, and the user will gain nothing by rewriting them in Java. Additionally, rewriting them in Java will make these programs slower and less efficient, at least in the near future.

The Java language is just another programming language.

Java is a wonderful programming language. Many programmers prefer it over the C or C++ languages. However, there are hundreds of great programming languages ​​around the world that have never achieved widespread adoption, while languages ​​with obvious shortcomings, such as C++ and Visual Basic, have achieved stunning success.

Why? The success of any programming language is determined primarily by the practicality of its support system rather than the elegance of its syntax. Are there useful, convenient and standard libraries that allow you to do exactly what a programmer needs? Has a convenient environment for creating and debugging programs been developed? Are the language and its tools integrated into the computer infrastructure? The Java language has made strides in server applications because its class libraries make it easy to do things that were previously difficult, such as networking and multithreading. The fact that Java has reduced the number of pointer bugs is also in its favor. Thanks to this, the productivity of programmers has increased. However, this is not the reason for his success.

Java programs are interpreted, meaning serious applications will run too slowly on a particular platform.

Many programs spend most of their time interacting with the user interface or waiting for data from the network. All programs, no matter what language they are written in, must respond to a mouse click within a certain time. Of course, you should not perform CPU-intensive tasks using the Java interpreter. However, on platforms that allow synchronous compilation, you just need to run the bytecodes for execution, and most issues will simply disappear.

After all, Java is great for developing network programs. Experience shows that it easily maintains high network transfer rates even during intensive calculations such as encryption. Since Java is faster than internet speeds, it doesn't matter that C++ programs can run even faster. Java is easier to program and programs written in it are machine-independent.

All Java programs run under Web browsers.

All applets written in Java actually run under the control of Web browsers. Actually, this is the definition of an applet - a program executed by a Web browser. However, it is entirely possible and appropriate to create stand-alone Java programs that run independently of the Web browser.

These programs (usually called applications) are completely machine independent. Just take the program and run it on another machine! Because Java is more user-friendly and less error-prone than C++, it is a good choice. When combined with database access tools such as the Java Database Connectivity package, the Java language becomes irresistible. It is especially convenient to learn it as a first programming language.
Most of the programs in this book are completely self-contained. Of course, applets are a lot of fun. However, Java applications are more important and useful in practice.

Java applets pose a great threat to security systems.

Several security bug reports have been published in the Java language. Most of them concerned the implementation of the Java language using a specific browser. Researchers took this as a challenge and began looking for security loopholes in the Java language to overcome the strength and complexity of the applet security model. Technical errors discovered were soon corrected, and as far as we know, no real system has ever been compromised. To appreciate the importance of this fact, remember the millions of viruses on the executable files of the Windows operating system and macros of the word processor Word, which indeed caused a lot of trouble, and the surprisingly toothless criticism of the weaknesses of the attacked platform. In addition, the ActiveX mechanism in the Internet Explorer browser could cause a lot of criticism, but the methods of hacking it are so obvious that only a few experts bothered to publish their research.

Some system administrators have even started turning off Java language protection in their browsers so that users can continue to download executable files, ActiveX controls, and documents created using the word processor Word. It's funny that currently the probability of overcoming the security system of Java applets is comparable to the probability of dying in a plane crash, while the risk of infecting a computer by opening a document created by a Word word processor is comparable to the risk of dying under the wheels of a car while running across the road in an hour peak.

The JavaScript language is a simplified version of the Java language.

JavaScript is a scripting language that can be used in Web pages. It was developed by Netscape and was first called LiveScript. The syntax of the JavaScript language is similar to the syntax of the Java language, but that is where the similarities end (except for the name, of course). A subset of the JavaScript language was standardized under the name ECMA-262, but its extensions needed for real work were not standardized.

Java - a language from Sun microsystems. It was originally developed as a language for programming electronic devices, but later began to be used for writing server software applications. Java programs are cross-platform, that is, they can run on any operating system.

Java Programming Basics

Java, as an object-oriented language, follows the basic principles of OOP:

  • inheritance;
  • polymorphism;
  • encapsulation.

At the center of Java, as in other OYAs, is an object and a class with constructors and properties. It is better to start learning the Java programming language not from official resources, but from manuals for beginners. Such manuals describe the capabilities in detail and provide code examples. Books like “The Java Programming Language for Beginners” explain in detail the basic principles and features of the named language.

Peculiarities

The Java programming language code is translated into bytecode and then executed on the JVM. Conversion to bytecode is carried out in Javac, Jikes, Espresso, GCJ. There are compilers that translate the C language into Java bytecode. Thus, a C application can run on any platform.

The Java syntax is characterized by the following:

  1. Class names must begin with a capital letter. If the name consists of several words, then the second one must begin in upper case.
  2. If several words are used to form a method, then the second of them must begin with a capital letter.
  3. Processing begins with the main() method - it is part of every program.

Types

The Java programming language has 8 primitive types. They are presented below.

  • Boolean is a logical type that accepts only two values, true and false.
  • Byte is the smallest integer type, measuring 1 byte. It is used when working with files or raw binary data. Has a range from -128 to 127.
  • Short has a range from -32768 to 32767 and is used to represent numbers. The size of variables of this type is 2 bytes.
  • Int also stands for numbers, but its size is 4 bytes. It is most often used to work with integer data, and byte and short are sometimes promoted to int.
  • Long are used for large integers. Possible values ​​range from -9223372036854775808 to 9223372036854775807.
  • Float and double are used to denote fractional values. Their difference is that float is convenient when high precision in the fractional part of a number is not required.
  • Double displays all characters after the "." separator, while float displays only the first ones.
  • String is the most commonly used primitive type used to define strings.

Classes and objects

Classes and objects play an important role in Learning the Java Programming Language for Beginners.

A class defines a template for an object; it necessarily has attributes and methods. To create it, use the Class keyword. If it is created in a separate file, then the name of the class and the file must be the same. The name itself consists of two parts: the name and the extension.Java.

In Java, you can create a subclass that will inherit the methods of the parent. The word extends is used for this:

  • class class_name extends superclass_name ();

A constructor is a component of any class, even if it is not explicitly specified. In this case, the compiler creates it independently:

  • public class Class( public Class())( ) public Class(String name)( ))

The name of the constructor is the same as the name of the class; by default, it has only one parameter:

  • public Puppy(String name)

Object is created from a class using the new() operator:

  • Point p = new Point()

It receives all the methods and properties of the class, with the help of which it interacts with other objects. One object can be used several times under different variables.

    Point p = new Point()

    class TwoPoints (

    public static void main(String args) (

    Point p1 = new Point();

    Point p2 = new Point();

    Object variables and objects are completely different entities. Object variables are references. They can point to any variable of a non-primitive type. Unlike C++, their type conversion is strictly regulated.

    Fields and Methods

    Fields are all the variables associated with a class or object. By default they are local and cannot be used in other classes. To access fields, use the “.” operator:

    • classname.variable

    You can define static fields using the static keyword. Such fields are the only way to store global variables. This is due to the fact that Java simply does not have global variables.

    Implemented the ability to import variables to gain access from other packages:

    • import static classname;

    Method is a subroutine for the classes in which it is declared. Described at the same level as variables. It is specified as a function and can be of any type, including void:

    • class Point(int x, y;

      void init(int a, int b) (

    In the example above, the Point class has an integer x and y, an init() method. Methods, like variables, are accessed by using the "." operator:

    • Point.init();

    The init property does not return anything, so it is of type void.

    Variables

    In the Java programming language tutorial, variables occupy a special place. All variables have a specific type, it determines the required location for storing values, the range of possible values, and the list of operations. Before values ​​can be manipulated, variables are declared.

    Several variables can be declared at the same time. A comma is used to list them:

    • int a, b, c;

    Initialization occurs after or during the declaration:

    int a = 10, b = 10;

    There are several types:

    • local variables (local);
    • instance variables
    • static variables (static).

    Local variables are declared in methods and constructors; they are created when the latter are run and destroyed upon completion. For them, it is prohibited to specify access modifiers and control the level of availability. They are not visible outside the declared block. In Java, variables do not have an initial value, so it is required to be assigned before the first use.

    Instance variables must be declared inside the class. They are used as methods, but can only be accessed after the object has been created. The variable is destroyed when the object is destroyed. Instance variables, unlike local ones, have default values:

    • numbers - 0;
    • logic - false;
    • links are null.

    Static variables are called class variables. Their names begin with an uppercase character and are specified by the static modifier. They are used as constants; accordingly, one specifier from the list is added to them:

    • final;
    • private;
    • public.

    They are launched at the beginning of the program and destroyed after execution stops. Just like instance variables, they have standard values ​​that are assigned to empty variables. Numbers have a value of 0, boolean variables have a value of false, and object references are initially null. Static variables are called as follows:

    • ClassName.VariableName.

    Garbage collector

    In the tutorial "The Java Programming Language for Beginners", the section on automatic garbage collection is the most interesting.

    In Java, unlike the C language, it is impossible to manually remove an object from memory. For this purpose, an automatic removal method has been implemented - a garbage collector. With traditional deletion via null, only the reference to the object is removed, and the object itself is deleted. There are methods to force garbage collection, although they are not recommended for use in normal work.

    The module for automatically deleting unused objects works in the background and is launched when the program is inactive. To clear objects from memory, the program stops; after freeing the memory, the interrupted operation is resumed.

    Modifiers

    There are different types of modifiers. In addition to those that determine the access method, there are modifiers of methods, variables, and classes. Methods declared private are only available in the declared class. Such variables cannot be used in other classes and functions. Public allows access to any class. If you need to get a Public class from another package, you must first import it.

    The protected modifier is similar in effect to public - it opens access to the fields of the class. In both cases, the variables can be used in other classes. But the public modifier is available to absolutely everyone, and the protected modifier is only available to inherited classes.

    The modifier that is used when creating methods is static. This means that the created method exists independently of instances of the class. The Final modifier does not control access, but rather indicates the impossibility of further manipulation of the object's values. It prohibits changing the element for which it is specified.

    Final for fields makes it impossible to change the first value of the variable:

      public static void mthod(String args) (

      final int Name = 1;

      int Name = 2;// will throw an error

    Variables with the final modifier are constants. They are usually written in capital letters only. CamelStyle and other methods do not work.

    Final for methods indicates a prohibition on changing a method in an inherited class:

      final void myMethod() (

      System.out.printIn(“Hello world”);

    Final for classes means that you cannot create class descendants:

      final public class Class (

    Abstract - modifier for creating abstract classes. Any abstract class and abstract methods are intended to be further extended in other classes and blocks. Modifier transient tells the virtual machine not to process the given variable. In this case, it simply will not be saved. For example, transient int Name = 100 will not be saved, but int b will be saved.

    Platforms and versions

    Existing families of the Java programming language:

    • Standard Edition.
    • Enterprise Edition.
    • Micro Edition.
    • Card.

    1. SE is the main one, widely used for creating custom applications for individual use.
    2. EE is a set of specifications for enterprise software development. Contains more features than SE, so it is used on a commercial scale in large and medium-sized enterprises.
    3. ME - designed for devices with limited power and memory, they usually have a small display size. Such devices are smartphones and PDAs, digital television receivers.
    4. Card - designed for devices with extremely limited computing resources, such as smart cards, SIM cards, ATMs. For these purposes, the bytecode, platform requirements, and library components were changed.

    Application

    Programs written in the Java programming language tend to be slower and take up more RAM. A comparative analysis of the Java and C languages ​​showed that C is a little more productive. After numerous changes and optimizations of the Java virtual machine, it has improved its performance.

    Actively used for Android applications. The program is compiled into non-standard bytecode and executed on the ART virtual machine. Android Studio is used for compilation. This IDE from Google is the official one for Android development.

    Microsoft has developed its own implementation of the Java virtual machine MSJVM. It had differences that broke the fundamental concept of cross-platform - there was no support for some technologies and methods, there were non-standard extensions that only worked on the Windows platform. Microsoft released the J# language, the syntax and overall operation of which is very similar to Java. It did not conform to the official specification and was eventually removed from the standard Microsoft Visual Studio Developer Toolkit.

    Java programming language and environment

    Software development is carried out in the following IDEs:

    1. NetBeans IDE.
    2. Eclipse IDE.
    3. IntelliJ IDEA.
    4. JDeveloper.
    5. Java for iOS.
    6. Geany.

    The JDK is distributed by Oracle as a Java development kit. Includes a compiler, standard libraries, utilities, and an executive system. Modern integrated development environments rely on the JDK.

    It is convenient to write code in the Java programming language in Netbeans and Eclipse IDE. These are free integrated development environments, they are suitable for all Java platforms. Also used for programming in Python, PHP, JavaScript, C++.

    IntelliJ IDE from Jetbrains is distributed in two versions: free and commercial. Supports writing code in many programming languages; there are third-party plugins from developers that implement even more languages.

    JDeveloper is another development from Oracle. Completely written in Java, so it works on all operating systems.

In this guide, we'll cover everything you need to know before you start studying. programming in Java. You will learn about the capabilities of the platform, its application, and how to start learning Java correctly.

What is the Java programming language?

In 1991, the "Green Team", a division of Sun Microsystems, led by James Gosling, created a language for programming consumer electronic devices. At that time it was called Oak (“Oak”). Why "Oak"? Simply because this tree grew outside the window of Gosling’s office.

The Green Team demonstrated the use of Oak in an interactive TV. But for digital cable television of those years, this technology was too advanced. At the same time, the Internet was gaining popularity, for which the new programming language was best suited.

After some time, the new language was renamed Green, and after that - Java, in honor of coffee from the island of Java. That's why the Java logo features a coffee mug.

During the development of Java, C/C++ was popular, so Gosling made the language's syntax similar to C/C++ and implemented the " write once - run anywhere" In 1995, Sun Microsystems released the first official version of Java. And at the same time it was announced that Java would be included in the Netscape Navigator browser.

In 2010, Sun Microsystems, along with the Java programming language, was acquired by Oracle Corporation.

Java version history

  1. June 1991 – start of the development project programming language Java.
  2. JDK 1.0 – January 1996.
  3. JDK 1.1 – February 1997.
  4. J2SE 1.2 – December 1998.
  5. J2SE 1.3 – May 2000.
  6. J2SE 1.4 – February 2002.
  7. J2SE 5.0 – September 2004.
  8. Java SE 6 - December 2006.
  9. Java SE 7 – July 2011.
  10. Java SE 8 – March 18, 2014.
  11. Java SE 9 – September 21, 2017.

Java Programming Language Features

Java is a cross-platform language

Java code written on one platform ( that is, the operating system), can be run without modification on other platforms.

Java is used to run Java ( Java Virtual Machine, JVM). The JVM processes the byte code, after which the processor processes the code received from the JVM. All virtual machines work similarly, so the same code runs the same on all operating systems, which makes Java a cross-platform programming language.

Object-oriented programming language

There are different styles of programming, and one of the most popular is object-oriented programming. With this approach, a complex problem is broken down into smaller ones by creating objects. Thanks to this, the code can be reused.

Object-oriented functions are found in many programming languages, including Java, Python, and C++. If you're serious about learning to program, an object-oriented approach is worth incorporating into your learning plan.

Java is fast

Early versions programming language Java has often been criticized for being slow. But today the situation has changed dramatically. New versions of the JVM run much faster, and the processors that interpret them are becoming faster and faster.

Today Java is one of the fastest programming languages. Well-optimized Java code runs almost as fast as low-level programming languages ​​such as C/C++ and much faster than Python, PHP, etc.

Java is a secure platform

Java is:

  • a secure platform for developing and launching applications;
  • provides tools for automatic memory management, which reduces code vulnerability;
  • ensures secure data transfer.

Extensive core library

One of the reasons why Java is so widespread is its huge standard library. It contains hundreds of classes and methods from various packages that make life easier for developers. Eg,

java.lang is advanced functions for strings, arrays, etc.

java.util – library for working with data structures, regular expressions, date and time, etc.

kava.io - library for file input/output, exception handling, etc.

Application of the Java Platform

Before learning Java programming from scratch, you need to know that more than 3 billion devices around the world work on this platform. What exactly can it be used for:

  1. Android Applications - To develop Android applications, the Java programming language is often used in combination with the Android SDK ( from English software development kit - software development kit).
  2. Web Applications - Java is used to create web applications using server programs, Struts framework and JSP. Some popular web applications written in Java are: Google.com, Facebook.com, eBay.com, LinkedIn.com.

It's worth noting that these sites are not necessarily written exclusively in Java, and may use other programming languages ​​as well.

  1. Software development– such programs as Eclipse, OpenOffice, Vuze, MATLAB and many others are written in Java.
  2. Big Data processing – to process “big data” you can use the Hadoop framework written in Java.
  3. Trading systems– using the platform Oracle Extreme Java Trading Platform, you can write programs for trading.
  4. Embedded devices– today billions of devices, such as TVs, SIM cards, Blu-ray players, etc., are based on Java Embedded technology from Oracle.

Also programming in Java is used to develop games, scientific applications ( for example, for natural language processing) and in many other areas.

Java Terminology You Should Know

Java is a set of technologies ( programming language and computer platform), designed to create and run software. However, the term Java often refers to the programming language itself.

Programming language Java is a cross-platform, object-oriented, general-purpose programming language with extensive capabilities.

Java 9 is the latest version of Java at the time of this writing.

Java EE, Java Me and Java SE - these names stand for Java Enterprise Edition, Micro Edition and Standard Edition, respectively.

Java EE is aimed at applications that run on servers. Java ME is designed for power-constrained devices such as embedded devices. Java SE is the standard edition of Java for writing general programs.

If you are new to Java programming, we recommend starting with Java SE.

JVM - Java Virtual Machine (" Java virtual machine") is a program that allows a computer to run programs written in Java.

JRE – Java Runtime Environment (“ Java runtime") includes the JVM, associated libraries, and other components needed to run programs. But the JRE does not have a compiler, debugger, or other development tools.

JDK – Java Development Kit Java developer) contains the JRE and other development tools such as compilers, debuggers, etc.

How to run Java on your operating system

How to Run Java on Mac OS

Here's what to do for Java programming from scratch and installing the platform on Mac OS X or macOS:

  1. Download the latest version of Java ( JDK) with Java SE download pages.
  2. Double-click on the downloaded DMG file and follow the instructions of the installer.
  3. To verify the installation, open a terminal and enter the following command:

javac –version

If Java is installed correctly, the program version will be displayed on the screen ( for example javac 1.8.0_60).

The next step is to install the IDE ( integrated development environment) for writing and running Java code. We will install the free version of IntelliJ IDEA and run Java on it. Here's what you need to do to do this:

  1. Go to IntelliJ download page and download the free Community Edition.
  1. Open the downloaded DMG file and follow the installation instructions. For quick access, you can move IntelliJ IDEA to the Applications folder.
  2. Open IntelliJ IDEA. Select the option “Don’t import settings” (“ Don't import settings") and click "Ok". After this, accept the Jetbrains privacy policy by clicking on the “Accept” button.
  3. Now you can customize the interface for yourself. You can also skip this step and leave everything as default. If you are not sure, just skip this step by clicking the “Skip All and Set Defaults” button (“ Skip everything and set to default settings»).
  1. The program will show you a welcome page. Click on the button “Create New Project" (“ Create a new project»).
  2. In the next window, select "Java" in the left pane and click "New" at the top of the program window to select "JDK". Here you need to select the location where you installed the JDK, and then click Next.
  1. You will have the option to create a project from a template (“Create project from template”). We ignore it and click the “Next” button.
  2. In the next installation step programming language Java enter the project name and click the "Finish" button.
  3. In the left panel you will see your project. If the panel is not visible, go to the menu Views > Tool Windows > Project.
  4. Go to Hello > New > Java and give the class a name. We called it First.
  1. To run the program you just wrote, go to Run > Run... Click on First ( that is, the name of the file we created

How to Run Java on Linux

To run examples from programming lessons from scratch Java on Linux will need the JAVA SE Development Kit ( JDK) and IDE for developing your projects. Follow the instructions step by step to get started with Java.

Install Java

  1. Open a terminal and type the following command to install Java:

    sudo add-apt-repository ppa:webupd8team/java sudo apt update; sudo apt install oracle-java8-installer

  1. Accept the license agreement and terms of use by clicking “OK” and “Yes”, respectively.
  2. You have installed Java. To verify that the installation was successful, enter the following command in a terminal:

java –version

If the current version is displayed, the installation was successful. If not, check with Oracle help page.

Installing IntelliJ IDEA

  1. Go to .
  1. Download the free Community Edition by clicking the "Download" button.
  2. After downloading change the directory in the terminal to your downloads directory and extract the Java tar file into the /opt folder with the following command:

sudo tar xf .tar.gz -C /opt/

  1. After unpacking, change the directory to the bin folder of the IntelliJ IDEA program:

    cd /opt/ /bin

  2. To start the IDE, enter the following command:
  3. Select “Don’t import settings” (“ Don't import settings") and click "OK". After this, we accept the Jetbrains privacy policy by clicking on the “Accept” button.
  4. Now for the passage programming courses Java, you can customize the interface for yourself. Create a shortcut on your desktop for quick access to the program. After that, to launch the IDE, click “Next" at all the following stages.
  5. The program will show the welcome page. Click "Create New Project" (" Create a new project»).
  6. In the next window, select "Java" in the left pane and make sure that Java is selected in the Project SDK line. If not, then select the location where you installed JDK: /usr/lib/jvm/java-8-oracle.
  1. Click “Next” twice and create a project.
  2. In the next step, enter a project name and click the “Finish” button. Now in the left panel you will see your project. If this panel is not visible, go to the menu Views > Tool Windows > Project.
  3. Add a new Java class. Select src in the left pane with the right click and go to New > Java Class. Provide a class name. There should be no spaces in the class name.
  1. Write the Java code and save the project.
  2. To run the program, go to Run > Run... Click on HelloWorld ( Project name) - the program will compile the file and run it.

How to Run Java on Windows (XP, 7, 8 and 10)

To master Java programming basics and running the platform on Windows, you will need a JAVA SE Development Kit (JDK) and an IDE for developing projects. Follow the step by step instructions below:

Installing Java

  • Go to download page Java Standard Edition Development Kit.
  1. In the Java SE Development Kit section at the top of the table, click "Accept License agreement" (" Accept the license agreement"). Then click on the link Windows (x64) if you have a 64-bit operating system or Windows (x86) if you have a 32-bit OS.
  1. After downloading, run the installation file and follow the instructions that appear on the screen. Click " Next" Select all functions by pressing " This feature will be installed on local hard drive" and copy the installation location ( it is highlighted in yellow) in Notepad, then click again Next».
  1. During the installation process, you will be prompted to install the JRE. Click "Next" and then "Finish" to complete the installation.
  2. Now you need to edit the PATH variable. Go to Control Panel > System and Security > System. In the left pane, select " Additional system parameters".
  1. Click " Environment Variables". In chapter " System variables" Find the PATH variable and in the next window click "Edit".
  1. Select all text in the " Variable value" and copy it into a separate text file. This will make it easier to edit and check for errors. See if the copied text contains the line: C: ProgramData Oracle Java javapath; . If yes, then you can move on to the next step. If not, then paste the installation location you copied earlier at the beginning of the variable and add bin at the end of the line like this: C : Program Files (x 86) Java jdk 1.8.0_112 bin ;
  1. Click " Please note that your JDK version (jdk 1.8.0_112) may be different. Copy the value of the variable and paste it into the PATH box. OK
  2. " to save your changes. To check if the platform is installed correctly introduction to programming Java, open command line by typing cmd in the Windows search bar or through the “Run…” command ( Windows - R Oracle help page.

Installing IntelliJ IDEA

  1. Go to ). Enter the java -version command. If the current version of Java is displayed, the installation was successful. If not, check with.
  2. IntelliJ IDEA download page
  1. Once downloaded, run the installation file and follow the instructions that appear on the screen. Then create a desktop shortcut for the 64-bit version and add associations with the .java extension. Click "Next" and continue with the installation.
  1. Once installed, open IntelliJ IDEA by clicking on the desktop icon.
  2. Select "Don't import settings" (" Don't import settings") and click "OK". After this, we accept the Jetbrains privacy policy by clicking “Accept”.
  3. Now you can customize the interface for yourself. You can also skip this step and leave everything as default by clicking the “Skip All and Set Defaults” button.
  4. The program will show the welcome page. Click "Create New Project" (" Create a new project»).
  1. In the next window, select "Java" in the left pane and click "New" at the top of the program window to select JDK. Here you need to select the location where you installed the JDK during the Java installation, and then click “Next”.
  2. IntelliJ IDEA will find the JDK and recognize it. There is no need to mark any other options, just click “Next".
  3. On the next screen, enter the project name: HelloWorld and click Finish. If the program says that the directory does not exist, click OK. If you don't see the left pane, go to Views > Tool Windows > Project.
  4. To set the class name, select the src folder in the left pane. Right-click on it, go to New > Java and set the class name. There should be no spaces in the class name.
  1. Write the code and save the Java project programming lesson.
  2. To run the program, go to the menu Run > Run... Click on HelloWorld - the program will compile the file and run it.

Your first Java program

To introduce users to a new programming language, they use the Hello World program (“Hello, world!”). This is a simple program that displays the words Hello, World! In this section, we will teach you how to write this program in Java using IntelliJ IDEA.

  1. Open IntelliJ IDEA.
  2. Go to File > New > Project… > Java ( in the left navigation bar).
  3. Set the Project Name from programming course J a va. We'll call it Hello World and click Finish.
  4. Now we need to create a new Java class.
  5. Select the src folder in the left pane, then go to File > New > Java Class and name the new class HelloWorld.
  6. Copy the following code into the HelloWorld.java file and save it.

public class HelloWorld ( public static void main(String args) ( // prints "Hello, World!" System.out.println("Hello, World!"); ) )

  1. Click the start button ( Run). If everything is in order, you will see Hello, World! on the screen.

How to learn Java?

Official Java Documentation

Oracle, the company that owns Java, publishes quality tutorials. The official documentation covers all Java features and is updated regularly.

Note: the only negative is that the official Java documentation is not always written in the simplest language.

If you really want to learn programming in Java, buy a good book. Of course, 1000 pages cannot be read in one day. But a good tutorial will help you learn programming.

Java: The Complete Guide (10th Edition)

A great book for those just starting to learn Java. The latest edition includes all the features of the Java 8 release.

The book covers everything you need to know about Java programming, including syntax, keywords, and programming fundamentals, as well as the Java API library, Java applets, and more.

Java Philosophy (4th Edition)

If you are switching to Java from another programming language, this book is for you. If you are starting from scratch, it is best to read it along with the other.

Java 8. Pocket Guide: First Aid for Java Programmers

This book contains clear answers to questions that arise when teaching J ava programming from scratch. It briefly covers all the basic Java concepts (including Java 9). Don't want to flip through hundreds of pages looking for the right line? Buy this book.

Instead of a conclusion

If you start learning Java, you can't go wrong - it is a promising programming language, full of a wide variety of possibilities.

Before you start learning Java, here are a few tips:

  • Don't read educational articles and examples like a novel. The only way to become a good programmer is to write a lot of code.
  • If you're coming from another programming language (say, C#), you don't need to write code in the C# style.
  • Find Java communities online. Once you learn how to write simple programs in Java, find popular sites and forums dedicated to Java. Try to solve problems that other programmers have. This is a great way to expand your own knowledge. Plus, if you get stuck, you'll know where to ask for help.

We hope this article will encourage you to learn Java and help you start working on your first programs.

This publication is a translation of the article “ Learn Java Programming. The Definitive Guide", prepared by the friendly project team

Best articles on the topic