SOMO LA 12
Java Array
Array inatumika kuhifadhi value nyingi nyingi kwenye variable moja. Badala ya ku declare value kivyako
mfano:
String gari1= "Toyota";
String gari2 = "suzuki";
String gari3 = " hissan";
String gari4 = " TATA";
Arrays ipo ili kurahisisha namna iyo hapo juu.
Ku andaa array kwenye code za java unatakiwa ku define aina ya variable na mabano yaani mfano
String [ ] cars;
Tumesha declare ( tumeandaa ) variable ambayo ni Array inayo beba Strings na kuweka value unaweza kuweka value moja moja
kwa kutenganisha na comma ndani ya mabano.
String []cars = {"volvo","BMW","Ford","Mazda"};
vilevile unaweza kutengeneza array ya namba
int [] namba = {10,0,30,40};
Jinsi ya kutaja value flani zilizomo kwenye array yako
unaweza kutaja value flani kutokana na index namba yake
mfano
hii ita print value ya kwanza kwenye array yako
String []cars = {"volvo","BMW","Ford","Mazda"};
System.out.println(cars[0]};
Output: volvo
ZINGATIA:
index kwenye array huanza na 0 : [0]
yaan [0] maana yake ni element ya kwanza
[1] maana yake ni element ya pili
**Badili element kwenye Array**
ili kubadilisha value ya element flani utatakiwa kurejelea index namba yake
mfano
String []cars = {"volvo","BMW","Ford","Mazda"};
cars [0] = "opel";
System.out.println(cars[0]);
output: opel
Array Length ( Urefu wa Array)
ili kufahamu array ina element ngapi tumia neno length
mfano
String []cars = {"volvo","BMW","Ford","Mazda"};
System.out.println(cars.length);
output: 4
Java Array Loop
unaweza ku loop kwenye array yako kwa kutumia ( for - loop ) na length property kwa ku specify ni mara ngapi
unataka loop i run??
mfano ufuatao uta print element zote kwenye array ya cars
mfano
String []cars = {"volvo","BMW","Ford","Mazda"};
for ( int i=0 ; i < cars . length; i++){
System.out.println(cars[i]);
Mwisho wa somo la 12
0 Comments