When we consider 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 language syntax What do 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 pattern that describes the behavior of an object.
Method- is basically behavior. A class can contain several methods. It is in methods that logically recorded data is manipulated and all actions are performed.
Instance Variables- Each object has its own unique set of instance variables. The state of an object is created by the values assigned to these instance variables.
The first program and familiarization with the syntax of the language
Let's look at a simple code that will display the words "Hello world!" and the Java syntax.
Public class MyFirstJavaProgram ( public static void main(String args) ( /* This is my first java program. As a result of execution, “Hello world!” will be displayed on the screen */ System.out.println(“Hello world!”); / / Display 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 this name.
- Open a command prompt window and navigate to the directory where the file was saved. Let's assume it's "C:\".
- Type "Javac MyFirstJavaProgram.java" and press enter to compile the code. If there is no error in the code, command line will lead you to next line: (Assumption: The path variable is set).
- Now enter “java MyFirstJavaProgram” to run the program.
- You will now see "Hello World!" printed on the window.
Basic Java Syntax
It is very important to know and remember the following points in syntax:
- Case Sensitivity - Java is case sensitive, meaning the identifier Hello and hello have different meanings.
- Name of classes - 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 start 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 name of the program file should match exactly with the class name.
- When saving a file, you must save it using the class name (remember to be case sensitive) and add ".java" to the end of the name (if the names don't 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 a required part of every program.
Identifiers in Java
Identifiers- names used for classes, variables and methods. All Java components require names.
There are several rules in Java syntax that you need to remember about the identifier. They are as follows:
- Each identifier must begin with "A" before "Z" or "a" before "z", "$" or "_".
- After the first character can have any combination of characters.
- The keyword cannot be used as an identifier.
- The most important thing is that the identifier in Java is case sensitive.
- Example of correct spelling: age, $salary, _value, __1_value.
- Example of incorrect spelling: 123abc, -salary.
Transfers
Enumerations were introduced in Java 5.0. They constrain a variable to select only one of several predefined values. The values in this enumerable list are called transfers.
By using enumeration in Java, you can reduce the number of errors in your code.
For example, if we were looking at requests for fresh juice in a store, we could limit the size of the juice packs to small, medium and large. This makes it possible, through the use of an enumeration in Java, to ensure that no one orders any other package size other than small, medium or large.
Enum code example in Java
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 result from the above example:
Size: MEDIUM
Note: In Java, enumerations 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
Like other languages, in Java you can modify classes, methods, and so on, using modifiers. Modifiers in Java are divided into two categories:
- With access: default, public, protected, private.
- Without access: 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.
JSP pages have a hybrid syntax: a combination of the standard syntax conforming to the HTML specification and the JSP syntax defined by the Java Server Pages specification. The JSP syntax defines the rules for writing JSP pages consisting 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 sent to the JSP 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(analyzer) When parsing text, JSP highlighted global instructions at the very beginning. Thus, the JSP Engine (JSP runtime) analyzes the code and creates a servlet from the JSP. Directives represent messages to the JSP container. Syntax directives The JSP looks like this:
<%@ директива имяАтрибута="значение" %>Job Syntax directives in XML:
- page
- taglib (tag library)
- include
page directive
Directive page defines JSP page properties that affect the translator. The order of attributes in a directive page doesn't matter. Violation of syntax or the presence of unrecognized attributes results in a translation error. Example of a directive page The following code could serve:<%@ page buffer="none" isThreadSafe="yes" errorPage="/error.jsp" %>This directive declares that this page 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 called error.jsp.Directive page may contain page information:<%@ page info = "JSP Sample 1" %>List of possible directive attributes page presented in the table.
Attribute name | Meaning | Description |
---|---|---|
language | Line | Specifies the language used in the JSP file's scriptlets, expressions, or any included files, including the body of the translated code. The default value is "java" |
extends | Line | Specifies the superclass for the generated servlet. This attribute should be used with great care, since it is possible that the server is already using some superclass |
import | Line | Definition of packages to be imported, 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 there is one, otherwise a new session is created and bound to. Meaning false determines that sessions will not be used, and attempts to access the variable session will lead to an error when translating a JSP page into a servlet |
Buffer | none or buffer size in KB. | Sets the buffer size for JspWriter out. The default value depends on the server settings and should not exceed 8 KB. If the value is none output occurs directly to the object |
autoFlush | true or false | Determines whether the buffer should be released automatically when it is full or an error occurs. Default value true |
isThreadSafe | true or false | Meaning true(default) specifies the normal mode of servlet execution, where multiple requests are processed simultaneously using a single servlet instance, based on the assumption that the author has synchronized access to that instance's variables. A value of false signals that the servlet should inherit SingleThreadModel(single-threaded model), in which sequential or simultaneous requests are processed by separate servlet instances |
info | Line | Defines a string of JSP page information that will be accessed using the method Servlet.getServletInfo() |
errorPage | Line | The attribute value represents the URL page that should be displayed if possible errors causing exceptions |
isErrorPage | true or false | Signals whether this page can be used to handle errors for other JSP pages. The default value is false |
contentType | Line | Defines the encoding for the JSP page and response, as well as the MIME type of the JSP response. The default content type value is text/html, encodings - ISO-8859-1. For example: contentType="text/html;charset=ISO-8859-1" |
pageEncoding | Line | Defines the character encoding of the JSP page. Default is charset from attribute contentType, if it is defined there. If the value charset in attribute contentType undefined, value pageEncoding is set equal to ISO-8859-1 |
taglib directive
Directive taglib declares that a given JSP page uses a tag library, uniquely identifying it with a URI, and assigns a tag prefix that allows actions in the library. If the container cannot find the tag library, a fatal translation error occurs. Directive taglib has the following syntax:<%@ taglib uri="URI of the tag library to include"prefix=" Prefix name" %> Prefix " Prefix name" is used when accessing a library. An example of using a tag library mytags: <%@ taglib uri="http://www.taglib/mytags" prefix="customs" %> . . .include directive
Directive include allows you to insert text or code while translating a JSP page into a servlet. Directive Syntax include has the following form:<%@ include file="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 page on which the link is located, but, as with any other relative URI, you can tell the system the location of the resource of interest relative to the WEB server's home directory by adding a "/" to the beginning of the URI. The content of the include file is processed as plain JSP text and can therefore 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 at the 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 copying HTML into each individual file. Since the directive include connects files during page translation, then after making changes to the navigation bar, re-translation of all JSP pages using it is required. If the connected files change quite often, you can use the action jsp:include, which includes the file when accessing the JSP page.JSP declarations
Declarations are intended to define variables and methods in a scripting language, which are subsequently used in the JSP page. Syntax declarations has the following form:<%! код Java %> ads are located in the declaration block and are called in the expression block of the JSP page. The code in the ad block is usually written in Java language, however 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 advertisements are presented in the table. Announcement may contain several lines, such as in the code below for calculating the value of a function fact (int n), which must be equal to 1 when n is less than 2 and n! for 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 advertisements, are initialized and made available to scriptlets and others advertisements at the time the JSP page is initialized.JSP Scriptlets
Scriptlets include various pieces of code written in the script language defined in the directive language. Code fragments must comply with the syntactic constructs of the language scriptlets, i.e., as a rule, the syntax of the Java language. Scriptlets have the following syntax:<% текст скриптлета %>Equivalent syntax scriptlet for XML is:If in the text scriptlet it is necessary to use the sequence of characters %> precisely as a combination of characters, and not as a tag - an ending sign scriptlet, instead of the sequence %> you should use the following combination of characters %\>.The JSP specification provides a simple and clear example scriptlet, which allows the JSP page content to change dynamically 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 skriplet is inserted as written, and all static HTML text (template text) before or after skriplet converted using the operator print. This means that scriptlets do not necessarily need to contain completed Java chunks, and that blocks left open can have an impact on static HTML text outside of skriplet. Scriplets have access to the same automatically defined variables as expressions. Therefore, for example, if there is a need to display any information on a page, you need to 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 script language specified in the declaration language(usually Java). Result expressions JSP having a required type String, goes to standard output out using the current object JspWriter. If the result expressions cannot be cast to type String, either a translation error occurs if the problem was identified during the translation stage, or an exception is raised ClassCastException, if the discrepancy was identified during the request execution process. Expression has the following syntax: <%= expression text %> alternative syntax for expressions JSP when using XML:- 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 starts.
int a; ... actions on variable a ...; if(a) ( ... )
It is not correct in terms of Java syntax and will not compile.
- When used as a constructor - super should always be first operator in the subclass constructor.
In addition, it supports limited types, through specifying a superclass for parameter classes. For example, the declaration of a “generic class” class CLASS_NAME
One of the fundamental elements of many programming languages is conditionals . These designs allow you to direct the work of the program along one of the paths depending on certain conditions.
The following conditional constructs are used in Java: if..else and switch..case
if/else construct
An if/else statement tests the truth of a certain condition and, depending on the results of the test, executes certain code:
Int num1 = 6; int num2 = 4; if(num1>num2)( System.out.println("The first number is greater than the second"); )
After keyword if condition is set. And if this condition is met, then the code that is placed further in the if block after curly braces. The conditions are the operation of comparing two numbers.
Since, in this case, the first number is greater than the second, the expression num1 > num2 is true and returns true. Consequently, control moves to the block of code after the curly braces and begins to execute the instructions contained there, specifically the method System.out.println("The first number is greater than the second"); . If the first number were less than or equal to the second, the statements in the if block would not be executed.
But what if we want some action to also be performed if a 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 connect 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 . Design switch/case is similar to the if/else construct, since it allows you to process several conditions at once: Int num = 8; switch(num)( case 1: System.out.println("the number is 1"); break; case 8: System.out.println("the number is 8"); num++; break; case 9: System.out. println("the number is 9"); break; default: System.out.println("the number is not 1, 8, 9"); ) After the switch keyword, the expression to be compared comes in parentheses. The value of this expression is sequentially compared with the values placed 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 the case block to avoid executing other blocks. For example, if we removed the break statement in the following case: Case 8: System.out.println("the number is 8"); num++; case 9: System.out.println("the number is 9"); break; then since our variable num is equal to 8, then the block case 8 would be executed, but since in this block the variable num is increased by one, there is no break statement, then the block case 9 would begin to be executed. If we also want to handle the situation where no match is found, we can add a default block, as in the example above. Although the default block is optional. Starting with JDK 7, in addition to primitive types, you can also use strings in a switch..case expression: 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"); ) ) ) The ternary operator has the following syntax: [first operand - condition] ? [second operand] : [third operand] . Thus, three operands are involved in this operation. Depending on the condition, the ternary operator returns a second or third operand: if the condition is true , then the second operand is returned; if the condition is false , then the third one. 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 is checked Stanislav Gornakov In order to speak and read any foreign language, you need to learn the alphabet and grammar of that language. A similar condition is observed when studying programming languages, with the only difference, it seems to me, that this process is somewhat easier. But before you start writing the source code of the program, you must first solve the problem assigned to you in any form convenient for you. Let's create a certain class that is responsible, for example, for a telephone, which will have only two methods: turning on and off this very phone. Since we currently do not know the syntax of the Java language, we will write the Phone class in an abstract language. Class Phone ( Method Enable() ( // operations to turn on the phone ) Method Disable ( // operations to turn off the phone ) ) The Phone class might look something like this. Note that curly braces indicate the beginning and end of the body of a class, method, or any sequence of data, respectively. That is, parentheses indicate membership in a method or class. For every opening parenthesis there must be a closing parenthesis. To avoid confusion, they are usually placed at the same level in the code. Now let's write the same class only in Java. Class Telefon ( void on() ( // method body on() ) void off() ( // method body off() ) ) The keyword class in the Java language declares a class, followed by the name of the class itself. In our case, this is Telefon. Just a few words about the recording register. In almost all programming languages, it is important to save names in the register in which they were written. If you wrote Telefon, then such a spelling as telefon or TELefoN will generate an error during compilation. As we wrote initially, this is how we should continue to write. Reserved or keywords are written in their own specific case, and you cannot use them by naming them to methods, classes, objects, and so on. Spaces between words don't matter because the compiler simply ignores them, but they are important for code readability. In the body of the Telefon class there are two methods: on() - turns on the phone and off() method - turns off the phone. Both methods have their own bodies and, in theory, they should contain some source code that describes the necessary actions of both methods. For us now it doesn’t matter how these methods are implemented, the main thing is the syntax of the Java language. Both methods have on() parentheses within which parameters can be written, such as on(int time) or on(int time, int time1). With the help of parameters, there is a kind of connection between methods and the outside world. The on(int time) method is said to take a time parameter. What is it for? For example, you want your phone to turn on at a certain time. Then the integer value in the time parameter will be passed to the body of the method and, based on the received data, the phone will be turned on. If the parentheses are empty, then the method does not accept any parameters. Comments In the Telefon class, in the bodies of both methods there is an entry after two slashes: //. This entry denotes comments that will be ignored by the compiler, but are needed for code readability. The more information you comment on as you write the program, the more likely you will be to remember in a year what you have been working on all this time. Comments in Java can be of three types: //, /*…*/ and /**…*/. Comments written using the // operator must appear on one line: // One line!!! Error! You can't wrap it on the second line! // First line // Second line // ... // Last line Comments using the /*…*/ operators can span multiple lines. At the beginning of your comment, put /*, and at the end, when you finish commenting the code, put the operator */. The last type of comment /**…*/ is used when documenting code and can also be located on any number of lines. Java Data Types To set an arbitrary value, Java has data types. In the Telefon class we have created two methods. Both methods had no parameters, but when the example of the on(int time) method with a time parameter was given, they talked about passing a value to the method. This value indicated the time at which the phone supposedly should turn on. The int specifier determines the type of the time value. There are six data types in Java 2 ME. Byte – small integer value from –128 to 128; To declare some necessary value, use the following entry: Int time; long BigTime; char word; The semicolon operator is required after entries and is placed at the end of the line. You can combine several declarations of the same type, separated by commas: Mt time, time1, time2; Now let's improve our Telefon class by adding some values to it. We no longer need the on() and off() methods; let's add new methods that can actually solve certain problems. Class Telefon ( //S – display area //w – display width //h – display height int w, h, S; //method that calculates the 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's screen in pixels. The operation is useless, but very illustrative and easy to understand. The body of the Area() method has found itself and has the form S = w*h. In this method, we simply multiply the width by the height and assign or, as they say, store the result in the variable S. This variable will contain the values of the display area of \u200b\u200bthis phone. Now we have come close to the Java language operators, with which you can perform all kinds of operations and which we will talk about in the next part of this series of articles.Switch construction
Ternary operation
short – short integer value in the range from –32768 to 32767;
int – contains any integer value from –2147483648 to 2147483647;
long – very large integer value, from –922337203685475808 to 9223372036854775807;
char is a Unicode character constant. The range of this format is from 0 to 65536, which is equal to 256 characters. Any character of this type must be written in single quotes, for example: 'G';
boolean is a logical type that has only two values: false and true. This type is often used in loops, which will be discussed later. The meaning is very simple - if you have money in your pocket, it is supposed to be true, and if not, then it is false. Thus, if we have money, we go to the store for bread or beer (underline what is appropriate), if there is no money, we stay at home. That is, this is a logical value that contributes to the choice of further actions of your program.