Unit 1: Introduction to Java
Syntax and Various Punctuation ...
- Java is CaseSensitive. "String" is not the same as "string".
- All lines end with ;
- ... unless the line begins a code block { } in which case it ends with { or }
- white space and <ENTER> do not matter, although it is good form to have only one line of code per line of text
- = means "is assigned to"
== means "is equal to?" - Types of brackets and separators:
- { } defines blocks of code and automatically initializes arrays
- ( ) are used for most other needs - e.g BEDMAS, passing parameters in functions, if, for, ...
Encloses arguments in method definitions and calling; adjusts precedence in arithmetic expressions; surrounds cast types and delimits test expressions in flow control statements - [ ] are used for declaring arrays and accessing array elements
- ; terminates statements
- . Selects a field or method from an object; separates package names from sub-package and class names
- , separates successive identifiers in variable declarations; chains statements in the test, expression of a for loop
- : Used after loop labels
- Comments:
- // this is a one-line comment
- /* this comment is
a multiline comment */
- Strings and printing: we'll look at these in detail later
- Strings must be enclosed in " ". Single quotes ' ' are for characters, not strings.
e.g. "fossil" vs "f" vs 'f' . The first two are strings. The third is a (single) character.
Note: if you copy and paste from the internet or a document, make sure that your quotes are " " not “ ”. - This is the standard way to print text:
System.out.print("Hello world");
- If you want to add a new line at the end:
System.out.println("Hello world");
- Concatenating strings: use the + sign.
System.out.println("Mark = " + finalMark);
- Strings must be enclosed in " ". Single quotes ' ' are for characters, not strings.
- Escape characters:
There are five common escape characters. Make sure that you know how to use them.
- \n (newline)
- \t (tab)
- \\ (backslash)
- \" (double quotes)
- \' (single quote) You don't need to use \' in strings. Just type '. It's only needed in a char variable.
Style: Naming and Indenting
You'll want to come back to this section later on in the course
- There are different ways to indent programs. See Wikipedia "indent style"
- This is my recommended way to name variable, functions and classes. Please follow it.
- Java Style Recommendations. Most of this is excellent. Read this, and if you even understand 1/4 it will be very helpful