Tangible Software Solutions

VB.NET and Java Comparison and Equivalents


Equivalents were produced with the Free Edition of Instant C# (VB to C# converter) and the Free Edition of C# to Java Converter.


Java VB.NET
public abstract class AbstractClass
{
    public abstract void AbstractMethod();
}
Public MustInherit Class AbstractClass
    Public MustOverride Sub AbstractMethod()
End Class
Java VB.NET
public
no access modifier (package access)
private
no exact equivalent
protected
Public
Friend
Private
Protected
Protected Friend

The closest equivalent to Java anonymous inner classes in VB.NET is to use a private class which implements the corresponding interface (but if the interface is a functional interface, then the closest equivalent is to replace the functional interface with a delegate and the anonymous inner class with a lambda).

Java VB.NET
public class TestClass
{
    private void TestMethod()
    {
        MyInterface localVar = new MyInterface()
        {
            public void method1()
            {
                someCode();
            }
            public void method2(int i, boolean b)
            {
                someCode();
            }
        };
    }
}
Public Class TestClass
    Private Sub TestMethod()
        Dim localVar As MyInterface = New MyInterfaceAnonymousInnerClass(Me)
    End Sub

    Private Class MyInterfaceAnonymousInnerClass
        Inherits MyInterface

        Private ReadOnly outerInstance As TestClass

        Public Sub New(ByVal outerInstance As TestClass)
            Me.outerInstance = outerInstance
        End Sub

        Public Sub method1()
            someCode()
        End Sub
        Public Sub method2(ByVal i As Integer, ByVal b As Boolean)
            someCode()
        End Sub
    End Class
End Class

Unsized Array

Java VB.NET
int[] myArray = null; Dim myArray() As Integer = Nothing

Sized Array

Java VB.NET
int[] myArray = new int[2]; Dim myArray(1) As Integer

Access Array Element

Java VB.NET
x = myArray[0]; x = myArray(0)

Jagged Array

Java VB.NET
int[][] myArray = new int[2][]; Dim myArray(1)() As Integer

Rectangular Array

Java VB.NET
int[][] myArray = new int[2][3]; Dim myArray()() As Integer = RectangularArrays.RectangularIntegerArray(2, 3)

' ----------------------------------------------------------------------------------------
' Copyright © 2007 - 2024 Tangible Software Solutions Inc.
' This module can be used by anyone provided that the copyright notice remains intact.
'
' This module includes methods to convert Java rectangular arrays (jagged arrays
' with inner arrays of the same length).
' ----------------------------------------------------------------------------------------
Friend Module RectangularArrays
    Friend Function RectangularIntegerArray(ByVal size1 As Integer, ByVal size2 As Integer) As Integer()()
        Dim newArray As Integer()() = New Integer(size1 - 1)() {}
        For array1 As Integer = 0 To size1 - 1
            newArray(array1) = New Integer(size2 - 1) {}
        Next array1

        Return newArray
    End Function
End Module

