Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lecture 1.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
704 Кб
Скачать
☆

4.4. The first program

We may prepare our programs using some IDE (Integrated Development Environment) - check JavaWorld monthly for examples - or write the source code in some text editor and then compile and run the program from the command line. In the latter case one has to remember that:

  • a Java source code prepared in a text editor must be saved in pure text format in a file with an extension ".java" (for example "Test.java");

  • to compile the source file use the command javac (for example javac Test.java);

  • as a result of successful compilation there appears one or more class files (with the extension ".class", for example Test.class);

  • to execute our program we have to run the program java giving it the class name (without extension!) as the argument (for example java Test).

Remarks:

  1. The source code may be distributed over a number of files with the extension ".java". Each of the files contains a full definition of one or more classes.

  2. The name of a file must be exactly the same (taking the case of letters into account) as the name of the public class (qualified with the keyword public) contained in the file (what it means we will find out later). A source file may contain at most one public class.

  3. Running a virtual machine (with the command java) we pass it as the argument the name of the class containing the method main.

Here is our first program:

public class Test {

public static void main( String[] args ) {

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

}

}

Comments:

  1. The keywords of the language are marked blue.

  2. For now we do not bother with the odd words: public, static, void. We will learn about them from the forthcoming lectures.

  3. A Java program is a set of class definitions. Here we have the single class named Test. The keyword class is used to define classes. A class definition follows it and is enclosed in curly brackets (marked red here).

  4. The class Test includes the method named main.

  5. The body of a method is put between curly brackets (here marked green).

  6. The execution of a program starts with the method main (declared in exactly this way: public static void main(String[] args); the word args may be replaced with another as it is the name of a variable).

  7. As we see the method main has a parameter named args. It denotes an array of strings (objects of type String) which holds arguments passed to the program upon startup (from a command line or in other way). We do not use them in our program.

  8. Inside the method main we call the method println which prints its argument to the command prompt. The invocation of a method is an expression. Ended with a semicolon it becomes a statement which is to be executed by the program.

  9. For now we do not bother why and what for should we write System.out.println. We will learn about it later.

  10. The argument passed to the invocation of the method println is a string literal.

  11. The program must be compiled: javac Test.java.

  12. A successful compilation produces the file Test.class.

  13. After running the program (by typing "java Test" on the command line) we see the message "Hello World!".

All the whitespace characters (space, tab, newline) occurring between the language structures (names of variables or methods, keywords, literals and others) are omitted during the compilation. Comments are omitted during the compilation too. There are three types of comments in Java:

  • the text following a pair of characters // until the end of the line is a single-line comment

  • the text put between the pairs of characters /* and */ is a multiline comment (it may spread over a number of lines)

  • the text put between the sequences of characters /** and */ is a javadoc comment - it is processed by a program generating documentation (this type of comment is a multiline one too).

Example:

/**

The class TestCom demonstrates

the use of comments

(this is a javadoc comment)

*/

public class TestComm {

/*

This is a

multiline

comment

*/

/* it is a

comment too */

// this is a single-line comment

public static void main( String[] args ) {

// another comment

System.out.println( "Comments" ); // and one more

}

}

While compiling a program, the compiler is checking its syntactic correctness. If there are any errors, the compilation fails, there are no output class files and the compiler prints messages informing about encountered errors. For example if we forget about the closing parenthesis in the call to the method println in our test program:

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

the compiler produces the following message:

Test.java:4: ')' expected       System.out.println( "Hello World!";                                         ^ 1 error

A program which compiles without errors is syntactically correct, but its execution may fail if any runtime error occurs. The following program compiles cleanly:

public class TestRTE {

static String aString;

public static void main( String[] args ) {

System.out.println( aString.length());

}

}

but its execution causes the following error:

Exception in thread "main" java.lang.NullPointerException         at TestRTE.main(TestRTE.java:7)

Here we try to get the length of a string (with the invocation of length()) which does not exist (it was not initialized). Such errors are called exceptions. The JVM informs us about the type of the exception and about the class and method which caused it. It prints the line number in the source file where it occurred too.

4.5. Summary

The lecture presents some features of the Java environment. As it is an object-oriented language we have learned the basics of the object-oriented methodology. And what is most important: we can compile and run a Java program.

4.6. Exercises

  1. Modify the first program to make it display various messages:

    1. first and last name;

    2. the string "Hello" in the first line and your name in the second;

    3. arbitrary strings.

  2. Compile and run each version of the program.

Lecture 5

Types and operations

The lecture introduces the notion of data type. It explains representation of data in a program by means of variables and literals and describes operations that can be carried out on data.

5.1. Types. Primitive types.

Execution of a program results in the processing of data. The data is stored in computer's memory. Each data unit must have a type which specifies how the data is stored in memory, how much space it occupies and how operations are carried out upon that data. This information helps a compiler to build binary code properly.

The type of data is the set of permissible values for that data plus the set of operations which can be carried out upon this data. It specifies the size of memory needed to store the data and the manner of storing it in the computer's memory.

For example, data of integral type may have values which are integer numbers from a definite interval. The size of the interval depends on the size of data and the manner in which data is stored in memory. Data in a program is represented with the help of literals, variables and constants. Thus, the values of literals, variables and constants have types. We say: a variable of ... type, a constant of ... type, a literal of ... type. Just because expressions are made of variables, constants, literals and operations carried out upon them (defined by the operators), as well as function (method) invocations - the result of evaluation of an expression has some definite type too. Each type has its name. A programming language has a number of so called primitive types the names of which are reserved keywords of the language.

Type name

byte count

Permissible values

The meaning

byte

1

-128...127

integer numbers

short

2

-32768...32767

int

4

-2147483648... 2147483647

long

8

-9223372036854775808. ...9223372036854775807

float

4

-3.4028234663852886E38... ...-1.401298464324817E-45 1.401298464324817E-45... ...3.4028234663852886E38

real numbers

double

8

-1.7976931348623157E308... ...- 4.9E-324 4.9E-324 ... ... 1.7976931348623157E308

char

2

0...65556

Unicode characters

boolean

1

true | false

logical values: true or false

The types: byte, short, int, long, float, double and char are called numeric types. They represent data which are numbers. In particular, characters (the type char) are represented by unsigned (nonnegative) integer numbers. There is a number of different character coding systems (for example, an ASCII character is a nonnegative number less than 256). Java uses Unicode characters which are nonnegative numbers less than 65557 (not all of them are defined yet). Unicode allows representing characters of almost all languages (including simplified Chinese). Results of arithmetical operations are values of numeric types. Values of the type char are elements of strings. Arithmetical operations specified with the help of operators include: addition (+), multiplication (*), subtraction (-), division (/), remainder (%), incrementation (++) and decrementation (--) by 1. For operands of integral type, the division operation is the integer division, i.e. its result is of integral type (thus, the value of the expression 1/3 is 0 as the operands are integers and the result is rounded to an integer). The values of numeric types are subject to comparisons:< =, == (equal?), != (not equal?). The boolean type represents a logical quantity with two possible values, indicated by the literals true and false Values of this type are used in logical expressions as operands and results. Boolean expressions determine the control flow in several kinds of statements. For example, the expression a > b has the value of the boolean type specifying whether the result of comparison is true or false. The logical expression "x and y" is noted in Java as x && y . It is syntactically correct only if x and y are of boolean type. Its value (specifying whether x and y are true) is of boolean type too.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]