cop3804 - intermediate java review of cop2250 concepts

Post on 25-Dec-2015

227 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

COP3804 - INTERMEDIATE JAVA

Review of COP2250 Concepts

Java Development Kit (JDK)• The JDK provides the environment required to program in

Java.

• It includes:• the Java Virtual Machine• tools like javac.exe, java.exe, javadoc.exe• an extensive library of classes ready to be used in your applications

• Can be downloaded from: http://www.oracle.com/technetwork/java/javase/downloads/index.html

Application Programming Interface (API)

• The API is the library of classes (organized by packages) provided by the Java platform that is suitable for use in your own applications.

 • http://docs.oracle.com/javase/7/docs/api/index.html

Structure of a Java Program

public class ClassName

{

public static void main(String args[] )

{

// program execution begins here

}

}

Variables• Named storage location in the computer’s memory.

• Used as placeholders for information that might change throughout the execution of the program.

• Naming Convention:• Use descriptive names.• Use “camel case” beginning with a lowercase letter.• May use letters, digits, and underscore.• Do not use reserved words, spaces, or symbols.• Variable names are case sensitive.

 • Variable Declaration Syntax:

typeName variableName = value;

or

typeName variableName;

Variable Assignment• Variable values are changed with the assignment operator

(=).

• The expression to the right of the assignment operator is evaluated and the result is stored in the variable. The resulting value must have the same type as the variable.

Kinds of Variables• Instance Variables (Non-Static fields) – values are unique

to each instance of a class (objects).

• Class Variables (Static fields) – there is only one copy of this variable to be shared among all objects of the class.

• Local Variables – only visible to the method or block of code in which they are declared.

• Parameters – extra information passed to methods.

Data Types• Programs process values of different types: numbers, strings, etc. The type determines the

operations that may be performed, the amount of memory the variable uses, and the way the variable formats and stores data.

 • Variables may be of reference data type or primitive data type. Reference variables store

the address of an object in memory whereas primitive data types store a simple value.

 

Primitive Data Types • byte, short, int, and long for whole numbers• float and double for numbers with a fractional part • boolean• char

• A literal is a fixed value written in the code that may be assigned to a variable of a primitive type.

• Special support is provided for the java.lang.String class. Enclosing a character string within double quotes automatically creates a new String object; for example, String s = "this is a string";

Conversion between Primitive Data Types

double

float

long

int

short

byte

holds larger value

holds smaller value

• Converting from a type that holds a smaller value to a type that holds a larger value happens automatically.

• To convert the other way around, use the cast operator.

floating point

integer

Wrapper Classes• A class that contains a primitive type value.• The Java platform provides wrapper classes for each of the

primitive data types:• Byte• Boolean• Character• Double• Float• Integer• Long• Short

• The BigDecimal and BigInteger classes are used for high-precision calculations.

Cast Operator• The cast operator lets you manually convert the data type

of a value into another data type.

• Write the cast operator in front of the expression that needs to be converted.

• Syntax: (typeName) expression

• When casting from a double to an int, the fractional part gets discarded.

Constants• Values that do not change throughout program execution.• Identified with the reserved keyword final.• Naming convention: use all uppercase letters and

underscores.• May be declared locally inside a method, but if they are

needed in several methods, then they can be declared with the instance variables of the class as static and final.

• They may be declared as public since they cannot be modified.

• Example: Math.PI

Operators• Operators perform an operation on operands and return a

result.

• Assignment Operator: =

• Combined Assignment Operators: += -= *= /= %=

• Arithmetic Operators:• Addition + (also used for String concatenation) • Subtraction - • Multiplication *• Division / • Remainder %

Operators• Unary Operators:

• Unary plus + indicates positive value • Unary minus - negates an expression • Increment ++ increments a value by 1• Decrement -- decrements a value by 1• Logical complement ! inverts the value of a boolean

Operators• Equality and Relational Operators:

• Equal to == • Not equal to !=• Greater than >• Greater than or equal to >=• Less than <• Less than or equal to <=

• Logical Operators:• AND &&• OR ||

Operators and their Precedence

Operators Precedence

postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative * / %

additive + -

relational < > <= >= instanceof

equality == !=

logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= %=

Strings• Objects that represent a sequence of characters.

• The concatenation operator (+) is used to join strings together.

• When using + operator, if either expression is a string, the other one is converted to a string automatically. For objects, the toString method is invoked.

• Use a backslash as an escape character within string literals.i.e. “She said \”hello\”.”

Strings• To convert a string that has a numeric value into a

number, you may use the following methods:• Integer.parseInt converts a String to an int• Double.parseDouble converts a String to a double• Integer.valueOf converts a String to an Integer• Double.valueOf converts a String to a Double

