basic1 - The University of Winnipeg
Download
Report
Transcript basic1 - The University of Winnipeg
Java Basics - I
Yangjun Chen
Dept. Business Computing
University of Winnipeg
Jan. 2004
1
Outline: Basics -I
• Basic concepts:
class declaration
class body, methods
variables
identifiers
comments
• Primitive data types
• Operators
arithmetic operators
logic operators
bitwise operators
Jan. 2004
2
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
Jan. 2004
3
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.)
Jan. 2004
4
The Class Body
• The next block of code that is contained between the outer
pair of braces is called the body of the class:
-
-
Jan. 2004
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”;
}
5
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*/ }
Jan. 2004
6
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
Jan. 2004
7
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);
-
Jan. 2004
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.
8
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.
Jan. 2004
9
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:
-
-
Jan. 2004
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.
10
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:
-
Jan. 2004
int x;
String s1;
boolean ison;
11
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:
-
Jan. 2004
int x, y, z=8;
String name=“John”;
boolean ison=true;
int x=5, y=6, z=7;
12
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;}
}
Jan. 2004
Instance variables - can be used in
any of the methods
constructor
Local variables - can only
be used in this method
13
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.
Jan. 2004
14
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.
Jan. 2004
15
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
Jan. 2004
16
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.*/
Jan. 2004
17
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”
Jan. 2004
18
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
*/
Jan. 2004
19
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.
Jan. 2004
20
Scope Example
Class Myclass {
int inst;
…
void method1() {
…
{
…
int loc = 3;
…
}//inner block
…
}//method1
Jan. 2004
Void method2() {
…
} //method2
}//class
21
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
Jan. 2004
22
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()?
-
Jan. 2004
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).
23
Java Basics - Primitive Data Types
• There are eight primitive data types and they
handle common types for integers, floatingpoint numbers, characters and boolean values.
Jan. 2004
Type
Description
keyword
character
boolean
byte
short
integer
long
float
double
16-bit Unicode character
true/false values
8-bit signed integer numbers
16-bit signed integer numbers
32-bit signed integer numbers
64-bit signed integer numbers
32-bit signed floating-point numbers
64-bit signed floating-point numbers
char
boolean
byte
short
int
long
float
double
24
Integers
• Java has four types to represent integers:
-
Type
byte
short
int
Size
8 bits
16 bits
32 bits
long
64 bits
Rang
-128 to 127
-32,768 to 32767
-2,147,483,648 to
2,147,483,647
-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.
Jan. 2004
25
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.
Jan. 2004
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.
26
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.
Jan. 2004
27
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.
Jan. 2004
28
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.
Jan. 2004
29
Operators
Jan. 2004
Operator
Meaning
+
*
/
%
+=
-=
*=
/=
%=
++
--
addition
subtraction (also unary minus)
multiplication
division
modulus
addition assignment
subtraction assignment
multiplication assignment
division assignment
modulus assignment
increment
decrement
30
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
Jan. 2004
31
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:
-
-
Jan. 2004
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.
32
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
Jan. 2004
33
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}}
Jan. 2004
8 bits
... 1 0 0 ... 1 0
16 bits
34
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.
Jan. 2004
35
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.
-
2*x++
increment after
The result is 8 and the value of x would be 5.
• Now, if x was 4 again, what is the result of
• The decrement operator works in the same way but
instead of increasing the value, it would decrease
the value by 1.
-
Jan. 2004
What is 2*--x?
What is 2*x--?
36
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:
Expression
x+=y
x-=y
x*=y
x/=y
Jan. 2004
Meaning
x=x+y
x=x-y
x=x*y
x=x/y
37
Comparison Operators
• There are several comparison operators that test for
equality and magnitude.
• All of these expressions return a boolean value as a
result.
Operator
==
!=
<
>
<=
>=
Jan. 2004
Meaning
equal
not equal
less than
greater than
less than or equal to
greater than or equal to
Example
x == 4
x != 4
x<4
x>4
x <= 4
x >= 4
38
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
-
-
Jan. 2004
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.
39
Logic Operators
• OR Operator
-
-
Jan. 2004
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.
40
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.
-
Jan. 2004
It returns the negation of the expression, so if x is true, the
!x is false.
41
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.
Operator
Meaning
&
|
^
~
>>
>>>
<<
AND
OR
XOR
Bitwise complement
Shift right with sign extension
Shift right with zero fill
Shift left with zero fill
Jan. 2004
42
Bitwise Operators
&
110101
101010
|
100000
110101
110101
110101
Jan. 2004
110101
101010
111111
>>
>>>
<<
^
110101
101010
011111
|
111010
011010
101010
43
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;
}
}
}
Jan. 2004
44
Precedence
• All Java operators have a precedence that governs the order in
which the operators are evaluated.
Arithmetic:
*, /, %
+, -
Jan. 2004
Relational and logic:
!
> >= < <=
== !=
&
|
&&
||
45