Computers Windows Internet

JSP page syntax. Conditional constructs

Programming is writing the source code of a program in one of the programming languages. There are many different languages programming, 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 used to write the source code of a program. Computer systems are unable (yet) to understand human language, and even more so, human logic (especially feminine), so all programs are written in programming languages, which are subsequently translated into computer language or machine code. Systems that translate the source code of a program into machine code are very complex and, as a rule, they are created by more than a dozen months and more than a dozen programmers. Such systems are called integrated programming environments or tools.

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

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

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

Object Oriented Programming

Object-oriented programming is based on objects, which is somewhat similar to our world. If you look around you, then you can definitely find something that will help you more clearly understand the model of such programming. For example, I am now sitting at a table and typing this chapter on a computer that consists of a monitor, system unit, keyboard, mouse, speakers, and so on. All of these parts are the objects that make up the computer. Knowing this, it is very easy to formulate some kind of generalized model for 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 correct or even specify actions for the System unit object that affect the operation of the Monitor object. The presented process characterizes very well the entire object-oriented programming system.

Imagine some powerful software 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 linked 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, you will have to do a lot of work with all the source code of this program.

Object-oriented programming is much simpler, let's go back to the example of a computer system. Let's say you are no longer satisfied with a seventeen-inch monitor. You can safely exchange it for a twenty-inch monitor, of course, if you have certain material resources. The exchange process itself will not entail huge problems, except that the driver will have to be changed, and the dust from under the old monitor should be wiped off and that's it. Object-oriented programming is based on approximately this principle of operation, where a certain part of the code can represent a class of homogeneous objects that can be easily modernized or replaced.

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

Classes

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

This approach makes it very easy to simulate all sorts of processes in programming, making it easier to solve the assigned tasks. For example, there are four objects of four different classes: monitor, system unit, keyboard, and speakers. To play a sound file, use the keyboard to give the command system unit, 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 means and capabilities of this class. There can be as many objects of the same class as needed to solve the problem.

Methods

When the playback example was given sound file, then it was mentioned about giving a command or a message, on the basis of which certain actions were carried out. The task of performing actions is solved using the methods that each object has. Methods are a set of commands with which you can perform certain actions with an object.

Each object has its own purpose and is designed to solve a certain range of problems using methods. For example, what good would the Keyboard object be if you could not 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. Processing of such commands occurs using methods.

For example, you press the Esc key to cancel any action and thereby give a command to the method assigned to this key, which at the program level solves this problem. The question immediately arises about the number of methods of the Keyboard object, but there can be a different implementation here - from defining methods for each of the keys (which, in general, is unreasonable), to creating one method that will monitor the general state of the keyboard. That is, this method monitors whether a key was pressed, and then, depending on which of the keys is involved, 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 be owned or part of a particular class.

Syntax and semantics Java language

In order to speak and read any foreign language, it is necessary to learn the alphabet and grammar of that language. A similar condition is observed in the study of 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 posed to you in any form convenient for you.

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