• Use the equals method to compare two strings.

If Statements• Used to implement decisions in your programsif (amount <= balance) balance = balance - amount;

else

balance = balance – OVERDRAFT_PENALTY

Dangling Else ProblemThis may happen if you don’t have curly braces around nested if statements.

For example:

if( richter >= 0 )

if( richter <= 4 )

System.out.println(“The earthquake is harmless”);

else

System.out.println(“Negative value not allowed”);

An else clause gets paired with the nearest previous if clause that doesn’t already have an else.

Switch Statement• The switch statement compares a single value to multiple

constant alternatives.

• It can have a number of possible execution paths (when the break keyword is not used for some cases).

• The values in the case clauses must be constants.

• The values must be integers, characters, enumerations and as of Java 7, strings.

Conditional Operator• condition ? value1 : value2

• If the condition is true the value returned is value1, otherwise it’s value2.

For example:

y = x >= 0 ? x : -x;

Is equivalent to:

if (x >= 0)

y = x;

else

y = -x;

Formatting output• The printf method of the PrintStream class allows you to format your

output.• The first parameter is a string that includes format specifiers. The

rest is the arguments referenced by the format specifiers.

• %[flags][width][.precision]conversion-character

• Flags: • - : left-justify • + : output a plus ( + ) or minus (-) sign for a numerical value• 0 : forces numerical values to be zero-padded • , : comma grouping separator (for numbers > 1000) • : space displays a minus sign if the number is negative or a space

if it is positive

Formatting Output• Conversion Characters for the printf method

• d : decimal integer [byte, short, int, long]• f : floating-point number [float, double]• c : character Capital C will uppercase the letter • s : String Capital S will uppercase all the letters in the

string

While Loops• While loops are used to execute a block of code

repeatedly.

• A condition determines how many times the block of code executes.

• Syntax: while (condition)

statement

For Loops• For loops are used to repeatedly execute a block of code

for a specific number of times: from a start value of a variable to an end value.

• During each iteration, the variable gets incremented/decremented by a constant value.

• Syntax: for (i = start; i <= end; i++)

{ …

}

Reading and Writing to Files• The Scanner class breaks its input into tokens using a

delimiter pattern, which by default matches whitespace.

• The resulting tokens may then be converted into values of different types using the various next methods.

• You have used this class with System.in to prompt the user for values. We'll be using it now with a File object.

• The PrintWriter class prints formatted text to an output stream. We'll use it to print to a file.

• The FileWriter class lets you append data to an existing file.

Method Declaration• Syntax of a method implementation:

accessSpecifier returnType methodName(parameter list)

{

// body of the method

}

• Examples: public String getLetterGrade()

{

return letterGrade;

}

private String toProperCase(String str)

{

}

Parameter vs. Argument• Parameters refers to the list of variables in a method

declaration.

• Arguments are the actual values that are passed in when the method is invoked.

• When you invoke a method, the arguments used must match the declaration's parameters in type and order.

Call by value vs. call by reference• Parameter variables come into existence when the method

starts getting executed and they cease to exist when the method finishes.

• As the method starts, the parameter variable is set to the same value as the corresponding argument.

• If the parameter variable gets modified inside the method, that has no effect on the argument because they are separate variables.

• If the argument is a reference to an object, then mutator methods may be used inside the method to modify the state of the object.

Arrays• An array is a container object that holds a group of values of a single type. • The length is established when the array is created. After creation, its length

is fixed.• Each item in an array is called an element, and each element is accessed by

its numerical index.• The java.util.Arrays class provides some Array methods.

ArrayLists• Unlike arrays, array lists grow and shrink dynamically.• You don’t need to specify the size during its declaration.• All elements in an array list have to be objects, not

primitive values.• Syntax to create an array list:

new ArrayList<typeName>()

• The ArrayList class provides methods such as:• add• insert• remove• set• get

Enhanced For Loop• Iterates through all the elements in an array or array list.• It allows you to get the elements but not modify them.

Length of Array, ArrayList, and String• You get the length of an Array, an ArrayList and a String in

different ways:• For an Array, use the length property.• For an ArrayList, use the size() method.• For a String, use the length() method.

References

• Horstmann, Cay. Big Java 4th ed. New York, USA: John Wiley & Sons, Inc., 2010.

• Oracle. The Java Tutorials, 2013. Web. 25 Aug. 2013. http://docs.oracle.com/javase/tutorial/index.html

• Gaddis, Tony, and Godfrey Muganda. Starting out with Java: from Control Structures through Data Structures 2nd ed. Boston, USA: Addison-Wesley, 2012

top related