Tangible Software Solutions

The Most Trusted Name in Source Code Conversion

Division in Java vs. VB

Division is performed differently in Java and VB.  Java, like other C-based languages truncates the division result when both operands are integer literals or integer variables (or integer constants).  In VB, you must use the integer division operator (\) to get a similar result.

e.g.,

Java:

double d = 5 / 3;  //assigns 1 to d (truncated since both operands are integers)

VB - Option Strict On:

Dim d As Double = 5 / 3  'assigns 1.666... to d

Dim d As Double = 5 \ 3  'assigns 1 to d

VB - Option Strict Off:

With Option Strict Off in VB, the results can be confusing.  In the following example, contrary to what you might expect, 1 is not produced in both cases:

Dim d As Double = 5.4 \ 3  'assigns 1 to d

Dim d As Double = 5.6 \ 3  'assigns 2 to d

With Option Strict Off, VB first rounds the integer division operands (the first case rounds 5.4 to 5 and the second rounds 5.6 to 6), before truncating the division result.  With Option Strict On, this would not compile.

Copyright © 1997 - 2017 Tangible Software Solutions Inc.