If you can't read please download the document
Upload
karsen
View
75
Download
2
Embed Size (px)
DESCRIPTION
Spring 09- ICE0124 Programming Fundamentals I Java Programming. XuanTung Hoang [email protected]. Lecture No. 2. Introduction to Java Programming and Applications. Compiler/Interpreter Java language Java Platforms, JRE and JDK First programs: Hello world, and Addition - PowerPoint PPT Presentation
Citation preview
Spring 09- ICE0124 Programming Fundamentals IJava ProgrammingXuanTung [email protected] Lecture No. 2
Introduction to Java Programming and ApplicationsCompiler/InterpreterJava languageJava Platforms, JRE and JDKFirst programs: Hello world, and AdditionSyntax: Things to remember Other experiencesMemory conceptsPrimitive Data TypesExpression, Arithmetic and relation operators
XuanTung Hoang*
Interpreter and ComplierComputers need translators to translate high-level language to machine instructionsInterpreter translates programs (written in high-level languages) online :Translate and execute at the same timeStatement by statementCompiler translates the whole program into machine language before executionTurn programs text into executable file (in machine language format)When user wants to run the program, he/she loads the executable file into computer memory to execute.Portability issue: Different computer hardwares use different instruction sets (machine language)We need appropriate interpreter/compiler for each type of machine
XuanTung Hoang*
History of Java languageInitially, Java language is developed for consumer-electronic devices (embedded systems) (in 1991 by Sun Microsystems)Also, It turned out to be good for Web and Internet applicationsAdd dynamic contents (Java applet)Rapid development of distributed applicationsEase of deployment now Java becomes more and more attractive for embedded systems (its primary purpose)
XuanTung Hoang*
Java PlatformsSun Microsystems provides most of the utilities for users in Java Platform productsText editorBytecode compilerClass loaderBytecode Verifier JVM (interpreter)
XuanTung Hoang*
Java PlatformsJ2SE: Standard EditionJ2EE: Enterprise EditionJ2ME: Micro EditionJDK v.s. JRE
+ bytecode compiler+ Class libraries+
+ JVM (interpreter)+ JREJDK
XuanTung Hoang*
Java Development Process5 phasesCreating a program: use text editor to create program sourceCompiling: use compiler to turn program source into bytecode (.class files)Loading: use class loader to load .class files into memoryBytecode verification: bytecode verifier examines the bytecode for validity and security concernsExecution: Java Virtual Machine (is a kind of interpreter for bytecodes) executes the bytecodesCombination of compiling and interpretingEnhance portability of programs:Write Once Run AnywhereCompact bytecode files are easy to exchangeBytecode verifier guarantees securityJust-In-Time compiler enhances performance
XuanTung Hoang*
First Application
Hello.java
1
/* The first program in Java
2
It simply prints out a message */
3
class Hello {
4
public static void main( String[] args ) {
5
// print message
6
System.out.println("Hello world\n");
7
}
8
}
Output:
Hello world
XuanTung Hoang*
First Application: StructureHello.java defines one class: class HelloKeyword class is used for defining a classClass name follows keyword classClass body is surrounded by braces { }
Hello.java
1
/* The first program in Java
2
It simply prints out a message */
3
class Hello {
4
public static void main( String[] args ) {
5
// print message
6
System.out.println("Hello world\n");
7
}
8
}
XuanTung Hoang*
First Application: StructureClass body contains methods (or class functions) and variables:In the example we have only one method (method main) and no variablesMethod has return type (void) and parameters ( args )Parameters are given within parenthesis ( )If the method have no parameters, parenthesis are still requiredModifiers public and static characterize the methodBraces surrounds method bodymain method is the program entryEvery java program must have one main function
Hello.java
1
/* The first program in Java
2
It simply prints out a message */
3
class Hello {
4
public static void main( String[] args ) {
5
// print message
6
System.out.println("Hello world\n");
7
}
8
}
XuanTung Hoang*
First Application: StructureInside method body, there are statements.There is only one statement in the example.Each statement should be ended with a semicolon ;One statement may span multiple lines
Hello.java
1
/* The first program in Java
2
It simply prints out a message */
3
class Hello {
4
public static void main( String[] args ) {
5
// print message
6
System.out.println("Hello world\n");
7
}
8
}
XuanTung Hoang*
First Application: CommentsMulti-line comments with: /* */Single-line comments with: //Comments can be placed anywhere.Comments are for human (compiler ignores comments)Comments should explain the code
Hello.java
1
/* The first program in Java
2
It simply prints out a message */
3
class Hello {
4
public static void main( String[] args ) {
5
// print message
6
System.out.println("Hello world\n");
7
}
8
}
XuanTung Hoang*
More complex program: Addition
Addition.java
1
// Program that computes the sum of two numbers
2
import java.util.Scanner;
3
public class Addition {
4
public static void main( String args[] ) {
5
Scanner input = new Scanner( System.in );
6
int number1; // the 1st number
7
int number2; // the 2nd number
8
int sum; // sum of the two numbers
9
10
System.out.print("Enter the 1st number:");
11
number1 = input.nextInt();//read the 1st number
12
13
System.out.print("Enter the 2st number:");
14
number2 = input.nextInt();//read the 2nd number
15
16
sum = number1 + number2; // add numbers
17
// display result
18
System.out.printf( "Sum is %d\n", sum );
19
20
// display the result in another way
21
System.out.printf( "Sum is (again) %d\n",
22
number1 + number2 ); // display result
23
}
24
}
XuanTung Hoang*
More complex program: Additionimport statement specifies external classes that we use in our programIn the example: Scanner is the class we useScanner is a class in class libraries provided by JDK
Addition.java
1
// Program that computes the sum of two numbers
2
import java.util.Scanner;
3
public class Addition {
...
...
24
}
XuanTung Hoang*
More complex program: AdditionVariables declarationUsing Scanner object to read inputDo computation & display result
Addition.java
1
// Program that computes the sum of two numbers
2
import java.util.Scanner;
3
public class Addition {
4
public static void main( String args[] ) {
5
Scanner input = new Scanner( System.in );
6
int number1; // the 1st number
7
int number2; // the 2nd number
8
int sum; // sum of the two numbers
9
10
System.out.print("Enter the 1st number:");
11
number1 = input.nextInt();//read the 1st number
12
13
System.out.print("Enter the 2st number:");
14
number2 = input.nextInt();//read the 2nd number
15
16
sum = number1 + number2; // add numbers
17
// display result
18
System.out.printf( "Sum is %d\n", sum );
19
20
// display the result in another way
21
System.out.printf( "Sum is (again) %d\n",
22
number1 + number2 ); // display result
23
}
24
}
XuanTung Hoang*
Read input and display outputRead input with Scanner classImport Scanner classimport java.util.Scanner;Create Scanner objectScanner input = new Scanner( System.in );Read input from user using nextInt() methodnumber1 = input.nextInt();Read textbook, section 2.5Display input with print, println, printfSystem.out.print(abc): output the string abcSystem.out.println(abc): outputs the string abc then goes to the next lineSystem.out.printf(result is %d, sum): output a string with format specifiersRead textbook section 2.4
XuanTung Hoang*
Things to remember Java is case-sensitive: class and Class are differentSkeleton of a classSkeleton of a class function (method)Skeleton of a simple java programSimple Java program has one class that contains main methodName of the source file must be identical to the class name (class identifier)Statements end with ;Braces enclose blocks of codeBraces should go in pairs (Good practice: Open and close brace together)Read input from user and output result to screen
XuanTung Hoang*
Other experiencesObserve outputs of java compiler (javac.exe) when compiling java program (.java file)When the compilation is successfulWhat files are produced by javac.exeWhat is stored inside those files (files produced by javac)When the compilation failedSpecify the problem in your source code
XuanTung Hoang*
Variable and MemoryExample of variables:
A variable is associated with a location in memoryA variable has:Name: is used to access the memory locationType (data type): specifies how the variable is treated by the computerSize: The size of the memory location; is determined according to type of the variableValue: is stored in binary format at the memory locationtypename
Scanner input = new Scanner( System.in );
int number1; // the 1st number
int number2; // the 2nd number
int sum; // sum of the two numbers
XuanTung Hoang*
Variable and Memory: Illustration
What does the following 16-bit string represent ? 00010100100000000
If you dont understand, please read textbook, section 2.6
XuanTung Hoang*
Primitive data types and ObjectsThere are many data typesWe can even define our own data typeData types are classified into primitive data types and reference types (objects)Primitives data types: are most fundamental use small, fixed number of bytes are built into Java are used as building block for developing more complex data types (objects)There are 8 primitive data types:byte, short, int, long, fload, double, char, boolean
Is Int a Java primitive data type ?Integral numbersFloating point numberscharactersLogical (True/false)
Scanner input;
int number1; // the 1st number
int number2; // the 2nd number
int sum; // sum of the two numbers
XuanTung Hoang*
Number data typesNumber literalsValid integers:2007 2007L (long integer)Valid floating point numbers:2007, 2007.02007f, 2007.1f (float)2007d, 2007.1d (double)3.4E+3 (scientific notation) Can we use byte data type to store the number 2007 ?
Integer Primitive Data Types
type
Size
Range
byte
8 bits
-128 to +127
short
16 bits
-32,768 to +32,767
int
32 bits
(about)-2 billion to +2 billion
long
64 bits
(about)-10E18 to +10E18
Floating Point Primitive Data Types
Type
Size
Range
float
32 bits
-3.4E+38 to +3.4E+38
double
64 bits
-1.7E+308 to 1.7E+308
XuanTung Hoang*
char data type and Character tableSize of char is 2 bytes (16 bits)Character table is used to map 16-bit codes to letters (Unicode) Character literal:Valid characters:a, b, A, \n, \t
Is it a character C ?
XuanTung Hoang*
boolean data typeAccept only two values: true and falseThey are Java keywords
XuanTung Hoang*
Expressions and Arithmetic ExpressionsExpression is a combination of literals, operators and parenthesis to produce a valueExample:a + b * c (a, b, c are variables already declared)Expressions dealing with number variables and operators are arithmetic expressionsArithmetic operators in Java: + , -, *, /, %Be careful with division operator /:Integer division is different from floating point division3 / 2 13.0 / 2 1.5How about remainder operator with floating point numbers ?
XuanTung Hoang*
Order of calculation and PrecedenceOrder of calculations:Parenthesis*, /, %+/-Left to rightExamples
XuanTung Hoang*
Equality and Relation operatorsEquality operators : ==, !=Relational operators: , =See fig 2.14, section 2.8, textbook
Questions:Assume that we declare integer variable a and b and assign values 3 to a, and 4 to b.Is a < b a valid expression ?What values are produced by a < b, a < b, a == b?
XuanTung Hoang*
Equality and relation operatorsBe careful when using == with float/double variablesDoes this produce true ?4.0/3.0 == 1.0 + 1.0/3.0How about this ?1.0/3.0 = 0.333333333333333Floating point arithmetic is NOT exactExact equality sometimes impossible to achieve Logically we expect true but the computer report falseAvoid using equality with floating point numbers
XuanTung Hoang*
Twos complement notation(Appendix E6, textbook)Assume 4-bit signed integersArithmetic negation "-" is equivalent to "~" then + 1
XuanTung Hoang*
Floating-point number precisionTwo data type (primitive) for floating point numbers: float and doublefloat: 32-bit (4-byte). Ex: 0.12fdouble: 64-bit (8-byte). Ex: 4.15dFloating-point numbers are treated as double by defaultExample: 9.02 and 9.02d are all double numbersFloating-point number arithmetic are approximate
XuanTung Hoang*
AssignmentAssignment operator, =Stores the value evaluated on the right hand side into the variable on the left hand sideExample:
int number1;
int number2;
int sum;
number1 = 4; // stores value 4 into variable number1
number2 = input.nextInt(); //get a number from user and stores it into variable number2
sum = number1 + number2; // add number1 and number2 and stores it into sum