Computers Windows Internet

Conditional constructions. Eclipse working environment. Java identifiers

The syntax of the Java language is based on the syntax of the C language, but there are the following differences:

identifiers:

  • when writing the identifier, both Latin letters and letters of national alphabets can be used.
  • identifier can contain dollar sign.

Here are the basic syntax rules

  • Uppercase and lowercase letters are considered different characters, so J and j are completely different variables.
  • When writing the identifier, Latin letters and letters of national alphabets, numbers, underscore and dollar signs are used. The identifier cannot start with a number or contain spaces. The length of the identifier is not limited, but for the sake of readability of the program, you should strive to use short and meaningful names.
  • There are two types of comments.
    • Multi-line comment. Comments in the text are enclosed in brackets like
      / * this is the text of the comment * /
      and can be entered anywhere, in particular within operators.
    • One line comment. View comment:
      // this is the text of the comment - valid only until the end of the line
  • Each sentence ends with "; ".
  • Multiple statements can be placed on a line.
  • The curly braces () indicate a compound statement. All operators placed between them are treated as one operator.
  • All used types must be described before their first use. Ads can be located anywhere in the program.
  • A character is enclosed in single quotes, a string in double quotes.

Keywords

Keywords have special meanings to the compiler and these words can only be used in the sense in which they are defined. Reserved words cannot be used as custom identifiers.

Any change in the variables of one changes the variables of the other. When an object is declared, the address of the memory location is retrieved, which is usually the address of the first memory location in the reserved area containing all data related to the object. Any manipulation of this object refers to this address. Comparison of two instances of an object is performed by reference of these instances.

Java enum code example

It is a process that adds functionality to a class without having to rewrite all the code in that class. The new class inherits all the data and methods of the class from which it is derived. Then it is necessary that a constructor without a parameter exists in the parent class. For example, you can use a different approach to drawing solid rectangles than the one already discussed, for example by creating a new rectangular class that inherits the rectangular parent class. to the data of the rectangle, it must be public, which is contrary to the principle of encapsulation.

V Java language the following words are reserved keywords

Reserved words true, false and null are not key, but they cannot be used as identifiers in a program.

Keywords can be broken down into groups:

The solution is to define class variables with a protected modifier. Members of a class that is protected by protected are accessible from derived classes, but not from other classes. Click in the context of an applet to activate it. Many languages ​​allow arguments to be passed either by value or by address. Since the actual addresses of the arguments are unknown to the method, the method cannot modify them.

What is a conditional structure?

If the argument is passed to the address of the method, the argument variable is passed to the method: changes made to the value of the variable by the method are immediate and final. Conditional structures are called statements for testing whether a condition is true or not. These conditional structures can be associated with structures that are repeated in accordance with the implementation of the condition, these structures are called loop structures.

Primitive data types

byte, short, int, long, char, float, double, boolean

Loops and branches

if, else, switch, case, default, while, do, break, continue, for

Exceptions

try, catch, finally, throw, throws

Scopes private, protected, public
Declaration, import

import, package, class, interface, extends, implements, static, final, void, abstract, native

Shorter way of doing the test

The syntax for this expression. It is possible to carry out a test with a much less severe structure thanks to the following structure called the ternary operator.

  • The condition must be between parentheses.
  • When the condition is true, the left statement is executed.
  • When the condition is false, the correct statement is executed.
When the test expression is equal to one of the values ​​following the field, the following list of commands is executed.

Basic language operations

The default keyword precedes a list of operators that will be executed if the expression never equals one of the values. These structures are sometimes called repetitive instructions or iterations. The most common way to execute a loop is to create a counter and stop the loop when the counter exceeds a certain value.

Create, return, call

new, return, this, super

Multithreading

synchronized, volatile

Reserved keywords
Special appointment

instanceof, enum, assert, transient, strictfp

Operation signs

Operation signs are intended to indicate arithmetic, logical and other operations. The most commonly used operation signs are shown in the table.

This statement executes a list of commands as long as the condition is met. It may take one or more values ​​to cycle without ending the cycle. The syntax for this expression is "continuous", it is usually associated with a conditional structure, otherwise the lines between this statement and the end of the loop will be obsolete.

Relevant Discussions Found on the Forum

Fortunately, thanks to the continuous instruction, you can consider this value separately and then continue the loop! On the contrary, it may be necessary to stop the loop prematurely for a different condition than the one specified in the loop header. We will have three aspects of identifiers that you need to grasp. Valid identifiers: rules used by the compiler to determine if a name is valid. You should know and use them in your future applications. ... An identifier is a name that identifies a class, variable, or method in a program.

