Title: Java Basics II
1Java Basics - II Yangjun Chen Dept. Business
Computing University of Winnipeg
2Outline Java Basics - II
- Modifiers (Specifiers)
- Statements
- Array
- Control flow
- - condition statements
- if
- switch
- - loop structure
- for
- while
- do
- others String, print, new, constructor
3Modifiers
- Modifiers are special keywords that modify the
definition of a class, method, or variables.
modifiers
Modifiers for methods
Modifiers for variables
Modifiers for classes
4Modifiers for Methods and Variables
- static
- final
- private
- protected
- public
-
access modifiers
5Modifiers 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.
6Modifiers for Methods and Variables
Class Circle static double
PI3.141592635 double radius double
circumference double diameter
7Modifiers for Methods and Variables
- Here, PI shouldnt 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 PI3.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.
8- Difference between instance and class variables
- Class Circle
- static double PI3.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 -
-
9- Difference between instance and class methods
- Class 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()
-
-
10Modifiers for Methods and Variables
- There are three access modifiers in Java
- - private
- protected
- public
- 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
11Modifiers for Methods and Variables
- protected Access Modifier
- - The protected modifier allows access to a
member within the same package and within any
subclasses. - - We wont 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
12Modifiers 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.
13Statements
- 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 spnew Point(45, 15),
ep final int Max100000 - int almostMaxMax - 500
14Statements
- 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
15Statements
- 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.
16Statements
- - Example
- double magnitude(double x, double y)
-
- double sqrSum xx yy
- 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)
-
17Array
- 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 cant 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 int10
- - 3. Store things in the array
- temp0 6
18Array
- 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
19Multidimentional Array
- This is just an array of arrays and is declared
in the same manner as regular arrays. - - Example int temp new int105
- - 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,
- temp63 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
20if 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.
21if 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
- else
- statement2 //expression is false
22switch 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.) -
23switch Statement
Switch (expression) case constant1 some
statements case constant2 some
statements default some statements
//end of switch
24switch 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. -
25switch Statement
Switch (expression) case constant1 some
statements break case constant2 some
statements break default some
statements //end of switch
26for 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. -
27for 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 lt 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
-
28for Statement
- So the for loop looks like this
-
- for (int i 0 i lt 10 i )
-
- System.out.println(i)
- //end of the for loop
- What is the output?
-
29while 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.
30do 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.
-
31Loop 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
-
32 int i 0 label for (int j 0 j lt 10
j) while (i lt 10) System.out.println(
i) break i
33 label for (int j 0 j lt 10 j) int
i 0 while (i lt 10) System.out.println(
i) continue i
34 int k0 label for (int j k j lt 10
j) int i 0 while (i lt 10)
System.out.println(i) k continue
label
35 label for (int j 0 j lt 10 j) int
i 0 while (i lt 10) System.out.println(
i) break label i
36big_loop while (!done) if (test(a, b) 0)
continue //Control goes to point 2 try
for (int j 0 j lt 10 j) if (aj
null) continue //Control goes to
point 1 else if bj null) continue
big_loop //Control goes to point 2 doit(aj,
bj) //point 1. Increment and start loop
again with the test finally
cleanup(a, b) //point2. Start loop again
with the (!done) test
37break_test if (check(i)) try for (int j
0 jlt10 j) if (j gt i )
break //Terminate just this loop. if
(aij null) break break_test //Do the
finally clause and //terminate the if
statement. finally cleanup(a, i, j)
38Strings
- 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 myStringBrand 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.charAt0
39Print 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!)
-
40Print 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.
41new 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)
42new 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 324 PM)
43Constructors
Class Date Date ( )
Date (int x, int y, int z, int u, int v)
Date (String s) ...
44Constructors
- 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 or
- different type of arguments
45Constructors
- 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).
46Constructors
- 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.
47Backslash codes Code Meaning code Meaning \b Ba
ckspace \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)