Fundamental Java Syntax Summary Sheet for CISC101, Spring 2006 Notes: Items in italics are things that you must supply, either a variable name, literal value, or expression. Variable Naming Rules Java is Case - Sensitive! Start with a letter, letters and numbers only and the underscore character, no spaces, any length. Operator Precedence Table (Items at the top execute first, followed by those below. All items in the same section have the same precedence.) "Javaspeak" would be "Method invocation", rather than "Function call"! It is recommended that you stick with the postfix operators only. We will not use "~". The "+" operator is "overloaded" in Java! We will not use these "shift" operators either. Use "&&" and " " instead of "&" and " ".
Primitive Types char // '\u0000' to '\uffff' The most often used types are "int", "double" byte // -128 to 127 and "boolean". short // -32768 to 32767 int // -2147483648 to 2147483647 long // -9223372036854775808 to 9223372036854775807 float // ±1.4 x 10-38 to ±3.4 x 10 38 to 7 significant digits double // ±4.9 x 10-308 to ±1.7 x 10 308 to 15 significant digits boolean // true or false In Java, you must declare any variable (primitive type or Object) before you can use it. Basic Program Structure Without the use of any external packages: public class Classname { Saved in a text file called "Classname.java". public static void main (String[] args) { // Your code goes here // end main method // end class Importing the javax.swing and java.io packages for example: import javax.swing.*; // for GUI screen Input/Output import java.io.*; // for File Input/Output public class Classname { These two packages are part of all standard Java distributions. public static void main (String[] args) { // Your code goes here - this code can also use any Object in the javax.swing // package // end main method // end class No packages, but with the declaration of another method: public class Classname { public static return_type method_name (parameter_list) { // Your method code goes here // end method declaration public static void main (String[] args) { // Your code goes here // main can invoke the other method // end main method // end class "return_type" is any primitive or defined Object type, or "void". "method_name" must follow variable naming rules. "parameter_list" consists of none, one, or more parameters, separated by commas, where a parameter consists of a type declaration followed by a valid variable name. For example, a parameter list consisting of two int values would be like "int a, int b".
Comments In-Line comments start with "//". Block comments start with "/*" and end with "*/". Program Structure Blocks of code, including class definitions and method code are contained within sets of "{" and "". Statements are terminated with a ";". Methods & Class Attributes The syntax for method declaration is shown above. If a method has a return type other than "void", it must have at least one "return" statement within the method: return variable_value_or_expression; The type of variable_value_or_expression must match the return type declared in the method declaration. Methods can be declared in any order in a class. Variables called class attributes can be declared at the same level as methods. Class attributes are known inside every method in a class. All structural code must be contained within a method. Conditional Statements "if" statements, without statement blocks: if (expression_that_evaluates_to_a_boolean_value) // a single statement that executes if the expression is true else // the "else" part is optional // a single statement that executes if the expression is false with statement blocks: if (expression_that_evaluates_to_a_boolean_value) { // multiple statements that execute if the expression is true else { // the "else" part is optional // multiple statements that execute if the expression is false // end if an if-else-if "chain" with statement blocks: if (expression1) { // if expression1 is true else if (expression2) { // if expression2 is true else if (expression3) { // if expression3 is true else { // if none of the above are true // end if-else-if You can have as many "else if" statements as you like. Java also has a switch statement that performs a very similar function:
The "switch" statement: switch (expression) { case value1: // statements if expression equals value1 case value2: // statements if expression equals value2 case value3: // statements if expression equals value3 case value4: // statements if expression equals value4 default: // if none of the above match expression and all the values must be of an integer type: byte, short, int, long or char. You can have as many case statements as you like and the default: part is optional. // end switch Repetition Structures or "Loops" Example of a "while" loop: // this loop computes 1 + 2 + 3 +... + N int i = 1; while (i <= N) { sum = sum + i; i = i + 1; // end while Example of a "do-while" loop: // same calculation as at left int i = 1; do { sum = sum + i; i = i + 1; while (i <= N); // end do-while Example of a "for" loop: // same calculation as above int i; for (i = 1; i <= N; i++) { sum = sum + i; // end for or: for (int i = 1; i <= N; i++) sum = sum + i; or using the for each loop in Java 5.0 : double[] data = {...; for (double e : data) {... //e is an element in data Screen Output/Input Text Screen Output: System.out.print(whatever_you_want_to_print); or: System.out.println(whatever_you_want_to_print); // adds a CR/LF to the end of the output
Formatted output (in Java 5.0 ): System.out.printf(format_String, variable_name); format_string contains a placeholder, like %8.2f, (for double s), along with other characters. These placeholders determine the width of the space reserved to output the value, the number of digits to display after the decimal. The final letter determines the way the value is displayed. Use something like %8d for int types. See the Java 5.0 API for more detailed information. Output Format Control Strings: \n Adds a Line Feed character \t Adds a Tab character \r Adds a Carriage Return character \\ Adds the "\" character \' Adds the "'" character \" Adds the """ character \u#### Adds the specified Unicode character These sequences can be embedded in any String literal. "####" is a hex value between 0000 and ffff. Console input using the Scanner class (in Java 5.0 ): import java.util.scanner; public class JavaScannerInput { public static void main(string[] args) { Scanner input = new Scanner(System.in); System.out.print("Please provide a number: "); double anum = input.nextdouble(); System.out.printf("Formatted output: %8.2f\n", anum); // end main method // end JavaScannerInput class Text File Input in Java 5.0 You must have imported java.io.* and java.util.* to use these classes. To create an input stream: Scanner streamname = new Scanner(new FileReader(fileName)); To read from the file (reads one entire line from file, and removes leading or trailing white space): String inputline = streamname.nextline(); Other Scanner class methods; nextint() // reads an int "filename" can contain just the filename (if the file is in the same folder as your program) or a full path to the file. nextdouble() // reads a double hasnextline() // returns true if not at the // end of the file To close any text or binary input or output stream: streamname.close();
Text File Output To create an output stream: PrintWriter streamname = new PrintWriter(new FileOutputStream(fileName)); To write to the file: streamname.print(data); // no end of line character streamname.println(data); // appends end of line character Binary File Input To create an input stream: ObjectInputStream streamname = new ObjectInputStream(new FileInputStream(fileName)); To read from the file (reads one int value): int variable_name = streamname.readint(); Binary File Output To create an output stream: There are "read" methods for every primitive type. To read String's use the "readutf()" method. To write String's use the "writeutf()" method. You must read binary values in exactly the same order in which they were written. You cannot edit binary files with a text editor. ObjectOutputStream streamname = new ObjectOutputStream (new FileOutputStream (filename)); To write to the file (writes one int value): streamname.writeint(variable_name_or_value); Random Access File I/O Use: RandomAccessFile randfile = new RandomAccessFile(fileName, rw ); randfile contains methods to write or read any byte in the file, such as seek(), readbyte() and writebyte(). Other methods write or read primitive type values. They have the same names as the methods for binary file operations. Exceptions with File I/O For many read and write operations, you will need to be prepared to catch exceptions such as FileNotFoundException and the general IOException. You can use the EOFException to detect the end of a binary file when reading. Catching Exceptions Binary files can be used to read and store objects directly. Use the readobject() and writeobject() methods. readobject() returns an Object, so it must be cast back to its original type. try { // code that might generate an exception catch (Exception e) { // code that does something useful! // end try catch block This code catches all exceptions. You can catch specific exceptions using something like: catch (NumberFormatException e) Many catch blocks can be used.
String Declaration String String_variable_name = some_string_literal; // Initialization is optional or String String_variable_name = new String(some_String_literal); String Methods. Used as in: stringname.methodname(parameter(s)) length() // returns the length of the string as an int equals(otherstring) // returns true if otherstring matches the String equalsignorecase(otherstring) // returns true if otherstring matches the String, // ignoring upper/lower case compareto(otherstring) // returns a negative int if otherstring > String, a // positive int if otherstring < String, 0 if they match tolowercase() // returns the String all in lower case touppercase() // returns the String all in upper case trim() // returns the String without leading and/or trailing spaces charat(position) // returns the char at the specified position substring(start) // returns the right part of the String, starting from // position start substring(start, endplusone) // returns the String starting from position start and // ending at position endplusone - 1 indexof(searchstring) // returns the position of the first occurrence of // searchstring in the String indexof(searchstring, start) // returns the position of the first occurrence of // searchstring in the String searching from position start replace(oldchar, newchar) // returns a String that has all occurrences of // oldchar replaced with newchar format(format_string, values) // returns a formatted string from the numeric values // supplied, works just like printf (Java 5.0 only) A Few Wrapper Class Methods. Integer.parseInt(strInt) // returns strint (a String representation of an int) as an // actual int Double.valueOf(strDouble).doubleValue() // returns strdouble (a String representation of // a double) as an actual double Double.parseDouble(strDouble) // Available in newer Java versions Character.isDigit(charVal) // returns true if charval lies between 0 and 9 Character.isLeter(charVal) Character.isUpperCase(charVal) Character.isLowerCase(charVal) Character.toUpperCase(charVal) Character.toLowerCase(charVal) // returns true if charval is a letter A Few Math Class Methods. Math.PI Math.abs(aNumber) Math.pow(aNumber, exponent) Math.round(aFloat) Math.round(aDouble) // π expressed as a double // returns the absolute value of anumber as a double // returns a double of anumber raised to exponent // returns nearest int to afloat // returns nearest long to adouble Arrays int[] myarray = new int[10]; // myarray.length returns 10 int[][] ddarray = new int[20][5]; // ddarray.length returns 20, ddarray[0].length // returns 5