
Java Language Introduction
This language overview is aimed at experienced developers, new to the Java Language. Java has taken much of the C/C++ syntax, making simplifications and revisions to suit to its own philosophy.
The Java Language is introduced under the following headings:
| Operator | Description | Comment / Example |
| /* */ // |
encloses multi-line comment indicates rest of line is a comment |
|
| = | assignment | |
| ; | terminates a line | x = x + y; |
| == != |
checks for equality, e.g. if (x==1) check for inequality |
If you accidentally use if (x=1), the compiler flags the mistake. For string comparion, always use the equals method: str1.equals(str2) |
| > >= < <= |
greater than, gr. than or equal less than, less than or equal |
|
| ! | NOT (negates a boolean expression) | |
| += -= *= | shorthand operator to add/subtract/multiple two numbers and assign to first | x += s (is like x = x + s, doing addition or string concat. depending on whether these are numbers or strings) |
| ++ -- | quick increment (decrement) | x++ is like x = x + 1 |
| && || |
Logical and, Logical or respectively. |
(a && b) if a is false, b is not
evaluated (or executed) (a || b) if a is true, b is not evaluated (or executed) |
| a ? b : c | Conditional operator | if boolean expr. "a" is true, use expr. "b", otherwise use expr. "c" |
Variable Access:
Class variables or properties (or fields, as Java calls them) have the following access levels:
NUMERIC (all numbers are signed)
CHARACTER/STRING
BOOLEAN
DATE
ARRAYS
4.1 Simple Output
Println and Print can be used to produce simple output, as shown below:
System.out.println("Hours worked: " + hours + "Payrate: " + pay);
System.out.print("Important Note: ")
Println ends the output with a newline character.
4.2 Viewing Simple Output from an Applet
When running an applet, the println output will no longer be immediately viewable in a browser. There are two simple approaches to viewing the println output (e.g. for rudimentary debugging):
4.3 Simple Input from User
Simple data input (typed directly from the keyboard) requires that an array of bytes be read and moved to a string. For direct keyboard input, the possibility of an exception must be handled.
byte buffer[] = new byte[50];
String name;
System.out.println("Input your name:");
try{
System.in.read(buffer);
}
catch (java.io.IOException e) {System.out.println("Exception reading input");}
// move user input into a string name = new String(buffer,0,buffer.length); // could also trim to remove trailing CR/LF
If the desired user input was a number, the input value could then be moved from the string to a number with the appropriate functions (along with error-checking, in case the user entered a non-numeric).
4.4 Formatting Numbers for Output
The following code formats decimal values to common North American formats.
import java.text.*; // import this before class definition (DecimalFormat belongs)
String displayNum;
Decimal myNum;
DecimalFormat dec0 = new DecimalFormat("#,##0;(#,##0)");
DecimalFormat curr2 = new DecimalFormat("$#,##0.00;($#,##0.00)");
DecimalFormat dec2 = new DecimalFormat("#,##0.0#;(#,##0.0#)");
DecimalFormat perc2 = new DecimalFormat("#.00%");
myNum = 43.497; displayNum = curr2.format(winRatio); // result: "$43.50" (rounds to two decimals)
myNum = 3001; displayNum = dec2.format(winRatio); // result: "3,001.0" (shows at least one decimal)
myNum = 0.17299; displayNum = perc2.format(winRatio); // result: "17.30%" (rounds to two decimals)
Note: Java also supports more general formatting mechanisms which will display numbers in local format, e.g. it will show decimals as periods in North America, commas in Europe, etc.
Statements blocks are delimited with { }. Brace brackets are optional there is a single
level statement in the scope. However, it is good style to always include brace
brackets. Note that the syntax of the listed constructs is like C's.
IF STMT
if ((a==b) && (b<c)) {
statements
} else {
statements
}
SWITCH STMT (limited to char, byte, short, int data types)
switch (age) {
case 1:
...
break;
case 2:
...
break;
default:
...
}
FOR LOOP
for(i=0; i<10; i++) {
statements
}
WHILE LOOP
i=0
while (i<10) {
...
i++
}
Like other object-oriented languages, Java provides different "access" methods for method declaration. A number of examples follow.
Public method access with float Return Value
public float computePay(float HoursWorked, float RatePaid) {
return (HoursWorked * RatePaid);
}
Protected method access with no Return Value
protected void paint(Graphics g) {
...
}
Note: protected access allows access within the package and by any descendants.
Default method access, returning a byte array
byte[] getKeyboardInput() {
...
return buffer;
}
Note: default access allows access within the package only, but not by objects (even
descendants) outside the package.
Private-Protected method access with Return Value
private protected int locate(String s) {
...
return location;
}
Note: private protected access allows within the class and its descendants.
Private method with Return Value
private String make(String s) {
...
return result;
}
Note: private access allows access only from within the class.
6.2 Method Parameters
| Visual Basic Sample | Java Sample |
Defining the function:Public Function manip_string( ByVal inString As String, ByRef outString As String) As Boolean boolean ret_code = true .. some logic If(.. bad condition ..)Then ret_code = false End if .. Return ret_code End Function NOTE: First parm is input, second parm is the result (if OK) while the return code indicates the operation's success or failure. |
public String manipString (inString)
throws BadInputStringException{
.. some logic If (.. bad condition ..) {
throw new BadInputStringException(
"Invalid Input");
}
..
}
NOTE: inString is input while output is returned as a String. Method success/failure is indicated by throwing an exception. |
Calling the function:If (manip_string(x, y)) Then .. normal processing Else .. when its fails End If
|
try {
y = manipString(x);
.. normal processing
}
catch(BadInputStringException e) {
.. when its fails
}
|
Each Java classes is generally placed into it own source file (there can be at most one public class per source file). A class has a series of methods and properties.
7.1 Declaring a Class
// this class is public (i.e. accessible outside its package)
public class Customer {
String custName; // class-level variable
// Constructor: can declare zero, one or many constructors (which take different parms)
public Customer (string name) {
this.custName = name; // "this" is optional here but refers to current object
}
// as many methods can be defined as needed
public printName(string name) {
System.out.println("Customer Name is " + name);
}
}
7.2 Class Inheritance
To inherit from an existing class, the extends keyword is used. Inheritance works the same as other object-oriented languages (e.g. start with Base Class methods/properties, can override or extend methods, etc.).
public class RetailCust extends Customer {
...
}
7.3 Variable Declaration (to create class instance)
Customer myCust; // declares class but does not create instance Customer myOtherCust = new Customer; // declares and creates an instance of Customer
7.4 Class Variable Assignment and Comparison
Customer myCust1 = new Customer("ABC Mfg");
Customer myCust2 = new Customer("Carpets Unlimited");
Customer myCust3;
myCust3 = myCust1; // points myCust3 to the same instance as myCust1;
myCust2 = myCust1; // points myCust2 to the same instance and frees up other object for garbage collection
if (myCust3 == myCust2) // checks if both variables point at the same object instance
... back to Java Topics