Introduction to Programming in Java
Patrick edit Master subtitle style Click toMichael Chiuco
8/8/12
Background
8/8/12
What is Java?
Historically came from C and C++, but simpler object models and fewer low level functions. Compiled into bytecode that runs on Java Virtual Machines (write once run anywhere)
8/8/12
So how is Java different?
Java is interpreted rather than translated through the bytecode Compared to C and C++, Java has garbage collection (from automatic memory management) Unfortunately it is also slower
8/8/12
class Test{ public static void main (String args[]){ System.out.println(Hello World!); } }
8/8/12
Lets start programming in Java!
Basic java programming
8/8/12
Basic Java Programming
Identifiers, Data types, variables, and literals
8/8/12
Programming in Java
Identifiers any name in Java
Properties: Cannot start with a digit Must start with an underscore or alphanumeric character The only allowed symbols are underscores and currency symbols
1. 2.
3.
8/8/12
Programming in Java
4. 5.
Case sensitive Reserved words cant be used. mynam3 my#name myname$
Examples: myname myName my_name
8/8/12
Variables in Java
Java is statically typed, meaning the data type and variable name should be written explicitly
Example: int x = 0; char start = a;
8/8/12
What are the are readily available?
boolean byte short int long float double char true or false -2^7 to 2^7 - 1 -2^15 to 2^15-1 -2 ^ 31 to 2 ^ 31-1 -2 ^ 63 to 2 ^ 63 - 1 1.40129846432481707e-45 to 3.40282346638528860e+38 4.94065645841246544e-324d to 1.79769313486231570e+308d 0 to 65,535
8/8/12
So what are Literals?
A Java literal is any constant value associated with a variable. Three reserved words can be literals: true, false and null
Examples: int x = 128; char start = x; byte l = 127;
8/8/12
Concatenating Strings
To concatenate strings we can do either:
Hey! + I just met you + and + this is crazy Call me".concat(maybe");
8/8/12
How do I declare an array?
Syntax: int[] <var_name> = new int[<size>] Where: <var_name> = variable name <size> = size of the array Example: int[] arr = new int[10];
8/8/12
Are there multi-dimensional arrays?
Yes of course!
Examples: int[][] x = new int[10][10]; char [][][] stack = new char[10][5][5]; The syntax is practically the same!
8/8/12
How do I access array values?
Java has implemented a zeroindexing scheme (starts with 0) for their arrays.
int[] x = {1,2,3,4,5,6,7}; x[6] = 7;
8/8/12
How do I get the array length?
Java arrays have an attribute named length and can be accessed as such:
int x = {1,2,3,4,5,6,7,8,9}; int y = x.length; System.out.println(y); //prints 9
8/8/12
Basic Java Programming
Operators and Flow control
8/8/12
What are Arithmetic Operators
They are operators used to perform basic numerical manipulation.
8/8/12
Unary Operators
Previous code: x = 1; Increment
Increases the value by one Example: System.out.println(++x); //prints 2
Decrement
Decreases the value by one Example: System.out.println(--x); 8/8/12
Unary Operators
Note:
++x is not the same as ++x (the same goes with decrementing) Try System.out.println(--x); And System.out.prinln(x--);
8/8/12
Additive Operators
Previous code: int x = 1; int y = 2; Addition (+) Adds two numbers on either side Example: x + y = 3; Subtraction (-) Subtracts two numbers on either side. Example: y - x = 1 8/8/12
Multiplicative Operators
Previous code: int x = 1; int y = 2;
Multiplication (*)
Multiplies two numbers on either side. Example: x * y = 2
Division (/) Divides two numbers on either side. Example: x/y = 0; //because they are integers 8/8/12
Multiplicative Operators
Previous code: int x = 1; int y = 2;
Modulus
Gets the remainder of the two numbers. Example y % x = 0;
8/8/12
Operators and Flow Control
Relational operators
8/8/12
Relational Operators
Previous code: int x = 1; int y = 2; Greater than(>) Checks if left operand is greater than the right operand Example: y > x is true Less than (<) Checks if the left operand is greater than the right operand
8/8/12
Relational Operators
Previous code: int x = 1; int y = 2; Greater than or equal(=>) Checks if left operand is greater than or equal the right operand Example: y >= x is true Less than (<=) Checks if the left operand is greater than the right operand
8/8/12
Relational Operators (Equality)
Previous code: int x = 1; int y = 2; Equal to (==) Checks if the two values are equal Not Equal to (!=) Checks if the two values are not equal
8/8/12
Operators and Flow Control
Logical operators
8/8/12
Logical Operators
Previous code: boolean x = true; boolean y = false;
&& (AND) True only when both operands are true Example: x && y is false || (OR) True when one of the operands are 8/8/12 true
Logical Operators
Previous code: boolean x = true; boolean y = false;
! (Negation) Negates the value of the operand Example: !x is false
8/8/12
Logical Operators
<condition>?<if_true>:<if_false> (Ternary Operator) A short hand for the if-then-else statement. boolean check = true; int x = check ? 1 : 2;
8/8/12
Logical Operators
The following is an equivalent to the previous code.
if(check){ x = 1; }else{ x = 2; } 8/8/12
Operators and Flow Control
Assignment operators
8/8/12
Arithmetic Assignments
+=, -=, *=, /= and %=
These operators do the arithmetic and assume the first operand to be the assignee Example: C += A is equal to C = C + A C -= A is equal to C = C - A
8/8/12
instanceof Operator
instanceof checks if a certain variable is an instance of a certain object Car a = new Car(); boolean b = a instanceof Car; Note: does not work on unrelated classes.
8/8/12
Operator Precedence
Category Postfix Unary Multiplicative Additive Shift Relational Equality BitwiseAND BitwiseXOR BitwiseOR LogicalAND LogicalOR Conditional Assignment Comma Operator ()[].(dotoperator) ++--!~ */% +- >>>>><< >>=<<= ==!= & ^ | && || ?: =+=-=*=/=%= >>=<<=&=^=|= , Associativity Lefttoright Righttoleft Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Lefttoright Righttoleft Righttoleft Lefttoright
8/8/12
Operators and Flow Control
Flow control
8/8/12
If-then statements
if (<boolean statement>){ } Example: int i = 0 if( i == 0){ System.out.print(i); } 8/8/12
Example
if(<boolean statement>){ }else{ } Example: int i = 0
8/8/12
If-then-else statements
The if-then statement can be extended to use else or elseif. As in:
if(<boolean statement>){ }else{ }
OR
if(<boolean_statement>){ }else if(<boolean_statement){ }else{
8/8/12 }
Example
String callme = ;
if(callme.equals(maybe)){ System.out.println(Call me); }else if(callme.equals(I just met you)){ System.out.println(This is crazy); }else{ System.out.println(This is not Carly Rae); } 8/8/12
Case Statement
int month = 8; String monthString; switch (month) {
case 1: monthString = "January"; break; case 8: monthString = "August"; break; default: monthString = "Invalid month;break; } System.out.println(monthString);
8/8/12
Differences of if-then and case
If-then statements can evaluate based on expressions, values, ranges and conditions. A case statement can only evaluate based on a single enumerated value, integer or String object.
8/8/12
Operators and Flow Control
Looping statements
8/8/12
Looping Statements
while evaluates an expression and executes the statement below, while it is true. Example:
int count = 1; while(count < 11){ System.out.println(count); count ++; 8/8/12 }
Looping Statements
do-while executes the statement then evaluates the condition below. Example:
do{ System.out.println(count); count++; }while(count < 11); 8/8/12
Looping Statements
for-loop The for loop does the following:
1.
Initializes the loop counter and the loop Checks the condition Increments or decrements the counter
2. 3.
Example:
8/8/12 for(int i = 1; i<10; i++){
Looping Statements
The for loop has a special form for collections.
int[] x = {1,2,3,4,5}; for(int number: x){ System.out.println(number); }
8/8/12
Difference between the three
The for and while loops evaluate their conditions before the statements. The do-while looping evaluates the statements below it at least once.
8/8/12
Operators and Flow Control
Branching statements
8/8/12
Branching Statements
break; Breaks out of a looping or conditional statement. There two are different break types, labelled and unlabelled.
1.
2.
8/8/12
Branching Statements
Labelled break:
spaghetti: for(int j = 0; j<4; j++){ for(int i = 5; i<7; i++){ if(i == 5){ break spaghetti; } } } Note: this breaks the outer most loop.
8/8/12
Branching Statements
Unlabelled break:
spaghetti: for(int j = 0; j<4; j++){ for(int i = 5; i<7; i++){ if(i == 5){ break; } } } Note: this breaks the inner most loop;
8/8/12
Branching Statements
continue; Skips an iteration of the current loop. As with the break, it has two forms: labelled and unlabelled.
8/8/12
Branching Statements
String[] s = [Hello! , Pail]; for(string str: s){ for(int i = 0; i<str.length(); i++){ if(s.charAt(i) != l){ continue; } } }
This breaks the inner most loop
8/8/12
Branching Statements
class ContinueWithLabelDemo { public static void main(String[] args) { String searchMe = "Look for a substring in me"; String substring = "sub"; boolean foundIt = false; int max = searchMe.length() - substring.length(); test: for (int i = 0; i <= max; i++) { int n = substring.length(); int j = i; int k = 0; while (n-- != 0) { if (searchMe.charAt(j++) != substring.charAt(k++)) { continue test;
8/8/12
Branching Statements
return;
Terminates the current method call and brings back the control to the calling method. May or may not have any return value. Example:
return null; return; 8/8/12
Basic Java Programming
Java strings, and Inputoutput
8/8/12
Are there strings in java?
String s = Hello World!; Whenever a string literal is seen by the compiler, a String object is made.
8/8/12
Creating Strings
String s = Hello!; String s = new String([h,e,l,l,o]);
There are several more constructors for Strings, but these are the most common.
8/8/12
String functions you have to know
String.length(); - gets the string length String.charAt();
- gets the character at a certain point of a string
8/8/12
What is a StringBuffer?
It stores a series of characters that can be changes. String objects cant be changed.
8/8/12
StringBuilder Constructors
Constructor StringBuffer() StringBuffer(CharSequence cs) Description Creates a StringBuffer with 16 a capacity of 16 Creates a StringBuffer with a capacity of the CharSequence plus 16 Creates a String Buffer with the given capacity Creates a StringBuffer with a capacity of the given string plus 16
StringBuffer(int initCapacity) StringBuffer(String s)
8/8/12
StringBuffer Illustration
StringBuffer sb = new StringBuffer(7); String sample = HELLO; sb.append(sample);
8/8/12
Are other String representations?
A StringBuilder is basically a String that can be manipulated within the program. StringBuilders have different methods that allows parts of it to be readily manipulated.
8/8/12
StringBuilder Constructors
Constructor StringBuilder() StringBuilder(CharSequence cs) Description Creates a String Builder with 16 a capacity of 16 Creates a String Builder with a capacity of the CharSequence plus 16 Creates a String Builder with the given capacity Creates a String Builder with a capacity of the given string plus 16
StringBuilder(int initCapacity) StringBuilder(String s)
8/8/12
StringBuilder Methods
.append();
Adds the given object or data to the end of the Builder.
Ex: StringBuilder sb = new StringBuilder(Call me); sb.append(maybe); System.out.println(sb.toString());//prints Call me maybe
8/8/12
.delete()
StringBuilder Methods
.reverse()
Reverses the given sequence of Strings from the Builder. Ex: StringBuilder sb = new StringBuilder(Carly); System.out.println(sb.reverse());
.insert()
8/8/12
So what are the differences between the three?
StringBuffer and StringBuilder are changeable or mutable within the program. StringBuffer can be implemented in a threaded system. StringBuilder is faster in a singlethreaded program. 8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12
8/8/12