0% found this document useful (0 votes)
18 views11 pages

Java Enhanced For Loop and Array Examples

The document explains the Extended for loop (also known as Enhanced for loop or for-each loop) introduced in Java 5, which simplifies the process of iterating over elements in an array without the need for initialization, condition, and increment/decrement. It includes example programs demonstrating how to read and display String and User-defined class objects using both traditional and Extended for loops, as well as discussions on Object Arrays and Multi-Dimensional Arrays. Additionally, it covers the concept of Jagged Arrays and provides example code for each topic.

Uploaded by

160817735119
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views11 pages

Java Enhanced For Loop and Array Examples

The document explains the Extended for loop (also known as Enhanced for loop or for-each loop) introduced in Java 5, which simplifies the process of iterating over elements in an array without the need for initialization, condition, and increment/decrement. It includes example programs demonstrating how to read and display String and User-defined class objects using both traditional and Extended for loops, as well as discussions on Object Arrays and Multi-Dimensional Arrays. Additionally, it covers the concept of Jagged Arrays and provides example code for each topic.

Uploaded by

160817735119
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dt : 18/2/2022

faq:

define Extended for loop?

=>Extended for loop introduced by Java5 version and which is

Auto-retrieval loop used to display elements from Array objects.

syntax:

ii
for(data_type var_name : Container_name)

ath
{

//loop_body

aip
}

Ex:
hM
for(Integer k : a)

//loop_body
tes

}
a

Advantage:
nk

=>In Extended for we use Container_name and data_type,but

there is no concept of Initialization,Condition and Incre/Decre.


Ve

Note:

=>This Extended for also known as Enhanced for loop or for-each

loop.

========================================================
Ex_program :

Wap to read and display String objects using Array?

[Link]

package maccess;
import [Link].*;
public class DemoArray2 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){

ii
try {

ath
[Link]
("Enter the Number of String Objects:");
int n = [Link]([Link]());
//read in the form of String and Convert into
integer

aip
String a[] = new String[n];
//Array to hold n String objects
[Link]
("Enter "+n+" String Objects");
hM
for(int i=0;i<[Link];i++)
{
a[i] = [Link]();
}//end of loop
[Link]
("===Display using Old for loop==");
tes

for(int i=0;i<[Link];i++)
{
[Link](a[i].toString()+" ");
}//end of loop
a

[Link]
nk

("\n===Display using Entended for===");


for(String k : a)
{
[Link]([Link]()+" ");
Ve

}//end of loop
}catch(Exception e) {
[Link]();
}
}//try with resource

}
}
o/p:

Enter the Number of String Objects:

Enter 3 String Objects

java

program

ii
nit

ath
===Display using Old for loop==

java program nit

aip
===Display using Entended for===

java program nit


hM
========================================================

Ex_Program :

Wap to read and display User defined class Objects?


tes

[Link]

package test;
public class Product {
a

public String pCode,pName;


public float pPrice;
nk

public int pQty;


public Product(String pCode,String pName,float pPrice,
int pQty) {
Ve

[Link]=pCode;
[Link]=pName;
[Link]=pPrice;
[Link]=pQty;
}
public String toString() {
return pCode+"\t"+pName+"\t"+pPrice+"\t"+pQty;
}
}
[Link]

package maccess;

import [Link].*;

import [Link];

