/** * Description of the class */ accessSpecifier class ClassName { /////////////////////////// // Data Members (fields) /////////////////////////// accessSpecifier fieldType fieldName; // description of field ////////////////// // Constructors ////////////////// /** * Describe what constructor does * @param p1 describe the first parameter * @param p2 describe the second parameter */ accessSpecifier ClassName(paramType paramName, paramType paramName) { // constructor body } ///////////// // Methods ///////////// /** * Describe purpose and use of the method. * @param p1 describe the first parameter * @param p2 describe the second parameter * @return describe the value returned */ accessSpecifier returnType methodName(paramType paramName, paramType paramName) { // method body } }
/** * A Human has a name and an age. A human's name can be changed at any time. * A human's age only changes when the human has a birthday. */ public class Human { private String name; // the human's name private int age; // the human's age /** * Creates a human with the given name. The human starts out at age 0. * @param initName the name to give the human */ public Human(String initName) { name = initName; age = 0; } /** * Returns the name of this human. * @return the name of the human */ public String getName() { return name; } /** * Returns the age of this human. * @return the age of the human */ public int getAge() { return age; } /** * Changes the name of this human to the new name given. * @param newName the new name for the human */ public void setName(String newName) { name = newName; } /** * Causes the human to have a birthday (i.e., adds a year to the age). */ public void haveBirthday() { age = age + 1; } }
Data Type | Contains | Range of values |
---|---|---|
byte | integer | -128 to +127 |
short | integer | -32768 to +32767 |
int | integer | -2147483648 to +2147483647 |
long | integer | -9223372036854775808 to +9223372036854775807 |
float | real number | -3.40282347E+38 to +3.40282347E+38 |
double | real number | -1.79769...E+308 to +1.79769...E+308 |
char | character | A - Z, a - z, 0 - 9,
!@#$%^&*() etc. denote literals in single quotes (e.g., 'b') can also be thought of as a small integer |
boolean | boolean value | only two possible values: true and false |
arithmetic operators
+ | addition |
- | subtraction |
* | multiplication |
/ | division |
% | modulus (remainder) |
Note: applying an operator to two integer operands results in an integer result. For example, the result of 13 / 5 (an int divided by an int) is 3.
unary operators
+ | unary plus | ++ | increment | |
- | unary minus | -- | decrement |
compound assignment operators
+= | -= | *= | /= | %= |
For each compound assignment operator op=, x op= y; is the same as x = x op y; |
== | equal to | != | not equal to | |
> | greater than | >= | greater than or equal to | |
< | less than | <= | less than or equal to |
! | NOT (unary) |
&& | AND |
|| | OR |
See Java operator precedence for information about Java's order of operations.
if ( boolean expression ) if block else else block
switch ( arithmetic expression ) { case label 1 : case body 1 case label 2 : case body 2 ... case label n : case body n }
while ( boolean expression ) block
do { block } while ( boolean expression );
for ( initialization ; boolean expression ; increment ) block
Java Syntax
public interface InterfaceName { method prototypes }
Example
public interface Ownable { Owner owner(); boolean updateOwner(Owner newOwner); }
Java Syntax
public class ClassName implements InterfaceName1, InterfaceName2, ... { data members constructors methods }
Example
public class Car implements Ownable { // data members private Owner myOwner; // constructors // other Car methods public Owner owner() { return myOwner; // method implementation } public void updateOwner(Owner newOwner) { myOwner = newOwner; return true; } }
Example: throw new IllegalArgumentException();
using try-catch
try { code that might raise an exception } catch (ExceptionType1 identifier1) { code to handle exception type 1 } catch (ExceptionType2 identifier2) { code to handle exception type 2 } ... finally { // note: the finally clause is optional code executed no matter what happens in try block }
using a throws clause
... methodName(parameter list) throws ExceptionType { ... ... methodName(parameter list) throws ExceptionType1, ExceptionType2, ... { ...
Example: public static void main(String [] args) throws IOException { ...
Define a new class that is a subclass of Exception (either directly or through the inheritance hierarchy).
Example
public class EmptyBagException extends Exception { public EmptyBagException() { super(); } public EmptyBagException(String msg) { super(msg); } }
See also:
For console input, use a Scanner object
Scanner stdin = new Scanner(System.in);
String inputLine = stdin.nextLine();
char c = inputLine.charAt(0); int i = Integer.parseInt(inputLine); long l = Long.parseLong(inputLine); float f = Float.parseFloat(inputLine); double d = Double.parseDouble(inputLine);
For console output, use System.out
print println
For file input, use a Scanner object
File srcFile = new File("myFile.txt"); Scanner fileIn = new Scanner(srcFile);
hasNext, hasNextInt, etc. next, nextInt, nextLine, etc. close
If the file has several pieces of information on each line, read one line at a time (using nextLine), then use the split method of the String class to divide the line into tokens (individual pieces of information) based on delimiters (the characters used to separate the pieces of information):
For file output, use a PrintStream object
File dstFile = new File("myFile.txt"); PrintStream outFile = new PrintStream(dstFile);
new PrintStream(File file) new PrintStream(String fileName)
print println close