Basic Syntax
Syntax
• Comments
• Reserved words
• Modifiers – will cover in future classes • Statements
• Blocks
Comments
• Used to document code
– Variables – Functions – Classes
• Ignored by the compiler
Comments
• Single line comment
– Used to comment a single line of code
• Multiline comment
– Used to comment several lines of code
• Javadoc comment
– Comments that are interpreted by the Javadoc
Comments
• Single line comment
– //
• Multiline comment
– Start = /* – End = */
• Javadoc comment
– Start = /** – End = */
Comment Examples
//this is a single line commentpublic class HelloWorld //also single line comment
{
/**
* This is a javadoc comment * @param args
*/
public static void main(String args[]) {
System.out.println("Hello World“/* Comment*/);
/*
multiline comment */
Reserve Words
• Words that have special meaning to the compiler
• Part of the language syntax • Cannot be used as variables
• Example reserve words
– public, private, new, static, final, if, else, etc…
• List of reserve words
– https://docs.oracle.com/javase/tutorial/java/nutsan
dbolts/_keywords.html
Reserve Words Example
public class HelloWorld {
public static void main(String args[]) {
System.out.println("Hello World“); }
Statements
• Represent an action or sequence of actions • End all statements with semicolons
Statements Example
public class HelloWorld{
public static void main(String args[]) {
System.out.println("Hello World“);
Blocks
• Separate pieces of the program • Examples:
– Classes – Functions
– if/else blocks – Loops
Blocks Example
public class HelloWorld{//start block for the class
public static void main(String args[])
{//start block for the function
System.out.println("Hello World“);
}//end block for the function
Main Method
• The starting point of the program • Invoked by the Java interpreter
• Takes an array of strings as input parameters
– Input arguments
Main Method Example
public class HelloWorld{
public static void main(String args[]) {
//code for program here }
Example - HelloWorld
• HelloWorld.java
Variables
• Consist of letters, digits, dollar signs (‘$’) and underscores (‘_’)
• Can be any length
• Cannot start with a digit
• Cannot be a reserve word
Variable Naming Convention
• All words are combined into a single word
–Ex: “thisIsAVariableName”
• Camel Case
–First word starts with a lowercase letter –Other words start with an uppercase letter
• Variable names should be interpretable
–Ex: “userName”, “password”
–Bad example: “xxxxxxxxx”, “di3298nyqwvt”
• Do not use ‘i’, ‘j’, ‘k’, etc…
–typically used as loop variables when iterating over
Constants
• Variables that will/should never change
• Should be declared with the final key word
• Usually declared with the static key word
• By convention, should be all capital letters
• By convention, words separate by underscores
• Example: PI variable in Math class
Declaring Variables
• int x;
– Declares ‘x’ to be an integer variable
• double radius;
– Declares ‘radius’ to be a double variable
• char a;
– Declares ‘a’ to be a character variable
Assignment Statements
• Statements that assign a value to a variable
• x = 1;
• radius = 1.0;
Declaring and Initializing
• Can declare and initialize a variable in one
step
• Examples
– int x = 1;
– double d = 1.4;
Numerical Primitive Data Types
Type Bits(bytes) Minimum Value Maximum Value
byte 8 (1) -27 (-128) 27-1 (127)
short 16 (2) -215 (-32768) 215-1 (32767)
int 32 (4) -231 (-2147483648) 231-1 (2147483647)
long 64 (8) -263 263-1
float 32 (4) ~-1.4e-45 ~3.4e38
Numerical Operators
Operator Symbol Example Result
Addition + 5 + 2 7
Subtraction - 5 - 2 3
Multiplication * 5 * 2 10
Division / 5 / 2
5.0 / 2 2.52
Modulus % 5 % 2 1
Shortcut Assignment Operators
Operator LongExample ExampleShort
+= x = x + 10 x += 10
-= x = x - 10 x -= 10
*= x = x * 10 x *= 10
/= x = x / 10 x /= 10
Increment Operators
• Preincrement
– Increments the variable by 1 then evaluates the
new value
– ++x;
• Postincrement
– Evaluates the new value then increments the
variable by 1 then
– x++;
Decrement Operators
• Predecrement
– Decrements the variable by 1 then evaluates the
new value
– --x
• Postdecrement
– Evaluates the new value then decrements the
variable by 1 then
x--Example - IncrementDecrement
• IncrementDecrement.java
Floating Point Literals
• Written with a decimal point
• Default to double type
Floating Point Literals
• Examples
– double x = 5;
• 5 is considered an integer
– double x = 5.0
• 5.0 is considered a double
– double x = 5.2f
• 5.2f is considered a float
– double x = 1.5e+3
• x = 1500
Floating Point Numbers
• Not stored as exact numbers • Stored as approximations
• Example
– System.out.println(1.0 - 0.9);
– Displays 0.09999999999999998 instead of 0.1.
• Keep this in minds when using them!
– Money
Example - DoubleTest
• DoubleTest.java
Numeric Conversion Rules
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted into float.
3. Otherwise, if one of the operands is long, the other is converted into long.
Example - DividingIntegers
• DividingIntegers.java
Example - Division 1
int x = 5;int y = 2;
double z = x / y;
System.out.println(z);
Example - Division 1
int x = 5;int y = 2;
double z = x / y;
System.out.println(z); // int / int = int
// 5 / 2 = 2.5
// 2.5 gets truncated to 2
int x = 5; int y = 2;
double z = (x * 1.0) / 2; System.out.println(z);
What gets printed out? Why?
int x = 5; int y = 2;
double z = (x * 1.0) / 2; System.out.println(z);
What gets printed out? Why?
int * double double 5 * 1.0 5.0
37
int x = 5; int y = 2;
double z = (x * 1.0) / 2; System.out.println(z);
What gets printed out? Why?
double / int double 5.0/2 2.5
Character Data Type
• Can be written as ASCII or Unicode
• ASCII
– char letter = 'A';
• Unicode
– char letter = '\u0041';
• Unicode characters start with \u
• Unicode character range
– Hexadecimal ‘\u0000’ to ‘\uffff’
– 65,536 characters
• Can use increment/decrement on char variables
Escape Characters
Character Escape Sequence
Backspace \b
Tab \t
Linefeed \n
Carriage Return \r
Backslash \\
Single Quote \‘
Example - Escape Sequences
• EscapeCharacters.java
Programming Errors
• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to throw an exception
– If the exception is not caught the program will end
• Logic Errors
Syntax Error Example
public class SyntaxError{
public static void main(String[] args) {
i = 30;
System.out.println(i + 4); }
}
Runtime Error Example
public class RuntimeError{
public static void main(String[] args) {
int i = 1 / 0; }
Logic Error Example
public class LogicError {
public static void main(String args[]) {
int number = Integer.parseInt(args[0]); if(number < 5 && number > 0)
{
System.out.println(“Number is [0, 5]”); }
}
Comparison Operators
Operator Description
< Less than
<= Less than or equal to > Greater than
>= Greater than or equal to
== Equal to
One-way if Statement
if(boolean expression){
//Execute statements }
• Boolean expression is enclosed in paranthesis
• No semi-colon after boolean expression
• Optional brackets around the “if” block
One-way if Statement
boolean expression
Statements
True
Two-way if Statement
if(boolean expression) {
//Execute statements if true }
else {
//Execute statements if false }
Two-way if Statement
boolean expression
Statements
True False
Multiple if Statements
if(boolean expression){/*code*/}else if(boolean expression){/*code*/} else if(boolean expression){/*code*/} else{/*code*/}
Multiple if Statements
if(score >= 90){grade = ‘A’;}
else if(score >= 80) {grade = ‘B’;}
else if(score >= 70) {grade = ‘C’;}
else
Logical Operators
• NOT
– True when input is false
• AND
– True when all inputs are true
• OR
– True when any inputs are true
• XOR
Truth Table
55 A Value B Value NOT (!A) AND (A && B) OR (A || B) XOR (A ^
B)
FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE TRUE
Operator Precedence
• Increment and Decrement (var++, var--)
• Unary Plus and Minus (+, -) • Type casting
• Not (!)
• Multiplication, division, and remainder (*, /, %) • Binary addition and subtraction (+, -)
• Comparisons (<, <=, >, >= ) • Equality (==, !=)
• Exclusive OR (^)
Operator Precedence
• Parenthesis evaluated first
– Inner to outer
• Precedence rules are applied next
• Rules of the same precedence are evaluated left-to-right
– except for assignment operators which are
evaluated right-to-left
Loops
• for loops
• while loops
• do-while loops
While Loop
• Executes while a condition is true
while(condition) {
//execute code }
While Loop Example
int i= 0;While(i < 100) {
More While Loop Conditions
• while(true) • while(x < 5)
• while(!stack.empty())
• while(x<list.size())
• While(x < 5 && y > 0)
For loop
• for(initial actions, conditional, action after each iteration)
• Three parameters
– Initial action = takes place before the loop starts
– Conditional statement = determines if then loop continues – Action after each iteration = executes after every loop
iteration
• Any / All parameters can be empty (rarely are)
For Loop Examples
• for(int i=0; i < 7; i++)
• for(int i=0, int j=0; i<5 && j <5; i++, j=j+2)
• for(; i<7; i++)
• for(; ; x+=0.5)
Break
• Unlabeled
– Terminates the inner most loop
• Labeled
– Can terminate outer loops
Break
• Breaks the code flow • Breaks the loop logic
• Bad programming practice
• Anything coded with breaks can be done without breaks
• Only use in switch statements
Break Example
int x=0;
while(true) {
System.out.println(x); if(x > 10)
break; }
int x=0;
while(x <= 10) {
System.out.println(x); }
Continue
• Unlabeled
– Skips current iteration of the inner-most loop
• Labeled
– Skips the current iteration of outer loops – Uses a label to find where to skip
Continue
• Breaks the code flow • Breaks the loop logic
• Bad programming practice
Switch Statement
• Similar to if/else if structure • Code is often nicer looking
• Used for searching for cases to execute code
Switch Example
Switch(grade) case ‘A’:
System.out.println(“Good Job”) break;
case ‘B’:
System.out.println(“Try harder”) break;
case ‘F’:
System.out.println(“Bad Job”) break;
Switch Rules
• Switch value must be a char, byte, short, or int
• Case type must match the switch type
• Code executes when case value matches the switch value
• break statements are optional
– Next case will execute without break – Like “falling through” the code
• Default case is optional
– Good for error checking on switch value
Nested loops
int[] someArray = {5, 3, 8, 1, 7, 0,3};for(int i=0; i<someArray.length; i++) {
for(int j=i; j<someArray.length; j++) {
if(someArray[i] > someArray[j]) {
int temp = someArray[i];
someArray[i] = someArray[j]; someArray[j] = temp;
} }
Naming Convention
• http://
www.oracle.com/technetwork/java/codeconve ntions-135099.html