90 likes | 253 Vues
G6DICP - Lecture 3. Statements, comments, & simple arithmetic. Anatomy of a Java Program (1). class HiThere { public static void main (String[] args) { System.out.println("Hello World!"); } }. Anatomy of a Java Program (2). Reserved words
E N D
G6DICP - Lecture 3 Statements, comments, & simple arithmetic
Anatomy of a Java Program (1) class HiThere { public static void main (String[] args) { System.out.println("Hello World!"); } }
Anatomy of a Java Program (2) • Reserved words • class is a Java "reserved word". • Identifier • HiThere is an identifier. • This is a name we make up to identify a component of the program (in this case the program itself). • Identifiers must be a single word. • Java is case sensitive. class HiThere
Anatomy of a Java Program (3) • Code Blocks • Braces ( ie { } ) delimit an isolated block of code. • All programs have several (usually many) blocks. • Braces must be balanced. • Braces are often nested. class HiThere { }
Anatomy of a Java Program (4) class HiThere { public static void main (String[] args) { } } • Methods • Methods contain blocks of functional code. • Methods are named by an identifier. • This is a method called main - applications execute their main method on starting. • NB the syntax of main must be exactly as shown.
Anatomy of a Java Program (5) class HiThere { public static void main (String[] args) { System.out.println("Hello World!"); } } • Statements • The program contains a single statement (statements are terminated by a semi-colon). • println • This statement calls a library method called System.out.println. • Methods may be provided with an argument (data), which is contained in brackets. • The argument of println is a string • A string is a sequence of characters. • Java strings are delimited by double quotes.
Anatomy of a Java Program (6) /* A Simple Java Program */ class HiThere { public static void main (String[] args) // This is the main method { System.out.println("Hello World!"); } } • Style • Line breaks and indents are ignored by the compiler, but help greatly with readability. • Comments • Comments are ignored by the compiler. • Comments may be delimited by /* */ • Comments may be delimited by // to the end of the line.
Arithmetic • Arithmetic is accomplished by "numeric operators". + - / * System.out.print("The answer is "); System.out.println( 2 + 2 );
Numeric Data Types • Integer • Whole numbers (eg 1, 2, 9, 923) • Floating Point • Decimals (eg 1.0, 3.14, 99.238) • NB Scientific Notation • The letter 'E' means Times 10 raised to the power ... • Examples:1E+01 = 10 (ie 1*101)4.6E+03 = 4600 (ie 4.6*103)4.6E-03 = 0.0046 (ie 6*10-3) • Integer Division • Operator / integer or floating point division • Operator % modulus