[Java] From Java to VB.NET ―A memo for writing style―

23 minute read

About this article

Background of creation

I’ve been working on Java for 3 months in new employee training, but the language I use in my department was Visual Basic .NET, so I had to learn anew. However, I wonder if there are so many cases of “Migrating from Java to VB.NET” (C# is normal now…?), and I could not find a site that did detailed grammar comparison, so I wrote it myself. did.

Target/Purpose

  • I have a complete understanding of Java writing and programming concepts
  • I want to be able to write programs in VB.NET from now on

I provide a reference for comparing Java and VB.NET to someone (well, I’m synchronizing a few people with myself).

Environment

  • Windows 10
  • Visual Studio 2019
  • .NET Framework 4.7.2

Even so, there should be almost no environment-dependent code.

Notes on description

  • Visual Basic .NET (VB.NET) is simply called “VB” below.
  • The Java and VB code in the same section basically do the same thing.

References (general)

  • Hiroshi Hayama “Basic Visual Basic 2019” (Impress, 2019) -The textbooks you are using to learn VB. If you know other languages such as Java, you can read it in about a full time x a week.
  • [From Java shop to become VB.net programmer-Qiita](https://qiita.com/5zm/items/44d05463875ff0e29da0#3-%E3%82%B5%E3%83%B3%E3%83(%97%E3%83%AB) -A few articles that looked at VB from a Java perspective.
  • [Visual Basic Documentation-Getting Started, Tutorials, References. Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/visual-basic/)

Basic code structure

main

Main.java


public class Main {
    public static void main(String[] args) {
        System.out.println("Hello Java!");
        int a; String b; double c;
    }
}
  • Blocks are separated by {}
  • Modifiers such as public are lowercase
  • End the sentence with ; (newline itself has no meaning)

Form1.vb


Public Class Form1
    Private Sub ShowMessage(sender As Object, e As EventArgs) _
    Handles Button1.Click
        Console.WriteLine("Hello VB!")
        Dim a As Integer :Dim b As String :Dim c As Double
    End Sub
End Class
  • Blocks are divided as (modifier) Class ~ End Class
  • End of line is end of statement. -If you want to intentionally break a line in a long sentence, insert the line continuation character _. -However, from VB2010, it is possible to break a line without a line continuation character under certain conditions (implicit line continuation). -For detailed rules, refer to New Features of Visual Basic [email protected]
  • If you want to put multiple statements on one line, separate them with :.

Comment

Comment.java


// Single line comment

/*
 * Multi-line comment
 */

Comment.vb


'Single line comment

*There is no multi-line comment in VB

Documentation comment

The one that can generate API documentation with a dedicated tool and display the explanation by hovering over the method name.

  • Java: Describe in Javadoc format. /** ~ */ -In Eclipse, place the cursor on the target member and then generate with Alt+Shift+J

JavaDoc.java


/**
 * Multiplies the two integers specified by the argument and returns the result.
 * @param a multiplied by 1
 * @param a multiplied by 2
 * @return result of multiplication
 */
public static int doCalc(int a, int b) {
    return a * b;
}
  • VB: Describe in XML. ''' -In Visual Studio, you can generate it by typing ''' on the line just above the target member.

XmlDoc.vb


''' <summary>
Multiplies the two integers specified by the''' argument and returns the result.
''' </summary>
''' <param name="a">multiply number1</param>
''' <param name="b">multiply number 2</param>
''' <returns>Result of multiplication</returns>
Public Shared Function DoCalc(a As Integer, b As Integer) As Integer
    Return a * b
End Function

Reference

  • [Insert XML document comment-Visual Studio Microsoft Docs](https://docs.microsoft.com/en-us/visualstudio/ide/reference/generate-xml-documentation-comments?view=vs-2019)

File/folder structure

*Some parts omitted

Java (Eclipse) example

  • JavaProject -bin -package -Main.class (Java bytecode built) -src -package -main.java (source code) -lib -doc -.project (Eclipse project file) -.settings -.classpath

VB.NET Windows Forms Application (Visual Studio) Example

  • VisualStudioSolution -VisualStudioSolution.sln (VS solution file) -FirstProject -FirstProject.vbproj (VB project file) -bin -Debug -FirstProject.exe (executable file for debugging built) -Release -My Project -obj -App.config -Form1.vb (source code [operation]) -Form1.Designer.vb (Source code [Design]) -Second Project -(Same as First Project)

In Visual Studio, multiple projects can be combined into a solution. (Eclipse also has a working set)

Variable

Data type classification

  • Java -Basic types (byte, short, int, long, float, double, char, boolean) -Reference type (String etc.)
  • VB -Value type (Byte, Short, Integer, Long, Single (float equivalent), Double, Decimal (decimal type), ` Char, Boolean, **Date** etc.) -Reference type (String` etc.)

The date type must use standard APIs such as java.util.Date, java.util.Calender, and java.time in Java (that is, it must be a reference type). However, in VB, you can manage the date and time Date type Is prepared as standard.

Declaration and access modifier

DeclareVariable.java


int number; // package private
String message; // package private
public int publicNumber;
private String privateMessage;

DeclareVariable.vb


Dim Something' Private
Dim Number As Integer'Private
Dim Message As String'Private
Public PublicNumber As Integer

In VB standard setting, the type specification can be omitted when declaring variables. In that case, the data type of the variable is automatically determined according to the data type of the initial value (type estimation). If there is no initial value, it is regarded as Object type. If you set Option Strict On, type inference is disabled.

Variable name rules

Character Java VB Remarks
Half-width alphanumeric characters  
Japanese characters Of course not recommended
_ Underscore
& ×  
Number starts with × ×  

Initialization

InitiarizeVariable.java


int number = 100;
String message = "Hello";

InitiarizeVariable.vb


Dim Number As Integer = 100
Dim Message As String = "Hello"
Dim Pi = 3.14'Automatically treated as type Double
Dim BlankNumber As Integer'The initial value is automatically "0"
Dim BlankMessage As String'The initial value is automatically "Nothing"

constant declaration

Constant.javafinal int MAX_STOCK = 100;


public static final String VERSION_ID = "v1.0.1-RELEASE";

Constant.vb


Const MAX_STOCK As Integer = 100
Const VERSION_ID As String = "v1.0.1-RELEASE"'Shared cannot be used in Const statement

Reference

  • [Data Type Overview (Visual Basic) Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/visual-basic/language-reference/data-types/)

Operator

arithmetic operators

|Features|Java|VB.NET|Remarks| |—|—-|——|—-| |Addition |a + b|a + b|| | Subtraction |a-b|a-b|| | Multiplication |a * b|a * b|| | Division |a / b|a / b|| | Integer division (quotient) |N/A|a \ b|[VB] Both a and b must be of integer type.
The result of 23 \ 5 is 4 | |Remainder|a %b|a Mod b|23% 5 or 23 Mod 5 result in 3| |Exponentiation| (none as operator) |a ^ b|Note that VB ^ has the highest precedence among arithmetic operators | |Increment|++a or a++|N/A|In VB, there is no choice but to write a += 1| |Increment|--a or a--|N/A|In VB, there is no choice but to write a -= 1 etc.|

Division of integers

In Java, if both the number to be divided a and the number to be divided b are integers, the fractional part of the result is truncated and becomes an integer. This does not change even if the assignment destination is a variable such as double type.

DivideInteger.java


double x;
x = 23 / 5; // x becomes 4.0

If at least one is a decimal (double precision floating point number), the result is also a decimal.

java.DivideDouble.java


double x;
x = 23 / 5.0 // x becomes 4.6

On the other hand, in VB, the calculation is performed so that the accuracy is as low as possible.

DivideInteger.vb


Dim x As Double
x = 23/5'x becomes 4.6 instead of 4

In VB as well as in Java, if you want to divide integers, use the \ operator.

DivideWithBackSlashOperator.


Dim x As Double
x = 23 \ 5'x becomes 4

Exponentiation in Java

In Java, use java.lang.Math.pow(a, b). The first argument a is the base, the second argument b is the exponent (that is, a ^ b in VB).

Assignment operator

|Features|Java|VB.NET|Remarks| |—|—-|——|—-| |Assigned as is |a = b|a = b|| | Substitution of addition result |a += b|a += b|| | Substitute the subtraction result |a -= b|a -= b|| | Substitute the multiplication result |a *= b|a *= b|| |Substitution of division result |a /= b|a /= b|| |Substitutes the result of integer division |N/A|a \= b|| | Substitute the remainder |a %b|N/A|There is no corresponding [VB]Mod|

(Bit operation system omitted)

Comparison operator

|Features|Java|VB.NET|Remarks| |—|—-|——|—-| |a is less than b |a <b|a <b|| |a is less than or equal to b |a <= b|a <= b|| |a is greater than b |a> b|a> b|| |a is more than b |a >= b|a >= b|| |a is equal to b |a == b|a = b|There is one = in VB | |a is not equal to b |a != b|a <> b||

Logical operator

In the table below, A and B represent conditional expressions (expressions that return True/False).

Logic Functions Java VB.NET
AND (AND) A and B N/A A And B
AND (AND) A and B (short circuit evaluation) A && B A AndAlso B
OR (OR) A or B N/A A Or B
OR (OR) A or B (short circuit evaluation) A && B A OrElse B
AND (NOT) Not A !A Not A
Exclusive Or (XOR) A or B, but not A and B ^A A Xor B

Short circuit rating: If A is False, the entire conditional expression is False, so proceed without evaluating B. At this time, even if some method is written in B, it is not executed. By using this, you can write an expression in B that causes an error unless A becomes True. Example: If Integer.TryParse(str, num) AndAlso num <5 Then ...

concatenation operator

Java uses + to concatenate strings, but VB uses &.

It is possible to concatenate strings with + in VB as well, but if one of them is not a string type, unintended results or an error may occur, so Microsoft recommends the use of &. ing.

Operator reference page

  • [Operator Introduction to Java Code](https://java-code.jp/64)
  • [Operator-Visual Basic Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/visual-basic/language-reference/operators/)

Type conversion

Conditional branch

if statement / If statement

ConditionalBranch.java


if (age <20) canBuyAlcohol = true;

if (age <13) {
    fareType = "child";
} else if (age <18) {
    fareType = "student";
} else {
    fareType = "adult";
}

ConditionalBranch.vb


If age <20 Then canBuyAlcohol = True'If one line, don't need End If

If age <13 Then
    FareType = "child"
ElseIf age <18 Then
    FareType = "student"
Else
    FareType = "adult"
End If

In VB, it is also possible to write multiple statements on one line using “:” as follows.

ConditionalBranchInOneLine.vb


If 20 <age Then FareType = "adult" :CanBuyAlcohol = true Else CanBuyAlcohol = false

Switch / Select Case statement

Match one value

ConditionalBranch2.java


switch (num) {
    case 1:
        gender = "male";
        break;
    case 2:
        gender = "female";
        break;
    case 3:
        gender = "other";
        break;
    default:
        gender = "unanswered";
        break;
}

The switch statement expression (num above) is only basic type + String type (Java SE 7 or later).

ConditionalBranch2.vb


Select Case Num
    Case 1
        Gender = "male"
    Case 2
        Gender = "female"
    Case 3
        Gender = "Other"
    Case Else
        Gender = "Unanswered"
End Select

Match multiple values

ConditionalBranch3.java


switch (phoneNumberPrefix) {
    case 090:
    case 080:
    case 070:
        isMobile = true;
        break;
    default:
        isMobile = false;
        break;
}

ConditionalBranch3.vb


Select Case PhoneNumberPrefix
    Case 090, 080, 070
        IsMobile = true
    Case Else
        IsMobile = false
End Select

specify a range of values

ConditionalBranch4.java


// It's not possible with Java's Switch statement (you have no choice but to bite another variable)

ConditionalBranch4.vb


Select Case MonthNumber
    Case 3 To 5
        Season = "Spring"
    Case 6 To 8
        Season = "summer"
    Case 9 To 11
        Season = "autumn"
    Case Else
        Season = "winter"
End Select

use comparison operators

ConditionalBranch5.java


// Cannot be done with Java's Switch statement (obviously it is better to use if statement)

ConditionalBranch5.vb


Select Case Score
    Case Is <60
        Grade = "F"
    Case Is <70
        Grade = "C"
    Case Is <80
        Grade = "B"
    Case Is <90
        Grade = "A"
    Case Else
        Grade = "S"
End Select

Repeat

for statement / For statement

```java:ForLoop.javafor (int i = 0; i <= 9; i++) { System.out.println(i + “This is the second iteration”); }



#### **`ForLoop.vb`**
```vb

For i As Integer = 0 To 9 Step 1'If the increment value is 1, Step can be omitted.
    Debug.WriteLine(i & "This is the second iteration.")
Next

In both languages, you can use variables declared outside the For statement instead of declaring the loop counter inside the initialization statement of the For statement. In that case, the variable can be used even after exiting the For statement.

ForLoop2.java


int i;
for (i = 0; i <= 9; i++) {
    System.out.println(i + "This is the second iteration");
}
System.out.println(i + "repeated times");

ForLoop2.vb


Dim i As Integer
For i = 0 To 9 Step 1'If the increment value is 1, Step can be omitted.
    Debug.WriteLine(i & "This is the second iteration.")
Next
Debug.WriteLine(i & "repeated times")

Extended for statement / For-Each statement

ForEachLoop.java


int[] scoreArray = {70, 80, 90};

// normal for statement
for (int i = 0; i <scoreArray.length(); i++) {
    System.out.println(scoreArray[i]);
}

// extended for statement
for (int score: scoreArray) {
    System.out.println(score);
}

ForEachLoop.vb


Dim ScoreArray() As Integer = {70, 80, 90}

'Normal for statement
For i As Integer = 0 To UBound(ScoreArray)
    Debug.WriteLine(ScoreArray(i))
Next

'For Each statement
For Each score As Integer In ScoreArray
    Debug.WriteLine(score)
Next

while statement / While-End While statement

Continue executing as long as the condition is true.

WhileLoop.java


int i = 0;
while (i <10) {
    System.out.println(i + "This is the second iteration");
    i++;
}

WhileLoop.vb


Dim i As Integer = 0
While i <10
    Debug.WriteLine(i & "This is the second iteration.")
    i += 1
End While

*For is more suitable than While in this sample

do-while statement / Do-Loop statement

Post-judgment type (executed once)

DoWhileLoop.java


Random rd = new Random();
int num = 0;
do {
    num = rd.nextInt(100) + 1;
    System.out.println(num);
} while (num %2 == 0);

DoLoopWhile.vb


Dim rd As Random = new Random()
Dim Num As Integer = 0

Do
    Num = rd.Next(1, 100)
    Debug.WriteLine(Num)
Loop While Num Mod 2 = 0

In VB, in addition to the Loop While condition (repeat until the condition becomes false), you can also use the Loop Until condition (repeat until the condition becomes true).

DoLoopUntil.vb


Dim rd As Random = new Random()
Dim Num As Integer = 0

Do
    Num = rd.Next(1, 100)
    Debug.WriteLine(Num)
Loop Until Num Mod 2 <> 0

Until The following conditions are reversed, but both DoLoopWhile.vb and DoLoopUntil.vb have the same processing.

Pre-judgment type (may not be executed even once)

DoLoopWhile2.vb


Dim i As Integer = 0
Do While i <10
    Debug.WriteLine(i & "This is the second iteration.")
    i += 1
Loop

DoLoopUntil2.vb


Dim i As Integer = 0
Do Until i >= 10
    Debug.WriteLine(i & "This is the second iteration.")
    i += 1
Loop

exit the loop

  • Java: break;
  • **VB: **Exit Do, Exit For, Exit While

Proceed to the next iteration on the way

  • **Java: **continue;
  • **VB: **Continue Do, Continue For, Continue While

Array

declaration

Note that the meaning of the numbers specified in parentheses is different.

ArrayDecralation.java


int[] numArray = new int[5];

It becomes an array with a total of 5 elements of index 0, 1, 2, 3, 4. The number of elements in the array is specified by [n].

ArrayDeclaration.vb


Dim NumArray(4) As Integer

It becomes an array with a total of 5 elements with indexes 0, 1, 2, 3, 4. The maximum value of the index is specified by (n).

Initialization

ArrayInit.java


int[] numArray = {10, 20, 30, 40, 50 };

ArrayInit.vb


Dim NumArray() As Integer = {10, 20, 30, 40, 50}

Substitution/use

ArrayUse.java


numArray[3] = 31;

int a = numArray[3];

ArrayUse.vb


NumArray(3) = 31

Dim a As Integer = NumArray(3)

Multidimensional array

MultiDArray.vb


int[][] numArray = new int[3][4];
double[][] doubleArray = {{ 0.0, 0.1, 0.2 }, {1.1, 2.2, 3.3, 4.4 }};

MultiDArray.vb


Dim NumArray(2, 3) As Integer
Dim DoubleArray(,) As Double = {{ 0.0, 0.1, 0.2 }, {1.1, 2.2, 3.3, 4.4 }}

At first glance, it seems that (, ) forgets to enter the maximum index value, but it is equivalent to [][] in Java.

Changing array size

In Java, the size of an array once created cannot be changed, and there is no choice but to create a new array and transfer the values to it.

However, in VB you can resize the array using the ReDim statement.

ChangeArraySize.vb


Dim NumArray(9) As Integer

'...

ReDim Preserve NumArray(6)

If you add Preserve, the value of the original element is retained (*** all elements are empty if you do not add it). When the number of elements is reduced, the reduced elements are deleted (in the above example, the three elements with indexes 7, 8, and 9 are deleted).

Array length (number of elements)

  • Java -Use array name.length (which returns the number of elements).

ArrayLength.java


int[] numArray = new int[5];

for (int i = 0; i <numArray.length; i++) {
    numArray[i] = i;
}
// The contents of the array will be {0, 1, 2, 3, 4}
  • VB: -Use array name.Length (return number of elements). -If you want to process all elements repeatedly, use UBound(array name) (return maximum index value). -To in the For statement means <= instead of <. -Therefore, if you write 0 To array name.Length, it will pass through the length of the array in the final round, resulting in System.IndexOutOfRangeException. -If you really don’t want to remember UBound(), you can use array name.Length-1, but…

ArrayLength.java


Dim NumArray(4) As Integer

For i As Integer = 0 To UBound(NumArray)
    NumArray(i) = i
Next
'The contents of the array will be {0, 1, 2, 3, 4}

Method/Procedure

Concept organization (not completely organized)

Basically, there is no practical problem even if you think that “method” = “procedure”.

Both words appear in VB, whereas in Java only “methods” appear. What you’re doing is the same “to put together a series of processes”, but “method” seems to be a word that considers the origin of the procedure even in procedures.

Feeling that “property” (field) and “function” (method) that “object” has.

However, if you google “what is the difference between a method and a procedure in visual basic” in English, only the pages that say “function vs procedure” instead of “method vs procedure” will be hit (method = function?) This area seems to be involved in the history of programming languages (functions and subroutines).

Reference-Understand terms such as VBA macros, procedures and methods-t-hom’s diary

Comparison of terms

|Target|Java|VB| |—-|—-|—-| | Processing that does not return a return value | Method (void) |Sub procedure | | Returning process | Method (other than void) | Function procedure | |Process to read/write class field|getter/setter method|Property procedure| |Process belonging to an individual instance|Instance method|(normal Sub/Function procedure)| |Process belonging to the entire class |static method|Shared (Shared) method| |Processing according to event|N/A|Event handler (a form of Sub procedure)

Sub procedure

Processing that does not return the return value. (Since there is no direct return value, variables and objects existing in the caller can be rewritten and data can be returned by using reference.)

  • Java: Access modifier [static] void name (type name argument name, ...) { ~ }

VoidMethod.java


public void showMessage(int a, int b) {
    System.out.println(a + b);
}
  • VB: Access modifier [Shared] Sub name (argument name As type name, ...) ~ End Function -Event handlers also belong here (the one with the Handles clause at the end)

SubProc.vb


Public Sub ShowMessage(Str1 As String, Str2 As String)
    Debug.WriteLine(a + b)
End Sub

Function procedure

Return processing of the return value.

  • Java: Access modifier [static] Return value type name (type name argument name, ...) { ~ } -specify the return value with return

ReturnMethod.java



public int doCalc(int a, int b) {
    return a * b;
}
  • VB: Access qualifier [Shared] Function name (argument name As type name, ...) As return type ~ End Function -Specify the return value with Return

FunctionProc.vb


Public Function DoCalc(a As Integer, b As Integer) As Integer
    Return a * b
End Function

Property procedure

→Explanation in class items

Exit the procedure

ExitMethod.java


public void showMessage() {
    if (errFlag) {
        return; // Actually, even void method can be exited by this
    } else {
        System.out.println("Successful processing")
    }
}

public int doCalc(int a, int b) {
    int result = a * b;
    if (result >10) {
        return 0; // it is not allowed to exit without returning a value
    } else {
        return result;
    }
}

ExitProcedure.vb


Public Sub ShowMessage()
    If ErrFlag Then
        Exit Sub'Exit Sub in VB
    Else
        Debug.WriteLine("Processing success")
End Sub

Public Function DoCalc(a As Integer, b As Integer) As Integer
    Dim result As Integer = a * b
    If (result >10) Then
        Exit Function'Returns 0 because the return value is an Integer type
    ElseIf (result >50) Then
        DoCalc = result + 1
        Exit Function'Return the value set in the variable DoCalc
    Else
        Return result
    End If
End Function

In Java, it is impossible to exit a method other than void without return, but it is possible in a VB Function procedure. However, depending on the type of the return value, it may cause unexpected behavior such as generating a slimy exception, so it is necessary to Return.

Variable length argument

  • Java: argument is (data type...variable name) -Within the method, it can be treated like an array variable -If other arguments are also specified, the variable length argument must be at the end of the argument list

VariadicMethod.java


public static int getSum(int... numbers) {
    int sum = 0;
    for (int i = 0; i <numbers.length; i++) {
        sum += numbers[i];
    }
    return sum;
}
  • VB: (ParamArray variable name As data type []) -Properties are the same as Java.

VariadicFunction.vb


Public Shared Function GetSum(ParamArray Numbers As Integer[]) As Integer
    Dim Sum As Integer = 0
    For i As Integer = 0 To UBound(Numbers)
        Sum += Numbers(i)
    Next i
    Return sum;
End Function

References for variadic arguments

-How to create a method with variable length arguments? [C#/VB]: .NET [email protected]

Option argument

Optional arguments when calling.

  • Java: (Maybe) I don’t have it as a language specification. -Don’t confuse the Optional type introduced in Java 8 as it is a completely different concept.
  • VB: (Optional variable name As data type = default value) -If omitted on call, default value is assumed to have been passed. -Therefore, the default value must be specified. -All arguments for argument migration with Optional specified must be Optional (write all Optional arguments and then write Optional arguments) -It is OK to provide multiple Optional arguments.

OptionalArguments.vb


Public Shared Function Calc(Num1 As Integer, Num2 As Integer, Optional CalcMethod As Integer = 0)
    If CalcMethod = 0 Then
        Return Num1 + Num2
    ElseIf CalcMethod = 1 Then
        Return Num1-Num2
    ElseIf CalcMethod = 2 Then
        Return Num1 * Num2
    ElseIf CalcMethod = 3 Then
        Return Num1 / Num2
    Else
        Return 0
    End If
End Function

In this example, if you call it like Calc(5, 10), the pattern of CalcMethod = 0 (that is, addition) is executed.

Receive multiple values as return values

  • Java: There is no choice but to return the object in a class.

ReturnMultiValue.java


public static Result getResult(int a, int b) {
    Result result = new Result();
    result.setSum(a + b);
    result.setDiff(a-b);
    result.setProduct(a * b);
    result.setQuotient((double) a / b);
    Return result;
}

Result.java


public Class Result {
    int Sum;
    int Diff;
    int Product;
    double Quotient;

    // getter / setter
}
  • VB: You can return multiple values using tuple -Tuple: A collection of multiple variables on the spot -Is it easy to understand if it is an image of creating a temporary class?

Tuple.vb


Public Sub Main()
    'Declare a tuple with a name
    Dim Result As (Sum As Integer, Diff As Integer, Product As Integer, Quotient As Double)

    Result = GetResult(5, 10)

    'Use the value in the tuple
    Debug.WriteLine(Result.Sum)
    Debug.WriteLine(Result.Diff)
    Debug.WriteLine(Result.Product)
    Debug.WriteLine(Result.Quotient)
End Sub

'Function procedure that returns a tuplePublic Shared Function GetResult(a As Integer, b As Integer) As (Integer, Integer, Integer, Double)
    Return (a + b, a-b, a * b, a / c)
End Function

Entry point

The first method to be executed when the program is launched.

In Java, the method named main is always the entry point, but in VB this is not always the case. When you create a Windows Forms project, the first form you create becomes the entry point. For how to change this, try [Create Java main method in VB.NET! Rise Will Staff Blog](https://www.risewill.co.jp/blog/archives/8286) is detailed.

Class

Constitution

  • Java class public class Main{ } -Field -Method -getter/setter methods

  • An example according to the JavaBeans format.

JavaClass.java


public class JavaClass {
    // field (indicating the state/property of the object)
    private int field;

    // method (indicating behavior/behavior of object)
    public void method(){
        // ...
    }

    // Method> getter (provides read functionality for encapsulated private fields)
    public int getField() {
        return field;
    }

    // method> setter (provides ability to write to encapsulated private fields)
    public void setField(int value) {
        this.field = value;
    }
}
  • VB class Public Class Main ... End Class -Field (member variable) -May be prefixed with _ to distinguish from properties -Property -Get procedure -Set procedure -Procedure (method) -Event

VBClass.vb


Public Class VBClass
    'Field (member variable)
    Dim _field As Integer

    'Property
    Property field() As Integer
        Get
            Return _field
        End Get
        Set(ByVal value As Integer)
            _field = value
        End Set
    End Property

    'Procedure
    Public Sub Procedure()
        '...
    End Sub
End Class

Learn more about properties

Basic

Property is a set of getter/setter methods in Java (only one of Get procedure and Set procedure can be implemented). The difference from Java is that the property is treated like a field from outside the class.

For example, when accessing the private field field of the above sample code JavaClass.java from other class, it is necessary to write the following code.

AccessToField.java


public class Main {
    public static void main(String[] args) {
        JavaClass jc = new JavaClass();

        // The following 2 lines result in a compilation error
        int num = jc.field;
        jc.field = 100;

        // instead, write
        int num = jc.getField();
        jc.setField(100);
    }
}

In this way, since access is denied with object variable name.field name, the content of the field is rewritten by receiving the content of the field as the return value of the getter method or by passing the value as an argument to the setter method instead. Will be the way.

If you write the same movement in VB, it will be like this.

AccessToField.vb


Public Class Main
    Public Shared Sub Main
        Dim vbc As New VBClass()

        Dim num As Integer = vbc.field'Get call
        vbc.field = 100'Set call
    End Sub
End Class

By writing a property name like a field, the Get/Set procedure defined for that property is implicitly called.

Automatic implementation property

For properties that simply return/write a value, the code can be simplified by using Automatic implementation property.

AutoImplProperty.vb


Public Class AutoImplProperty
    Public Property Name As String
    Public Property Owner As String = "DefaultName"
    Public Property Items As New List(Of String) From {"M", "T", "W"}
    Public Property ID As New Guid()
End Class

(Auto-implemented properties-Visual Basic | Microsoft Docs)

At this time, a hidden Private field (backing field) with _ added to the property name is automatically created. In the above example, backing fields _Name, _Owner, _Items, _ID will be created (so if you declare a field with the same name as yourself, you will get a compilation error).

Property: Field = 1:n is OK

Also, properties do not have to correspond one-to-one with fields. In other words, you can pick up values from multiple fields and concatenate them into a single field. You can also take one group of values and actually store them in two or more fields. (Of course, it is necessary to define Get/Set procedure corresponding to it). There is an easy-to-understand example in Microsoft Docs, so I quote it (adding Public Class ~ End Class so that it is easy to understand that it is a member in the class).

The following property stores the full name as two component names: first name and last name. When the calling code reads fullName, the Get procedure combines the two component names and returns the full name. When the calling code assigns a new full name, the Set procedure attempts to split it into two component names. If no space is found, everything is stored as first name. . Property Procedures-Visual Basic | Microsoft Docs

CombinedProperty.vb


Public Class Combined Property
    Dim firstName, lastName As String

    Property fullName() As String
        Get
        If lastName = "" Then
            Return firstName
        Else
            Return firstName & "" & lastName
        End If

        End Get
        Set(ByVal Value As String)
            Dim space As Integer = Value.IndexOf(" ")
            If space <0 Then
                firstName = Value
                lastName = ""
            Else
                firstName = Value.Substring(0, space)
                lastName = Value.Substring(space + 1)
            End If
        End Set
    End Property
End Class

Caller:

CallProperty.vb


fullName = "MyFirstName MyLastName"
MsgBox(fullName)

Also see the following pages for the differences between properties and member variables.

  • [Difference between property and variable-Visual Basic Microsoft Docs](https://docs.microsoft.com/ja-jp/dotnet/visual-basic/programming-guide/language-features/procedures/differences-between-properties-and-variables)