Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

The first program

Programs and algorithms | Algorithms and programming languages | Fundamentals of programming I | Student is obliged to write down and run this program by himself | Data in a program (variables and literals) | Operations on data (operators and expressions) | Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Types of variables. Declarations. |


Читайте также:
  1. A first attempt
  2. A FIRST LOOK AT COMPUTERS
  3. A friend of yours wants to develop a programme to protect the city where he lives. Give him a piece of advice.
  4. A lucky break saves Hustler from failure and turns it into a national sensation, while Larry and Athelia become the first couple of porn.
  5. Algorithms and programming languages
  6. America’s First President
  7. Application Form for the Unilever Leadership Internship 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:

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:

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.

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.

 

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


Дата добавления: 2015-11-16; просмотров: 81 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Introduction to objects| Types. Primitive types.

mybiblioteka.su - 2015-2024 год. (0.007 сек.)