Jan. 20041 Java Basics - II Yangjun Chen Dept. Business Computing University of Winnipeg.
-
date post
18-Dec-2015 -
Category
Documents
-
view
215 -
download
0
Transcript of Jan. 20041 Java Basics - II Yangjun Chen Dept. Business Computing University of Winnipeg.
Jan. 2004 1
Java Basics - II
Yangjun Chen
Dept. Business ComputingUniversity of Winnipeg
Jan. 2004 2
Outline: Java Basics - IIOutline: Java Basics - II
• Modifiers (Specifiers)• Statements• Array• Control flow
- condition statements:ifswitch
- loop structure:forwhiledo
• others: String, print, new, constructor
Jan. 2004 3
ModifiersModifiers
• Modifiers are special keywords that modify the definition of a class, method, or variables.
modifiers
Modifiersfor methods
Modifiersfor variables
Modifiersfor classes
Jan. 2004 4
Modifiers for Methods and VariablesModifiers for Methods and Variables
• static• final• private• protected• public
access modifiers
Jan. 2004 5
Modifiers for Methods and VariablesModifiers for Methods and Variables
• Static and final Modifiers- The static keyword is used in the declaration of class variables and
class methods.- At times we want to associate a variable or a method with the class
rather than with every instance (every object) of the class.- Within a class, a static variable can be accessed by referring to its
name. - From outside of the class, a static variable can be visited using the dot notation:
className.variableName.- A static method can be visited from outside of the class using the dot notation: className.methodName.
Jan. 2004 6
Modifiers for Methods and VariablesModifiers for Methods and Variables
Class Circle {static double PI=3.141592635;double radius;double circumference;double diameter;… …
}
Jan. 2004 7
Modifiers for Methods and VariablesModifiers for Methods and Variables
• Here, PI shouldn’t be a variable. (It is just a constant.)• To make it not changeable, we add the keyword final to the
declaration. Class Circle {
final static double PI=3.141592635;… …
}- Any attempt to modify PI now will generate an error.- Final modifier can not be used for methods.
• Access modifiers allow you to control the visibility and access to variables and methods inside your class.
Jan. 2004 8
• Difference between instance and class variablesClass Circle {
static double PI=3.141592635;double radius = 2.0;double circumference = 12.56;double diameter =4.0;… …
}
Class ComputationCircles {double x, y, z, w;double computation() {x = Circle.PI;Circle o = new Circle();y = o.radius; z = o.circumference; w = o.diameter;… …}
}
Jan. 2004 9
• Difference between instance and class methodsClass Circle {
… ...static double m1( ) { … }double m2 ( ) { … }
}
Class ComputationCircles {double x, y, z, w;double computation() {… ...x = Circle.m1();Circle o = new Circle();y = o.m2();… …}
}
Jan. 2004 10
Modifiers for Methods and VariablesModifiers for Methods and Variables
• There are three access modifiers in Java:- private
protectedpublic
• private Access Modifier- The private modifier creates a non-accessible member.- A private method or variable restricts access only to those methods in the same class.- The private identifiers are unknown to other classes even if the extend (subclass) from the class.
- To declare a member private, simply put the keyword private in front of its declaration.
private int number;
Jan. 2004 11
Modifiers for Methods and VariablesModifiers for Methods and Variables
• protected Access Modifier- The protected modifier allows access to a member within the same
package and within any subclasses.- We won’t study packages at this point. (They are basically a collection of classes that you can define yourself and used as a library.)- You can declare an identifier protected by placing the protected
keyword in front of its declaration.
protected int number;• public Access Modifier
- The public modifier allows access to a member inside or outside of the class.
public int number;
Jan. 2004 12
Modifiers for ClassesModifiers for Classes
• There are three modifiers for classes in Java.- public
This makes a class accessible to outside of the package.- final
This prevents a class from being extended.- abstract
In an abstract class, some abstract methods (with only method signature; no implementation) are defined. Therefore, an abstract
class can not be instantiated.
Jan. 2004 13
StatementsStatements
• There are several types of statements:- Declaration statements, expression statements, return statements and compound statements.
• Declaration Statements- declare new variables by specifying the type, variable name, properties and optionally initialize the variable. - some example are:
Button clear;
private Point sp=new Point(45, 15), ep;final int Max=100000;int almostMax=Max - 500;
Jan. 2004 14
StatementsStatements
• Expression Statements- Expression statements cause the expression to be evaluated and then any other actions in the statement are executed. - some example are:
clear = new Button(“Clear”);
i++;p = q;
Jan. 2004 15
StatementsStatements
• Return Statements- statements in a method with non-void return types that return some
information back to the location where the method was called.- A return statement is of the following form:
return (expression);- The expression can be any expression that is of the same type as the header declaration of the method.- When a return is encountered, it forces the immediate exit from the
method.
Jan. 2004 16
StatementsStatements
- Example:
double magnitude(double x, double y){
double sqrSum = x*x + y*y;return Math.sqrt(sqrSum);
}• Compound Statements
- a collection of statements enclosed in curly braces.- Example:
{Integer obj = new Integer(8);System.out.println(obj.value);
}
Jan. 2004 17
ArrayArray
• An array is a collection of items.• Each array has some number of slots, each of which can hold
an individual item.- An item can be any object or primitive variable; but an array can be only of one type of items;- You can’t have an array with different types in it.
• Steps to create an array:- 1. Declare a variable to hold the array
int temp[];- 2. Create new array object and assign it:
temp = new int[10];- 3. Store things in the array
temp[0] = 6;
Jan. 2004 18
ArrayArray
• Note that the array index starts from zero, so if the array is of size 10, the index values will run from 0 to 9.
• It is also possible to initialize the array during declaration:- int temp[] = {1, 2, 3, 4, 5};
Jan. 2004 19
Multidimentional ArrayMultidimentional Array
• This is just an array of arrays and is declared in the same manner as regular arrays.- Example: int temp[][] = new int[10][5];- This will create an array that has 10 rows and 5 columns.- This will allow us to store 50 values in temp.- You would access each item of the array by specifying both indices,
for example,temp[6][3] = 12;This will store the value 12 into location with row index 6 and column index 3.
- int temp[][] = {{33, 71}, {-16, 45}, {99, 27}};
Jan. 2004 20
if Statementif Statement
• The if statement- written as:
if (boolean expression)statement; //controlled statement
- If the boolean expression evaluates true, then the controlled statement is executed. If it is false, then the controlled statement is skipped.- The controlled statement can also be a compound statement.
Jan. 2004 21
if Statementif Statement
• The if … else statement- This is another form of the if statement.
- It allows some code to be executed if the boolean expression is
true and some other code if false.
- written as:
if (boolean expression)statement1 //expression is true
elsestatement2; //expression is false
Jan. 2004 22
switch Statementswitch Statement
• The switch statement- Instead of chaining if …else statements, a switch statement can be
used for testing equality.
- This is like a case statement in some other languages.
- The expression must evaluate to a primitive type and the constants
must be literals of final variables.
- The defaul case is evaluated if the expression fails to match any of
the constants.
(The default may be omitted, but it is a good idea to have it
here.)
Jan. 2004 23
switch Statementswitch Statement
Switch (expression) {case constant1:
some statements;
case constant2:some statements;
…default:
some statements:} //end of switch
Jan. 2004 24
switch Statementswitch Statement
• Whenever a label (case constant:) is matched, execution of the program continues from there through the switch statement executing each line. - This is the fall through behavior.
• To avoid this, a statement is used.
- A break statement will force the exit from a switch statement
- In almost all cases, you would write a switch statement with a
break statement separating each case statement.
Jan. 2004 25
switch Statementswitch Statement
Switch (expression) {case constant1:
some statements;break;
case constant2:some statements; break;
…default:
some statements:} //end of switch
Jan. 2004 26
for Statementfor Statement
• The for loop in Java looks as follows:for ( init ; expression ; increment) {
some statements;} //end of the for loop
• The init is an expression that will introduce the start of the for loop.- Example: int i = 0;- declares and initializes the index i for this loop.
Jan. 2004 27
for Statementfor Statement
• The expression is a boolean expression that is evaluated before each pass of the loop.- If it is true, then the loop is executed.- Example: i < 10;
• The increment expression is any expression of function call.• The increment is commonly used to bring the state of the loop
closer to returning false and completing.- Example: int i ++;
Jan. 2004 28
for Statementfor Statement
• So the for loop looks like this
for (int i = 0; i < 10; i ++){
System.out.println(i);} //end of the for loop
• What is the output?
Jan. 2004 29
while Statementwhile Statement
• while loops like for loops will repeat the execution of a block of code until a specific condition is met.
• A while loop looks like the following:
while (boolean expression){
statements
} //end of the while loop
• As long as the boolean expression evaluates true, the code in the loop is executed.
Jan. 2004 30
do Statementdo Statement
• Another loop that is quite similar to the while loop is called the do loop.
• A do loop takes the form:
do {statements
} while (boolean expression)• The difference between this loop and the while loop is that the
condition is tested at the end of the loop.- do loop always execute the loop at lease once.
Jan. 2004 31
Loop ConstructsLoop Constructs
• For all these loops, you can use the break statement to exit the loop at any time.
• There is also a continue statemment that forces the loop to start over at the next iteration.
Label1:outer-iteration {
inner-iteration {…
break; //break out of the inner iteration…
continue; //move back to the beginning of the inner iteration
continue label1; //move all the way back to Lable1
break lable1; //break out of both iterations}}
Jan. 2004 32
int i = 0;label:for (int j = 0; j < 10; j++) {
while (i < 10) {System.out.println(i);break; i++;
}}
Jan. 2004 33
label:for (int j = 0; j < 10; j++) {
int i = 0;while (i < 10) {
System.out.println(i);continue; i++;
}}
Jan. 2004 34
int k=0;label:for (int j = k; j < 10; j++) {
int i = 0;while (i < 10) {
System.out.println(i);k++;continue label;
}}
Jan. 2004 35
label:for (int j = 0; j < 10; j++) {
int i = 0;while (i < 10) {
System.out.println(i);break label;i++;
}}
Jan. 2004 36
big_loop: while (!done) {if (test(a, b) == 0) continue; //Control goes to point 2
try {for (int j = 0; j < 10; j++) {
if (a[j] == null)continue; //Control goes to point 1
else if b[j] == null)continue big_loop; //Control goes to point 2
doit(a[j], b[j]);//point 1. Increment and start loop again with the test
}}finally {cleanup(a, b);}//point2. Start loop again with the (!done) test;
}
Jan. 2004 37
break_test: if (check(i)) {try {
for (int j =0; j<10; j++) {if (j > i ) break; //Terminate just this loop.if (a[i][j] == null)
break break_test; //Do the finally clause and
//terminate the if statement.
}}
finally {cleanup(a, i, j)}}
Jan. 2004 38
StringsStrings
• Strings are a combination of characters and instances of the class String in Java.- They are not simply an array of characters.
• String literals are a series of characters enclosed in quotation marks. A string declaration would look like:- String myString=“Brand new String”;
• Unlike many other language strings can not be indexed character by character.- There are methods in the String class that will retrieve characters for you.
String s = “This is a string!”;char char_a = s.charAt[0];
Jan. 2004 39
Print StatementsPrint Statements
• The System.out.println method prints massage out to the standard output of your system - to the screen, to a special window, or maybe to a log file.
• It also prints a new line character at the end of a string.• System.err.println() prints on standard err instead.• You can concatenate arguments to println() using the +
operator.• Example:
- System.out.println(“Hello” + “World!”);
Jan. 2004 40
Print StatementsPrint Statements
• Using print() instead of println() does not break the line.• Example:
System.out.print(“Hello”);System.out.print(“World!”);System.out.println();
• This will yield the same output as the previous example.• System.out.println() breaks the line and flushes the output.
Jan. 2004 41
new Operatornew Operator
• The new operator is used for creating new instance of classes or objects.
• To create a new object, use the new operator with the name of the class you want to create an instance of, then parentheses after that.
String str = new String();Random r = new Random();Triple origin = new Triple();
- The parentheses need not be empty; they can contain arguments that determine the initial values of instance variables or other properties.- Example:
Point pt = new Point(0, 0);
Jan. 2004 42
new Operatornew Operator
• The number and type of arguments that can be used in the parentheses with new are defined by the class’ constructor method.- Example:
Date d1 = new Date();Date d2 = new Date(71, 7, 1, 7, 30);
Date d3 = new Date(“April 3 1993 3:24 PM”);
Jan. 2004 43
Class Date {… …Date ( ) { … }Date (int x, int y, int z, int u, int v) { … }Date (String s) { … }… ...
}
ConstructorsConstructors
Jan. 2004 44
ConstructorsConstructors
• In the above example, we have shown three different constructors for the Date class. This is called method overloading or in this case constructor overloading.
• Overloading is when you have methods with the same name but with different arguments. The compiler will distinguish between the methods by different arguments- different arguments mean
different number of arguments ordifferent type of arguments
Jan. 2004 45
ConstructorsConstructors
• Constructors are special methods that are used to initialize new object, set its variables, and perform any other functions the object needs to initialize itself.
• These methods are called by Java automatically when you create a new object.
• Constructors always have the same name as class with no return type.
• For example, say we had a class Circle and always wanted the center to start at (100, 100).
Jan. 2004 46
ConstructorsConstructors
Class Circle {int x, y;Circle( ) {
x = 100;y = 100;
}…
}• So every time we create an object of class Circle, the
constructor will be called automatically setting x and y to 100, respectively.
Jan. 2004 47
Backslash codes:
Code Meaning code Meaning\b Backspace \N Octal constant\n Newline (where N is 0 to 7)\r Carriage return \NN Octal constant\f from feed (where N is 0 to 7)\t Horizental tab \MNN Octal constant\” Double quote (where M is 0 to 3 and\’ Single-quote character N is 0 to 7)\0 Null \uxxxx Unicode character\\ Backslash (where xxxx are four
hexadecimal constants)