Computers Windows Internet

Conditional constructions. Java Server Page. JSP page syntax

JSP pages have a combined syntax: a combination of the standard syntax as defined by the HTML specification and the JSP syntax as defined by the specification Java Server Pages. JSP syntax defines the rules for writing JSP pages composed of standard HTML tags and JSP tags.

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 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 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 page JSP does not use buffering, which makes it possible to simultaneously access the given JSP page many users, and that an error page with the name 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 to define 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.

One of the fundamental elements of many programming languages ​​is conditional constructions... These constructions allow you to direct the work of the program along one of the paths, depending on certain conditions.

The Java language uses the following conditionals: if..else and switch..case

If / else construct

The if / else expression checks the truth of a certain condition and, depending on the results of the test, executes a certain code:

Int num1 = 6; int num2 = 4; if (num1> num2) (System.out.println ("The first number is greater than the second");)

A condition is placed after the if keyword. And if this condition is met, then the code that is placed further in the if block after the curly braces is triggered. The operation of comparing two numbers acts as a condition.

Since, in this case, the first number is greater than the second, the expression num1> num2 is true and returns true. Consequently, control passes into the block of code after the curly braces and starts executing the instructions contained there, specifically the System.out.println method ("The first number is greater than the second"); ... If the first number were less than or equal to the second, then the statements in the if block would not be executed.

But what if we want some action to be taken if the condition is not met? In this case, we can add an else block:

