Java Exercises: Check if a positive number is a palindrome or not

Java Basic: Exercise-115 with Solution

Write a Java program to check if a positive number is a palindrome or not.

Pictorial Presentation:

Java Basic Exercises: Check a positive number is a palindrome or not

Sample Solution:

Java Code:

import java.util.*; 
public class Exercise115 {
 public static void main(String[] args)
        int num;
        Scanner in = new Scanner(System.in);	
        System.out.print("Input a positive integer: ");
        int n = in.nextInt(); 
        System.out.printf("Is %d is a palindrome number?\n",n);
private static boolean palindrome(int num) {
        String str = String.valueOf(num);
        int i = 0;
        int j = str.length() - 1;
        while (i < j) {
            if (str.charAt(i++) != str.charAt(j--)) {
                return false;
        return true;

Sample Output:

Input a positive integer: 151                                          
Is 151 is a palindrome number?                                         


Flowchart: Java exercises: Check a positive number is a palindrome or not

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to given a string and an offset, rotate string by offset (rotate from left to right).
Next: Write a Java program which iterates the integers from 1 to 100. For multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". When number is divided by both three and five, print "fizz buzz".

What is the difficulty level of this exercise?

Java: Tips of the Day

Execution of console commands:

Java allows you to execute console commands directly from code using a class Runtime. It is very important not to forget about exception handling.

For example, let's try to open a PDF file through a Java terminal:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellCommandExec {
  public static void main(String[] args) {
    String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";
    try {
      Runtime rt = Runtime.getRuntime();
      Process processObj = rt.exec(gnomeOpenCommand);
      InputStream stdin = processObj.getErrorStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
      String myoutput = "";
      while ((myoutput=br.readLine()) != null) {
        myoutput = myoutput+"\n";
    catch (Exception e) {