Java Example – Array Reversal
In the following example, we use a custom reverse method to reverse the array:
Example 1
public
class
RunoobTest
{
/* reverse the array */
static
void
reverse
(
int
a
[
]
,
int
n
)
{
int
[
]
b
=
new
int
[
n
]
;
int
j
=
n
;
for
(
int
i
=
0
;
i
<
n
;
i
++
)
{
b
[
j
1
]
=
a
[
i
]
;
j
=
j
1
;
}
/Input the reversed array/
System
.
out
.
println
(
"The reversed array is: \n"
)
;
for
(
int
k
=
0
;
k
<
n
;
k
++
)
{
System
.
out
.
println
(
b
[
k
]
)
;
}
}
public
static
void
main
(
String
[
]
args
)
{
int
[
]
arr
=
{
10
,
20
,
30
,
40
,
50
}
;
reverse
(
arr, arr.
length
)
;
}
}
The output of the above code is:
The reversed array is:
50
40
30
20
10
Example 2
public
class
RunoobTest
{
/* create a method: swap the first with the last, the second with the second-to-last, and so on */
static
void
reverse
(
int
a
[
]
,
int
n
)
{
int
i, k, t
;
for
(
i
=
0
;
i
<
n
/
2;
i
++
)
{
t
=
a
[
i
]
;
a
[
i
]
=
a
[
n
i
1
]
;
a
[
n
i
1
]
=
t
;
}
System
.
out
.
println
(
"The reversed array is: \n"
)
;
for
(
k
=
0
;
k
<
n
;
k
++
)
{
System
.
out
.
println
(
a
[
k
]
)
;
}
}
public
static
void
main
(
String
[
]
args
)
{
int
[
]
arr
=
{
10
,
20
,
30
,
40
,
50
}
;
reverse
(
arr, arr.
length
)
;
}
}
The output of the above code is:
The reversed array is:
50
40
30
20
10
Example
import
java.util.*
;
public
class
RunoobTest
{
/* use the java.util.Arrays.asList(array) method */
static
void
reverse
(
Integer
a
[
]
)
{
Collections
.
reverse
(
Arrays
.
asList
(
a
)
)
;
System
.
out
.
println
(
Arrays
.
asList
(
a
)
)
;
}
public
static
void
main
(
String
[
]
args
)
{
Integer
[
]
arr
=
{
10
,
20
,
30
,
40
,
50
}
;
reverse
(
arr
)
;
}
}
The output of the above code is:
[50, 40, 30, 20, 10]
Java Examples