Chapter 1 Helper Sheet
Java Template for introductory projects - just know how to use it when you
have it for reference:
public class classname{
public static void main(String[] args) {
the program work is all in here
}
}
Types:
- no decimals: byte -> short -> integer -> long
- decimals: float -> double
- characters: char (and String, which is really a class of characters)
- yes/no: boolean
Create a variable:
type name ; OR type name = value; // (For String use
" ", for char use ' ')
ex: int x = 1;
Change a variable:
variable = something; // something can be another variable
or math using * / + -
ex: x = y * 2 / 3 + a;
Print to the screen:
System.out.println ( what you want to output ); // inside parentheses
put "string" and variables separated with +
ex: System.out.println ("The average is" + avg + "\n The
product is:" + product);
Play with strings:
- stringvar.charAt(3) // will be a character
- stringvar.length() // will be an integer
- stringvar.equals(somethingOtherString) // will be either true or
false (a boolean)
- stringvar.toUpperCase() // will be a String that is all uppercase
- stringvar.toLowerCase() // will be a String that is all lowercase
- stringvar.subString(2) // will be a String starting in position 2
to the end
- stringvar.subString(2, 5) // will be a String starting in position
2 and ending in position 4
ex: newString = myOriginalString.toLowerCase();
Also, strings can be put together into another string with the +
ex: newString = string1 + string2;
Variable name (Identifier) rules:
- An identifier must begin with a letter or an underscore _
- Java is case sensitive upper case (capital) or lower case letters are considered
different characters. Average, average and AVERAGE are three different identifiers.
- Numbers can also appear after the first character.
- Identifiers can be as long as you want but names that are too long usually
are too cumbersome.
- Identifiers cannot be reserved words (special words like int, main, etc.)
- By convention, variables should begin with a lower case unless they are
really representing something that wont ever change
- By convention, a variable whose value should never change should be all
capitalized.
Comments:
- // -> comment line ex: // this is a comment
- /* xxx */ comment between marks