Download
slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Java Basics - I Yangjun Chen Dept. Business Computing University of Winnipeg PowerPoint Presentation
Download Presentation
Java Basics - I Yangjun Chen Dept. Business Computing University of Winnipeg

Java Basics - I Yangjun Chen Dept. Business Computing University of Winnipeg

165 Vues Download Presentation
Télécharger la présentation

Java Basics - I Yangjun Chen Dept. Business Computing University of Winnipeg

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Java Basics - I Yangjun Chen Dept. Business Computing University of Winnipeg

  2. Outline: Basics -I • Basic concepts: • class declaration • class body, methods • variables • identifiers • comments • Primitive data types • Operators • arithmetic operators • logic operators • bitwise operators

  3. HelloWorld Application • Let’s take a look at a little bit more complicated program. • import java.lang.* • //A simple Java application • public class HelloWorld { • public static void main(String args[]) { • s obj=new s(); • System.out.println(obj.s1);}} • class s {String s1=“HelloWorld!”;} • Java concepts: class declaration, class body, methods, • variables, identifiers, comments

  4. Class Declaration • The third line in our program is the class declaration. • public class HelloWorld • This line creates a class called HelloWorld with it’s implementation contains in the following pair of braces • { and }. • “public” keyword • - makes this class accessible to the outside world. • (More exactly, the key word makes it accessible to the packages which do not contain it.)

  5. The Class Body • The next block of code that is contained between the outer • pair of braces is called the body of the class: • - body in the first class: • { • public static void main(String args[]) { • s obj=new s(); • System.out.println(obj.s1); • } • } • - body in the second class: • { • String s1=“HelloWorld”; • }

  6. Methods • The body of the first class contains only one method, namely main(). • - A method is somewhat like a function or procedure that may or may not take in arguments, performs a task, and then optionally sends back some information. • When a method is invoked, the statements in the body are executed. When the method finishes, the control will be returned to the part of the program where the method was first invoked. • A method takes the form: • modifiers returntype methodname(arguments) { • /*list of statements or body of method*/ }

  7. Methods • If the return TypeName is “void”, nothing will be returned. • If the return TypeName is not “void”, then the method will return values of some type or returns back the invocation point with some information. • The first class contains a method: main(String args[]) • - It has an argument args which is an array of String • - The return type is void so this method does not return any information

  8. Method Invocation • The body of the main() method contains two statements. • - The second statement invokes the method println() • - The general form to invoke the method is: • objectName.methodName(argument list); • Example: System.out.println(obj.s1); • - The arguments used in the method invocation must match • those in the definition of the method. • - println()’s argument is a string and obj.s1 evaluates to a string. So it matches.

  9. Where does the program start? • We are finished with the program, but where does the main() • method get invoked? • The main() method is always automatically called when the class containing it is executed.

  10. Variables • Variables are named locations in memory where values can be stored. • - A variable has a name, a type, and a value. • - It must be declared before it can be used. • There are actually three kinds of variables in Java: • - instance variables • declared at the class level and represent data that • belong to an object of the class. • - class variables • similar to instance variables except that their values apply to all that class’s instances rather than having different values for each object.

  11. Variables • - local variables • - declared in a method and has meaning only within that method • - after the method is finished, that local variable will cease to exist. • We won’t look at class variables at this point. • For instance variables, the declaration consists of a type followed by a variable name: • - int x; • - String s1; • - boolean ison;

  12. Variable Declaration • Declarations of the same type can be strung together: • - int x, y, z; • - String firstname, lastname; • You can also initialize variables upon declaration: • - int x, y, z=8; • - String name=“John”; • - boolean ison=true; • - int x=5, y=6, z=7;

  13. Variable Declaration • Example: • class Triple { • double x, y, z; • Triple() { • x=0.0; y=0.0; z=0.0; • } • double sum() { • double theSum=0.0; • theSum=x+y+z; • return theSum;} • } Instance variables - can be used in any of the methods constructor Local variables - can only be used in this method

  14. Variables • Each instance of a class (each object) has its own collection of instance variables. • Suppose “origin” and “center”were two instances of the class Triple. • - Variable x in origin and center would be two separate instance variables. • Local variables must be initialized before they can be used. Otherwise, a compilation error will occur when compiling your program.

  15. Java Identifiers • Variables, method names, class names and package names are collectively known as identifiers. • The first class is named HelloWorld, but we can have chosen any legal Java name as long as it has not been already defined. • Legal Java names: • - any string of letters, digits, and the underscore as long as it starts with • a letter. • - legal names: limitValue, x, swithch72b, a_b_c • - illegal names: 2wayStreet, my vaiable, #$rr$! • Java identifiers are all case sensitive. • - HelloWorld, helloWorld, and helloworld are all different names. • Any identifier can not be the same as a Java keyword.

  16. Comments in Java • The following line is a comment: • //A simple Java Application • This is a single line comment in Java. • - The Java compiler will ignore everything after the double slash • “//” to the end of the line. • - This allows us to document our code. • There are three types of comments in Java: • - single line comment • - multi-line or block comment • - document comment

  17. Single and Multi-line Comments • Single line comments: • - // This is a single line comment • - x=0; //A comment after initializing x • Multi-line comments: • - Begins with /* and ignores everything until a */ is encountered • /*This is a single line multi-line comments, Multi-line comments can • go on for many , many, many lines.*/

  18. Documentation Comments • The documentation comment works like the multi-line comment but begins with /** and ends with */ • - This type of comment can be extracted from your code using a Java tool called javadoc. • - This tool will generate an HTML file that can be viewed by a web browser. • The javadoc can be used in two ways: • - embedded HTML • - “doc tags”

  19. Examples of Documentation Comments • Embedded HTML • /** • * <pre> • * System.out.println(new Date()); • *</pre> • */ • Doc Tag • /**The first Thinking in Java example program. • * @author Bruce Eckel • * @author http://www.BruceEckel.com • * @version 1.0 • */

  20. Identifier Scope • Now that we know how to declare identifiers, where can we use them? • The scope of an identifier is the portion of a class where the identifier may be used. • Class variables, instance variables, and method names can be used anywhere in the class. • Local variables can only be used after they are declared and within the closest set of braces that enclose the declaration.

  21. Scope Example • Class Myclass { • int inst; • … • void method1() { • … • { • … • int loc = 3; • … • }//inner block • … • }//method1 Void method2() { … } //method2 }//class

  22. Scope Example • Class Myclass { • int num=2; • … • void method1() { • int num=3; • … //is num2 or 3 here? • }//method1 • void method2() { • … //is num 2 or 3 here? • }//method2 • }//class

  23. Scope Example • What is the value of num? • - It is easy to see that num would be 2 in method2() because we can’t see the local variable in it. • But what is the value of num in method1()? • - The value of num in method1 is 3. • - Java’s rules for this are common to other languages: the most local variable is the one that is used. • - In this case, we say that the local variable (value 3) shadows the less local one (value 2).

  24. Java Basics - Primitive Data Types • There are eight primitive data types and they handle common types for integers, floating- point numbers, characters and boolean values. TypeDescriptionkeyword character 16-bit Unicode character char boolean true/false values boolean byte 8-bit signed integer numbers byte short 16-bit signed integer numbers short integer 32-bit signed integer numbers int long 64-bit signed integer numbers long float 32-bit signed floating-point numbers float double 64-bit signed floating-point numbers double

  25. Integers • Java has four types to represent integers: • - Type Size Rang • byte 8 bits -128 to 127 • short 16 bits -32,768 to 32767 • int 32 bits -2,147,483,648 to • 2,147,483,647 • long 64 bits -9,233,372,036,864,775,808 to 9,233,372,036,854,775,807 • Which type you use depends on the range of values you expect that variable to hold. • If a value becomes too large for its type then it is truncated.

  26. Integers • All primitive types have a default value when they are declared unless you initialize them. • - For an integer type, the default is zero • - To declare a variable of type int: int x; • It is the same as writing int x=0; • - We can also initialize the variable upon declaration: • int x=5; • Integers may also be expressed in octal or hexadecimal forms. • - An octal: begin with the digit 0 and be followed by the digits 0 through 7: 0173 • - A hexadecimal: begin with digit 0x or 0X and be followed by 0 through 9 and a (A) through f (F): 0X11EF.

  27. Floating Point Numbers • There are two types for floating-point numbers: • - float • 32 bits, single precision • approximately 7 decimal digits of accuracy • - double • 64 bits, double precision • approximately 10 decimal digits of accuracy • Java also allows scientific notation: • - 0.12e-16 is equivalent to 0.000000000000000012 • The default value for floating-point number is 0.0.

  28. Characters • Java uses the Unicode character set which means every char type has 16 bits of precision, unsigned. • Strictly speaking, the character type is an integral type since the characters are stored by their 16 bit Unicode representation. • - Example: the character ‘A’ is stored in Java as the number 65 - 0000 0000 0100 0001. • The default value for char type is the character with code zero, written ‘\0’, which is a non-printing character.

  29. Arithmetic Operators and Expressions • An expression is the simplest form of a statement in Java that actually accomplishes a task. • Most of the expressions in Java use operators. • Operators are special symbols for things like arithmetic, assignments, increment, decrement and logical operations. • Java has 12 arithmetic operations.

  30. Operators Operator Meaning + addition - subtraction (also unary minus) * multiplication / division % modulus += addition assignment -= subtraction assignment *= multiplication assignment /= division assignment %= modulus assignment ++ increment -- decrement

  31. Operators • Each operator takes two operands, one on either side. • - The subtraction operator can also be used to negate a single operand. • Integer division results in an integer. • - Because integer don’t have fractional parts, any remainder is ignored. • - Example: 31/9 results in 3. • The modulus (%) operator gives the remainder after integer division: 31%9 = 4. • -5%3 = -2 • 5%-3 = 2 • - 5%-3 = -2

  32. Operators • There are no mixed arithmetic operators. • For expressions that involve mixed types, shorter types are “promoted” to longer types. • - byte, short, char are all promoted to an int. • - int to long , to float, or to double are performed as needed. • Example: • - 9.0/4, the integer 4 is first promoted to a floating-point number equivalent to 4.0, and then the floating-point division is performed yielding 2.25. • - The result would be a floating-point type.

  33. Type Casting • Instead of letting the compiler perform promotion for you, it is possible to do it explicitly by yourself. • This is what is known as a type casting. • For example, if we had a float with the value 1.0, we could type cast it into an integer by doing the following: • - int x; • x = (int) 1.0; • Casting takes on the form: • (typeName) expression

  34. Type Casting • Example: • class GoodAssignment { • public static void main(String args[]) { • byte b; • int i=127; • b=(byte) i; • System.out.println(b); //display 127}} • class GoodAssignment { • public static void main(String args[]) { • byte b; • int i=258; • b=(byte) i; • System.out.println(b); //display 2}} 8 bits 0 ... 1 0 ... 1 0 16 bits

  35. Increment and Decrement • Increment ++ and decrement -- are both unary operators. • The increment operator can only be applied to a numeric variable and causes the value to be incremented by 1. • There are two ways to use this operator • - before the operand or • - after the operand. • The simplest way to show the difference between the two uses is by example.

  36. Increment and Decrement • Suppose we had an int variable x with the value 4, then what is the result of • - 2*++x increment first • - The result is 10 and the value of x would be 5. • Now, if x was 4 again, what is the result of • - 2*x++ increment after • - The result is 8 and the value of x would be 5. • The decrement operator works in the same way but instead of increasing the value, it would decrease the value by 1. • - What is 2*--x? • - What is 2*x--?

  37. Assignment Operators • Variable assignments are a form of expression and can be strung together like this: • - x = y = z = 0; • - The right side of an assignment is always evaluated first before the assignment takes place. • There are shorthand assignment operators in Java that are taken from C and C++. They are: • ExpressionMeaning • x+=y x=x+y • x-=y x=x-y • x*=y x=x*y • x/=y x=x/y

  38. Comparison Operators • There are several comparison operators that test for equality and magnitude. • All of these expressions return a boolean value as a result. • OperatorMeaning Example • == equal x == 4 • != not equal x != 4 • < less than x < 4 • > greater than x > 4 • <= less than or equal to x <= 4 • >= greater than or equal to x >= 4

  39. Logic Operators • Logical Operators can be used to represent the logical combinations AND, OR, NOT, XOR. • - You would use these operators in expressions that result in a boolean value. • AND Operator • - use either & or && operator: A & B, A && B. • - The expression will evaluate to true if both expressions on either side of the logical operator are true. • - If either side of the expressions are false, then result is false. • - The & operator will evaluate both sides of the expression regardless of the outcome. • - The && operator will first evaluate the left side. If it is false, the expression will return false and not evaluate the right side. This is often called a “short-circuited” expression.

  40. Logic Operators • OR Operator • - The OR operator has two variants just like AND operator. They are | and ||: A | B, A || B. • - OR expressions return true if either or both sides of the expression are true. • - If both sides of the expressions are false, then result is false. • - The | operator will evaluate both sides of the expression regardless of the outcome. • - The || operator will first evaluate the left side. If it is true, the expression will return true and not evaluate the right side.

  41. Logic Operators • XOR Operator • - Use the ^ operator: A ^ B. • - Evaluate to true if it’s operands are different (one true and one false, or vice versa.) • In general, the && and || operators are used for logical combinations. • The &, |, and ^ operators are more commonly used for bitwise logical operations. • The NOT operator uses the ! Symbol. • - It returns the negation of the expression, so if x is true, the !x is false.

  42. Bitwise Operators • Number can be represented by a set of bits (a series of 0s and 1s) • Binary digits take on the value of 0 or 1. • Example: • the binary number (110101)2 represents the decimal number 53. • OperatorMeaning • & AND • | OR • ^ XOR • ~ Bitwise complement • >> Shift right with sign extension • >>> Shift right with zero fill • << Shift left with zero fill

  43. 110101 • 101010 • 100000 • 110101 • 101010 • 111111 & 110101 110101 011010 101010 >> >>> << Bitwise Operators • 110101 • ^ 101010 • 011111 | | 110101 111010

  44. import java.lang.*; //bit operations public class ShowBits { public static void main(String args[]) {byte b = -5; for (int i = 7; i>=0; i--) { if ((b & 0x80) == 0) System.out.println("bit " + i + "is 0"); else System.out.println("bit " + i + "is 1"); b <<= 1; } } }

  45. Precedence • All Java operators have a precedence that governs the order in which the operators are evaluated. Arithmetic: Relational and logic: *, /, % +, - ! > >= < <= == != & | && ||