| Arrays |
| Comments |
| Conditional statements |
| Focus |
| Formatting |
| Listbox |
| String operations |
| Operators |
| Vectors |
In Java arrays are objects. Arrays i java can'¨t be resized
easily. If case you need resizing, you should use a different
object called a vector.
An array must be explicitely created. this is done withj the
new operator.
Note: Arrays are azero based
To create an array of 100 integer elements:
int[] myArray = new int[100];
If you wil supply initial values (Note you do not have to use the new keyqword here):
int[] myArray = { 1, 2, 3, 4, 5, 6};
An anonymous array can be sued if you want to pass an array to a method, and you don't want to create a local variable for it:
printlabels(new String[] { "Region", "Sales" }
for (int i = 0; i < myArray.length; i++)
System.out.println(i);
You can copy one array into another, but both variables refres to the sam array:
int [] myArray1 = myArray2;
import java.util.Arrays;
Arrays.sort(myArray);
Use method binarySearch of java.util.Arrays
Arrays can be passed as arguments to methods, and they can be changed from withing the method !
public static void sort(int[] myArray)
Arrays are always passed by reference to methods, so they can be changed directly from withing the method. Below is an example of how to pass an array to a method an change it. Remember to import java.util.Arrays.
import java.util.Arrays;
public class FirstSample {
public static void sort_array(int[] myArrayparameter)
{
Arrays.sort(myArrayparameter);
}
public static void main(String[] args)
{ int[] myArray = new int[3];
myArray[0] = 5;
myArray[1] = 3;
myArray[2] = 8;
sort_array(myArray);
for ( int i = 0; i < 3;i++)
{ System.out.println(myArray[i]);
}
}
}
Result:
3 5 8
Declaring a multidimrensional array:
int[][] balance;
balance = new int [3][5];
Shorthand to declare multidimensional array without use of new:
int[][] lastTwoYearsSales = { {1997, 1998 }, {15350, 27500}}
Example of using a multidimensional array:
import java.util.Arrays;
public class FirstSample {
public static void calc_diff(int[][] myArray)
{for (int row=0; row < 5; row++)
{myArray[2][row] = myArray[1][row] - myArray[0][row];
}
}
public static void main(String[] args)
{ //Declare new two-dimensional array called balance
int[][] balance;
balance = new int [3][5];
//Fill the array. The last column (3) will be calculated
//as the difference between column 1 and 2 in the method
//calc_diff
balance[0][0] = 20000;
balance[0][1] = 7500;
balance[0][2] = balance[0][0] - balance[0][1];
balance[0][3] = 2000;
balance[0][4] = balance[0][2] - balance[0][3];
balance[1][0] = 35000;
balance[1][1] = 6000;
balance[1][2] = balance[1][0] - balance[1][1];
balance[1][3] = 4500;
balance[1][4] = balance[1][2] - balance[1][3];
calc_diff(balance);
for (int row=0; row < 5; row++)
{
System.out.println(balance[0][row] + " " +
balance[1][row] + " " +
balance[2][row]);
}
}
}
One line:
//This is a comment
Multiple lines:
/* This is comments on
on multiple lines
*/
| priceCategory = (price > 10) ? 1 : 2 | IIF. If price is greater than 10 then priceCategory = 2 else priceCategory = 1 |
| if (manWoman.equals("man")) {do something...} |
| postfix operators | [] . (params)
expr++
expr-- |
| unary operators | ++expr
--expr
+expr
-expr ~ ! |
| creation or cast | new
(type)expr
|
| multiplicative | * / %
|
| additive | + -
|
| shift | << >> >>>
|
| relational | < > <= >= instanceof
|
| equality | == !=
|
| bitwise AND | &
|
| bitwise exclusive OR | ^
|
| bitwise inclusive OR | |
|
| logical AND | &&
|
| logical OR | ||
|
| conditional | ? :
|
| assignment | = += -= *= /= %= &= ^= |= <<= >>=
>>>=
|
if (<condition>)
{ <statement>
}
if (<condition>)
{ <statement>
}
else if (<condition>)
{ <statement>
}
else
{ <statement>
}
while (<condition>)
{ <statement>
}
int i = 0;
while (i<10)
{ i++;
System.out.println(i);
}
do { <statements> } while (<condition>)
int i = 0;
do
{ i++;
System.out.println(i);
}
while (i < 10);
for (int i = 1; i <= 10; i++)
{
System.out.println(i);
}
switch(x)
{ case 1;
......
break;
case 2;
......
break;
default:
}
Note that the default clause is optional.
The break statment can be used to break out of a loop.
If you want to break out of a nested loop, you can preceede the loop with a label. Thje break statement will then move past the labeled block.
read_data:
while ....
for .....
break read_data;
use the requestFocus method to set focus to component and the transferFocus to move the focus to the nex component.
Example:
logonButton.requestFocus();
Import: java.text.*;
Use one of the thee methods:
NumberFormat.getNumberInstance()
NumberFormat.getCurrencyInstance()
NumberFormat.getPercentInstance()
You can use setMaximumFractionDigits to suppress print of all digits. The last digist is rounded up.
Example:
double x = 10000.0 / 3.0;
NumberFormat nf = NumberFormat.getNumberInstance();
String n = nf.format(x);
System.out.println(x);
System.out.println(n);
Result:
3333.3333333333335
3.333,333
Example of currency formatting (Uses the java.util.Locale class):
double x = 10000.0 / 3.0;
NumberFormat nf =
NumberFormat.getCurrencyInstance(Locale.GERMANY);
String n = nf.format(x);
System.out.println(n);
Result:
3.333,33 DM
You can creayte your own formats:
DecimalFormat df = new DecimalFormat("0.#####")
The result will be: 3333.33333
Declare a listbox:
JList companyCodeList;
Declare a listbox: with initial values:
JList companyCodeList = new JList(new String[] {"1000", "1200", "1400"});
Inserting elements after the List has been initialised:
Use a vctor to store the listeelements in, and the use the setListData method to uiset the vector for listeelements:
Vector listElements = new Vector(0,1);
..... fill the vector....
companyCodeList.setListData(listElements);
int number = 1;
String myString = String.valueOf
(i);
String Fornavn = "Henrik";
String Efternavn = "Frank"
String Navn = Fornavn + " " + Efternavn;
String greeting = "Hello world";
String newgreeting = Greeting.substring(0, 4)
The variable newgreeting will now contain "Hello"
String greeting = "Hello";
int n = greeting.length();
n resolves to 5.
Note that there is no method to replace characters. You wioll have to build a whole new string instead.
string1.equals(string2)
Returns true if string1 and string2 are equal (Case sensitive).
"Hello".equalsIgnoreCase("hello")
Use this method to nmake the compare case insesitive.
Important: Never use = = to test if two strings are equal. This will only test whteher the strings are stored at the same location.
To see all the string methods refer to the java.lang.String class
| x++ | Adds 1 to the current value of x |
| x-- | Subtracts 1 from the current value |
You can also use ++x and --x. The difference appears when you are using the operators inside expression. The prefix form does the addition first, the postfix
It is not recommended to use these operators inside expressions.
| (3 = = 7 ) | Test for equality - In this case it resolves to false. The usual operators <, >, <=, >= can also be used |
| A && B | Logical AND |
| || | Logical OR |
The vector works much like an array, but can shrink and grow
automatically. The vector class is a library class defined in the
java.util package.
It is important to remember that a vector always holds objects, so
you can't store e.g. and int. Instead use the wrapper class
Integer. Other wrapper classes are Long, Float, Double, Short,
Byte, Character, Void, and Booolean. This also mean that you may
have to use casting when you are retreiving elemnst from the
vector..
Example:
import java.util.*;
public class VectorTest {
public static void VectorPrint(Vector myVector)
{//Print contents of the vector
for (int i=0; i < myVector.size(); i++)
System.out.println(myVector.elementAt(i));
//Print size of vector
System.out.println("The size of the vector is: " + myVector.size());
System.out.println("---------------------------------------------");
}
public static void main(String[] args) {
// This makes a new vector with 3 elements and a capacity increment of 2.
// If you don't specify a capacity encrement, the vector will by default
// double up for each encrement, causing its size top grow exponential.
// Note that this will not create elements in the vector, but only
// give it the potetial to store 3 elements
Vector vector1 = new Vector(3,2);
// Use the add element method to add new elements
// Note that this method uses objects as parameter, and therefore does not
// accept int types, so you have to use the wrapper class Integer.
for (int i=0; i < 3; i++)
vector1.addElement(new Integer(i) );
// Print contents of vector
VectorPrint(vector1);
// Add a new element to the vector. You will first have to
// increase its capacity by 1, so that it can store 4 elements
vector1.setSize(4);
vector1.setElementAt(new Integer(10), 3);
VectorPrint(vector1);
// This is another method to add a new element at the end of the vector
vector1.add(new Integer(15));
VectorPrint(vector1);
}
}
Result:
0
1
2
The size of the vector is: 3
---------------------------------------------
0
1
2
10
The size of the vector is: 4
---------------------------------------------
0
1
2
10
15
The size of the vector is: 5
---------------------------------------------
| Converted from CHM to HTML with chm2web Standard 2.7 (unicode) |