28
Basics 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files. All programs written in this chapter will have the same structure: Greeting.java /* My first Java program prints "Hello word!" to the screen. */ class GreetingProg { public static void main(String[] args) { System.out.print("Hello World!"); // prints a polite sentence to the screen } } - key word class + nameOfTheProgram + { - code is ended by a final matching } - later we will study code files which can not directly operate (classes); code files containing a main method are programs, they can be executed and provide a result - instructions are grouped between a set of { and } - all text between /* and */ or after // is ignored by java and can be used to comment the source code - be careful when you type: the Java compiler and interpreter are case-sensitive, so GreetingProg greetingprog 1.2 Compile and execute 1.2.1 Step 1: compile the source code into java bytecode The compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The result is a bytecode file. With most programming languages, you either compile or interpret a program so that you can run it on your computer. The Java programming language is unusual in that a program is both compiled and interpreted. First, the compiler installed on the programmer computer translates a program into an intermediate language called Java bytecodes. It generates instructions for the Java Virtual Machine (JVM). The generated bycode does not depend on the computer used to write and compile the program, neither on the computer targeted to run the program (Mac, Linux, Windows…) but only on the source code. You only need to compile once. The JVM is an interpreter, it parses and runs each Java bycode instruction on the computer. There are JVM implementations for a lot of different plat-forms. Every computer with a JVM implementation can run the bycode. Interpretation occurs each time the program is executed. The following figure illustrates how this works:

1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

Basics

1 First Java Program

1.1 Source file A source file contains text, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files. All programs written in this chapter will have the same structure:

Greeting.java/* My first Java program prints "Hello word!" to the screen. */ class GreetingProg { public static void main(String[] args) { System.out.print("Hello World!"); // prints a polite sentence to the screen } } - key word class + nameOfTheProgram + { - code is ended by a final matching } - later we will study code files which can not directly operate (classes); code files

containing a main method are programs, they can be executed and provide a result - instructions are grouped between a set of { and } - all text between /* and */ or after // is ignored by java and can be used to comment the

source code - be careful when you type: the Java compiler and interpreter are case-sensitive, so

GreetingProg ≠ greetingprog

1.2 Compile and execute

1.2.1 Step 1: compile the source code into java bytecode The compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The result is a bytecode file. With most programming languages, you either compile or interpret a program so that you can run it on your computer. The Java programming language is unusual in that a program is both compiled and interpreted. First, the compiler installed on the programmer computer translates a program into an intermediate language called Java bytecodes. It generates instructions for the Java Virtual Machine (JVM). The generated bycode does not depend on the computer used to write and compile the program, neither on the computer targeted to run the program (Mac, Linux, Windows…) but only on the source code. You only need to compile once. The JVM is an interpreter, it parses and runs each Java bycode instruction on the computer. There are JVM implementations for a lot of different plat-forms. Every computer with a JVM implementation can run the bycode. Interpretation occurs each time the program is executed. The following figure illustrates how this works:

Page 2: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

That’s the reason why you’ve heard that with the Java programming language, you can "write once, run anywhere." You can compile your program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM. That means that as long as a computer has a Java VM, the same program written in the Java programming language can run on Windows 2000, a Solaris workstation, or on an iMac. 1. type javac Greeting.java 2. check that it generated a GreetingProg.class file 3. edit this file, can you understand its content? Possible error:

Bad command or file name (Windows 95/98) The name specified is not recognized as an internal or external command, operable program or batch file (Windows NT) bash: javac: command not found (Linux)

If you receive this error, your OS cannot find the Java compiler, javac. Solution 1: precede the command by the complete path: C:\jdk1.4\bin\javac HelloWorldApp.java If you choose this option, each time you compile or run a program, you'll have to precede your javac and java commands with C:\jdk1.4\bin\. Solution 2: temporary change your command path: Windows: set path=%path%;c:\Compilateurs\j2sdk1.4.1\bin Linux: PATH=/usr/local/jdk1.3.1/bin:$PATH If you choose this option, you’ll have to reset the path each time you open a new command terminal. Solution 3: permanently change your command path: Windows: Start Menu / Parameters / Configuration panel / System / Advanced / Environment Variables Linux: change your .cshrc file: set path = ( $HOME/bin /usr/bin /usr/local/jdk1.3.1/bin . )and activate your changes by “source .cshrc”

1.2.2 Step 2: locate the java interpreter and execute java GreetingProg The Java interpreter installed on your computer implements the Java VM. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand. Possible error:

Page 3: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

Exception in thread "main" java.lang.NoClassDefFoundError: GreetingProg

If you receive this error, java cannot find your bytecode file, GreetingProg.class. Solutions: First, check that the bycode file is in the current directory, and you spelled it correctly. If you still have problems, you might have to change your CLASSPATH variable. Add current directory to your class path list: set CLASSPATH=%CLASSPATH%;. (“.” represents the current directory)

Exercise 1.1.1 Exercise 1.1.2 Exercise 1.1.3 Exercise 1.1.4 Exercise 1.1.5 Exercise 1.1.1

2 Variables “variable” = item of data named by an identifier. Before using a variable for the first time, it must declared. The declaration - “reserves” the name so it cannot be used by another variable in the same program block - indicates the kind of data this variable will be used to store (the variable's type determines

what values it can hold and what operations can be performed on it: for example, the declaration int myNumber declares that myNumber has an integer data type (int). Integers can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables.)

examples:

int myNumber; boolean isHappy;

Several variables of the same type may be declared in a single line: int myNumber, yourNumber, score;

2.1 Primitive data types The Java programming language has two categories of data types: primitive and reference (or object). We will study objects later. A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. The following table lists, by keyword, all of the primitive data types supported by Java, their sizes and formats, and a brief description of each.

byte Byte-length integer 8-bit two's complement short Short integer 16-bit two's complement int Integer 32-bit two's complement Integers

long Long integer 64-bit two's complement float Single-precision floating point 32-bit IEEE 754 Real

numbers double Double-precision floating point 64-bit IEEE 754 other types char A single character 16-bit Unicode character

Page 4: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

boolean A boolean value (true or false) true or false Note: - 8-bit two’s complement:

- positive number: 0 followed by binary representation of the number on 7 bits: 5 = 00000101

- negative number: example: -5 → opposite = 5 = 00000101 → one’s complement of 5 = 11111010 → +1 = 11111011, 8-bit two’s complement of -5

- note that 11111011 + 00000101 = 0 (with a remain of 1) - 32-bit IEEE 754:

- write the number as 1,xxxxx * 2y - encoding = seeeeeeeemmmmmmmmmmmmmmmmmmmmmmm where s indicates

the sign, e indicates the exponent and m indicates the number after the comma - example: 525,5 = 1000001101,1 = 1,0000011011 * 29 = 1,00000110011 * 21001 =

10000100100000000000010000011011

Exercise 1.2.1 Note: In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-dependencies.

2.2 Initialization and affectation When you declare a variable of a primitive data type, a default value is assigned to it: 0 for number, false for booleans and the nul character for char. After you declared a variable, you can affect it a value using the = sign:

myNumber = 4; myLetter = ‘v’; isHappy = true;

Notes: - The value assigned to the variable must be of the appropriate type, the type used during

the variable declaration. Example: myNumber = true is incorrect. - You can assign a value to a variable on the same line as the declaration. Example: int

myNumber = 4; - You can assign a value to a variable long after you’ve declared it but not before.

2.3 Literal values

178 int a series of digits with no decimal point is typed as an integer

8864L long You can specify a long integer by putting an 'L' or 'l'

after the number ('L' is preferred as it cannot be confused with the digit '1')

37.266 37.266D 26.77e3

double double double

A series of digits with a decimal point is of type double

87.363F float You can specify a float by putting an 'f' or 'F' after the number.

Page 5: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

A literal character value is any single Unicode character between single quote marks. The two boolean literals are simply true and false.

2.4 Memory byte age; int year;

Year 0

Age 0

age = 23;

Year 0

Age 23

2.5 Constants You can declare a variable to be final. The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages. To declare a final variable, use the final keyword in the variable declaration before the type:

final int aFinalVar = 10; The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialization of a final local variable. Simply declare the local variable and initialize it later, like this:

final int blankfinal; . . . blankfinal = 0;

A final local variable that has been declared but not yet initialized is called a blank final. Final variables are for instance useful for representing interest rates or tax rates which usually do not change during the execution of the program.

Exercise 1.2.2 Exercise 1.2.3

Page 6: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

3 Operators

3.1 Operators on numbers - comparison: <, <=, >, >=, ==, != : number x number → boolean - opposite: +, - : number → number - +, -, *, /, % (remainder) : number x number → number - incrementation ++, decrementation -- : number → number (prefixed or postfixed : i++

adds 1 to i and returns the value of i before it was incremented, while ++i adds 1 to i and returns the new value of i)

- cast operator: double j = 3.4; // int i = j; int i = (int)j;

- string concatenation operator + : number x text → text

3.2 Operators on booleans comparison : ==, != : boolean x boolean → boolean negation ! : boolean → boolean & and && ("imperative and " and "conditional and") | and || ("imperative or" et "conditional or") : boolean x boolean → boolean ^ (xor) : boolean x boolean → boolean

4 Control flow operations

4.1 Conditional

4.1.1 if then else if (BooleanExpression) { actionIfTrue; } else if (BooleanExpression2) { action2IfTrue; } else if (BooleanExpression3) { actionIf3True; } … else { actionIfFalse; } …

4.1.2 Switch case switch (expression_of_type_char_byte_short_or_int) { case value1 : { ifValue1ActionStartsHere; } case value2 : { ifValue2ActionStartsHere; } … default : { actionElse; } } use « break » to exit the switch block statement

Page 7: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

4.2 Loops

4.2.1 Do… While… Do while (BooleanExpression) { action } do { action } while (BooleanExpression)

4.2.2 Iterations for (initialization; condition_to_start; increment) { action }

5 Structured programming, methods Consider the following code:

progWithoutMethod.javaclass ProgWithoutMethod { public static void main(String[] args) { System.out.println("================"); System.out.println("| |"); System.out.println(" a cat"); System.out.println("| |"); System.out.println("================"); System.out.println("================"); System.out.println("| |"); System.out.println(" a dog"); System.out.println("| |"); System.out.println("================"); System.out.println("================"); System.out.println("| |"); System.out.println(" a mouse"); System.out.println("| |"); System.out.println("================"); } } The same task is repeated several times. To simplify the code and save the programmer some work, it is possible to group the repeated instructions in a function, with a generic text which explains how to handle the text in general, and call this function with a particular text.

progWithMethod.javaclass ProgWithMethod { public static void main(String[] args) { prettyPrint("a cat"); prettyPrint("a dog"); prettyPrint("a mouse"); } static void prettyPrint(String theText) { System.out.println("================"); System.out.println("| |"); System.out.println(" " + theText);

Page 8: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

System.out.println("| |"); System.out.println("================\n"); } } Another example:

progWithoutMethod2.javaclass ProgWithoutMethod2 { public static void main(String[] args) { int year=1997; int age = 2004-year; int rate = 1; if (age < 18) rate = age; else { if (age > 60) rate = 100 - age; else rate = 50; } System.out.println("rate: " + rate); year=1976; age = 2004-year; rate = 1; if (age < 18) rate = age; else { if (age > 60) rate = 100 - age; else rate = 50; } rate = rate + 10; System.out.println("rate: " + rate); } }

progWithMethod2.javaclass ProgWithMethod2 { public static void main(String[] args) { int price = computeRate(1997); System.out.println("rate: " + price); price = computeRate(1976); price = price + 10; System.out.println("rate: " + price); } static int computeRate(int birthdayYear) { int age = 2004-birthdayYear; int rate = 1; if (age < 18) rate = age; else { if (age > 60) rate = 100 - age; else rate = 50;

Page 9: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

} return rate; } } The first line of the method indicates: - type of return value or void if no return type - type and number of parameters keyword “return” precedes the result of the method unless the method does not return a result (void return type), the return keyword is mandatory in every execution flow instructions following “return” in a flow are not executed static int computeRate(int birthdayYear) { int age = 2004-birthdayYear; int rate = 1; if (age < 18) return age; else { if (age > 60) return (100 – age); else return 50; } }

14

Syntaxe des méthodesSyntaxe des méthodes

float calculerTauxReduction(boolean estEtudiant, int age) {float tauxReduction;if (estEtudiant)

tauxReduction = 0.5F;else if (age < 25)

tauxReduction = 0.7F;else

tauxReduction = 1F;return tauxReduction;

}

type du résultat(« void » si la méthode ne retourne pas de valeur)

nom de la méthode

parenthèses contenant les paramètres(obligatoires même si la méthode n’utilise

pas de paramètre)

type du premier paramètre

nom du premier paramètre

paramètres séparés par des virgules

si le type du résultat est différent de void, le résultat est renvoyé à l’appelant grâce au return.

un return est la dernière instruction exécutée

accolades délimitant le bloc de la méthode

5.1 Scope of variables class Prog { static int a = 1; public static void main(String[] args) { int b = 2; int c = compute(a, b);

. . . . . . .

Page 10: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

System.out.println("c = " + c); } static int compute(int d, int e) { System.out.println("basis = " + d); int result = 0; for (int i=0; i<e; i++){ result = result+d; d--; } result = result - a; return result; } }

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

method parameters can not be initialized like the other variables:

forbidden: int compute (int d= 2) { Montrer ce qui se passe en mémoire avec le programme.

5.2 Usefulness - Divide a problem into smaller, easier to solve, ones. - More easy to read, debug and maintain - Reuse code

Exercise 1.5.1 Exercise 1.5.2 Exercise 1.5.3 Exercise 1.5.4 Exercise 1.5.5 Exercise 1.5.6 Exercise 1.5.7

6 Recursive methods A method is said to be recursive when its code calls the method it-self. Example: x! Non recursive version Recursive version int factorial(int n) { int resultat = 1; for (int i = 1; i <= n; i++) { resultat = resultat * i; } return resultat; }

int factorial(int n) { if (n == 0) return 1; else return n*factorielle(n-1); }

Advantage: “natural” solution to some problems Drawback: calls are stacked until the final condition is met; result is built by unstacking the successive calls. Consequence: a recursive solution may use up a lot of memory space. Be sure that the number of recursive calls is limited!

Exercise 1.6.1 Exercise 1.6.2 Exercise 1.6.3 Exercise 1.6.4

Page 11: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

7 Write nice code Remember that upper case and lower case are significant. There are rules for variables and method name and capitalization: http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html Indenting your code nicely, commenting it helps you and helps other to work with your code.

Page 12: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

8 Arrays

Page 13: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 14: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 15: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 16: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 17: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 18: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 19: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 20: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 21: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 22: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 23: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 24: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 25: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other
Page 26: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

Exercise 1.8.1 Exercise 1.8.2 Exercise 1.8.3

9 Basic Input/Output Objective: discover some functionalities to make your programs more interactive Details will be studied later, this part only presents “ready-to-use” solutions

9.1 Command line arguments To read arguments passed by the user on the command line (arguments are separated by a space character):

CommandLineExample.javaclass CommandLineExample { public static void main(String[] arg) { System.out.println("You typed " + arg.length + " argument(s) on the command line"); for (int i = 0; i < arg.length; i++) { System.out.println("argument " + i + ": " + arg[i]); } } } Examples of execution: >java CommandLineExample You typed 0 argument(s) on the command line >java CommandLineExample hello world! You typed 2 argument(s) on the command line argument 0: hello argument 1: world!

Exercise 1.9.1

9.2 Character string transformation To convert a character string into a int data type:

String2intExample.javaclass String2intExample { public static void main(String[] arg) { String text = arg[0]; int number = (new Integer(text)).intValue(); number = number + 10; System.out.println("number + 10 = " + number); } } If the text does not represent a numerical value, the execution fails with a Number Format Exception error. We will solve this later.

Exercise 1.9.2

9.3 Keyboard input KeyboardInputExample.java

Page 27: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

import java.io.*; class KeyboardInputExample { public static void main (String[] arg) throws IOException { System.out.print("What is your favorite color?\n"); String inputLine = (new BufferedReader(new InputStreamReader(System.in))).readLine(); if (inputLine.equals("blue")) System.out.print("like the sea!"); else { System.out.print("I like " + inputLine + " too!"); } } }

Exercise 1.9.3

9.4 Read data from a file ReadDataFromFile.java

import java.io.*; class ReadDataFromFile { public static void main(String[] arg) throws IOException { System.out.println("Read file 1 character by character:"); FileReader textFile = new FileReader(new File("mayle.txt")); int charUnicode = textFile.read(); while (charUnicode != -1) { char singleChar = (char)(charUnicode); System.out.println("character: " + singleChar); charUnicode = textFile.read(); } System.out.println("Read file 1 line by line:"); textFile = new FileReader(new File("mayle.txt")); BufferedReader bTextFile = new BufferedReader(textFile); String line = bTextFile.readLine(); while (line != null) { System.out.println("line : " + line); line = bTextFile.readLine(); } } }

9.5 Write data to a file WriteDataToFile.java

import java.io.*; class WriteDataToFile { public static void main (String[] arg) throws IOException { PrintWriter generatedFile = new PrintWriter(new FileWriter("creation.txt"));

Page 28: 1 First Java Programraffy/Java/01-Basics/cours.pdf · 1 First Java Program 1.1 Source file A source file contains text, written in the Java programming language, that you and other

for (int i = 0 ; i < 5 ; i++) { System.out.print("give a word: "); String line = (new BufferedReader(new InputStreamReader(System.in))).readLine(); generatedFile.println(line); } generatedFile.close(); } }

Exercise 1.10.1