Operation Short description
+ Addition
- Subtraction
* Multiplication
/ Division
= Assignment
++

Increment (increase by 1); x ++; equivalent to x = x + 1;

--

Decrement (decrease by 1); x--; equivalent to x = x-1;

+= y + = x; equivalent to y = y + x;
-= y- = x; equivalent to y = y-x;
*= y * = x; equivalent to y = y * x;
/= y / = x; equivalent to y = y / x;
%= y% = x; equivalent to y = y% x;
== Equals
!= not equal
> More
< Smaller
>= more or equal
<= less than or equal to
% remainder of integer division
&& logical AND
|| logical OR
! logical negation NOT

Note.

Here are the rules you need to know. In practice, there is no limit to the number of characters that an identifier can contain. You cannot use a keyword as an identifier in your programs.

  • It doesn't have to start with a number.
  • Below is a complete list of available keywords.
Here are some examples of valid IDs.

Here are some examples of invalid identifiers, you should know why. If you agree to these conventions and start coding, they can reduce your testing, maintenance, and improvement efforts. And also think about curly braces, they are sometimes written on the same line, which makes the code illegible.

          1. Division
            • If two integers are divided, then we have the result of integer division:
              5/3 = 1. But the remainder of the integer division is 5% 3 = 2.
            • if one of the arguments is a real number, then we have the usual division:
              5 / 2.0 = 2.5
          2. Incrementing and decrementing

There are two forms of increment: prefix form, postfix form.

Also, the names usually have to be a combination of the verb name. ... They are just private instance variables. The only way they can access from outside of their class is through the methods of the class. Methods that change the value of a property are called setters, and methods that get the value of a property are called getters. Keep in mind that you don't need to have a variable named label in your class. The property name is inferred from getters and setters, not from variables in your class. The event model is often used in graphical applications, when an event like a click is triggered, other objects that may have cures, when this event occurs, get information.

Prefix form

First, the variable will be increased (or decreased) by one, then further calculations will be performed with the new value.

int a = 5; int b = 5; int y = 10 + --a; int z = 10 + ++ b; System.out.println ("a =" + a); System.out.println ("b =" + b); System.out.println ("y =" + y); System.out.println ("z =" + z);

The output will be:

a = 4
b = 6
y = 14
z = 16

In this example, the variable a is first decremented by 1, b is increased by one, and then the expression for y and z is calculated.

These objects are called listeners. Method names used to add a listener with an event source must use the add prefix followed by the listener type. Method names used to remove a listener must use the remove prefix followed by the listener type, using the same rules as the add record method. The type of listener to add or remove must be passed as an argument to the method. Remember that a valid identifier for a variable is also a valid identifier for a method or class.

Postfix form

For the postfix form, the expression is first evaluated with the old value of the variable, and the value of the variable is increased (or decreased) by one after the expression is evaluated.

int a = 5; int b = 5; int y = 10 + a--; int z = 10 + b ++; System.out.println ("a =" + a); System.out.println ("b =" + b); System.out.println ("y =" + y); System.out.println ("z =" + z);

The output will be:
a = 4
b = 6
y = 15
z = 15

In other words, you have to accept that the identifier is legal even if it doesn't follow naming standards. Here we are dealing with one of the most important chapters: conditions are another fundamental concept of programming. In a class, reading and execution are performed sequentially, that is, line by line. With conditions, we can manage different scenarios without reading all the code. You will quickly realize that all your projects are just sequences and relationships of conditions and cycles.

Let's go straight to the heart of the matter. Before you can create and evaluate conditions, you will need to know that we will use so-called "logical operators" for this. They are mainly used in the setting to evaluate various possible cases. know.

The expression will be evaluated with the old value of the variables. After evaluating the expressions for y and z variable a decreases by 1, variable b will increase by one.

Logical operations

If the first value in the "&&" operation is false, then the second value is not checked, in the "or" operation, vice versa, if the first value is true, then the second is not checked.

For the latter, you will better understand the example that will be given at the end of this chapter. This allows you to specify the condition "The same fight as the previous one." ... Imagine a program that asks the user to enter a relative integer. Conditional structures will allow us to manage these three scenarios. The structure of these conditions is as follows.

Let's use our little example. In this case, our class displays "positive number". Let's explain what's going on. When you presented us with the conditional structure, you put curly braces, and you don't put them there. In fact, curly braces are present in the "normal" conditional structure, but when the code within one of them consists of only one line, the curly braces become optional.

Truth table of operations "&&", "||"

A B A && B A || B
False False False False
False True False True
True False False True
True True True True

Here's an example.

