public class Arrays {
public static void main(String[] args) {
String[] alphabet = {"a", "b", "c", "d", "e", "f", "g"};
// With for loop
System.out.println("Old fashioned way");
int size = alphabet.length;
for(int i=0; i< size; i++){
System.out.print(alphabet[i] + " ");
}
// With for-each loop
System.out.println("\n\nWith For-Each Loop");
for(String letter : alphabet){
System.out.print(letter + " ");
}
}
}
Here is the output:
Old fashioned way
a b c d e f g
With For-Each Loop
a b c d e f g
Here with multi dimensional array example
public class Arrays {
public static void main(String[] args) {
// Double Arrays
String[][] users = {
{"Jon", "Snow", "js@test.com","78965412"},
{"Dany", "Targeryan", "dt@test.com", "45632101"},
{"Arya", "Stark", "as@test.com", "12304569"}
};
int numOfUsers = users.length;
int numOfFields = users[0].length;
// With old fashioned way
System.out.println("\n\nWith old Fashoned Way");
for(int i=0; i< numOfUsers; i++){
for(int j=0; j< numOfFields; j++){
System.out.print(users[i][j] + " ");
}
System.out.println();
}
// Little More Intelligent Way
System.out.println("\n\nLittle More Intelligent Way");
for(int i=0; i< numOfUsers; i++){
String name= users[i][0];
String lastname = users[i][1];
String mail = users[i][2];
String phone = users[i][3];
System.out.println(name+ " " + lastname+ " " + mail + " " + phone);
}
// With ForEach Loop
System.out.println("\n\nWith ForEach Loop");
for(String[] user: users){
for(String us: user){
System.out.print(us + " ");
}
System.out.println();
}
}
}
Here is the output:
With old Fashoned Way
Jon Snow js@test.com 78965412
Dany Targeryan dt@test.com 45632101
Arya Stark as@test.com 12304569
Little More Intelligent Way
Jon Snow js@test.com 78965412
Dany Targeryan dt@test.com 45632101
Arya Stark as@test.com 12304569
With ForEach Loop
Jon Snow js@test.com 78965412
Dany Targeryan dt@test.com 45632101
Arya Stark as@test.com 12304569
Hiç yorum yok:
Yorum Gönder