Click here to Skip to main content
15,902,634 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package programmingbasics1;
import java.util.Scanner;

/**
 *
 * @author Vedha
 */
public class Palindrome {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int arr[]=new int[5];
        int arr_new[]=new int[5];
        for(int i=0;i<5;i++)
        {
            System.out.print("Enter array integer at "+i+": ");
            arr[i]=sc.nextInt();
        }
        
        for(int i=0,j=4;i<5&&j>=0;i++,j--)
        {
            arr_new[i]=arr[j];
        }
        System.out.print("Old array: ");
        for(int k=0;k<5;k++)
            System.out.print(arr[k]+" ");
        System.out.println();
        System.out.print("New array: ");
        for(int k=0;k<5;k++)
            System.out.print(arr_new[k]+" ");
        System.out.println();
        
        if(arr==arr_new)
           System.out.print(" It is a Palindrome");
        else
            System.out.print("It is not a Palindrome");
    }
    
}


What I have tried:

I have posted my code, I'm not able to find the error in this.
Posted
Updated 11-Feb-17 19:36pm

This
Java
if(arr==arr_new)

is not how to compare the contain of 2 arrays.
This is true only if both array share the same address in memory.
You must manually compare each element.
 
Share this answer
 
Arrays are object in Java, when you use
==
you are looking for the same object instance of different names that point to the same memory location. To compare the equality of all elements in two objects (arrays in this case), you have to use
equals
. Change this
if(arr==arr_new)
to
if(Arrays.equals(arr, arr_new))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900