Java does not support VB.NET-style 'ByRef' parameters. All Java parameters are passed by value (if it's a reference, then the reference is passed by value). However, you can wrap the parameter type in another type (we call it 'RefObject').

Here's a simple example:

VB Java
Public Sub refParamMethod(ByRef i As Integer)
    i = 1
End Sub

Public Sub callRefParamMethod()
    Dim i As Integer = 0
    refParamMethod(i)
End Sub
public void refParamMethod(tangible.RefObject<Integer> i)
{
    i.argValue = 1;
}

public void callRefParamMethod()
{
    int i = 0;
    tangible.RefObject<Integer> tempRef_i = new tangible.RefObject<Integer>(i);
    refParamMethod(tempRef_i);
    i = tempRef_i.argValue;
}

package tangible;

// ----------------------------------------------------------------------------------------
// Copyright © 2007 - 2024 Tangible Software Solutions Inc.
// This class can be used by anyone provided that the copyright notice remains intact.
//
// This class is used to replicate the ability to pass arguments by reference in Java.
// ----------------------------------------------------------------------------------------
public final class RefObject<T>
{
    public T argValue;
    public RefObject(T refArg)
    {
        argValue = refArg;
    }
}

The closest equivalent to the standard VB casting operators (CType and the corresponding CInt, CStr, etc.) are calls to the 'parse' methods (Integer.parseInt, Short.parseShort, etc.) if the argument is a string, otherwise they are converted to the standard Java casting operator.

The Java equivalent to VB's DirectCast is the standard Java casting operator.

The VB TryCast operator conversion always uses the Java instanceof operator.

VB.NET Java
Dim y As String
x = CBool(y)
x = CInt(y)

x = CType(y, Foo)
x = DirectCast(y, Foo)
x = TryCast(y, Foo)
String y = null;
x = Boolean.parseBoolean(y);
x = Integer.parseInt(y);

x = (Foo)y;
x = (Foo)y;
x = y instanceof Foo ? (Foo)y : null;

In VB, the keyword 'From' is used to initialize collections during construction.

VB.NET Java
' List:
Dim myList As New List(Of Integer)() From {1, 2, 3}

' Dictionary:
Dim myD As New Dictionary(Of String, Integer) From {
    {string1, 80},
    {string2, 85}
}
import java.util.*;

// ArrayList: (Java 9 List.of would also work here)
ArrayList<Integer> myList = new ArrayList<Integer>(Arrays.asList(1, 2, 3));

// HashMap: (Map.ofEntries requires Java 9)
HashMap<String, Integer> myD = new HashMap<String, Integer>(Map.ofEntries(Map.entry(string1, 80), Map.entry(string2, 85)));

ArrayLists/Lists

Java's java.util.ArrayList collection and the .NET System.Collections.Generic.List collection are very close equivalents.

Java VB.NET
void ArrayLists()
{
    java.util.ArrayList<Integer> myList = new java.util.ArrayList<Integer>();
    myList.add(1);
    myList.add(1, 2);
    int i = 1;
    myList.set(0, i);
    i = myList.get(0);
}
Imports System.Collections.Generic

Private Sub ArrayLists()
    Dim myList As New List(Of Integer?)()
    myList.Add(1)
    myList.Insert(1, 2)
    Dim i As Integer = 1
    myList(0) = i
    i = myList(0).Value
End Sub

HashMaps/Dictionaries

Java's java.util.HashMap collection and the .NET System.Collections.Generic.Dictionary collection are very close equivalents.

Java's java.util.TreeMap collection and the .NET System.Collections.Generic.SortedDictionary collection are also very close equivalents.

Java VB.NET
void HashMaps()
{
    java.util.HashMap<String, Integer> map = new java.util.HashMap<String, Integer>();
    String s = "test";
    map.put(s, 1);
    int i = map.get(s);
    i = map.size();
    boolean b = map.isEmpty();
    map.remove(s);
}
Imports System.Collections.Generic

Private Sub HashMaps()
    Dim map As New Dictionary(Of String, Integer?)()
    Dim s As String = "test"
    map(s) = 1
    Dim i As Integer = map(s).Value
    i = map.Count
    Dim b As Boolean = map.Count = 0
    map.Remove(s)
End Sub

Local Constant

VB.NET Java
Const myConst As Integer = 2 final int myConst = 2;

Class Constant

VB.NET Java
Public Const myConst As Integer = 2 public static final int myConst = 2;

Local Variable

VB.NET Java
Dim myVar As Integer = 2 int myVar = 2;

Inferred Types

There is no inferred typing in Java, so the type is inferred by the converter:

VB.NET Java
Option Infer On
...
Dim myVar = 2
int myVar = 2;

Shared/Static Field

VB.NET Java
Public Shared S As Integer public static int S;

Read-Only Field

VB.NET Java
Public ReadOnly R As Integer = 2 public final int R = 2;

VB Static Local Variable

VB.NET Java
Sub Method()
    Static s As Integer
    s += 1
End Sub
private int Method_s;
void Method()
{
    Method_s += 1;
}
VB.NET Java
Class Foo
    Public Sub New()
        Me.New(0) ' call to other constructor
    End Sub

    Public Sub New(ByVal i As Integer)
    End Sub

    Protected Overrides Sub Finalize()
    End Sub
End Class
class Foo
{
    public Foo()
    {
        this(0); // call to other constructor
    }

    public Foo(int i)
    {
    }

    protected void finalize() throws Throwable
    {
    }
}
Java VB.NET
int
boolean
java.lang.String (no Java language built-in type)
char
float
double
java.lang.Object (no Java language built-in type)
java.math.BigDecimal (no Java language built-in type)
java.time.LocalDateTime (no Java language built-in type)
short
long
no unsigned types in Java
byte (signed byte)
no unsigned types in Java
no unsigned types in Java
no unsigned types in Java
Integer
Boolean
String
Char
Single
Double
Object
Decimal
Date
Short
Long
Byte (unsigned byte)
SByte (signed byte)
UShort (unsigned short)
UInteger (unsigned int)
ULong (unsigned long)

Simple enums in Java have simple equivalents in VB:

Java VB
public enum Simple
{
    FOO,
    BAR
}
Public Enum Simple
    FOO
    BAR
End Enum

More complex enums in Java unfortunately have exceedingly complex equivalents in VB:

Java VB
public enum Complex
{
    FOO("Foo"),
    BAR("Bar");

    private final String value;

    Complex(String enumValue)
    {
        this.value = enumValue;
    }

    public void InstanceMethod()
    {
        // ...
    }
}
Imports System.Collections.Generic

Public NotInheritable Class Complex
    Public Shared ReadOnly FOO As New Complex("FOO", InnerEnum.FOO, "Foo")
    Public Shared ReadOnly BAR As New Complex("BAR", InnerEnum.BAR, "Bar")

    Private Shared ReadOnly valueList As New List(Of Complex)()

    Shared Sub New()
        valueList.Add(FOO)
        valueList.Add(BAR)
    End Sub

    Public Enum InnerEnum
        FOO
        BAR
    End Enum

    Public ReadOnly innerEnumValue As InnerEnum
    Private ReadOnly nameValue As String
    Private ReadOnly ordinalValue As Integer
    Private Shared nextOrdinal As Integer = 0

    Private ReadOnly value As String

    Friend Sub New(ByVal name As String, ByVal thisInnerEnumValue As InnerEnum, ByVal enumValue As String)
        Me.value = enumValue

        nameValue = name
        ordinalValue = nextOrdinal
        nextOrdinal += 1
        innerEnumValue = thisInnerEnumValue
    End Sub

    Public Sub InstanceMethod()
        ' ...
    End Sub

    Public Shared Function values() As Complex()
        Return valueList.ToArray()
    End Function

    Public Function ordinal() As Integer
        Return ordinalValue
    End Function

    Public Overrides Function ToString() As String
        Return nameValue
    End Function

    Public Shared Operator =(ByVal one As Complex, ByVal two As Complex) As Boolean
        Return one.innerEnumValue = two.innerEnumValue
    End Operator

    Public Shared Operator <>(ByVal one As Complex, ByVal two As Complex) As Boolean
        Return one.innerEnumValue <> two.innerEnumValue
    End Operator

    Public Shared Function valueOf(ByVal name As String) As Complex
        For Each enumInstance As Complex In Complex.valueList
            If enumInstance.nameValue = name Then
                Return enumInstance
            End If
        Next
        Throw New System.ArgumentException(name)
    End Function
End Class
VB.NET Java
Try
    ...
Catch x As FooException
    ...
Catch y As BarException When z = 1
    ...
Finally
    ...
End Try
try
{
    ...
}
catch (FooException x)
{
    ...
}
// There is no Java equivalent to 'When':
catch (BarException y) // When z = 1
{
    ...
}
finally
{
    ...
}

Java doesn't have extension methods, so a VB.NET extension method is just converted to an ordinary Java static method (calls to the method have to be adjusted to static calls using the class name).

VB.NET Java
Public Module ContainsExtension
    <System.Runtime.CompilerServices.Extension> _
    Public Sub ExtensionMethod(ByVal myParam As String)
        ' ...
    End Sub
End Module
Class TestClass
    Private Sub TestMethod()
        Dim s As String = "test"
        s.ExtensionMethod()
    End Sub
End Class
public final class ContainsExtension
{
    public static void ExtensionMethod(String myParam)
    {
        // ...
    }
}
public class TestClass
{
    private void TestMethod()
    {
        String s = "test";
        ContainsExtension.ExtensionMethod(s);
    }
}
Java VB.NET
for (String s : StringList)
{
    ...
}
For Each s As String In StringList
    ...
Next s

Java's functional interfaces are closely related to VB.NET delegates.

Java VB.NET
@FunctionalInterface
public interface FooFunctional
{
    void invoke();
}

public class UseFunctionalInterface
{
    void method()
    {
        FooFunctional funcVar = () -> voidMethod();
        funcVar.invoke();
    }
    void voidMethod()
    {
    }
}
Public Delegate Sub FooFunctional()

Public Class UseFunctionalInterface
    Overridable Sub method()
        Dim funcVar As FooFunctional = Sub() voidMethod()
        funcVar()
    End Sub
    Overridable Sub voidMethod()
    End Sub
End Class

Java generics and VB generics are implemented in totally different ways — Java generics uses the concept of 'type erasure' (compiling to Object and casts), while VB generics is a run-time feature, but you can usually achieve the same result by converting one to the other.

Defining a Generic Class

Java VB.NET
public class GenericClass<T>
{
}
Public Class GenericClass(Of T)
End Class

Defining a Generic Class with a Constraint

Java VB.NET
public class GenericClass<T extends SomeBase>
{
}
Public Class GenericClass(Of T As SomeBase)
End Class

Defining a Generic Method

Java VB.NET
public <T> void Method(T param)
{
}
Public Sub Method(Of T)(ByVal param As T)
End Sub

Defining a Generic Method with a Constraint

Java VB.NET
public <T extends SomeBase> void Method(T param)
{
}
Public Sub Method(Of T As SomeBase)(ByVal param As T)
End Sub
Java VB.NET
import Foo.*;
import static Foo.Bar.*;

*no equivalent*
*no equivalent*
Imports Foo
Imports Foo.Bar

' namespace alias:
Imports foo = SomeNamespace
' type alias:
Imports bar = SomeNamespace.SomeType

Java does not have indexers, so you must use get/set methods instead:

VB.NET Java
Default Public Property Item(ByVal index As Integer) As Integer
    Get
        Return field(index)
    End Get
    Set(ByVal value As Integer)
        field(index) = value
    End Set
End Property
public final int get(int index)
{
    return field[index];
}
public final void set(int index, int value)
{
    field[index] = value;
}

Basic Inheritance

VB.NET Java
Class Foo
    Inherits SomeBase

End Class
class Foo extends SomeBase
{
}

Inheritance Keywords

VB.NET Java
MustInherit    (class)
MustOverride    (method)
Overrides
NotInheritable    (class)
NotOverridable    (method)
Shadows
abstract    (class)
abstract    (method)
@Override (annotation)
final    (class)
final    (method)
no Java equivalent

Defining Interfaces

Java VB.NET
public interface IFoo
{
    void Method();
}
Public Interface IFoo
    Sub Method()
End Interface

Implementing Interfaces

Java VB.NET
public class Foo implements IFoo
{
    public void Method()
    {
    }
}
Public Class Foo
    Implements IFoo

    Private Sub Method() Implements IFoo.Method
    End Sub
End Class

*note that you can use a method name which does not match the interface method name, provided that the 'Implements' name matches

Expression Lambda

Java VB.NET
myVar = (String text) -> text.Length; myVar = Function(text As String) text.Length

Multi-statement Lambda

Java VB.NET
myVar = (String text) ->
{
    return text.Length;
}
myVar = Function(text As String)
    Return text.Length
End Function

For Loop

VB.NET Java
For i As Integer = 1 To 9
Next i
for (int i = 1; i <= 9; i++)
{
}

For Each Loop

VB.NET Java
For Each s As String In StringList
Next S
for (String s : StringList)
{
}

While Loop

VB.NET Java
Do While condition
Loop

or:

While condition
End While
while (condition)
{
}

Do While Loop

VB.NET Java
Do
Loop While condition
do
{
} while (condition);

Loop Until

VB.NET Java (no specific 'loop until' construct)
Do
Loop Until condition
do
{
} while ( ! condition);

Do Until

VB.NET Java (no specific 'do until' construct)
Do Until condition
Loop
while ( ! condition)
{
}
VB.NET Java
Public Module Utility
    Public Sub UtilityMethod()
        ...
    End Sub
End Module

or:

Public NotInheritable Class Utility
    Private Sub New() ' prevent instantiation
    End Sub

    Public Shared Sub UtilityMethod()
        ...
    End Sub
End Class
public final class Utility
{
    public static void UtilityMethod()
    {
        // ...
    }
}

Java 15 has 'text blocks', but check the documentation — the rules about indentation are very convoluted. Prior to Java 15, the closest you can get is a string concatenation which spans multiple lines.

VB.NET Java
Dim s As String = "multiline
    string"
// Java 15 text blocks:
String s = """
multiline
    string""";

// before Java 15:
String s = "multiline" + "\r\n" +
    " string";

Most programming languages allow 'overloading' operators to implement specialized behavior for the operator when used on an instance of a type. Java doesn't allow this, but the same behavior is achieved through static methods:

VB.NET Java
Public Class SomeType
    Private IntValue As Integer

    Public Shared Operator +(ByVal X As SomeType, ByVal Y As SomeType) As Integer
        Return X.IntValue + Y.IntValue
    End Operator

    Public Sub OperatorTest()
        Dim o1 As New SomeType()
        Dim o2 As New SomeType()
        Dim i As Integer = o1 + o2
    End Sub
End Class
public class SomeType
{
    private int IntValue;

    public static int opAdd(SomeType X, SomeType Y)
    {
        return X.IntValue + Y.IntValue;
    }

    public final void OperatorTest()
    {
        SomeType o1 = new SomeType();
        SomeType o2 = new SomeType();
        int i = SomeType.opAdd(o1, o2);
    }
}
VB.NET Java
+, -, *, >, >=, <, <=, <<, >>
&    (string concatenation)
()    (indexing)
CInt(CUInt(x) >> y)
And
Or
AndAlso
OrElse
Not
Xor
Mod
x ^ y
=
Is
IsNot
<>

If(x, y, z)
If(x, y)

x / y    (where x and y are integers)
x / y    (where x and y are doubles)
x \ y    (where x and y are integers)

x \ y    (where x and y are doubles)
unchanged
+    (string concatenation)
[]
x >>> y
&
|
&&
||
! or ~    (depending on context)
^
%
Math.pow(x, y)    (no exponentiation operator)
= or ==    (depending on context)
==
!=
!=

x ? y : z
x != null ? x : y

x / (double)y
x / y
x / y

Java does not allow optional parameters. Overloaded methods are the only alternative in Java to optional parameters. A VB.NET method with n optional parameters is converted to n + 1 overloaded methods. The overloaded methods call the overloaded method with the maximum number of parameters (which contains your original method code), passing the default values originally specified for the original optional parameters.

Here's an example of the simplest possible case:

VB.NET Java
Public Sub TestOptional(Optional ByVal x As Integer = 0)
    ...
End Sub
public void TestOptional()
{
    TestOptional(0);
}
public void TestOptional(int x)
{
    ...
}
Java VB.NET
package FooPackage; // only one per file

public class FooClass
{
}
Namespace FooPackage ' can have many per file
    Public Class FooClass
    End Class
End Namespace
Java VB.NET
private void Method(Object... myParam)
{
}
Sub Method(ParamArray ByVal myParam() As Object)
End Sub

Java does not have properties, so you must use get/set methods instead:

VB.NET Java
Public Property IntProperty() As Integer
    Get
        Return intField
    End Get
    Set(ByVal value As Integer)
        intField = value
    End Set
End Property
public int getIntProperty()
{
    return intField;
}
public void setIntProperty(int value)
{
    intField = value;
}

For simple cases, VB's Select construct can be converted to the Java switch construct. However, if any of the Case statements include range or non-constant expressions, then the equivalent is an if/else block.

VB Java
' converts to switch:
Select Case x
    Case 0
        ...
    Case 1
        ...
End Select

' converts to if/else:
Select Case x
    Case 1 To 3
        ...
    Case Is < 10, Is > 20, Is = 15
        ...
End Select
// converts to switch:
switch (x)
{
    case 0:
        // ...
        break;
    case 1:
        // ...
        break;
}

// converts to if/else:
if (x >= 1 && x <= 3)
{
    ...
}
else if ((x < 10) || (x > 20) || (x == 15))
{
    ...
}

Java static initializer blocks and VB.NET shared constructors serve the same purpose.

Java VB.NET
class Foo
{
    public static int field;

    static
    {
        field = 1;
    }
}
Class Foo
    Public Shared field As Integer

    Shared Sub New()
        field = 1
    End Sub
End Class

The string equality operators mean different things in Java and VB. In Java, it means identity equality, but in VB it means value equality.

Java VB
String one = "one";
String two = "two";

// testing that 2 string objects are the same object
// caution: Java string internment often
// makes this true whenever 'equals' is true:
boolean res = one == two;

// null-tolerant string comparison
res = Objects.equals(one, two);

// non-null-tolerant string comparison (exception if 'one' is null)
res = one.equals(two);
Dim one As String = "one"
Dim two As String = "two"

' testing that 2 string objects are the same object
' caution: VB string internment often
' makes this true whenever '==' is true:
result = String.ReferenceEquals(one, two)

' null-tolerant string comparison
result = one = two 'or: result = String.Equals(one, two)

' non-null-tolerant string comparison (exception if 'one' is null)
result = one.Equals(two)
Java VB.NET
synchronized (x)
{
    ...
}
SyncLock x
    ...
End SyncLock
Java VB.NET
boolean b = f instanceof Foo;
Class t = w.class;
Dim b As Boolean = TypeOf f Is Foo
Dim t As Type = GetType(w)

The VB.NET 'Using' statement is a shortcut for a Try/Finally block which disposes an object of type System.IDisposable. Java 7 introduces the 'try with resources' statement, which operates on objects of type java.io.Closeable:

VB Java
Using f As New Foo()
End Using

// Java 7 or higher:
try (Foo f = new Foo())
{
}

// Before Java 7:
Foo f = new Foo();
try
{
}
finally
{
    f.close();
}

Only simple cases of VB legacy error handling can be converted to Java.

VB.NET Java
Public Sub LegacyErrorHandling()

    On Error GoTo ErrorHandler
    ' ... main logic

ErrorHandler:
    ' ... error handling code
End Sub
public void LegacyErrorHandling()
{
    try
    {
        // ... main logic
    }
    catch
    {
        // ... error handling code
    }
}
VB.NET Java (omitting null handling)
LCase(x)
UCase(x)
Left(x, 2)
Right(x, 2)
Mid(x, 3)
InStr(x, y)
InStrRev(x, y)
x.toLowerCase()
x.toUpperCase()
x.substring(0, 2)
x.substring(x.length() - 2)
x.substring(2)
x.indexOf(y) + 1
x.lastIndexOf(y) + 1

These are rarely used, but still supported.

VB.NET Java
Dim myIntegerVar%
Dim myStringVar$
Dim myFloatVar!
Dim myDoubleVar#
int myIntegerVar = 0;
String myStringVar = null;
float myFloatVar = 0;
double myDoubleVar = 0;

Copyright © 2004 – 2024 Tangible Software Solutions Inc.