《1_1 Introduction to Java.ppt》由会员分享,可在线阅读,更多相关《1_1 Introduction to Java.ppt(94页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Introduction to JavaSSE USTCQing DingWhat is Java Technology?lThe Java technology is:A programming languageA development environmentAn application environmentA deployment environmentProgramming LanguagelAs a programming language,Java can create all kinds of applications that you could create using a
2、ny conventional programming language.A Development EnvironmentlAs a development environment,Java technology provides you with a large suite of tools:A compiler(javac)An interpreter(java)A documentation generator(javadoc)A class file packaging tooland so on.An Application and Runtime EnvironmentlJava
3、 technology applications are typically general-purpose programs that run on any machine where the Java runtime environment(JRE)is installed.lThere are two main deployment environments:The JRE supplied by the Java 2 Software Development Kit(SDK)contains the complete set of class files for all the Jav
4、a technology packages,which includes basic language classes,GUI component classes,and so on.The other main deployment environment is on your web browser.Most commercial browsers supply a Java technology interpreter and runtime environment.Java FeatureslSome features of Java:The Java Virtual MachineG
5、arbage CollectionCode SecurityThe Java Virtual MachinelJava Virtual Machine(JVM)an imaginary machine that is implemented by emulating software on a real machineprovides the hardware platform specifications to which you compile all Java technology codelBytecodea special machine language that can be u
6、nderstood by the Java Virtual Machine(JVM)independent of any particular computer hardware,so any computer with a Java interpreter can execute the compiled Java program,no matter what type of computer the program was compiled onGarbage CollectionlGarbage collection threadresponsible for freeing any m
7、emory that can be freed.This happens automatically during the lifetime of the Java program.programmer is freed from the burden of having to deallocate that memory themselvesCode SecuritylCode security is attained in Java through the implementation of its Java Runtime Environment(JRE).lJREruns code c
8、ompiled for a JVM and performs class loading(through the class loader),code verification(through the bytecode verifier)and finally code executionCode SecuritylClass Loaderresponsible for loading all classes needed for the Java programadds security by separating the namespaces for the classes of the
9、local file system from those that are imported from network sourcesAfter loading all the classes,the memory layout of the executable is then determined.This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtimeCode SecuritylB
10、ytecode verifiertests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objectsPhases of a Java ProgramlThe following figure describes the process of compiling and executing a Java programProgramming FundamentalsDissecting my First Java
11、 ProgramDissecting my First Java ProgramDissecting my First Java ProgramDissecting my First Java ProgramDissecting my First Java ProgramDissecting my First Java ProgramDissecting my First Java ProgramDissecting my First Java ProgramCoding GuidelineslYour Java programs should always end with the.java
12、 extension.lFilenames should match the name of your public class.So for example,if the name of your public class is Hello,you should save it in a file called Hello.java.lYou should write comments in your code explaining what a certain class does,or what a certain method does.Java CommentslCommentsTh
13、ese are notes written to a code for documentation purposes.Those texts are not part of the program and does not affect the flow of the program.l3 Types of comments in JavaC+Style CommentsC Style CommentsSpecial Javadoc CommentsC+-Style CommentslC+Style comments starts with/lAll the text after/are tr
14、eated as commentslFor example:/This is a C+style or single line commentsC-Style CommentslC-style comments or also called multiline comments starts with a/*and ends with a*/.lAll text in between the two delimeters are treated as comments.lUnlike C+style comments,it can span multiple lines.lFor exampl
15、e:/*this is an exmaple of aC style or multiline comments*/Special Javadoc CommentslSpecial Javadoc comments are used for generating an HTML documentation for your Java programs.lYou can create javadoc comments by starting the line with/*and ending it with*/.lLike C-style comments,it can also span li
16、nes.lIt can also contain certain tags to add more information to your comments.lFor example:/*This is an example of special java doccomments used for n generating an htmldocumentation.It uses tags like:author Florence Balagtasversion 1.2*/Java StatementslStatementone or more lines of code terminated
17、 by a semicolon.Example:System.out.println(“Hello world”);Java BlockslBlockis one or more statements bounded by an opening and closing curly braces that groups the statements as one unit.Block statements can be nested indefinitely.Any amount of white space is allowed.Example:public static void main(
18、String args)System.out.println(Hello);System.out.println(world”);Java Statements and Blocks Coding Guidelines1.In creating blocks,you can place the opening curly brace in line with the statement.For example:public static void main(String args)or you can place the curly brace on the next line,like,pu
19、blic static void main(String args)Java Statements and Blocks Coding Guidelines2.You should indent the next statements after the start of a block.For example:public static void main(String args)System.out.println(Hello);System.out.println(world);Java IdentifierslIdentifiersare tokens that represent n
20、ames of variables,methods,classes,etc.Examples of identifiers are:Hello,main,System,out.lJava identifiers are case-sensitive.This means that the identifier Hello is not the same as hello.Java IdentifierslIdentifiers must begin with either a letter,an underscore“_”,or a dollar sign“$”.Letters may be
21、lower or upper case.Subsequent characters may use numbers 0 to 9.lIdentifiers cannot use Java keywords like class,public,void,etc.We will discuss more about Java keywords later.Coding Guidelines1.For names of classes,capitalize the first letter of the class name.For example,ThisIsAnExampleOfClassNam
22、e2.For names of methods and variables,the first letter of the word should start with a small letter.For example,thisIsAnExampleOfMethodNameCoding Guidelines3.In case of multi-word identifiers,use capital letters to indicate the start of the word except the first word.For example,charArray,fileNumber
23、,ClassName.4.Avoid using underscores at the start of the identifier such as _read or _write.Java KeywordslKeywords are predefined identifiers reserved by Java for a specific purpose.lYou cannot use keywords as names for your variables,classes,methods.etc.lThe next slide contains the list of the Java
24、 Keywords.Java KeywordsJava LiteralslLiterals are tokens that do not change-they are constant.lThe different types of literals in Java are:Integer LiteralsFloating-Point LiteralsBoolean LiteralsCharacter LiteralsString LiteralsJava Literals:IntegerlInteger literals come in different formats:decimal(
25、base 10)hexadecimal(base 16)octal(base 8).Java Literals:IntegerlSpecial Notations in using integer literals in our programs:DecimallNo special notationlexample:12HexadecimallPrecede by 0 x or 0Xlexample:0 xCOctallPrecede by 0lexample:014Java Literals:Floating PointlRepresents decimals with fractiona
26、l partsExample:3.1416lCan be expressed in standard or scientific notationExample:583.45(standard),5.8345e2(scientific)Java Literals:BooleanlBoolean literals have only two values,true or false.Java Literals:CharacterlCharacter Literals represent single Unicode characters.lUnicode charactera 16-bit ch
27、aracter set that replaces the 8-bit ASCII character set.Unicode allows the inclusion of symbols and special characters from other languages.Java Literals:CharacterlTo use a character literal,enclose the character in single quote delimiter.lFor examplethe letter a,is represented as a.special characte
28、rs such as a newline character,a backslash is used followed by the character code.For example,n for the newline character,r for the carriage return,b for backspace.Java Literals:StringlString literals represent multiple characters and are enclosed by double quotes.lAn example of a string literal is,
29、“Hello World”.Primitive Data TypeslThe Java programming language defines eight primitive data types.boolean(for logical)char(for textual)byteshortintlong(integral)doublefloat(floating point).Logical-booleanlA boolean data type represents two states:true and false.lAn example is,boolean result=true;l
30、The example shown above,declares a variable named result as boolean type and assigns it a value of true.Textual-charlA character data type(char),represents a single Unicode character.lIt must have its literal enclosed in single quotes().lFor example,a/The letter at/A tablTo represent special charact
31、ers like (single quotes)or (double quotes),use the escape character.For example,/for single quotes/for double quotesTextual-charlAlthough,String is not a primitive data type(it is a Class),we will just introduce String in this section.lA String represents a data type that contains multiple character
32、s.It is not a primitive data type,it is a class.lIt has its literal enclosed in double quotes(“”).lFor example,String message=“Hello world!”;Integral byte,short,int&longlIntegral data types in Java uses three forms decimal,octal or hexadecimal.lExamples are,2/The decimal value 2077/The leading 0 ind
33、icates an octal value0 xBACC/The leading 0 x indicates a hex valuelIntegral types has int as default data type.lYou can define its long value by appending the letter l or L.lFor example:10LIntegral byte,short,int&longlIntegral data type have the following ranges:Integral byte,short,int&longlCoding G
34、uidelines:In defining a long value,a lowercase L is not recommended because it is hard to distinguish from the digit 1.Floating Point float and doublelFloating point types has double as default data type.lFloating-point literal includes either a decimal point or one of the following,E or e/(add expo
35、nential value)F or f/(float)D or d/(double)lExamples are,3.14/A simple floating-point value(a double)6.02E23/A large floating-point value2.718F/A simple float size value123.4E+306D/A large double value with redundant DFloating Point float and doublelFloating-point data types have the following range
36、s:VariableslA variable is an item of data used to store the state of objects.lA variable has a:data typelThe data type indicates the type of value that the variable can hold.namelThe variable name must follow rules for identifiers.Declaring and Initializing VariableslDeclare a variable as follows:=i
37、nitial value;lNote:Values enclosed in are required values,while those values in are optional.Declaring and Initializing Variables:Sample ProgramDeclaring and Initializing Variables:Coding Guidelines1.It always good to initialize your variables as you declare them.2.Use descriptive names for your var
38、iables.Like for example,if you want to have a variable that contains a grade for a student,name it as,grade and not just some random letters you choose.Declaring and Initializing Variables:Coding Guidelines3.Declare one variable per line of code.For example,the variable declarations,double exam=0;do
39、uble quiz=10;double grade=0;is preferred over the declaration,double exam=0,quiz=10,grade=0;Outputting Variable DatalIn order to output the value of a certain variable,we can use the following commands:System.out.println()System.out.print()Outputting Variable Data:Sample ProgramSystem.out.println()v
40、s.System.out.print()lSystem.out.println()Appends a newline at the end of the data outputlSystem.out.print()Does not append newline at the end of the data outputReference Variables vs.Primitive VariableslTwo types of variables in Java:Primitive VariablesReference VariableslPrimitive Variablesvariable
41、s with primitive data types such as int or long.stores data in the actual memory location of where the variable islReference Variablesvariables that stores the address in the memory locationpoints to another memory location where the actual data isWhen you declare a variable of a certain class,you a
42、re actually declaring a reference variable to the object with that certain class.ExamplelSuppose we have two variables with data types int and String.int num=10;/primitive typeString name=Hello;/reference typeExamplelThe picture shown below is the actual memory of your computer,wherein you have the
43、address of the memory cells,the variable name and the data they hold.OperatorslDifferent types of operators:arithmetic operatorsrelational operatorslogical operatorsconditional operatorslThese operators follow a certain kind of precedence so that the compiler will know which operator to evaluate fir
44、st in case multiple operators are used in one statement.Arithmetic OperatorsArithmetic Operators:Sample ProgramArithmetic OperatorslNote:When an integer and a floating-point number are used as operands to a single arithmetic operation,the result is a floating point.The integer is implicitly converte
45、d to a floating-point number before the operation takes place.Increment and Decrement Operatorslunary increment operator(+)lunary decrement operator(-)lIncrement and decrement operators increase and decrease a value stored in a number variable by 1.For example,the expression,count=count+1;/increment
46、 the value of count by 1is equivalent to,count+;Increment and Decrement OperatorsRelational Operators Relational operators compare two values and determinesthe relationship between those values.The output of evaluation are the boolean values true orfalse.Logical OperatorslLogical operators have one
47、or two boolean operands that yield a boolean result.lThere are six logical operators:&(logical AND)&(boolean logical AND)|(logical OR)|(boolean logical inclusive OR)(boolean logical exclusive OR)!(logical NOT)Java ArrayAgendalWhat is an arraylDeclaration of an arraylInstantiation of an arraylAccessi
48、ng array elementlArray lengthlMulti-dimensional arrayIntroduction to ArrayslSuppose we have here three variables of type int with different identifiers for each variable.int number1;int number2;int number3;number1=1;number2=2;number3=3;lAs you can see,it seems like a tedious task in order to just in
49、itialize and use the variables especially if they are used for the same purpose.Introduction to ArrayslIn Java and other programming languages,there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently.This type of variable is called an array
50、.lAn array stores multiple data items of the same data type,in a contiguous block of memory,divided into a number of slots.Declaring ArrayslTo declare an array,write the data type,followed by a set of square brackets,followed by the identifier name.lFor example,int ages;orint ages;Array Instantiatio