This is called indentation! It will be very helpful to find you in your future programs. Imagine for two seconds that you have a 700 line program with 150 conditions and everything is written along the left edge. It will be difficult to distinguish tests from code. Before moving on, you should know that you cannot check for string equality! We will discuss this point later. We will now use the Boolean operators we saw at the beginning, checking if a given number is in a known range.

For example, it will check if an integer is between 50 and. This operator introduces you to the concept of set intersection. Here we have two conditions, each of which defines a set. Thus, the condition will regroup the numbers belonging to these two sets, that is, numbers from 51 to 99, inclusive. Consider the interval you want to define.

boolean a = true; boolean b = true; boolean c = false; boolean d = false; System.out.println ("true && true =" + (a && b)); // true true result true System.out.println ("true && false =" + (a && c)); // true false the result is false System.out.println ("false && true =" + (c && a)); // false ture result false System.out.println ("false && frue =" + (c && d)); // false false result false System.out.println ("true || true =" + (a || b)); // true true result true System.out.println ("true || false =" + (a || c)); // true false result true System.out.println ("false || true =" + (c || a)); // false ture result true System.out.println ("false || false =" + (c || d)); // false false the result is false

The switch is mainly used when we want the conditions "a la carte". Take the example of a survey with two questions: for each of them, we can only get 0 or 10 points, which gives us three notes and therefore three possible ratings, for example.

Come re-read this chapter on occasion. ... In this case, we use a switch to avoid unnecessary if repeated, and to lighten the code a little. Here are the operations performed by this expression. The class evaluates the expression after the switch, otherwise it goes to the next tab, and so on. To better appreciate the usefulness of this instruction, remove all breaks; and compile your program. The ternary conditions are quite complex and relatively little used. The peculiarity of these conditions is that three operands are involved, but also that these conditions are used to assign data to a variable.

The output will be:

true && true = true
true && false = false
false && true = false
false && false = false
true || true = true
true || false = true
false || true = true
false || false = false

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.

This is what this type of structure looks like. Decorate what's going on. The assignment is valid: you can use your max variable. You can also perform calculations before influencing the values. Don't forget that the value you are going to assign to a variable must be of the same type as your variable. Also note that there is nothing stopping you from inserting a 3D condition into another ternary condition.

Conditions allow only certain pieces of code to be executed. ... If the command block contains more than one line, you must surround it with curly braces to clearly identify the beginning and end of the command block. To be able to put a condition in place, you must compare variables using boolean operators.

JSP pages, in addition to HTML tags, contain JSP tags of the following categories:

JSP directives

JSP directives provide global information regarding specific requests sent to the server, and provide information needed at 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.

You can put as many boolean comparisons as you want in the state. The role of loops is to repeat the same operations multiple times. All programs, or almost all, need such a function. We will use loops to let the program start over from the beginning, wait for a specific user action, view a series of data, etc.

The loop runs as long as the condition is met. Therefore, we will use the concepts of the previous chapter! This means almost "as long as". Then we have a condition: it allows you to stop the loop. A loop is only useful when we can control it, and therefore make it repeat the instruction a certain number of times.

Syntax JSP directives as follows:

<%@ директива имяАтрибута="значение" %>

Task syntax directives in XML:

JSP directive can have multiple attributes. In this case, the directive can be repeated for each of the attributes. At the same time, couples "AttributeName = value" can be located under one directive with a space as a separator.

There are three types of directives:

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

JSP page directive

JSP page directive defines the properties of the JSP page 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" %>

The page directive declares that this JSP page does not use buffering, that it is possible for multiple users to access this JSP page at the same time, and that an error page named error.jsp.

JSP page directive 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:
<%@ 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 ServletResponse
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 case of possible errors that cause 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

JSP taglib directive

JSP directive taglib declares that the given JSP page uses a tag library, uniquely identifies it with a URI, and maps the 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" %> . . .

In 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.

JSP include directive

JSP 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 directive

JSP directive declarations are intended for defining variables and methods in the scripting language, which are later used in the JSP page. Syntax declarations looks like this:

<%! код Java %>

declarations 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.

Declarations 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 <= 1) return 1; else return n * fact (n - 1); } %>

declarations do not produce any output to standard output out... Variables and methods declared in declarations are initialized and made available to scriptlets and others ads at the time the JSP page is initialized.

Scriptlets 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 chunks left open 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); %>

Expressions expressions

Expressions expressions in a JSP page, an executable expression written in the scripting language specified in the language declaration (typically Java). Result expressions JSP, which is of the required type String, is sent to the standard output stream 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:

<%= текст выражения %>

alternative syntax for JSP expressions when using XML:

expression text

Execution order expressions on 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 page request:

Current time:<%= new java.util.Date () %>

In order 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.