public class DemoArray3 {

public static void main(String[] args) {

ii
Scanner s = new Scanner([Link]);

ath
try(s;){

try {

aip
[Link]

("Enter the number of Products:");


hM
int n = [Link]([Link]());

Product p[] = new Product[n];

//Array holding n product objects


tes

[Link]("Enter "+n+" Products:");

for(int i=0;i<[Link];i++)
a

{
nk

[Link]("Enter the PCode:");

String pCode = [Link]();


Ve

[Link]("Enter the PName:");

String pName = [Link]();

[Link]("Enter the PPrice:");

float pPrice =

[Link]([Link]());
[Link]("Enter the PQty:");

int pQty = [Link]([Link]());

p[i] = new Product(pCode,pName,pPrice,pQty);

}//end of loop

[Link]("==Uisng Old for loop==");

for(int i=0;i<[Link];i++)

ii
{

ath
[Link](p[i].toString());

}//end of loop

aip
[Link]("===Using Extended for===");

for(Product k : p)
hM
{

[Link]([Link]());

}//end of loop
tes

}catch(Exception e) {[Link]();}

}//end of try-with-resource
a

}
nk

o/p:
Ve

Enter the number of Products:

Enter 3 Products:

Enter the PCode:

A121
Enter the PName:

Mou

Enter the PPrice:

123.45

Enter the PQty:

12

ii
Enter the PCode:

ath
A122

Enter the PName:

aip
KKB

Enter the PPrice:


hM
234.56

Enter the PQty:

10
tes

Enter the PCode:

A124
a

Enter the PName:


nk

CDR

Enter the PPrice:


Ve

456.34

Enter the PQty:

11

==Uisng Old for loop==

A121 Mou 123.45 12


A122 KKB 234.56 10

A124 CDR 456.34 11

===Using Extended for===

A121 Mou 123.45 12

A122 KKB 234.56 10

A124 CDR 456.34 11

ii
----------------------------------------------------

ath
Diagram:

aip
hM
tes

======================================================
a

Assignment:
nk

wap read and display Multiple Student details with result using
Ve

Array?

====================================================

faq:

define Object Array?

=>The Array which is declared with '[Link]' class is

known as Object Array.


syntax:

Object o[] = new Object[size];

Note:

=>'[Link]' class is the PClass of all the classes used

ii
in JavaApp.

ath
=>Object Array can hold Dis-Similer objects,which means objects

of different classes.

Ex_program:

aip
hM
[Link]

package maccess;
import [Link];
public class DemoArray4 {
@SuppressWarnings("removal")
tes

public static void main(String[] args) {


Object o[] = new Object[3];
//Object Array to hold 3 Objects
o[0] = new Integer(121);//Integer Object
a

o[1] = new String("XYZ");//String Object


o[2] = new Product("A121","KB",123,12);
nk

[Link]("===Display from Object Array==");


for(Object k : o)
{
Ve

[Link]([Link]());
}//end of loop
}
}

o/p:

===Display from Object Array==


121

XYZ

A121 KB 123.0 12

==================================================

[Link] Dimensional Arrays:

=>The Arrays which are declared with multiple dimensions are

ii
known as Multi-Dimensional Arrays.

ath
Ex:

2-D Arrays

aip
3-D Arrays

4-D Arrays
hM
.....

Note:
tes

=>In realtime Multi-D Arrays are less used when compared to

Single-D Arrays.
a

=>But,Using 2-D Arrays we can construct 'Jagged Arrays'.


nk

syntax of 2-D Array:

Class_name arr_var[][] = new Class_name[rows][cols];


Ve

faq:

define Jagged Arrays?

=>Array which is holding Array Objects is known as Jagged Array.


Ex_Program : [Link]

package maccess;
public class DemoArray5 {
public static void main(String[] args) {
Integer a1[] = {1,2,3};
Integer a2[] = {11,12,13,14};
Integer a[][] = {a1,a2};//Jagged_Array
[Link]("===Display from Jagged_Array===");
for(Integer k[] : a)
{
[Link]("Array : ");

ii
for(Integer z : k)

ath
{
[Link]([Link]()+" ");
}//InnerLoop or Nested loop
[Link]();
}//end of outer loop

aip
}
}
hM
o/p:

===Display from Jagged_Array===


tes

Array : 1 2 3

Array : 11 12 13 14
a
nk

diagram:
Ve
ii
ath
aip
hM
=========================================================
a tes
nk
Ve

Common questions

Powered by AI

Java arrays are powerful constructs that can store fixed-size sequential elements of the same type, either primitive or objects. Java supports arrays of primitive data types (like int, char, etc.) and user-defined class objects. This dual capacity allows developers to efficiently handle both numeric data and complex structures such as instances of classes, enabling extensive manipulation of data within a single, unified structure .

The `toString()` method is significant as it provides a string representation of an object, which is essential for debugging and logging. Overriding this method allows customized display output for class instances, enhancing readability and diagnosis of object state. However, its limitations include potential performance overhead for complex objects and the risk of exposing sensitive internal data if not carefully implemented. Thus, thoughtful design is required to balance utility and privacy .

Enhanced for loops offer a more streamlined approach for both user-defined class objects and primitive data types in Java. They abstract the iterative process by directly operating on elements, reducing boilerplate code including index management. While their use with user-defined objects simplifies object access and operations, it limits the ability to modify the underlying array in place, unlike a traditional loop that allows for both element inspection and modification through index access .

Java's Object class serves as the root of the class hierarchy, enabling polymorphism through features like method overriding and dynamic method dispatch. It allows all Java objects to be treated uniformly, supporting heterogeneity by facilitating collections that can hold any object type. This foundational aspect empowers developers to write flexible and reusable code, accommodating a wide range of data types within a single idiomatic framework .

An Object Array is preferred when you need to store and process a collection of heterogeneous objects, as it can hold objects of different classes. This flexibility is useful when dealing with complex systems requiring diverse data representations. A regular primitive array is limited to storing elements of a single data type, making Object Arrays more versatile for varying requirements .

In the `Product` class, encapsulation is exemplified by storing product codes and names as private fields, making them accessible only through the class's methods or permissible operations. This approach helps in safeguarding data integrity and controlling access, as it restricts external manipulation, enforces constraints, and enhances modularity, centralized management, and potential integration with other components without revealing the underlying implementation details .

The try-with-resources statement in Java is beneficial for automatically managing resource closure, particularly useful in I/O operations where resources like streams need explicit closing to avoid resource leaks. It simplifies the code and reduces the risk of forgetting to close resources manually, thus improving the robustness and maintainability of error-handling mechanisms within Java applications .

The primary advantage of an extended for loop is its simplicity in syntax, eliminating the need for initialization, condition, and increment/decrement operations. It automatically iterates over all the elements of an array or a collection, making the code cleaner and reducing the chance for errors related to loop boundary conditions or increments .

Jagged Arrays in Java are essentially arrays of arrays, where each sub-array can have different lengths. This contrasts with traditional multi-dimensional arrays, which must have the same number of elements in each row. Jagged Arrays are advantageous in scenarios where the data set is inherently irregular, such as handling variable-length data records, like rows with varying numbers of columns in a spreadsheet-like structure .

Transitioning from single-dimensional to multi-dimensional arrays, particularly jagged arrays, presents challenges such as increased complexity in indexing and element access patterns. Understanding that each sub-array can be of a different length necessitates careful handling of data to avoid runtime errors. Developers must also adapt to more complex logical structures when iterating and processing these arrays, requiring a more nuanced understanding of array initialization and memory management .

You might also like