day 4 objectives constructors wrapper classes operators java control statements practice the...

24
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language

Upload: clifford-barton

Post on 24-Dec-2015

230 views

Category:

Documents


0 download

TRANSCRIPT

Day 4 Objectives

• Constructors

• Wrapper Classes

• Operators

• Java Control Statements

• Practice the language

ConstructorsA constructor is a method that constructs objects of its class.

When we define a constructor for a class, it is defined much likewe define other methods for a class. The rules are as follows:

• A constructor must have the same name as the class itself.• A constructor cannot specifically define a return value.

When you create an object you use the following syntax:

House mc = new House();

So, we’ve used constructors before, we just were not aware of it.

When we created objects of type House we used the default constructor.

Call to the Objectsdefault constructor

Constructors• If we do not explicitly define our own constructor for a Class, Java automatically generates a default constructor that has no arguments.

• Default constructors are used simply to create objects of a Class and are called via the new operator.

• As soon as we declare our own constructor for a Class the default constructor can no longer be used.

Why would we define our own constructors?

• Not only are constructors used to create objects of a particular class, they are also commonly used to initialize the fields (variables) of an object.

Creating Constructors• If we were to create a constructor for our MyCar class it may look something like the following:

public class House {private int width;private int length

public MyCar(int theWidth, int theLength) {length = theLength;length = theWidth;

}}

House mc = new House(42, 35);

• Lets create a Class that uses a constructor to initialize it’s fields

Wrapper Classes• Wrapper Classes are a set of classes that allow us to use primitive types, such as integers, in places where we need an object.

• When you create objects from Wrapper classes the object ‘wraps’ itself around a primitive data type.

• You can then use the methods available from that object to manipulate the value wrapped.

• Every primitive data type has an associated wrapper class in the java.lang package.

Why use Wrapper Classes?• You may need to convert a String to an actual number.• You may need to take a primitive and convert it to some other type.• Some classes can only deal with other objects. Not primitives.

Wrapper Primitive

Boolean boolean

Byte byte

Character char

Double double

Float float

Integer int

Long long

Short short

Wrapper Classes Start with a capital letter.

Character and Integer wrapper Classes have long names instead of just the short version.

Wrapper Classes

An example of the Integer wrapper class:

int x = 15;int y;int z;

String mark = “85”;

Integer m = new Integer(mark);

y = m.intValue();z = x + y;

What does z equal?

• Lets build a Java app that demonstrates wrapper classes.

Java OperatorsImportant Java Operators

! Logical Notnew Object Creation(type)expression Casting (Type Conversion)* Multiplication/ Division+ Addition

String Concatenation- Subtraction+= Used for incrementing numeric values

or used for concatenating Strings.

int a = 10;a+=2;a is now equal to 12.

int a = 10;a = a + 2;a is now equal to 12Same

Results

Java Operators

< Less Than> Greater Than>= Greater than or equal to<= Less than or equal to= = Equal to!= Not equal to&& Logical AND|| Logical OR= Assignment (Set Equal To)

CastingFor primitive data types we have to explicitly use a cast operatorif we wish to cast from a larger data to a smaller data type.

Example:double a = 3.34d;float b;

The following line will fail because we are trying to assigna float value to an int. Floats have a larger range of valuesand so we have to specify an explicit cast.

b = a; Will fail.

b = (float)a Will compile. (float) is the cast operator.

Casting• If we want to assign a variable of a smaller data type to a variable of a larger data type no explicit cast is needed.

Example:long a;int b = 500;

a = b;

• We are assigning a variable of type int (b) to a variable of type long (a)

• No explicit cast is needed because (a) has a larger range of values than (b).

• Lets demonstrate with an example.

Control Structures

If Statements ([ ] means optional)

if (boolean_expression) {statement_or_block

}[else {

statement_or_block}]

• The else clause is optional

Control Structures

int x = 4;

if (x = = 10) {System.out.println(“x is equal to 10”);

}else {

System.out.println(“x not equal to 10”);}

Important Note:

Note the difference between the assignment operator and the equality operator. The single ‘=‘ assigns a value to avariable. The ‘==‘ evaluates for equality.

Control Structuresif statementsYou can also nest if statements or use else ifsint x = 125;

if (x > 100) {if (x > 150) {

System.out.println(“Greater than 150”);}

}else if (x > 50) {

System.out.println(“Greater than 50”);}else {

System.out.println(“50 or less”);}

Control Structuresswitch statements

Use the switch statement to select one or more alternativestatements or blocks of code to execute.

switch (integral_expression) {case selector1:

statements or blocks[break;]

[case selector2:statements or blocks]

[….][default:

statements or blocks]}

Control Structures• The expression following the switch statement must have type byte, short, int, or char.

• Any number of case labels are allowed.

• The label default is optional. It can be anywhere in the switch statement, but is typically at the end.

• The integeral_expression is evaluated. Control then goes to the first case label where the value of the selector equals that of the switch expression. No further matching will be done.

• If none of the labels match the expression and a default label is present, control will pass to the statements following the default label.

• Using break is optional, but is very common.

Control Structuresswitch statementsint x = 40;

switch(x) {case 40:

System.out.println(“x = = 40”);break;

case 50:System.out.println(“x= = 50”);break;

default:System.out.println(“Some other

value”);}Output will be: x = = 40

Control Structuresfor statements

Use a for loop when you know in advance how many times to repeat the loop.

for (initialization; termination_expression; step) {statement_or_block

}

for (int i = 0; i < 3; i++) { Output:System.out.println(i); 0

} 1 2

Control StructuresIf the counter (i) is declared and initialized in the for loop thescope of i is inside the loop only.

for (int i = 0; i < 3; i++) {System.out.println(i);

}System.out.pritnln(i); Program will fail here.

If the counter is declared outside the loop and used as the counterthe variable can be seen outside of the for loop.

int i;for (i = 0; i < 3; i++) {

System.out.println(i);}System.out.println(i); Program will proceed.

Control Structures

while statements

while (boolean_expression) {statement_or_block

}

Example:

int i = 0;

while ( i <= 2) {i++;System.out.println(“i= “ + i);

}

Output will be:i=1i=2i=3

Control Structuresdo statements

Use do statements to program conditional loops when you wantto force the body of the loop to execute at least once.

int x = 0;Output will be:

do {x++; 1System.out.println(x); 2

} while (x <=2); 3

Control Structures

Getting out of loops

You can leave loops prematurely with the keywords break andcontinue.

break will terminate the loop and give control to the next statementoutside the loop.

Continue will terminate the current iteration of the loop only.

Control passes to the top of the loop where the boolean expressionis evaluated to determine whether to pass through the loop again.

Control Statements

Example of break and continue inside loops

for (int k = 0; k <=5; k++) {if (k = = 3) {

break;}System.out.println(“loop count “ + k);

}

The output is:

loop count 0loop count 1loop count 2

Control Structures

for (int k = 0; k <=5; k++) {if (k = = 3) {

continue;}System.out.println(“loop count “ + k);

}

The output is:

loop count 0loop count 1loop count 2loop count 4loop count 5