Int num1 = 6; int num2 = 4; if (num1> num2) (System.out.println ("The first number is greater than the second");) else (System.out.println ("The first number is less than the second");

Int num1 = 6; int num2 = 8; if (num1> num2) (System.out.println ("The first number is greater than the second");) else if (num1

We can also combine several conditions at once using logical operators:

Int num1 = 8; int num2 = 6; if (num1> num2 && num1> 7) (System.out.println ("The first number is greater than the second and greater than 7");)

Here the if block will be executed if num1> num2 is true and at the same time num1> 7 is true.

Switch construct

Design switch / case is similar to the if / else construction, since it allows you to process several conditions at once:

Int num = 8; switch (num) (case 1: System.out.println ("number is 1"); break; case 8: System.out.println ("number is 8"); num ++; break; case 9: System.out. println ("number is 9"); break; default: System.out.println ("number is not 1, 8, 9");)

The expression to be compared follows the switch keyword in parentheses. The value of this expression is sequentially compared with the values ​​after the case operator. And if a match is found, then a specific case block will be executed.

A break statement is placed at the end of a case block to avoid execution of other blocks. For example, if the break statement were removed in the following case:

Case 8: System.out.println ("number is 8"); num ++; case 9: System.out.println ("number is 9"); break;

then since our variable num is equal to 8, then the case 8 block would be executed, but since in this block the num variable is increased by one, there is no break statement, then the case 9 block would start executing.

If we also want to handle the situation when no match is found, then we can add a default block, as in the example above. The default block is optional though.

Starting with JDK 7, in the switch..case expression, in addition to primitive types, you can also use the strings:

Package firstapp; import java.util.Scanner; public class FirstApp (public static void main (String args) (Scanner in = new Scanner (System.in); System.out.println ("Enter Y or N:"); String input = in.nextLine (); switch ( input) (case "Y": System.out.println ("You pressed the letter Y"); break; case "N": System.out.println ("You pressed the letter N"); break; default: System.out .println ("You pressed an unknown letter");)))

Ternary operation

The ternary operation has the following syntax: [first operand is a condition]? [second operand]: [third operand]. Thus, three operands are involved in this operation at once. Depending on the condition, the ternary operation returns the second or third operand: if the condition is true, then the second operand is returned; if the condition is false, then the third. For example:

Int x = 3; int y = 2; int z = x

Here, the result of the ternary operation is the variable z. First, the condition x

When we look at a java program, it can be defined as a collection of objects that interact by calling each other's methods. Now let us briefly understand Java syntax what does class, object, methods and instance variables mean.

An object- objects have state and behavior. For example: a dog can have a state - color, name, as well as behavior - nod, run, bark, eat. An object is an instance of a class.

Class- can be defined as a template that describes the behavior of an object.

Method- is primarily a behavior. A class can contain multiple methods. It is in methods that logically recorded data is manipulated and performed.

Instance variables- each object has its own unique set of instance variables. The state of the object is generated by the values ​​assigned to these instance variables.

The first program and familiarity with the syntax of the language

Let's take a look at a simple code that will display the words "Hello world!" And, for one, the Java syntax.

Public class MyFirstJavaProgram (public static void main (String args) (/ * This is my first java program. Execution will display "Hello world!" * / System.out.println ("Hello world!"); / / Displaying a message on the screen))

  • Open notepad and add the code above.
  • Save the file as "MyFirstJavaProgram.java". Below we will look at the Java syntax and find out why under that name.
  • Open a command prompt window and change to the directory where the file was saved. Let's assume it's "C: \".
  • Type "Javac MyFirstJavaProgram.java" and hit enter to compile the code. If there is no error in the code, the command line will take you to the following line: (Assumption: The path variable is set).
  • Now enter "java MyFirstJavaProgram" to run the program.
  • You will now see “Hello World!” Printed in the window.
C:> javac MyFirstJavaProgram.java C:> java MyFirstJavaProgram Hello world!

Java syntax basics

It is very important to know and remember the following points in the syntax:

  • Case Sensitivity - Java is case sensitive, meaning Hello and hello have different meanings.
  • Class names - for all, the first letter must be in uppercase.
  • If multiple words are used to form a class name, the first letter of each inner word must be in uppercase, for example, "MyJavaClass".
  • Method names - In Java syntax, all method names must begin with a lowercase letter.
  • If multiple words are used to form a method name, then the first letter of each inner word must be in uppercase, for example, "public void myMethodName ()".
  • Program file name - the program file name must match exactly with the class name.
  • When saving the file, you must save it using the class name (remember about case sensitivity) and add ".java" at the end of the name (if the names do not match, your program will not compile), for example, "MyJavaProgram" is the name of the class then the file should be saved as "MyJavaProgram.java".
  • public static void main (String args) - program processing begins with the Main () method, which is an obligatory part of every program.

Java identifiers

Identifiers- the names used for classes, variables and methods. All Java components require names.

There are several rules in Java syntax to remember about an identifier. They are as follows:

  • Each identifier must start with "A" through "Z" or "a" through "z", "$" or "_".
  • Any combination of characters can be after the first character.
  • The keyword cannot be used as an identifier.
  • Most importantly, an identifier in Java is case sensitive.
  • Correct spelling example: age, $ salary, _value, __1_value.
  • An example of a misspelling: 123abc, -salary.

Enumerations

Enumerations were introduced in Java 5.0. They constrain the variable to select only one of several predefined values. The values ​​in this enumerated list are called transfers.

By using enumeration in Java, you can reduce the number of errors in your code.

For example, if you were looking at orders for fresh juice in a store, you could limit the size of the juice pack for small, medium, and large. This makes it possible to use enumeration in Java so that no one orders any other package size other than small, medium, or large.

Java enum code example

class FreshJuice (enum FreshJuiceSize (SMALL, MEDIUM, LARGE) FreshJuiceSize size;) public class FreshJuiceTest (public static void main (String args) (FreshJuice juice = new FreshJuice (); juice.size = FreshJuice.FreshJuiceSize.MEDIUM; System.out .println ("Size:" + juice.size);))

The resulting output from the above example:

Size: MEDIUM

Note: in Java, enums can be declared either independently or within a class. Methods, variables, constructors can also be defined inside an enumeration.

Variable types

  • Local variables.
  • Class variables (static).
  • Instance variables (dynamic).

Modifiers

As with other languages, in Java you can modify classes, methods, and so on using modifiers. Modifiers in Java fall into two categories:

  • With access: default, public, protected, private.
  • Accessless: final, abstract, strictfp.

We'll take a closer look at class modifiers, method modifiers, and others in the next section.

Array

In Java, an array is an object that stores multiple variables of the same type. However, the array itself is an object. We'll look at how to create and populate an array in later chapters.

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 on the previous point - 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, the freeing of memory works only within the Java virtual machine and does not return once allocated memory to the OS 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 specify 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 take 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 (the String class), 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 a 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 Enum superclass. 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 the superclass from the subclass, or access a member of the superclass of the hidden 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 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 in this way to mark variables containing unique runtime identifiers 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 when 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.
  • A Java source file is a text file that contains one or more class definitions. The Java translator assumes

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

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

    So here is your first Java program

    :

    class HelloWorld (

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

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

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

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

    \> javac HelloWorld.Java

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

    > java HelloWorld

    Little has been done, but we have verified that the installed Java translator and runtime work.

    Step by step

    HelloWorld is a trivial example. However, even such a simple program for a beginner in the languageJava can seem dauntingly complex as it introduces you to a host of new concepts and syntax details. Let's go through each line of our first example carefully, analyzing the elements that make up a Java program.

    class HelloWorld (

    This line uses a reserved word

    class. It tells the translator that we are going to describe a new class.The full class description is placed between the opening curly brace on the first line and its matching closing curly brace on line 5. The curly braces onJava is used in exactly the same way as in C and C++.

    public static void main (String args) (

    This, at first glance, an overly complex example line is a consequence of an important requirement inherent in the development of the Java language. The point is that in

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

    Breaking this line into separate tokens, we immediately come across the keyword

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

    The next keyword is

    static. With the help of this word, methods and class variables are declared that are used to work with the class as a whole. Methods that use the static keyword in their declaration can only work directly with local and static variables.

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

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

    Finally, we get to the method name

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

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

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

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

    This line executes the method

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

    The closing curly brace on line 4 ends the method declaration

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

    Lexical basics

    Now that we have covered a minimal Java class in detail, let's go back and look at the general aspects of the syntax of this language. Programs for

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

    Comments (1)

    Although comments do not affect the executable code of the program in any way,

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

    a = 42; // if

    42 - the answer, what was the question?

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

    * This code is somewhat convoluted ...

    * I'll try to explain:

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

    javadoc,which uses Java compiler components to automatically generate documentation for class interfaces. The convention used for comments of this kind is this: in order to place a documenting comment before the declaration of a public class, method or variable, you need to start it with / ** (forward slash and two asterisks). Such a comment ends in the same way as a normal comment - with the * / symbols. The javadoc program can distinguish between some special variables in the doc comments that start with the @ symbol. Here's an example of such a comment:

    * This class can do wonderful things. We advise anyone who

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

    * basic.

    * @see Java. applet. Applet

    * © author Patrick Naughton

    class CoolApplet extends Applet (/ **

    * This method has two parameters:

    key is the name of the parameter.is the value of the parameter with the namekey.

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

    Reserved keywords

    Reserved keywords are special identifiers that, in the language

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

    table 2

    Java reserved words

    Note that the words

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

    Table 3

    Reserved method names

    Java

    Identifiers

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

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

    Literals

    Constants in

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

    Integer literals

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

    7, valid for octal digits. The hexadecimal constant is distinguished by leading zero-x characters (0x or 0X). The range of values ​​for a hexadecimal digit is 0 ..15, and as digits for the values ​​10 ..15 uses letters from A to F (or from a to f). With hexadecimal numbers, you can concisely and clearly represent computer-oriented values, for example by writing Oxffff instead of 65535.

    Integer literals are values ​​of type

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

    Floating point literals

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

    Java floating point numbers are treated as doubles by default. If you need a constant likefloat, to the right of the literal, you must assign the character F or f. If you are a fan of redundant definitions, you can add to literals like double the character D or d. Default valuesdoubles are stored in a 64-bit word, less precise values ​​like float - in 32-bit.

    Boolean literals

    A boolean variable can only have two values ​​-

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

    Character literals

    Symbols in

    Java - these are the indices in the symbol tableUNICODE. They are 16-bit values ​​that can be converted to integers and on which you can apply integer arithmetic operators, such as the addition and subtraction operators. Character literals are placed inside a pair of apostrophes (""). All visible symbols of the tableASCII can be directly inserted inside a pair of apostrophes: -"a", "z", "@". Several escape sequences are provided for characters that cannot be entered directly.

    Table 3.

    2. Escape sequences

    Control sequence

    Description

    Octal symbol

    (ddd)

    Hexadecimal character

    UNICODE (xxxx)

    Apostrophe

    Backslash

    Carriage return

    Line feed, new line

    Translation of the page

    (form feed)

    Horizontal tab

    (tab)

    Go back one step

    (backspace)

    String literals

    String literals in

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

    Operators

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

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

    Table 3.

    3. Operators of the language Java

    Separators

    Only a few groups of characters that may appear in a syntactically correct Java program are still unnamed. These are simple delimiters that affect the look and feel of your code.

    Name

    What are they used for?

    round brackets

    Allocate lists of parameters in the declaration and call of a method, and are also used to set the priority of operations in expressions, highlight expressions in program execution control statements, and in typecasting operators.

    braces

    square brackets

    Used in array declarations and when accessing individual array elements.

    semicolon

    Separates operators.

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

    for.

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

    Variables

    A variable is the main storage element in a Java program. A variable is characterized by a combination of identifier, type, and scope. Depending on where you declared the variable, it can be local, for example, to the code inside the for loop, or it can be an instance variable that is accessible to all methods of this class. Local scopes are declared using curly braces.

    Variable declaration

    The basic form of declaring a variable is as follows:

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

    7...];

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

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

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

    c using the Pythagorean theorem, the length of the hypotenuse is calculated, in this case the number 5, the magnitude of the hypotenuse of a classical right-angled triangle with sides 3-4-5.

    class Variables (

    public static void main (String args) (

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

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

    Your first step

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

    Java and examined in detail what it consists of (code blocks, comments). We have seen a list of keywords and operators, whose purpose will be explained in detail in later chapters. You are now able to independently distinguish between the main parts of any Java program and are ready to start reading.Chapter 4 , which details simple data types.