Declaring and Initializing Variables

     

Primitives

 

 boolean hasRoadRage = true; char size = 'm'; int age = 11; long userID = 42L; 

Arrays

Arrays can be created and populated as shown in the following. Make an array that has two cells for holding int values. The two cells are then populated with the values 11 and 12, respectively.

 

 int[] numbers = new int[2]; numbers[0] = 11; numbers[1] = 12; 

For the preceding array, calling array.length returns 2.

In the next example, an int array is created with three cells and populated at the same time.

 

 int[] numbers = {1,2,3}; 

Arrays can also be populated in loops . Here, we create a new object to be stored in each cell of an array.

 

 Employee[] employees = new Employee[5]; for (int x = 0; x < employees.length; x++) { employees[x] = new Employee(); }... 

Objects

Create a new object of type Button like this ( assuming you have imported the javax.swing.Button class):

 

 //reference type of Button, variable name is //saveButton, and we use the constructor that accepts //a String label. here we set the label's value to //'save' right away. Button saveButton = new Button("save"); 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net