JAVA Programming Language Lecture 2:Variables and Data Types Chengwei Zhang ( 张成伟 ) School of Electronic Information and Communications Huazhong University of Science and Technology Mar. 2015
Outline Quick View to Java Application Variables Primitive Data Types Practice Summary 2
Quick View to Java Application 1 // Sample 01: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 5 6 // main method begins execution of Java application 7 public static void main( String[] args ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); 10 11 } // end method main 12 13} // end class Welcome01 Output: Welcome to Java Programming! 3
Quick View to Java Application Output: Welcome to Java Programming! 10 March 2015 Java Programming Language 4
Quick View to Java Application 1 // Sample 01: Welcome1.java Comments start with: // Comments ignored during program execution Document and describe code Provides code readability Traditional comments: /*... */ /* This is a traditional comment. It can be split over many lines */ 2 // Text-printing program. Another line of comments Note: line numbers not part of program, added for reference 5
Quick View to Java Application 3 Blank line Makes program more readable Blank lines, spaces, and tabs are white-space characters Ignored by compiler 4 public class Welcome01 { Begins class declaration for class Welcome01 Every Java program has at least one user-defined class Keyword: words reserved for use by Java class keyword followed by class name Naming classes: capitalize every word SampleClassName, UndergraduateStudent, 6
Quick View to Java Application 4 public class Welcome01 { Name of class called identifier Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) Does not begin with a digit, has no spaces Examples: Welcome1, $value, _value, button7 7button is invalid Java is case sensitive (capitalization matters) a1 and A1 are different 7
Quick View to Java Application 4 public class Welcome01 { Saving files File name must be class name with.java extension Welcome1.java Left brace { Begins body of every class Right brace ends declarations (line 13) 7 public static void main( String args[] ) Part of every Java application Applications begin executing at main Parenthesis indicate main is a method Java applications contain one or more methods 8
Quick View to Java Application 7 public static void main( String args[] ) Exactly one method must be called main Methods can perform tasks and return information void means main returns no information 8 { Left brace begins body of method declaration Ended by right brace } (line 11) 9
Quick View to Java Application 9 System.out.println( "Welcome to Java Programming!" ); Instructs computer to perform an action Prints string of characters String - series characters inside double quotes White-spaces in strings are not ignored by compiler System.out Standard output object Print to command window (i.e., MS-DOS prompt) Method System.out.println Displays line of text Argument inside parenthesis This line known as a statement Statements must end with semicolon ; 10
Quick View to Java Application 11 } // end method main Ends method declaration 13 } // end class Welcome01 Ends class declaration Can add comments to keep track of ending braces Lines 8 and 9 could be rewritten as: Remember, compiler ignores comments Comments can start on same line after code 11
Quick View to Java Application Compiling a program Open a command prompt window, go to directory where program is stored Type javac Welcome1.java If no errors, Welcome1.class created Has bytecodes that represent application Bytecodes passed to Java interpreter 12
Quick View to Java Application Executing a program on CMD model Type java Welcome01 Interpreter loads.class file for class Welcome1.class extension omitted from command Interpreter calls method main Executing Welcome1 in a Microsoft Windows Command Prompt. 13
A modified Welcome01 sample 10 March 2015 Java Programming Language 14
VARIABLES 15
What is variables? Variables are locations in memory in which values can be stored. Every variable has a name, a type, a size and a value. Before you can use a variable, you have to declare it. After it is declared, you can then assign values to it. 16
Variable Types The variable type can be one of the three things: One of the eight basic primitive data types The name of a class An array of any kind class or primitive data type 17
Three kinds of variables local variables (discussed in Lecture 2) instance variables (discussed in Lecture 4) class variables (discussed in Lecture 4) no global variables? (discussed in Lecture 4) Why Java has no global variables? 10 March 2015 Java Programming Language 18
Local variables Inside method definitions or code segments Store information needed by a single method or some segment code 19
Instance variables (in Lecture 4) Attributes or the state of a particular object Store information needed by multiple methods in the object Have different values for each object 20
Class variables (in Lecture 4) Similar to instance variables Apply to all that class s instances Apply to the class itself Shared among the objects of the same class 21
Steps for using variables Declare variable Initiate variables value before using them Use the variables in a right way 10 March 2015 Java Programming Language 22
Declaring variables Variable declarations consist of a type and a variable name, e.g.: int count; String name; boolean validated; The variables with the same type can be stringed together, e.g.: double x, y, z; String fname, lname; Variable declarations can go anywhere in a method definition Most commonly declared in the beginning of the definition before they are used 23
Variables initial value The initial value of a variable can be given in declaration, e.g.: int a = 10, b = 5; String myname = Zhang Chengwei ; Only the last variable has initial value if there are multiple variables on the same line, e.g.: double x, y, z = 10.0; 24
Notes about variable names Case-sensitive Zhang is not same to zhang. Meaningful names int countofstudentnumber; boolean currentweatherisgood; int intuserage; String stradminname; 25
PRIMITIVE DATA TYPES 26
Eight primitive data types byte short int long char float double boolean 27
Integer Type Width Size(Value Range) long 64-9223372036854775808~9223372036854775807 (-2 63 ~ 2 63-1) int 32-2147483648~2147483647 (-2 31 ~ 2 31-1) short 16-32768~32767(-2 15 ~ 2 15-1) byte 8-128~127 Octal 03, 07 Hexadecimal 0xab 0X1a 10 March 2015 Does Java has no unsigned type s? Java Programming Language 28
Floating-point types Type Width Size double 64 1.7e-308~1.7e+308 float 32 3.4e-038~3.4e+038 18.0f 18.0d = 18.0 18. = 1.8e1 =.18E2 A float value can be assigned to a double variable. A double value can not be assigned to a float variable 29
Char Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. Incorporating Unicode into client-server or multi-tiered applications and websites offers significant cost savings over the use of legacy character sets. Width Size ASCII 7 0~127 ISO-Latin-1 8 0~255 Unicode 16 0~65536 30
ASCII character set 31
Special codes Escape Meaning Escape Meaning \n Newline \ Single quote \t Tab \ Double quote \b Backspace \ddd Octal \r Carriage return \xdd Hexadecimal \f Formfeed \udddd Unicode character \\ Backslash 32
Boolean types Type boolean Value true/false 33
OPERATORS 34
Five Basic Arithmetic Operators Java operation Arithmetic operator Algebraic expression Addition + f + 7 f + 7 Subtraction - p - c p - c Multiplication * bm b * m Division / x / y or x y x / y Java expression Modulus (Remainder) % r mod s r % s 35
Assignment Operator Arithmetic Compound Assignment Operators int a = 5, b = 3, c; Assignment operator Sample expression a =? += (addition) a += b 8 -= a -=b 2 *= a *= b 15 /= a /= b 1 %= a %= b 2 36
Type conversion Widening conversion Truncation 37
Type promoting byte int short int char int one is long, result is long one is float, result is float one is double, result is double 38
Comparison operators Equality operators ==!= Relational operators > < >= <= Must be inserted into the condition statement if, while, for 10 March 2015 Java Programming Language 39
Equality operators ==!= e.g. x == y x is equal to y. e.g. x!= y x is not equal to y. 40
Relational operators > e.g. x > y x is greater than y. < e.g. x < y x is less than y. >= e.g. x >= y x is greater than or equal to y. <= e.g. x <= y x is less than or equal to y. 41
Logical operators &, &&,! ^ 42
Logical operators - AND && (Condition And Operator) e.g. if (salary > 500) && (age++ >= 30) The expression will be true only if both operands tests are also true. & (Boolean Logical And Operator) e.g. if (salary > 500) & (age++ >= 30) The expression will be true only if both operands tests are also true. What s the difference between the two operators? 43
Logical operators - OR (Condition OR Operator) e.g. if (salary > 500) (age++ >= 30) The expression will be true at least one of operands tests is true. (Boolean Logical OR Operator) e.g. if (salary > 500) (age++ >= 30) The expression will be true at least one of operands tests is true. What s the difference between the two operators? 44
CONTROL STRUCTURES 45
Control Structures Sequential execution Program statements execute one after the other Transfer of control Three control statements can specify order of statements Sequence structure Selection structure Repetition structure Activity diagram Models the workflow Action-state symbols Transition arrows 10 March 2015 Java Programming 46 Language
No goto The finger of blame was pointed at the goto statement The notion of so-called structured programming became almost synonymous with goto elimination Java does not have a goto statement; however, goto is a reserved word and should not be used in a Java program 47
Homework 10 March 2015 Java Programming Language 48
Thanks 2015-3-9