I know how the ++ operator and -- operator works.This is my code to count the no of digit in an integer and it works perfectly.

import java.util.Scanner;

public class modified_sepadigit
{
    public static void main(String args[])
    {
        Scanner input=new Scanner(System.in);
        System.out.println("Enter a  number");
        int no=input.nextInt();
        int noOfDigit=0;
        int tempNo=no;
        while(tempNo>=1)
        {
            tempNo=tempNo/10;
            noOfDigit++;
        }
        System.out.println("No of digits:"+ noOfDigit);


    }
}

But if i change noOfDigit++ in the while loop to noOfDigit=noOfDigit++, then i always get ouput as 0.
Now i know that it is meaningless to write noOfDigit=noOfDigit++ when i can simply write noOfDigit++
What i think is that If that statement worked then i should get input as the (total no of digits in an number) -1 beacause of the way post increment works.
Can  anybody tell me why i am getting output as 0 always if i change noOfDigit++ in the while loop to noOfDigit=noOfDigit++ ?  

Recommended Answers

All 3 Replies

It prints out 0 because it takes noOfdigits, stores a copy then adds 1 and returns the copy. So you get the value of what it was, but also increments it at the same time. Therefore you print out the last value though it gets incremented.

ok i understood, that was nice explanation in the blog.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.