Download presentation
Presentation is loading. Please wait.
Published byNicholas George Modified over 9 years ago
1
G51PR1 Introduction to Programming I 2000-2001 University of Nottingham Unit 2 : Elementary Programming
2
Overview Writing Java programs –Simple program –Comments –Printing to the screen Constants and Variables Identifiers Syntax & Semantics Errors Primitive Types Literals Program Layout Operators –Comparison –Logical –Incremental Assignment Program Input Conversions
3
A simple program : // Program written by azt /* September 1998 */ import java.lang.*; /** Example class HelloWorld */ public class HelloWorld { public static void main(String argv[] ) { System.out.println("Hello World!"); } Filename: HelloWorld.java comments method body class body
4
Notes on the HelloWorld program Java is case-sensitive The import statement allows us to use the println() function of the out object (of class PrintStream) a member of the System class of the java.lang package. public class HelloWorld is the declaration of a new class called HelloWorld. main() is the entry point for the program, that is the point at which execution starts. The body of the class and main function is contained within the { and } symbols. Every statement which is an instruction to the computer must be ended with a semi-colon. main() and { and } are part of the layout of the program not instructions as such. The println() function allows us to print a string "Hello World!!". White space layout (tabs, newlines, spaces etc) is not enforced but should be used sensibly! More later on program layout.
5
Comments Three ways of commenting : 1. Rest of the line comment : // rest of this line is a comment 2. Multiple line comments : /* This is a multiple line comment like in C or C++ */ 3. JavaDoc Comments : /** * This comment will be included * in documentation * generated with 'javadoc'. */
6
Program Output // to print more complex items System.out.println("Hello " + "World!!!"); // or you could write System.out.print("Hello "); System.out.println("World!!!"); // you could write System.out.println("Colin Higgins"); System.out.println("School of Computer Science and IT"); System.out.println("University of Nottingham"); // or you could write System.out.println("Colin Higgins\nSchool of Computer Science and IT\nUniversity of Nottingham");
7
Constants and variables We wish to have identifiers to represent : 1. Constants whose values is required in the program; and 2. Variables which will be used for storing intermediate results. For each identifier we use, we must tell the computer the type we wish to use it for. The general syntax is: typename identifier; typename identifier1, identifier2 …; typename identifier = expression; typename identifier1 = expression1, identifier2 = expression2 ;
8
Examples int i; float scale; boolean correct, valid; double diamond, YourMoney; char Signature = ’X’; long StartValue = 123456789L; byte MyByte = 0x12, YourByte = 0x4F; String name = "Colin", uid = "cah"; In many circumstances constants are allowed : final float PI = 3.14159f; float diameter = 4.0f; float circumference = diameter * PI;
9
A Simple Example (with 2 errors) import java.io.*; class Add2Numbers { float PI=3.14F; public static void main(String argv[] ) { double a,b,c;// declare variables a = 1.75 ;// assign values b = 3.46 ; c = a + b;// add them together char c = ‘Y’; System.out.println(“sum= “ + c); System.out.println(“Pi=“ + PI ) } } // end class Add2Numbers
10
Identifiers Variables and constants, need to be given names to allow us to access them. An identifier is a sequence of allowable characters that names something within the program. The identifiers you choose must satisfy various rules and recommendations. The exact rules are somewhat complex in Java because of Unicode. Here is a simple guide: They must start with a letter. This may be followed by any number of letters, underscores and digits. Upper and lower case letters are distinct, that is LoopVariable is different from loopVariable. You should use meaningful variables. They should not clash with reserved or other special words eg float, boolean etc.
11
Identifiers Example To sum up, identifiers in java can contain any combination of upper-case, lowercase, numbers and `_', `$‘ but must not begin with a number. Valid: Invalid: stack, Stack, STACK_SIZE wav2snd, _snd, $snd 3d, 5$, #snd, snd:wav
12
Reserved Identifiers Some identifiers,have specific meanings in Java and cannot be used differently. abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try void volatile while
13
Syntax and Semantics The syntax of a language defines how you can put symbols, reserved words, and identifiers together to make a valid program The semantics of a language construct is the meaning of the construct; it defines its role in a program A syntactically correct program does not mean it is logically (semantically) correct A program will always do what we tell it to do, not what we meant to tell it to do
14
Errors A program can have three types of errors The compiler will find problems with syntax and other basic issues ( compile-time errors ) –If compile-time errors exist, an executable version of the program is not created A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally ( run-time errors ) A program may run, but produce incorrect results ( logical errors ) ?
15
Primitive Types The basic Java types are given below along with their use, number of bytes required and their ranges : 1. booleanLogic1 bittrue : false 2. byte8-bit signed integer1 byte-128 : +127 3. short16-bit signed integer2 bytes-32768 : +32767 4. int32-bit signed integer4 bytes-2147483648 : +2147483647 5. long64-bit signed integer8 bytes-2 : 2 - 1 6. char16-bit unsigned integer, representing Unicode chars 2 bytes0 : 65535 7. floatSingle precision IEEE 754 floating point 4 bytes1.4e-45 : 3.4e+38 8. doubleDouble precision8 bytes4.9e-324 : 1.8e+308 63
16
Literals A literal is an explicit data value used in a program Integer literals : 25 69 -4288 Floating point literals : 3.14159 42.075 -0.5 Char literal : ’a’ String literals : “Hello World“ Boolean literals : true false null
17
Literals Integers : 42, 0, -22, +69, 345678 Octals : 0177, 00, 0777, -023 Hexadecimals : 0x0, -0x1, 0x34af, 0XA9B3 Longs : 0L, 0l, 12345678L, 0xab12345L, -87654321L Floats : 123.456, -654.321, 0.0, 0.98 1.23f, 45.678F, 2.567d, 7.374D 6.564e+23, 1.23E-12, 4.35e+3D, -3.456E34f Boolean : true, false Characters : ‘a’, ‘b’, ‘A’, ‘3’, ‘{’, ‘ ’ ‘\b’, ‘\n’, ‘\r’, ‘\\’, ‘\t’, ‘\’’ \123, \234, \012 Strings : "This is a string literal", "Hello World!!!\n", "left\tcentre\tright\t" Null : null
18
Program layout Remember humans are good at pattern recognition so use this to minimise errors! Layout your program carefully. Leave plenty of white space. Indent as appropriate. Use one of the recommended conventions. Stick to the same convention. As programs become bigger, layout becomes more and more important. More later!
19
Operators Arithmetic : () * / % + - Example Program 1 : Convert Fahrenheit temperature to Celsius. float celsius; // input is a little tricky, so set a value here... float fahrenheit = 57f; celsius = (fahrenheit – 32) * 5 / 9; System.out.println("Celsius is " + celsius);
20
Example Program 2 I have a certain number of bicycle spokes; I need 44 to make one wheel; how many wheels can I make? How many spokes will I have left over? s tatic final int spokesPerWheel = 44; int wheels, leftOver; int spokes = 839; wheels = spokes / spokesPerWheel; leftOver = spokes % spokesPerWheel; System.out.println("Number of wheels is " + wheels); Etc.
21
Example Program 3 We know the number of football matches won drawn and lost for a given team; how many points do they have? (three for a win, one for a draw) int won = 7; int drawn = 4; int lost = 37; int points; points = won * 3 + drawn; System.out...
22
Comparison operators > // greater than < // less than >= // greater than or equal to <= // less than or equal to == // equals – watch for the double "="!!! != // not equals These can be used between any relevant types of object. The result delivered is a boolean; true or false. Note testing for equality "==" between floats or doubles is rarely, if ever, sensible due to the possibility of rounding errors. Examples : fahrenheit > 32 spokes >= 2 * spokesPerWheel
23
Logical operators && // conditional and || // conditional or ! // logical complement (not) & // boolean and | // boolean or ^ // boolean exclusive or We need general logical operators to combine the results of comparisons (or of booleans). Beware, the last three or these operators (& | ^) have other meanings in different circumstances! Examples : number >= 0 & number < 10 number >= 0 && number < 10 number = 10 ! ( number >= 0 & number < 10) Can I construct at least 2 wheels with less than 10 spokes left over? spokes = 2 * spokesPerWheel & spokes % spokesPerWheel < 10
24
Incremental operators These (like most of the operators and fundamental language control constructs) come from C/C++ : ++i // increment, deliver new value i++ // increment, deliver old value --i // decrement, deliver new value i-- // decrement, deliver new value "increment" means increase by a suitable value, usually 1. Compare : i = 0; System.out.println(i++); which prints out value 0, with i = 0; System.out.println(++i); which prints out value 1. In both cases i has value 1 afterwards.
25
Incremental Operators Example equivalent j = p + i++; j = p + i; i = i + 1; j = p + ++i; i = i + 1; j = p + i; j = p + (++i); i = i + 1; j = p + i; You will often see the free standing increment : i++; // increment i, sometimes you will see ++I to add 1 to i rather than : i = i + 1;
26
Assignment Assignment is also an operator. There are many types of assignments – Java like C/C++ is rich in operators. int i; i = 3; float f = 0.3456; char ch = ‘A’; assignment can be combined with other operators : i += 4; // plus-and-becomes ie i = i + 4 i -= j; // minus-and-becomes ie i = i – j; f *= 4.2; // multiply-and-becomes ie f = f * 4.2; a &= b; // logical &-and-becomes ie a = a & b; i += 1; // normally you would see i++;
27
Assignment The assignment operator has a value itself, as well as doing the assignment.Thus : i = j = k = 0; works like : i = ( j = ( k = 0 ) ); since ‘ = ’ is right to left associative. Note that in initialising declarations, you must still write in full : int i = 0, j = 0, k = 0; Example 1 How many bicycle wheels can I make, and how many spokes will I have used? wheels = spokes / spokesPerWheel; spokesUsed = wheels * spokesPerWheel;
28
Operator precedence It is necessary to carefully define the meaning of such expressions as : a + b * c in this case to give : a + ( b * c ) All operators have a priority, higher ones are evaluated first. Operators with equal priority are normally evaluated left-to-right (they are left (L) associative), so that : a – b – c is evaluated as : ( a – b ) – c
29
Operator precedence Operator Operand Type(s) Assoc. Operation Performed ++arithmeticR pre-or-post increment (unary) --arithmeticR pre-or-post decrement (unary) +, - arithmeticR unary plus, unary minus ~ integralR bitwise complement (unary) ! BooleanR logical complement (unary) (type) anyR cast *, /, % arithmeticLmultiplication, division, remainder +, -arithmeticLaddition, subtraction + stringLstring concatenation <<integralLleft shift >>integralLright shift with sign extension >>>integralLright shift with zero extension <, <=arithmeticLless than, less than or equal >, >=arithmeticLgreater than, greater than or equal Instanceofobject, typeLtype comparison
30
Operator Precedence Operator Operand Type(s) Assoc. Operation Performed ==primitive L equal (have identical values) != primitive L not equal (have different values) == object L equal (refer to same object) != object L not equal (refer to different objects) & integral L bitwise AND & boolean L boolean AND ^ integral L bitwise XOR ^ boolean L boolean XOR | integral L bitwise OR | boolean L boolean OR && boolean L conditional AND || boolean L conditional OR ?: boolean, any, any R conditional (ternary) operator = variable, any R assignment *=, /=, %=, +=, -=, >=, >>>=, &=, ^=, |= variable, anyRassignment with operation
31
Program input There are many different ways of inputting strings, chars, ints, floats, etc For now just follow the code shown below (and import java.io.*). To read a long from the keyboard use the following code : long Number = 0; DataInputStream dis = new DataInputStream(System.in); try { String userInput = new String(dis.readLine()); Number = (java.lang.Long.valueOf(userInput)).longValue(); } catch(IOException e) { System.out.println("Exception while reading input"); }
32
Example Here is a full example of reading and writing a value: public class hal { public static void main(String[] argv) { int i = 0; // Prompt and read System.out.print("Type a number: "); // Note, not println System.out.flush(); // causes output DataInputStream dis = new DataInputStream(System.in); try { String userInput = new String(dis.readLine()); i = (java.lang.Int.valueOf(userInput)).intValue(); } catch(IOException e) { System.out.println("Exception while reading input"); } System.out.println("Value was " + i); }
33
Conversions Other conversions are possible : boolean b = java.lang.Boolean.valueOf(String s).booleanValue; short sh = java.lang.Short.valueOf(String s).shortValue; and so on with : Character char Byte byte Integer int Long long Float float Double double Note for later: Character, Byte etc are immutable class wrappers around each of the primitive Java data types
34
Summary Writing Java programs –Simple program –Comments –Printing to the screen Constants and Variables Identifiers Syntax & Semantics Errors Primitive Types Literals Program Layout Operators –Comparison –Logical –Incremental Assignment Program Input Conversions
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.