Notes On Java Programming Liang
Notes On Java Programming Liang
Blocks of Code
A code block is a grouping of two or more statements, enclosed between opening and closing curly
brackets. A code block is a logical unit that can be used anywhere a single statement can.
Page 4 of 25
Example:
int count = 15;
double x = -5.96;
String hello = “Hello World”;
System.out.printf(“count = %d, x = %f, the string is %s\n”,
count, x, hello);
Data Types
• In Java, all variables have a type.
• Two categories of built-in data types
o Object-oriented types -- defined by classes
Page 5 of 25
Character Type
• Assign a value to a character type variable as follows
char xch;
xch = 'X'; // use single-quotes to assign a specific character
xch = 75; // Assign the character at ASCII code 75 to xch
Boolean Type
• The boolean type represents true / false values.
• Java defines the value using the keywords true and false.
• The outcome of a relational operator is a boolean value. E.g.
\\ Backslash
\r Carriage return
Page 6 of 25
\n New line
\f Form feed
\t Tab
\b Backspace
\s Space
• String literals
o A string is a set of characters enclosed by double quotes. E.g.
"this is a test"
o In addition to normal characters, a string literal can include any of the escape sequences listed
above.
int a = 9;
double x, y = -4.5, z = 0.25, w; // y and z are assigned initial
values
• It is possible to define a variable and initialize it dynamically, using any element valid at the time
of initialization, including literals, other variables, and even calls to methods. E.g.
Operators
• A operator is a symbol that tells the compiler to perform a specific mathematical or logical
manipulation.
Arithmetic Operators
Operator Meaning
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
• When the division (/) operator is applied to two integer operands, the remainder will be
truncated.
• The modulus operator (%) applied to two integers will return the remainder.
• Thus, for integers a and b
a = (a/b)*b + (a%b)
Operator Meaning
== Equal to
!= Not equal to
• Logical operators
Operator Meaning
& AND
| OR
^ XOR
|| Short-circuit OR
! NOT
Page 9 of 25
Shorthand Assignments
• The shorthand assignment operators are really compound statements
+= x += 5 is equivalent to x = x + 5
-= x -= y is equivalent to x = x - y
*= x *= -6 is equivalent to x = x * (-6)
/= x /= 2 is equivalent to x = x/2
%= x % 3 is equivalent to x = x % 3
|= A |= B is equivalent to A = A | B
^= A ^= B is equivalent to A = A ^ B
(target-type) expression
o Examples
double x, y;
int i;
• When a cast involves a narrowing operation (e.g. int cast to a byte), information may be lost.
Expressions
Type Conversion in Expressions
Page 10 of 25
o Within an expression, it is possible to combine two or more data types, as long as they are
compatible with each other.
o When mixing two or more data types in an expression, all are converted to the same type, using
Java's type promotion rules.
• char, byte, short are all converted to int.
• If one of the items is long, then all are converted to long.
• If one is float, then all are converted to float.
• If one is double, then all are converted to double.
The standard logical operators (&, |, and ^) evaluate both operands, even if the first operand
determines the outcome of the operation.
The short-circuit logical operators will skip evaluation of the second operand, if the first operand
determines the outcome.
In some cases, the shorthand assignment may be more efficient for the JVM to execute.
Page 11 of 25
Chapter 3: Selections
The if Statement
• The complete form of the if statement is
if (condition)
{
Statements …
}
else
{
More statements …
}
• The statement following the condition can be a single statement, in which case you do not need
to include brackets.
• An if-else-if ladder can be created as follows:
if (condition)
{
Statements …
}
else if (condition 2)
{
Statements 2 …
}
else if (condition 3)
{
Statements 3 …
}
…
else
{
More statements …
}
switch (expression) {
case constant1:
statement sequence …
break;
Page 12 of 25
case constant 2:
statement sequence …
break;
..
default:
statement sequence …
}
Conditional Statements
General format for conditional assignment statements
variable-name = (expression) ? value_1 : value_2;
The expression must evaluate to either a boolean value.
• Assign value_1 to variable-name if the expression is true.
• Assign value_2 to variable-name if the expression is false.
Example
y = (x < 0) ? -1 : 1;
In this example, if x < 0, y is assigned -1. Otherwise, it is assigned 1.
Page 13 of 25
Method Description
Trigonometric Methods
sin(radians)
cos(radians)
tan(radians)
asin(radians)
acos(radians)
atan(radians)
toRadians(degree)
toDegree(radians)
PI Static variable (constant)
Exponent Methods
exp(x) e raised to the power x
log(x) Natural logarithm
log10(x) Base-10 logarithm
pow(a, b) a^b
sqrt(x)
Rounding Methods
ceil(x) Returns double; x rounded up
floor(x) Returns double; x rounded down
rint(x) Returns double; rounds up or down
to nearest integer
round(x) Returns int if x is float, and long if x is
double. Value = Math.floor(x +
0.5)
min, mx, and abs Methods
min(a,b) Works with int, long, float, double
max(a,b)
abs(a,b)
Page 14 of 25
random Method
random() Returns a random double between ≥
0 and < 1.
Method Description
Simple Methods
int length() Returns the number of characters in the string
char charAt(index) Returns the character at the specified index (first index
is 0) of the string.
String concat(s1) Returns a string that concatenates string s1 to the
current string.
String toUpperCase() Returns a string with all characters of the original
string converted to upper case.
String toLowerCase() Returns a string with all characters of the original
string converted to lower case.
String trim() Returns a string that eliminates whitespace characters
at both ends of the string (‘ ‘, \t, \f, \r, or \n).
Comparing Strings
boolean equals(s1) Compares the contents of the current string to the
contents of s1
boolean
equalsIgnoreCase(s1)
Page 15 of 25
Examples
String message = “Welcome to Java”;
int I = message.length(); // I = 15
char c = message.charAt(0); // c = ‘W’
String s3 = s1.concat(s2);
alternatively, Java provides the following shorthand for concatenating strings
String s3 = s1 + s2;
String s3 = message.toUpperCase(); // s3 = “WELCOME TO JAVA”
Note that to compare the contents of two strings, you should use the equals() method, rather than
the == operator.
s2 == s1; // True if and only if s2 and s1 point to the same
object.
s1.equals(s2); // True if and only if s1 and s2 point to strings
containing the same content.
Page 16 of 25
Chapter 5 Loops
The for Loop
• The for loop will work with a single statement, or a block of statements, enclosed in brackets.
• The general form of a for loop is as follows:
• The initialization is usually an assignment statement that sets the initial value of the loop
control variable.
• The condition is a boolean expression that determines whether or not the loop will repeat.
• The iteration expression defines the increment of the loop control variable each time the loop is
repeated.
• The loop will continue to execute as long as the condition is true.
• The conditional expression is always tested at the top of the loop; the statement sequence
inside the loop will not be executed at all of the condition is not true to begin with.
while (condition) {
statement sequence …
}
do {
statement sequence …
Page 17 of 25
} while (condition);
• The condition is not checked until the end of the loop, so the do-while loop is guaranteed to
execute at least once.
Use continue
• Use control to force an early iteration of a loop, bypassing the remaining statements in the body
of the loop.
• For while and do-while loops, continue causes the program flow to go straight to the conditional
test.
• For a for loop, continue triggers the iteration and then the conditional test.
int i;
for (i = 0; i <= 100; i++) {
if (i % 2 != 0) continue;
System.out.println(i);
}
Page 18 of 25
Chapter 6: Methods
Methods are subroutines that manipulate the data defined by the class, and in many cases provide
access to that data.
Methods must be members of a class.
• General form of a method
{Optional modifiers} return-type methodName(parameter-list) {
// body of method
return val; // only if return-type is not void
}
• Use the return statement to exit a method and return a specific value. The value must be of
the type return-type.
• If the method has no value to return, then its return type must be void.
It is possible to pass one or more values, called parameters, to a method when it is called.
• The parameter values can be used within the method to calculate the return value or to modify
the instance variables of the class of which the method is a member.
The {Optional modifiers} in the general form include public and static:
• A public method is one that is visible outside of the class and package in which it was defined.
• A static method is one that can be called without creating an object of the class in which it is
defined.
Examples
public static int sum(int i1, int i2) {
int result = 0;
for (int i = i1; i <= i2; i++) result += i;
return result;
}
Creating arrays
o Separate statement following array variable declaration:
arrayRefVar = new elementType[arraySize];
o Alternatively, combine the declaration and assignment into one statement:
elementType[] arrayRefVar = new elementType[arraySize];
or
elementType arrayRefVar[] = new elementType[arraySize];
Initializing arrays
o First way: assign values after array has been created. For example
myList[0] = 5.6;
myList[1] = 4.5;
…
myList[9] = -11.6;
o Alternatively, we can use the array initializer shorthand
double[] myList = {1.9, 2.9, 3.4, -3.5};
Array Size
Getting array size from the length variable. Returning to the previous example
myList.length // myList.length has the value 10
Note that Java provides another type of for loop – called a “foreach” loop – which traverses the
elements in the array without an explicit reference to the index of each element.
For example,
for(double elem : myList) {
System.out.println(elem); // Prints out each element
}
Array sorting
Arrays.sort(arrayName); // sorts the entire array
/* To sort only a subset of indices, use the following */
Arrays.sort(arrayName, fromIndex, toIndex);
x = 10;
}
}
It is typically desirable to pass parameters to the constructor to be used when initializing an object. For
example,
class MyClass {
int x;