Class Phone
{
Include () 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 the curly braces denote the beginning and end of the body of a class, method, or any sequence of data, respectively. That is, the parentheses indicate the belonging to a method or class. Each open parenthesis must have a closing parenthesis. In order not to get confused, they are usually put at the same level in the code.

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

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

The class keyword 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 register of the record. In almost all programming languages, it is important to keep the names recorded in the case in which they were made. If you wrote Telefon, then already such a spelling as telefon or TELefoN will give an error during compilation. As it was written initially, so it is necessary to write further.

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

There are two methods in the body of the Telefon class: on () - turns the phone on and the off () method - turns off the phone. Both methods have their own bodies and, in theory, they should contain some kind of source code describing 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 parentheses on (), inside which parameters can be written, for example on (int time) or on (int time, int time1). With the help of parameters, there is a kind of connection between the 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 in certain time... Then the integer value in the time parameter will be passed to the body of the method and the phone will be turned on based on the received data. If the parentheses are empty, then the method takes no parameters.

Comments (1)

In the Telefon class, the bodies of both methods have an entry after two slashes: //. Such an entry denotes comments that will be ignored by the compiler, but are needed for readability of the code. The more information you comment out while writing the program, the more chances you will have to remember in a year what you've been working on all this time.

Comments in Java can be of three types, they are:

//, /*…*/ and /**…*/

Comments written using the // operator must be located on one line:

// One line
!!! Error! You cannot wrap to 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 are finished commenting the code, put the * / operator. The last kind of comment / ** ... * / is used when documenting the code and can also be located on any number of lines.

Java data types

Data types exist in Java to set an arbitrary value. 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 the time parameter was given, it was said about passing a value to the method. This value indicated the time by which the phone was supposedly to be turned on. The int specifier determines the type of the time value. Java 2 ME has six data types.

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 is a very large integer value, from –922337203685475808 to 9223372036854775807;
char is a Unicode character constant. Range this format 0 to 65536, which is 256 characters. Any character of this type must be written in single quotes, for example: ‘G’;
boolean - a boolean type, has only two values: false - false and true - true. This type is often used in loops about which a little later. The idea is very simple - if you have money in your pocket, presumably this is true, and if not, then false. Thus, if there is money, we go to the store for bread or beer (underline the necessary), if there is no money, we stay at home. That is, it is such a logical value that contributes to the choice of further actions of your program.

To declare some required value, the following entry is used:

Int time;
long BigTime;
char word;

The semicolon operator is required after the entries and is placed at the end of the line. You can combine several ads 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, we will add new methods that can really solve certain problems.

Class Telefon
{
// S - display area
// w - display width
// h - display height
int w, h, S;
// method that calculates the 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 screen in pixels. The operation is useless, but very indicative and easy to understand. The body of the Area () method has acquired 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 this phone.

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

Arithmetic operators

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

Here you assign the value 3 to the variable x. And the operator "equal" in programming languages ​​corresponds to writing two consecutive operators "equal": "==". 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 a value of 5, but after such a record, the previous value is lost and the product z * x (8 * 5) is written, which is 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 similarly related.

The decrement “––” and increment “++” operators are very specific, but very simple. There are often times in programming when you need to increase or decrease a value by one. This is often found in loops. The increment operation increases the variable by one.

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

The decrement operation decreases the variable by one.

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

Increment and decrement operations can be post and prefix:

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

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

The prefix increment is:

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

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

This expression is not true, nine is not equal to ten, so its value for this expression is false.

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

Logical operators

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

A * B && B * C;

In the event that only both parts of the expression are true, the value of the expression is considered true. If one of the parts is incorrect, then the value of the entire expression will be false.
In contrast to the "&&" operator, there is the "||" operator, which is not in vain called "OR".

A * B || B * C;

If any part of the expression is true, then the entire expression is considered 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 have led you, it seems to me, into a difficulty, isn't it? The fact is that in Java, as in mathematics, there is a priority or the 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 precedence of all the available operators in the Java language:

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

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

JSP pages have a combined syntax: a combination of the standard syntax that conforms to the HTML specification and the JSP syntax that is defined by the Java Server Pages specification. JSP syntax defines the rules for writing JSP pages, which are composed of standard HTML tags and JSP tags. JSP pages, in addition to HTML tags, contain JSP tags of the following categories:

JSP directives

Directives provide global information regarding specific requests to the JSP and provide information needed during the translation stage.

Directives are always placed at the beginning of the JSP page before all other tags, so that parser(parser) JSP, when parsing the text, at the very beginning, highlighted the global instructions. Thus, the JSP Engine (JSP runtime) parses the code and creates a servlet from the JSP. Directives are messages to a JSP container. Syntax directives The JSP looks like this:

<%@ директива имяАтрибута="значение" %>Task syntax directives in XML: Directive can have multiple attributes. In this case directive can be repeated for each of the attributes. At the same time, couples "AttributeName = value" can be placed under one directive with a space as a separator. There are three types of directives:

  • page (page)
  • taglib (tag library)
  • include (include)

Page directive

Directive page defines properties JSP pages that affect the translator. Order of attributes in a directive page does not matter. Violation of syntax or presence of unrecognized attributes results in a translation error. An example of a directive page the following code can serve:<%@ page buffer="none" isThreadSafe="yes" errorPage="/error.jsp" %>This directive declares that this page The JSP does not use buffering, that it is possible for many users to access a given JSP page at the same time, and that an error page named error.jsp.
Directive page may contain information about the page:<%@ page info = "JSP Sample 1" %>List of possible directive attributes page presented in the table.
Attribute nameMeaning Description
language Line Determines the language used in JSP file scriptlets, expressions, or any include files, including the body of translated code. The default is "java"
extends Line Specifies the superclass for the generated servlet. This attribute should be used with great care as it is possible that the server is already using a superclass.
import Line Definition of packages to import, for example:
& lt% @ page import = "java.util. *%>
Session true or false Meaning true(default) indicates that a predefined variable session(type HttpSession) must be bound to an existing session, if any, otherwise a new session is created and bound to. Meaning false determines that sessions will not be used, and attempts to access a variable session will result in an error when translating the JSP page to the servlet
Buffer none or the size of the buffer in kB. Sets the buffer size for the JspWriter out. The default value depends on the server settings and should not exceed 8 kB. If the value is none the output goes directly to the object
autoFlush true or false Determines whether the buffer should be emptied automatically when it overflows or an error occurs. The default is true
isThreadSafe true or false Meaning true(the default) specifies the normal execution mode of the servlet, where multiple requests are processed concurrently using a single servlet instance, assuming that the author has synchronized access to the variables of that instance. A false value signals that the servlet should inherit SingleThreadModel(single-threaded model) where sequential or concurrent requests are handled by separate instances of the servlet
info Line Defines a string of information about a JSP page that will be accessed using the method Servlet.getServletInfo ()
errorPage Line The attribute value is the URL of the page that should be displayed in the event possible mistakes throwing exceptions
isErrorPage true or false Signals whether this page can be used to handle errors for other JSP pages. The default is false
contentType Line Specifies the encoding for the JSP page and response, and the MIME type of the JSP response. The default value of the content type is text / html, encodings - ISO-8859-1. For example:
contentType = "text / html; charset = ISO-8859-1"
pageEncoding Line Determines the character encoding of the JSP page. The default is charset from attribute contentType if it is defined there. If the value charset in attribute contentType undefined, value pageEncoding is set equal ISO-8859-1

Taglib directive

Directive taglib declares that a given JSP page uses a tag library, uniquely identifies it with a URI, and maps a tag prefix with which the library can be acted upon. If the container cannot find the tag library, a fatal translation error occurs. Directive taglib has the following syntax:<%@ taglib uri="URI of the included tag library"prefix =" prefix name"%> Prefix" prefix name"is used when referring to the library. An example of using the tag library mytags: <%@ taglib uri="http://www.taglib/mytags" prefix="customs" %> . . . V this example the tag library has a URI "http: //www.taglib/mytags", the string is assigned as a prefix customs that is used in the JSP page when accessing elements of the tag library.

Include directive

Directive include allows you to insert text or code while translating a JSP page into a servlet. Directive syntax include looks like this:<%@ include file="The relative URI of the page to include"%> Directive include has one attribute - file... It includes the text of the specified resource in the JSP file. This directive can be used to place a standard copyright header on every JSP page:<%@ include file="copyright.html" %>The JSP container accesses the include file. If the include file has changed, the container can recompile the JSP page. Directive include treats a resource, such as a JSP page, as a static object. The given URI is usually interpreted relative to the JSP of the page on which the link is located, but as with any relative URI, you can tell the system the position of the resource of interest relative to the home directory of the WEB server by prefixing the URI with a "/" character. The content of the include file is treated as plain JSP text and therefore can include elements such as static HTML, script elements, directives, and actions. Many sites use a small navigation bar on every page. Due to the problems of using HTML frames, this task is often solved by placing a small table on top or in the left half of the page, the HTML code of which is repeated many times for each page of the site. Directive include- this is the most natural way to solve this problem, saving the developer from the nightmare of the routine of copying HTML into each separate file. Since the directive include includes files during page translation, then after making changes to the navigation bar, re-translation of all JSP pages using it is required. If the attached files change quite often, you can use the action jsp: include that connects the file when accessing the JSP page.

JSP declarations

Declarations (Declarations) are designed to define variables and methods in the scripting language, which are later used in the JSP page. Syntax declarations looks like this:<%! код Java %> ads are located in the declaration block and are called in the expression block of the JSP page. The code in the declaration block is usually written in Java, but application servers can use the syntax of other scripts. ads are sometimes used to add additional functionality when working with dynamic data obtained from properties of JavaBeans components. Examples of ads are presented in the table. Announcement can contain multiple lines, such as in the below code for calculating the value of a function fact (int n), which should be equal to 1 when n is less than 2 and n! with a positive value of n;<%! public static int fact (int n) { if (n ads do not produce any output to standard output out... Variables and methods declared in announcements are initialized and made available to scriptlets and other ads at the time the JSP page is initialized.

JSP Scriptlets

Scriptlets include various pieces of code written in the scripting language defined in the directive language... Code snippets must comply with the syntactic constructs of the language scriptlets, i.e., usually the syntax of the Java language. Scriptlets have the following syntax:<% текст скриптлета %>Syntax equivalent scriptlet for XML is: scriptlet text
If in the text scriptlet it is necessary to use the sequence of characters%> exactly as a combination of characters, and not as a tag - an end sign scriptlet, instead of the sequence%>, use the following combination of characters% \>.
The JSP specification provides a simple and straightforward example scriptlet that dynamically changes the content of the JSP page throughout the day.<% if (Calendar.getInstance ().get (Calendar.AM_PM) == Calendar.AM) {%>Good morning<% } else { %>Good Afternoon<% } %>It should be noted that the code inside scriptlet inserted as written and all static HTML text (template text) before or after scriptlet converted using the operator print... This means that scriptlets do not have to contain completed Java chunks, and that leaving open chunks can affect static HTML outside of scriptlet. Scripts have access to the same auto-defined variables as expressions. Therefore, for example, if there is a need to display any information on the page, you must use the variable out. <% String queryData = request.getQueryString (); out.println ("Дополнительные данные запроса: " + queryData); %>

JSP expressions

Expression in a JSP page is an executable expression written in the scripting language specified in the declaration language(how Java rule). Result expressions JSP of required type String, sent to standard output out using the current object JspWriter... If the result is expressions cannot be cast String, either a translation error occurs if the problem was detected at the translation stage, or an exception is thrown ClassCastException if the inconsistency was detected during the execution of the request. Expression has the following syntax: & lt% = expression text%> alternative syntax for expressions JSP when using XML: expression textExecution order expressions in the JSP page from left to right. If expression appears in more than one run-time attribute, then it runs from left to right in that tag. Expression must be a complete expression in a specific script (typically Java). Expressions are executed while the HTTP protocol is running. The expression value is converted to a string and included in the appropriate position in the JSP file. Expressions are commonly used to compute and display the string representation of variables and methods defined in a JSP page declaration block or derived from JavaBeans that are accessible from a JSP. The following code expressions serves to display the date and time of the request for this page: Current time: & lt% = new java.util.Date ()%> To simplify expressions there are several predefined variables that you can use. The most commonly used variables are:
  • request, HttpServletRequest;
  • response, HttpServletResponse;
  • session, HttpSession - associated with the request, if any;
  • out, PrintWriter - a buffered version of the JspWriter type for sending data to the client.

must necessarily match the name of the class whose main () method is called when the Java machine is started.

  • Object - the class from which to inherit all objects in Java, including arrays and strings ().
  • Access specifiers are individual for each member (specified before the declaration).
  • All class members are by default open to scope package... The default scope is a cross between private and protected, see.
  • Each * .java file can contain only one class declared as public and accessible from the outside.
  • The definition and declaration of a class is always in one file, it is impossible to put prototypes in headers.
  • Pointers are missing.
  • All class variables are actually references to objects, not the objects themselves. Their initialization for use must be done via new<конструктор-класса>(...) .
  • Based previous paragraph- when assigning one object variable to another, only the reference is changed but not the object copy.
  • Variables in a function are passed by value if it is elementary types(int, byte, long, etc ...), or by reference if they are objects.
  • The public static members of a class are accessed through the dot operator. , and not through ::, which in my opinion introduces some external confusion.
  • There is no destructor, but there is finalize ().
  • Finalize () should not be confused with the C ++ destructor. finalize () is called garbage collection only, which has nothing to do with the object going out of scope and the absence of at least one reference to this object.
  • You can force garbage collection by calling the Runtime.gc () method on the current Runtime object or the static System.gc () method. Judging by the experiments carried out, freeing memory only works within virtual machine Java and once allocated memory in the OS does not return until the machine ends.
  • In Java-style coding, functions throw exceptions instead of returning code. systemic errors or errors in the logic of the virtual machine. Therefore, a lot of functions must be executed inside a try (...) catch (...) (...) block that handles exceptions, or the method that calls them must explicitly indicate through throws the list of exceptions thrown by these functions that are not handled by them, for processing by their methods up the call stack.
  • Exceptions are divided into and.
  • The try (...) block can also end with a finally (...) block, which is executed regardless of the presence / absence of exceptions in the previous try (...) block. It is convenient to use this to perform any required actions regardless of the results of the execution of a block of code, for example, to automatically release all resources allocated in it.
  • char is not a single-byte type like with C / C ++, it is a 16-bit type that supports unicode strings.
  • bool is known as boolean in Java.
  • Conditional constructs accept only boolean type of variables or expressions. This means that the code is like:
    int a; ... actions on the variable a ...; if (a) (...)
    Not correct in terms of Java syntax and will not compile.
  • Constants are declared final and not const.
  • All arrays are objects.
  • Even string constants (like "any string const") are objects.
  • For strings (class String), only one operator is defined - +, concatenation.
  • Comparison of strings is done through the bool equals () method of the String class, for example s1.equals (s2).
  • The content of String objects is constant and does not imply changing a single element of the string, this is done for performance reasons. If you need such operations, you can use the StringBuffer class.
  • When concatenating an uninitialized string with a non-empty string, you get null + non-empty-string, for example s + = "| string"; will be equal to "null | string"
  • Arrays have a public member variable length, strings don't have instead, they use the length () method.
  • Java do not support multiple inheritance. Some of its functions are performed through "interfaces". Interfaces support multiple "inheritance" implementations of multiple interfaces in a single class, and in general many (interfaces) to many (classes) relationships and vice versa.
  • Interfaces allow the creation of links through which you can refer to objects of classes that implement these interfaces. True, the dynamic search for a suitable method when accessing through the reference-interface requires a lot of overhead, therefore it is not desirable.
  • Instead of enumerations, you can use interfaces without method declarations in them. In this case, all interface variables must be initialized when the interface is defined and their values ​​will automatically be constant. After that, through implements they can be "connected" to the defined class.
  • Also, since JDK 5 there are externally classic enumerations - enum. In fact, this is not just a list of named constants, but a special class inherited from the superclass Enum. Each element of the enumeration is an object of this class. The numeric value of an enumeration object can be obtained with the ordinal built-in function.
  • Custom operator overloading familiar in C ++, in Java not supported.
  • To work in an object environment with "primitive types" (int, float, char, etc ...), Java uses autobox / autobox into wrapper types (Integer, Float, Character, etc ...). In fact, this is an implementation of operator overloading for several built-in classes that implement the functionality of primitive types + object methods.
  • super - a keyword that allows you to call the constructor of a superclass from a subclass, or refer to a member of the superclass hidden by a member of the subclass.
    • When used as a constructor - super should always be first operator in the constructor of the subclass.
  • For determining abstract methods, the abstract keyword is used, a class containing an abstract method must also be defined as an abstract class ....
  • final prohibits overriding methods in child classes. For "short" methods declared as final, this keyword has the same effect as inline in C ++ - in subclasses instead of calling a function. may be inserted superclass method bytecode into calling class method code.
  • final also prohibits inheriting from a class declared as final.
  • Namespaces(namespace) in Java are implemented as packages(package).
  • To connect packages use import, you can also use import static ..(*|) to import static members of the class.
  • Java supports threads through the built-in Thread class and the Runable interface. For synchronization, use the synchronized specifier before the method in the class description, or synchronized ( ) (...) for a block of code synchronized with ... For signals between synchronized threads, methods of the parent Object class are used: wait () / notify () / notifyAll ().
  • transient - a modifier indicating that the value of an object / variable does not need to be "held" when saving an object, for example, when serializing it before writing it to disk / database. It is logical to mark variables containing unique identifiers runtime and other similar information that makes sense only in the current instance of the java process.
  • instanceof - runtime operation, returns true if there is a link to the class , or it can be cast to a reference to this class, otherwise false.
  • assert - Java assertions are used in much the same way as in C: assert [: Assertion fail description], but need to keep in mind that they are "embedded" into the compiled bytecode, and can be included with running java-ea.
  • this (...) - can be used inside the constructor of a class to call another constructor of the same class, matching the signature of the arguments.
  • Instead of templates are used generalizations, looks very similar: class CLASS_NAME (...). In generalizations it is forbidden use primitive types ( int, byte, char, etc ...). The parameters can be used only classes.
    In addition, supported limited types, by specifying the superclass for the parameter classes. For example, declaring a "generic class" class CLASS_NAME in which only descendant classes of the general numeric class Number are allowed.
  • It is convenient to use System.arraycopy () to quickly copy arrays.
  • Stanislav Gornakov

    In order to speak and read any foreign language, it is necessary to learn the alphabet and grammar of that language. A similar condition is observed in the study of 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 posed to you in any form convenient for you.

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

    Class Phone (Enable () method (// operations to turn on the phone) Method Turn off () (// operations to turn off the phone))

    The Phone class might look something like this. Note that the curly braces denote the beginning and end of the body of a class, method, or any sequence of data, respectively. That is, the parentheses indicate the belonging to a method or class. Each open parenthesis must have a closing parenthesis. In order not to get confused, they are usually put at the same level in the code.

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

    Class Telefon (void on () (// body of the method on ()) void off () (// body of the method off ()))

    The class keyword 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 register of the record. In almost all programming languages, it is important to keep the names recorded in the case in which they were made. If you wrote Telefon, then already such a spelling as telefon or TELefoN will give an error during compilation. As it was written initially, so it is necessary to write further.

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

    There are two methods in the body of the Telefon class: on () - turns the phone on and the off () method - turns off the phone. Both methods have their own bodies and, in theory, they should contain some kind of source code describing 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 parentheses on (), inside which parameters can be written, for example on (int time) or on (int time, int time1). With the help of parameters, there is a kind of connection between the 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 specific time. Then the integer value in the time parameter will be passed to the body of the method and the phone will be turned on based on the received data. If the parentheses are empty, then the method takes no parameters.

    Comments (1)

    In the Telefon class, the bodies of both methods have an entry after two slashes: //. Such an entry denotes comments that will be ignored by the compiler, but are needed for readability of the code. The more information you comment out while writing the program, the more chances you will have to remember in a year what you've been working on all this time.

    Comments in Java can be of three types, they are: //, / *… * / and / **… * /. Comments written using the // operator must be located on one line:

    // One line !!! Error! You cannot wrap to 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 are finished commenting the code, put the * / operator. The last kind of comment / ** ... * / is used when documenting the code and can also be located on any number of lines.

    Java data types

    Data types exist in Java to set an arbitrary value. 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 the time parameter was given, it was said about passing a value to the method. This value indicated the time by which the phone was supposedly to be turned on. The int specifier determines the type of the time value. Java 2 ME has six data types.

    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 is a 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 - a boolean type, has only two values: false - false and true - true. This type is often used in loops about which a little later. The idea is very simple - if you have money in your pocket, presumably this is true, and if not, then false. Thus, if there is money, we go to the store for bread or beer (underline the necessary), if there is no money, we stay at home. That is, it is such a logical value that contributes to the choice of further actions of your program.

    To declare some required value, the following entry is used:

    Int time; long BigTime; char word;

    The semicolon operator is required after the entries and is placed at the end of the line. You can combine several ads 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, we will add new methods that can really solve certain problems.

    Class Telefon (// S - display area // w - display width // h - display height int w, h, S; // method that calculates display area void 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 screen in pixels. The operation is useless, but very indicative and easy to understand. The body of the Area () method has acquired 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 ​​this phone. Now we come close to the operators of the Java language, with which you can perform all sorts of operations, and which we will talk about in the next part of this series of articles.


    Purpose, features and benefits of Eclipse

    Eclipse is an extensible IDE (Integrated Development Environment). An IDE is a conveniently organized set of tools needed to work on a software project.

    Eclipse is a universal platform that can be used to develop applications in any programming language (for example, you can use Python after installing the Pydev () connection, but Java is native to Eclipse (which, by the way, is written in Eclipse).

    The most important features of Eclipse are:

    1. Cross-platform. Eclipse runs on all common platforms: Windows, Linux, and MacOS X. More importantly, its functionality is the same on each of these platforms.
    2. Versatility and extensibility. Eclipse provides the ability to use a variety of third-party tools.
    3. Openness and gratuitousness. Eclipse is an OpenSource project (i.e. its source codes available to anyone and anyone can join the development of this tool). Eclipse has an active community that is constantly working to improve the program and expand its capabilities.

    Eclipse workspace

    The first thing you see when you start Eclipse is a dialog box that lets you choose where the workspace will be located. Workspace is the directory where your work will be saved.

    After choosing a workspace, the start page will appear on the screen, with suggestions to see tutorials, examples, etc. Select Workbench and you will be taken to the window working environment (Workbench), in which your further work will take place.

    The main components of a workspace are views, editors, and perspectives.

    Performance Is a small section within the workspace that is used to navigate through a certain category of objects (such as resources or packages), open editors, and display properties of active editors. For example, the Navigator view shows projects and other resources, while the Bookmarks view displays all of the bookmarks in the Workbench, along with the names of the files with which those bookmarks are associated. The figure shows the upper right corner of the workspace with the Outline view active.

    Any changes made to views are immediately saved.

    Another type of Workbench visual components - editors, which are used to view and edit some resource (for example, program code). When you select a resource, a suitable editor appears. For example, open any text document (with the .txt extension) using the File -> Open File ... command and you will see a built-in plain text editor. If you type something in this editor, an asterisk will appear on its tab where the file name is written. It means that the editor contains unsaved changes. They will be saved if you press Ctrl + S or select the File -> Save command.

    There are many useful views that you can add to the workspace window with the Window -> Show View command. However, instead of adding them one at a time, it is more convenient to switch perspective. Projection(or perspective) Is a collection of views and editors specially tailored to accomplish a task. After launching in Eclipse, the Java perspective opens, configured for the actual writing of the program. The Debug projection is often used to debug a program. You can switch the projection using the Window -> Open Perspective command. The name of the current projection is displayed in the upper right corner of the working environment (see figure).

    The first Java program

    Before you start programming, you need to create a project in which Eclipse will store all the resources related to your program.

    To create a project, run the command File -> New -> Project. In the window that appears, select Java Project and click Next. Provide a name for your project. Please note that a folder with the name of your project will be created in the directory you specified as a workspace (unless, of course, you change the settings in this window, which we will not do for the first time). Click the Finish button.

    Your project is now present in the PackageExplorer view on the left side of the workspace. You can delete it at any time by clicking on its name right click mouse and selecting Delete. After that, Eclipse will ask whether to destroy the folder with the project files at the same time (if necessary, you can also destroy it).

    If you haven't deleted the project, you can add files and folders to it using the context menu commands New -> File and New -> Folder respectively. If the project is large, then it needs a nested folder structure. But in the case of a Java project, things are a little different. The point is that the fragments of a Java program are grouped into packages and a separate folder is created for each package. The package is created by the New -> Package command. For the package, you also need to come up with a name. As a result, a new folder with this name will be created in the project folder. You can check.

    You may find it easier to browse project resources using the Navigator view. Open it with Window -> Show View command. You will see that in addition to the project and package directories, Eclipse has created two auxiliary files, .classpath and .project. They can be easily opened in the editor, but they are not of particular interest to us now.

    A Java program always consists of one or more classes... You can create a class using the New -> Class command in context menu Navigator views (or Package Explorer, doesn't matter). When creating a class, you need to select the package to which it will belong (select the package you just created) and come up with a name for it. It is common practice to start class names with an uppercase letter. If you do not follow this rule of good form, Eclipse will issue a warning, but nothing bad will happen.

    For our purposes, it is useful to check the box under "What methods do you want to create in your class?" opposite option public static void main (String args)... As a result, the main () method (function) will be generated in the class body. Java requires that at least one of the program's classes has a method with such a header. It is he who will be executed at the start of the program.

    As a result of our actions, a file with the name of our class and the extension .java will be created in the package folder. Eclipse will open a code editor that displays the contents of this file. It will be something like the following (package and class names, of course, may differ):

    package mainPack; public class MyClass (/ ** * @param args * / public static void main (String args) ())

    The commands that make up the body of the function can be written instead of the automatically generated comment // TODO Auto-generated method stub... We will write just one command that will print the classic "Hello, world!" Line to the screen:

    System.out.println ("Hello, world!");

    It remains to run the program. To do this, execute the Run -> Run command and get a dialog box with non-trivial launch settings. On the left side of this window, select Java Application ( Java application). After a little thought, Eclipse will find our class containing the main () method and offer to start the program from it (on the right side of the window, on the Main tab, the names of our project and our class should appear). In addition to this, a few more tabs are offered to the attention of the programmer. For example, on the second of them - Arguments - you are prompted to enter command line parameters (if the program is designed to be called from the command line with parameters). For our simple program, you do not need to specify anything else. Just click the Run button.

    As a result of the program's operation, data is output to the so-called console. In the MS DOS operating system, the entire monitor screen served as a console. Eclipse opens the Console view to us, in which (if everything is done correctly) the line "Hello, world!" is the output of our program.

    Now, to re-run the program (for example, if we decided to make some changes to it or need to show it to the teacher), you can go the easier way - execute the command Run -> Run Last Launched (run the previous application again) or just press Ctrl + F11.

    Java syntax basics

    Definitions

    Operand is the value involved in the operation.

    A method (function) is a part of a program that has its own name. This name can be used as a command in a program (such a command is called a method call). When a method is called, the commands that it consists of are executed. A method, similar to an operation, can return a result value.

    An expression is a sequence of operations and method calls executed in a certain order (by priority of operations, taking into account parentheses), which gives a certain value during calculation.

    A variable is a named area of ​​computer memory in which a program can store data of a certain type (called variable value) and access this data using the variable name.

    Program and algorithm concepts (repetition)

    Appointment any computer program- transformation of input data into output data. The program algorithm determines how the input data is converted to output data.


    Input data can come from a variety of sources. In educational projects, these data are most often entered while the program is running using the keyboard and mouse. In real programs, they can also be obtained from files, databases, networks, directly from various sensors, etc.

    The output data (the result of the program's work) is most often displayed on the screen, but it can also be saved to a file or database, sent to the network. Embedded programs generate special escape sequences as output that cause the device to which the program is associated to perform some action.

    Getting started writing a program MUST IMMEDIATELY UNDERSTAND:

    1. What is this program for at all (what does it do, in general terms)?
    2. What input data does this program have (and where does it come from)?
    3. What is the output of this program (and where to send it)?
    4. How should the input be converted to output (algorithm)? This is the most difficult part of a programmer's thinking, but while there is no answer to the three previous questions, it makes no sense to start it.

    When writing a simple program, you need to:

    1. Get input.
    2. Implement an algorithm for converting input data into outputs.
    3. Output the result of the program's work (output data): display it, send it over the network, etc.

    When working with complex software projects, it is necessary to conduct a detailed analysis of the requirements for the program (which may require a lot of communication with the customer), to carry out the design (to determine which parts the program will consist of, how these parts will interact with each other, display various aspects of the structure and behavior of the program in the form of diagrams, etc.). But in any case, start programming without understanding the input and output data and without understanding in general terms the essence of the algorithm pointless... And think at least in general terms of the essence of the algorithm, without knowing the input and output data impossible.

    Therefore, always start your exercises by defining the inputs and outputs. If you have any difficulties in this matter, contact your teacher.

    Literature on the topic:

    Basic Algorithm Constructions (Repetition)

    Attention! At this stage of training, you should already have knowledge of this topic. If they are not there, and the materials for repetition are incomprehensible or insufficient, you will not cope with the tasks! It is urgent to consult the literature on this topic.

    So, an algorithm is a sequence of actions to transform input data into output.

    The algorithm can be written in three main ways:

    The individual steps of the algorithm (regardless of how it is written) are linked to each other using three standard constructs that are implemented in absolutely all programming languages:

      Sequential execution. The steps are performed one after the other.

      Branching. Depending on the fulfillment of a certain condition (in the considered example, it is x> y?), One or another branch of the program is executed.

      Cycles. The sequence of steps of the program is executed several times. In fact, the loop is based on branching (the condition for exiting the loop is checked), but if this condition is not met, control is transferred to the beginning of the loop (back to the already completed step).

    Consider a problem: display all even numbers less than 10. For this problem, you can use an algorithm based on sequential steps and an algorithm that uses a loop. Diagrams for both options are shown in the figure:

    The first diagram looks clearer, but in the case when it is necessary to display not 5 numbers, but 100, the diagram (and the program corresponding to this algorithm) will increase 20 times, and in the program corresponding to the second algorithm, only one place will change: 10 will change to 100 That is why repetitive actions are designed in the form of cycles, although in many cases they can be dispensed with.

    Remember: the algorithm should be built from only three named constructs!

    Literature on the topic:

    1. School textbook of computer science.

    The basics of Java syntax basics

    1. The Java language distinguishes between uppercase and lowercase letters. This means that the names of all functions and keywords should be written exactly as they appear in the examples and reference books.
    2. Every command (operator) in the Java language must end with a semicolon.
    3. A Java program consists of one or more classes... Absolutely the entire functional part of the program (i.e. what it does) should be placed in methods certain classes. (Class and method, as an object-oriented programming concept, will be covered in Lesson 3. Class syntax will also be covered. In the first exercises, use the classes that Eclipse generates by default.)
    4. Classes are grouped into packages.
    5. At least one of the classes must have a main () method, exactly the same as in our example. (At first, it is not necessary to understand or try to remember the correct spelling of this method - Eclipse will generate everything itself if you tick the necessary box.) This method will be executed first.

    In the simplest case, a program can consist of one (or even none) package, one class within a package, and a single main () method within a class. Program commands will be written between the lines

    public static void main (String args) (

    and a closing curly brace) indicating the end of the method body. This approach should be followed when performing the simplest exercises.

    Comments (1)

    Comments are explanatory labels that programmers use to improve code comprehensibility. When compiling the program, comments are ignored, so anything can be written in them. The main thing is to show that this inscription is a commentary and should not be interpreted as program commands. In Java, this is done in one of the following ways:

    1. Two forward slashes // are inserted. From now on until the end of the line, you can write whatever you want - Java will treat it as a comment.
    2. At the beginning of a comment, characters / * are placed, and at the end - * /. In this case, the comment can span any number of lines.
    3. Highlight comments for documentation that are placed between markers / ** and * /. Their use will be discussed later.

    Literal writing rules

    about different forms of writing literals

    Integers (integer literals) in Java can be written in the usual way in decimal form: 12345, +4, -11.

    In addition, you can write integers in octal form, starting from zero (0777, -056) and in hexadecimal form, starting from zero and the Latin letter x (0xFFFF, 0x14, 0xA1BC).

    Valid literals are written in decimal notation, the integer part is separated from the decimal point.

    A real number can be written floating point, for example: 5.4e19, 17E-11, -123e + 4. The part of the number that comes before the letter e is called the mantissa, and the part that comes after the letter e is called the order. The notation means the following: you need to raise 10 to the power of the order and multiply by the mantissa. Sometimes it is actually more convenient to write 1e-9 than 0.000000001.

    Single characters are written in apostrophes, for example, "a", "D", "@".

    There are some special and control characters that are written using a special escape sequence. The most common ones are listed in the table:

    The escape sequence is also enclosed in apostrophes.

    The first line of the table says that any character can be specified using its code (with decimal encoding from 0 to 255) by writing this code in octal number system. For example, the letter "g" in the CP1251 encoding will be written with the escape sequence "\ 346"

    If necessary, you can specify the code of any character in Unicode encoding- after the backslash and the Latin letter u - in four hexadecimal characters. For example, "\ u0055" is the letter U.

    Character strings are enclosed in quotation marks. The opening and closing quotation marks must be on the same line of code.

    For strings, the concatenation operation + is defined, which allows you to collect several strings into one ("attributing" them to each other).

    If a string constant is too long and poorly perceived in the program code when writing it in one line, you can write it in several lines, concatenating them using the string concatenation operation. For example:

    "This is a very long string constant written down" + "on two lines of source"

    Control characters and codes are written inside a string in exactly the same way as backslash(but no apostrophes).

    Boolean literals are true and false.

    Identifiers

    about the rules of good style

    When programming, there is a constant need to come up with identifiers for naming objects.

    The identifier can consist of letters, numbers, underscore _ and dollar sign $ (the latter is not recommended, Java uses it for its own needs). The identifier cannot start with a digit. Java keywords (nor literals true, false and null).

    As noted above, the Java language distinguishes between simple and lowercase letters... This means that myAge, myage and MyAge are the names of completely different objects. Be careful: a register error is a very common case!

    Class names begin with an uppercase letter; if the name consists of multiple words, then each word begins with an uppercase letter. For example: MyClass, Book.

    Method and variable names begin with lowercase (small letters); if the name contains several words, then each next word begins with a capital letter. For example, myVar, x, y, newBigCounter.

    Constant names are written in full capital letters; if the name contains several words, an underscore is placed between them. For example PI, COUNT_OF_MONTHS.

    There are many benefits to using these guidelines. One of them is that you will know exactly how to place uppercase and lowercase letters when using standard Java libraries, the developers of which adhered to the recommendations.

    Data types

    about Java data types

    The int type is most commonly used to store integers in Java.

    In general, there are four integer types in the Java language: byte, short, int, long. They differ in the amount of memory that will be allocated for the variable and, accordingly, in the range of values ​​that can be stored in this variable. The most commonly used int type occupies 4 bytes in memory and is suitable for storing numbers from -2147483648 to 2147483647. The byte type consumes the least memory and is suitable for working with small numbers (from -128 to 127). The short and long types are 2 and 8 bytes respectively.

    The double type is suitable for real numbers.

    Real (real) numbers (or floating point numbers) are represented by two types: float and double. The float type takes up 4 bytes of memory and does not provide a high degree of precision when dealing with very large or very small numbers. It is recommended to use it when the fractional part is needed, but high accuracy is not required (for example, for measuring distances in meters, but taking into account centimeters and millimeters, or measuring prices in rubles, taking into account kopecks). If more accurate calculations are required, it is recommended to operate with values ​​of the double type (for example, such a variable can store the value of the sine of an angle).

    Valid literals such as 5.3, 8.0, 2e-3 are considered by Java to be double. If they are to be used as floats in the program, they must end with the letter f: 5.3f, 8.0f, 2e-3f.

    The char type is used to store single characters. Java considers it to be a kind of integer type (since each character is specified by its own Unicode code), so all integer operations apply to char.

    Boolean values ​​(either true or false) are represented by the boolean type.

    Thus, Java defines eight simple types, the features of which are presented in table:

    Declaring Variables

    In Java (as in many other languages), you need to describe it before using it. To describe a variable is to give it a name and define its type.

    When declaring a variable, the type is indicated first (which can be one of the simple types, the name of a class or interface), then the name of the variable. If a variable is needed initialize(assign initial value), the initial value is specified after the name through the equal sign. Several more variables of the same type can be declared separated by commas.

    Variable declaration examples:

    int x; // Declare an integer variable x double a, b; // Declaration of two real variables a and b char letter = "Z"; // Declare a character variable letter, initialized with an initial value of "Z" boolean b1 = true, b2, b3 = false; // Declare three boolean variables, the first of them will be true, the last will be false

    Basic language operations

    Variables and can participate in (from which, in turn, complex ones can be built). Let's consider the simplest operations of the Java language.

    Mathematical operations

    Comparison operations, the result is a boolean value: true or false

    Logical operations

    about Java operations

    && and || differ in that the value of the second is not necessarily calculated. For example, && evaluates the value of the first operand and, if it is false, immediately returns false, while || returns true immediately if it sees that the first operand is true. Java has similar operations & and | , they evaluate the values ​​of both operands before performing an operation on them.

    Shift operations

    (work with the bit representation of the first operand)

    Bitwise operations

    (work with bit representation of operands)

    Operation?:

    Operation ?: ternary, that is, it has three operands. The first operand is a condition, a boolean expression. The second and third operands are expressions of any other type. The operation works as follows: if the condition is true, it returns its second operand as a result, and if false, then the third.

    For example, the expression (5> 3)? 7 + 1: 2 * 2 will have the value 8, but the expression (5 == 3)? 7 + 1: 2 * 2 - value 4. This notation does not look very descriptive, but programmers often use it to shorten their code. So, instead of a sequence of commands:

    if (x> 0) y = 45 + a * 2; // if statement is discussed below else y = 45 - b * 3;

    you can write:

    Y = 45 + ((x> 0)? A * 2: -b * 3);

    Assignment operator

    After the variable is described, you can work with it in the program. In particular, it can be assigned a value of the appropriate type. Then, in the future, when using this variable in any expression, this current value will be automatically substituted for it.

    The value is associated with a variable using an assignment. In the Java language, it is written with a simple equal sign:

    Variable = expression;

    A variable is always specified to the left of the assignment operator. on the right must match the variable by type. It can be simple (for example, a number or a symbol):

    X = 7; // variable x is assigned the value 7 letter = "Q"; // letter is set to "Q"

    In general, an expression is something that can be calculated (for example, the result of a mathematical operation or the result returned by some method):

    A = 7.5 + 2.4; // variable a is assigned 9.9 as a result of calculations

    In addition to literals, other variables can participate in an expression. Their current value is substituted for them. As a result of the command:

    B = a + 1;

    variable b will be set to 10.9.

    So, the assignment operator works as follows. First, the value of the expression on the right side is calculated, and then the result is assigned to the variable specified on the left side. Even the following situation is possible:

    X = x + 4;

    This command increments the current value of the integer variable x by 4.

    And the following commands are written incorrectly and will not work:

    5 = x + 7; // there should be a variable on the left x + 3 = 14; // there should be just one variable on the left x = 4.5; // variable x can only take integer values

    Eclipse will try to indicate the error in these lines before executing the program by placing warning signs in the margin of the code editor. You can see how he does it.

    about type casting

    When a variable of one type is assigned a value of another type, it is used casting (conversion) of types... For numeric types (byte, short, int, long, float, double, char) it happens automatically if the type of the variable being changed can "accommodate" a value of another type.

    For example, if a variable of type int is assigned a value of type byte, the conversion from type byte to type int will automatically occur. Similarly, the float type can be cast to the double type, etc.

    If you try to assign a variable of a less precise type (for example, byte) to a value of a more precise type (for example, int), the compiler will generate an error message.

    For type casting, you can use cast operator- before the expression for which we want to perform the type conversion, parentheses are placed with the type to which the conversion is performed, inside the parentheses. When casting an integer type of higher precision to an integer type of lower precision, modulo division can be performed by the allowable range of the type to which the casting is performed, and when casting an expression of type double to an expression of type float, the precision of the expression will be reduced.

    long j = (long) 1.0; // use the casting operator to long, j = 1 char ch = (char) 1001; // use the cast to char operator, ch = "d" byte b2 = (byte) (100); // use the operator of type casting from int to byte, b2 = 100 byte b3 = (byte) (100 * 2); //Attention! modulo division occurs, b3 = -56

    The type mismatch error often occurs with valid literals. For example, you cannot perform the assignment a = 7.5 + 2.4; if the variable a is of type float, since literals 7.5 and 2.4 are considered to be of type double. To avoid an error, it is necessary to use typecasting:

    A = (float) (7.5 + 2.4);

    or to indicate that literals are also float:

    A = 7.5f + 2.4f; // this is also a valid command

    Almost every binary operation has its own kind of assignment operator. For example, for the addition + operation, there is a unary assignment operator + =, which increments the value of the operand by a given amount:

    X + = 8; // same as x = x + 8 (x increases by 8)

    Similarly for other operations: operators * =, - =, / =,% =, & = ^ =, etc.

    X * = 3; // same as x = x * 3 (x increases by 3 times) b1 ^ = b2; // same as b1 = b1 ^ b2

    Exercise 1

    Declare two integer variables, assign any values ​​to them. Print their sum and product.

    Prompt: you can use the project already created in Eclipse by pasting required commands after the command to output the line "Hello, world!" or instead of it.

    Increment and decrement operators

    about the increment and decrement operators

    The increment and decrement operators ++ and –– increment and decrement the value of the operand by one. It is much more convenient to use the x ++ command; instead of the command x = x + 1;

    The increment and decrement operators also return a value. This means that it is legal to execute the command

    Y = 7 * x ++;

    As a result, the variable x will increase by 1, and the variable y will take on a value seven times the old value of x. You can also run this command:

    Y = 7 * ++ x;

    As a result, the variable x will increase by 1, and the variable y will take on a value seven times the new value of x.

    Conditional if statement

    The simplest form of notation conditional operator looks like:

    if (condition) command

    The parenthesized condition is a boolean expression, i.e. can be true or false. If the condition is true, the command will be executed, otherwise nothing will happen. For example:

    if (x // if the value of the variable x is less than 17, assign x to 17

    If it is necessary that in the case when the condition is false, some other command is executed, use the extended form of the if statement:

    if (condition) command1 else command2

    about the else if construct

    In the example above, we might want to assign the variable x to 5 if the condition x is not executed (why do we need it, another question).

    if (x else x = 5;

    If it is necessary to use several mutually exclusive conditions, they can be written as follows:

    if (condition1) command1 else if (condition2) command2 else if (condition3) command3 ... else commandN

    Exercise 2

    Declare two integer variables, assign any values ​​to them. Use an if statement to find and output the maximum of them.

    Prompt: the algorithm for finding the maximum was considered while repeating the basic constructions of the algorithm.

    Compound commands

    Multiple Java language commands can be combined into one compound command using curly braces (). For example, you can write:

    (a = 12; letter = "D";)

    Compound commands can be used wherever regular commands are. For example, in an if statement, if several actions need to be performed when a condition is met:

    if (x "S";) else (x = 5;)

    The curly brace construction is also called block of commands and the curly braces are block boundaries.

    Note that the notation used in the example (when the boundaries of the block are placed on separate lines, and the contents of the block are written indented from its boundaries) is optional. This is just a style rule to make programs easier to understand and not get confused by curly braces, which are often used in a Java program.

    about the switch selection statement

    Switch selection statement

    Often the choice of the command to be executed depends on the value of some variable (or expression). For example, the user is prompted to enter an operation sign and, depending on the entered character, it is required to display the result of addition, subtraction, etc. or, if an incorrect character is entered, an error message. In this case, it is convenient to use the switch selection statement, which has the following notation:

    switch (expression) (case value1: command sequence 1 break; case value2: command sequence 2 break; ... default: default command sequence)

    Value1, value2, etc. are constants or expressions that involve only constants. Expression in brackets after keyword switch can contain variables. This expression is evaluated, and then the result is matched against one of the values ​​after the case keyword. If such a match is found, then the entire sequence of commands located between the colon and the nearest break command is executed. If no match is found, the default sequence of commands following the default keyword is executed. For example:

    char oper; // Operation sign, it will be selected by the user ... // Let's assume that by this moment the user has selected the sign switch (oper) (case "+": System.out.println (a + b); break; case "-": System.out.println (a - b); break; case "*": System.out. println (a * b); break; default: System.out.println ( "Invalid transaction sign"); }

    You can omit the default section. In this case, if no match is found, no command will be executed.

    While loop statement

    The while loop has the following form:

    while (condition) command

    If the parenthesized condition (representing a boolean expression) is true, the command will be executed - loop body(it can be a simple command or a sequence of commands in curly braces), after which the program will return to the execution of this statement and repeat this until the condition is false.

    Therefore, so that the program does not enter an infinite loop and does not hang, the loop body must provide for an exit option, that is, for example, commands in the loop body must somehow affect the variables included in the condition.

    For example, the following code snippet prints even numbers from 2 to 10:

    int x = 2; while (x<= 10){ System.out.println(x); x += 2; }

    about while loop with postcondition

    There is another way to write a while loop:

    do command while (condition)

    When using this option, the command is executed first, and then the condition is checked. Both options work the same way, but in the second case, the loop body (command) will be executed at least once, even if the condition is initially false.

    Exercise # 3

    Use a while loop to print all odd numbers from 1 to 10.

    Prompt: slightly change the algorithm for outputting even numbers.

    For loop operator

    The for loop is usually used when it is known in advance how many times the execution of a command (or a sequence of commands) should be repeated. It has the following form:

    for (init command; condition; jump command) loop-body

    Before the start of the cycle, the initialization command is executed. Then the jump condition (which is a boolean expression) is checked. If this condition is true, the command (or block of commands in curly braces) that makes up the body of the loop is executed. Then the jump command is executed and everything starts over. The jump instruction usually changes the variable that affects the truth of the condition, and the initialization instruction is the description of this variable.

    Typically a for loop is used like this:

    for (int i = 1; i<= 10; i++) тело_цикла;

    In this example, loop_body will be executed exactly 10 times. In this case, at each iteration, the variable i will be available (it is called the loop variable), which sequentially runs through the values ​​from 1 to 10. The next program fragment outputs even numbers from 2 to 10 (similar to the while loop example):

    for (int i = 1; i<= 5; i++) System.out.println(i*2);

    Exercise 4

    Use a for loop to print all odd numbers from 1 to 10.

    Break and continue statements

    When the body of the loop (for or while) consists of several commands, a situation may arise that there is no need to execute all of them at the next iteration. In this case, the break and continue statements are useful.

    The break statement terminates the execution of the current loop, regardless of whether its termination condition is met.

    The continue statement terminates the execution of the current loop iteration. That is, if this operator is encountered in the body of the loop, then the rest of the following commands are skipped and a new iteration (repetition) of the loop begins.

    Conclusion

    Despite the fact that the material of the first lesson is quite extensive, it should not cause difficulties for students who are already familiar with at least one programming language, since the constructions in all languages ​​are the same and you only need to master the rules for writing them (syntax). If the acquaintance with other programming languages ​​has been weak, you need more homework on the manual and the solution of additional tasks. The best option in this case is to read the recommended chapters from the literature before the next lesson.

    additional literature

    1. Vyazovik N.A. Java programming. (chapters 1 - 4, 7, 10)

    2. Khabibullin I.Sh. Java Self Tutorial 2. (Chapter 1)

    Pay special attention to the Java datatypes and casting rules, which are not covered in detail in this tutorial. A professional programmer should always control in his programs the possibility of a variable value going beyond the range allowed for its type. Typecasting errors are one of the most common and difficult to detect. Chapters 4 and 7 of the first book are highly recommended reading for all students applying for an excellent grade.