Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Compilation
Compilation
Source Program
Object Program
Secondary Memory
Main Memory
Interpreters, Virtual Machines
Another way to execute a program written in a high-level programming language is to use an interpreter for the language.
An interpreter is a program that acts like a processor that can directly execute a high level language.
Java Execution Enviroment
Phase 1 The program is created with an editor and stored on the disk
Compiler
The Java Compiler creates the bytecode and stores it on the disk.
The Classloader loads the bytecode in the memory.
Main Memory
Bytecide checker confirms the program is correct and does not contradict the security measures.
The interpreter reads the bytecode, translates it In the machine language and executes the result of the translation, storing the values of the data until the program is executed.
Phase 2
Phase 3
Editor
Class Loader
Bytecode
Bytecode
Phase 4
Phase 5
Main Memory
Main Memory
Java Application Program Development and Execution
public class FirstProgram {
public static void main(String[] args) {
// Display a message on the screen
System.out.println (“This is a simple Java program!");
}
}
Classes are the fundamental building blocks of Java programs. Every Java application contains a class with a main method.
When the application starts, the instructions in the main method are executed.
Each class contains definitions of methods. Each method contains a sequence of instructions enclosed between { }.
Use comments to help human readers understand your program.
A method is called by specifying an object, the method name, and the method parameters.
A string is a sequence of characters enclosed in quotation marks.
A Simple Program
5
Class Method
Method call String
Comment
The Edit-Compile-Test Loop
Errors A compile-time or syntax error is a violation of the
rules of the programming language. The compiler detects syntax errors.
A run-time or logic error or bug is when the program is syntactically correct and does something, but it doesn't do what it is supposed to do, that is causes the program to take an action that the programmer did not intend. You must test your programs to find logic errors.
Special software tools (so-called debuggers ) let you trace through a program to find logic errors.
6
Types and Variables In Java, every value has a type . “This is a simple Java program!” has the
type String, the object System.out has the type PrintStream, and the number 13 has the type int.
To store values so that you can use them at a later time. To remember an object, you need to hold it in a variable .
A variable is a storage location in the computer's memory that has a type, a name, and a contents.
You use variables to store values that you want to use at a later time. Ex: String message = “This is a simple Java program!";
PrintStream printer = System.out;
int luckyNumber = 13;
Variables can be used in place of the objects that they store: printer.println(message); // System.out.println("This is a simple Java
program!")
printer.println(luckyNumber); // Same as System.out.println(13)
Identifiers for variables, methods, and classes are composed of letters, digits, and underscore characters.
By convention, variable names should start with a lowercase letter. Class names should start with an uppercase letter.
7
Data Types in Java
Primitive data types int 4 bytes -2.147.483.648 2.147.438.647
short 2 bytes -32.768 32.767
long 8 bytes -9.223.372.036.854.775.808L-9.223.372.036.854.775.807L
float 4 bytes ±3,40282347E+38F double 8 bytes ± 1,79769313486231570E+308
char 2 bytes -32.768 32.767
Reference data types ( Their values are complex pointers to objects and arrays. They are managed by the JVM) • array • class • interface • null
8
9
Tokens in Java
Identifier::= letter (letter+digit)* letter::=(‘A’-’Z’)+(‘a’-’z’)+’_’+’$’ digit::=‘0’-’9’ Literals
• integers: 57 -456 0x5A9F 0745 6894576123L • reals: 3.402F -45.89 • boolean: true false • characters: ‘f’ ‘T’ ‘9’ ‘\u0A48’ \110 ‘\\’ ‘\n’ ‘\f’ ‘\t’ ‘\”’ ‘\’’ • strings: “This is a string” “” “0123456789\n” “+” “ “
Operators: + - * / % & | ^ ~ && || ! < > <= >= << >> >>> = ? ++ -- == += -= *= /= %= &= |= ^= != <<= >>= >>>= . [ ] ( )
Separators: { } ; , : Comments: /*…………*/ //…………. /**………..*/
10
Processing Strings
int charAt(int index)
int compareTo(String otherString)
boolean endsWith(String suffix)
boolean equals(Object otherObject)
boolean equalsIgnoreCase(String otherString)
int indexOf(String str)
int indexOf(String str, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
int length()
String replace(char oldChar, char newChar)
boolean startsWith(String prefix)
String substring(int intialIndex)
String substring(int intialIndex,int finalIndex)
String toLowerCase()
String toUpperCase()
String trim()
Expressions
Expression = description of a computation which produces an unique value of a well-defined type.
Operators
Operands : variables, constants, method calls, expressions
Expressions which result in a primitive value:
• Numerical expressions
• Boolean expressions,
• Logical expressions;
Expressions which result in an object.
Precedence and Associativity Rules for Operators
Operator type Operators Associativity
Postfix [] . (parameters) expr++ expr-- right
Unary ++expr --expr +expr -expr ~ ! right
Creation or cast new (type)expr right
Multiplicative * / % left
Additive + - left
Shift << >> >>> left
Relational < > <= >= instanceof left
Equality == != left
Bitwise AND & left
Bitwise XOR ^ left
Bitwise OR | left
Conditional AND && left
Conditional OR || left
Conditional ?: left
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= right
Sequence , left
Examples
int a=5; System.out.print((a=2) + a);
int a,b; a=b=1;
int[] ar={1,2,3}; int index=2; ar[index]=index=1;
Numerical expressions
Operands are fully evaluated from left to right before an operator is applied.
a+b*c;
Range of Numeric values int overFlow=Integer.MAX_VALUE +1 // MIN_VALUE
1.0/0.0 Infinity
0.0/0.0 NaN
+,- (unary)
*,/,%,+,-
*=,/=,%=,+=,-=
++,--
Type Conversion Contexts
Conversion Categories
Conversion contexts
Assignment Method Invocation
Casting Numeric Promotion
Widening/Narrowing Primitive Conversions
Widening Narrowing*
Widening Both Widening
Widening/Narrowing Reference Conversions
Widening Widening Both + optional unchecked conversion
Not applicable
Boxing/ Unboxing Conversions
Unboxing +optional widening primitive c. Boxing + optional widening reference c.
Unboxing +optional widening primitive c. Boxing + optional widening reference c.
Both Unboxing + optional widening primitive c.
*for constant expressions of non-long integer type
Widening and Narrowing of Primitive Types
• Implicit conversions
int a=10;
long l=a;
double d=a+l;
• The type of an arithmetic expression between two operands is the widest type AND at least int.
Implicit Primitive Narrowing Conversions
source is constant expression of : byte, short, char ,int
target is byte, short, char
the value of the source is in range of the target type
short s=5;
final int i=20;
byte b=i;
Widening and Narrowing of Primitive Types
Explicit conversions
Cast operator (<type>)
short x = (short)75;
int pixels = (int)(width/scale);
double result=(double)10/3;
double result2=1/(2/3.0)
(d*i) + (c /-s ) – (f * b)
Boolean expressions
<,<=,>,>=
nonassociative
==,!=
• primitive data equality
• object reference equality
• object value equality
!,&,|
&&,||
?:
20
Control Flow Structures
if(Condition)
Instruction1
if(Condition)
Instruction1
else
Instruction2
if(Condition1)
Instruction1
else if(Condition2)
Instruction2
else if(Condition3)
Instruction3
else
ElseInstruction
if-else Decision
switch(Expression) { case Constant1: InstructionList1 case Constant2: InstructionList2 ….... default: DefInstructionList }
Switch
while(Expression)
Instruction
While loop
do
Instruction
while(Expression)
do-while loop
for(InitExpress; Condition; IncremExpress)
Instruction
For Loop
break;
break label;
Loop interruption
continue;
Current Iteration
interruption