1# Migrating from Java to ArkTS 2 3<!--Kit: ArkTS--> 4<!--Subsystem: ArkCompiler--> 5<!--Owner: @fanglou--> 6<!--Designer: @qyhuo32--> 7<!--Tester: @kirl75; @zsw_zhushiwei--> 8<!--Adviser: @zhang_yixin13--> 9 10ArkTS is a new programming language that brings new development experience and opportunities to developers familiar with Java. It inherits the features of modern languages in terms of syntax and programming paradigms, and is deeply optimized for the ecosystem. Understanding the differences and commonalities between Java and ArkTS can help you quickly get started with application development and avoid common programming pitfalls. 11 12This topic compares ArkTS with Java from the perspective of basic syntax, language structure, and type system. For details, see [Introduction to ArkTS](./introduction-to-arkts.md). 13 14## Exploring the Differences Between Java and ArkTS 15 16The following will sort out the misunderstandings and pitfalls you may encounter when migrating a Java project to ArkTS due to differential syntax, type system, and application development mode. You are advised to master the basic syntax and runtime behavior of ArkTS, and then focus on the differences between ArkTS and Java. 17 18## Basic Syntax 19 20### Variable Declaration 21 22**Sample code in ArkTS**: 23 24```typescript 25// Type annotation (similar to Java). 26let age: number = 20; 27const program: string = 'ArkTS'; 28 29// Type inference (similar to that of local variable in Java). 30let version = 5.0; 31``` 32 33### Primitive Types 34| Java | ArkTS | Sample Code | Key Difference | 35|----------------|----------------------|-----------------------------------|-------------------------------| 36| `boolean` | `boolean` | `let isDone: boolean = false;` | They are defined similarly and used for logical judgments in Java and ArkTS, with no runtime boxing or unboxing operations. | 37| `byte` | `number` | `let b: number = 100;` | Java: the value of **byte** type is an 8-bit integer.<br>ArkTS: **number** represents small-range integer type.| 38| `short` | `number` | `let s: number = 300;` | Java: the value of **short** type is a 16-bit integer.<br>ArkTS: **number** represents small-range integer type.| 39| `int` | `number` | `let count: number = 10;` | Java: the value of **int** type is a 32-bit integer.<br>ArkTS: **number** represents double-precision floating-point type, which can store integers and floating-point numbers. | 40| `long` | `number` | `let largeNum: number = 9007199254740991;` | Java: the suffix **L** must be added, for example, **9007199254740991L**.<br>ArkTS: **number** represents all numeric types. | 41| `float` | `number` | `let pi: number = 3.14;` | Java: the suffix **f** must be added, for example, **3.14f**.<br>ArkTS: **number** represents all numeric types. No special identifier is required. | 42| `double` | `number` | `let e: number = 2.71828;` | Java: the **double** type is used.<br>ArkTS: **number** represents all numeric types. | 43| `char` | `string` | `let c: string = 'a';` | ArkTS: **string**, instead of **char**, is used to represent string type. | 44| `String` | `string` | `let message: string = 'Hello';` | They are defined similarly, but the **string** type of ArkTS supports template literals (for example, **${name}**) and more flexible operations. | 45 46### Complication Types 47| Java | ArkTS | Sample Code in ArkTS | Key Difference | 48|-----------------------------|--------------------------|-------------------------------------------------------------------------|-----------------------------------------------------------------------------| 49| **Array**: `int[] arr = new int[5];`| **Array**: `let arr: Array<number> = [1, 2, 3];`| `// Initialize an array at fixed length (similar to Java).`<br>`let fixedArr: number[] = new Array<number>(5);`<br>`// Initialize an array at dynamic length. Syntactic sugar is used.`<br>`let dynamicArr = [4, 5, 6];`<br>| The length of a Java array is fixed.<br>The length of an ArkTS array is dynamic. Operations such as **push** and **pop** are supported. You can use **[]** to simplify initialization. ArkTS array does not go out of bounds. If the array subscript exceeds the array length, **undefined** is returned.| 50| **List**: `List<String> list = new ArrayList<>();`| **Array**: `let strList: Array<string> = ['a', 'b'];`| `strList.push('c'); // Push an element to the end of an array.`<br>`let firstItem = strList[0]; // Access by index.`<br>| Java list separates APIs (such as **List**) from implementation classes (such as **ArrayList**).<br>ArkTS array uses basic types and set features, simplifying syntax.| 51| **Map**: `Map<String, Integer> map = new HashMap<>();`| **Map**: `let map: Map<string, number> = new Map();`| `map.set('key', 1); // Add a KV pair.`<br>`let value = map.get('key'); // Obtain the value.`<br>`map.has('key'); // Check whether the key exists.`<br>|Java **Map** requires explicit declaration of generic types.<br>ArkTS **Map** supports chain calls (such as **map.set('a', 1).set('b', 2)**), which is more direct.| 52| **Interface**: `interface Shape { double area(); }`| **interface**: `interface Shapes { area(): number; }`| `class Rectangles implements Shapes {`<br>` public width: number = 0;`<br>` public height: number = 0;`<br>` area(): number { return this.width * this.height; }`<br>`}`<br>| The syntax structures of Java and ArkTS are similar, but ArkTS APIs do not require explicit modifiers (such as **public** in Java) and support optional properties (such as **name?: string**).| 53| **Class**: `class Circle implements Shape { /* Class definition */ }`| **class**: `class Circles implements Shape { /* Class definition */ }`| `class Circles {`<br>` radius: number;`<br>` constructor(radius: number = 10) { // Support default parameter values.`<br>` this.radius = radius;`<br>` }`<br>`}`<br>| ArkTS classes support default property values and optional parameters. The constructor parameters can be directly declared as class properties (such as **constructor(public name: string)**), which is more concise.| 54| **Enum**: `enum Color { RED, GREEN, BLUE; }`| **enum**: `enum Colors { Red, Green, Blue }`| `enum Colors { Red = 1, Green, Blue };`<br>`let color = Colors.Green; // The value is 2, which is automatically incremented.`<br>| The basic concepts are the same. However, ArkTS enum does not support custom constructors and methods like Java. Only a simple numeric or string enum is supported.| 55 56 57### Functions 58 59**Sample code in ArkTS**: 60 61```typescript 62// Define a common function. 63function add(x: number, y: number): number { 64 return x + y; 65} 66 67// Define a concise arrow function. 68const multiply = (a: number, b: number): number => a * b; 69``` 70 71### Function Overloading 72 73Java supports compile-time polymorphism, allowing multiple methods with the same name in the same class. The methods are distinguished by the parameter list in terms of quantity, type, and sequence. 74 75* Overloading is implemented through multiple specific methods, each of which has an independent method body. 76 77* The parameter list (type, quantity, and sequence) must be different, but the return value type can be the same or different. 78 79* A specific method is selected based on the parameter type during compilation. 80 81**Sample code in Java**: Java function overloading 82 83```java 84class Example { 85 // Method 1: accept an int parameter. 86 void print(int value) { 87 System.out.println("Integer: " + value); 88 } 89 90 // Method 2: accept a string parameter. 91 void print(String value) { 92 System.out.println("String: " + value); 93 } 94} 95``` 96 97ArkTS provides polymorphism at the type declaration level, which is used only for type check and document prompt. There is only one implementation function. 98 99* Overload signatures via type declarations, but there is only one implementation function. 100 101* The implementation function must be compatible with all overload signatures. Generally, you need to manually determine the parameter type in the function body. 102 103* The type checker matches the declaration based on the called parameters, but only one function is available at runtime. 104 105**Sample code in ArkTS**: ArkTS function overloading 106 107```typescript 108function foo(x: number): void; /* First function definition */ 109function foo(x: string): void; /* Second function definition */ 110function foo(x: number | string): void { /* Function implementation */ 111} 112 113foo(123); // Use the first function definition. 114foo('aa'); // Use the second function definition. 115``` 116 117### Utils 118 119The ArkTS basic class library and container class library enhance the basic features of the programming language, including high-precision floating-point operations, binary buffer, XML generation, parsing, conversion, and multiple container libraries, reducing development workload and improving efficiency. For details, see [Overview of the ArkTS Common Library](../arkts-utils/arkts-utils-overview.md). 120 121## Language Structure 122 123Java is a typical object-oriented programming language, which means that all projects are developed based on classes and objects. 124 125ArkTS adopts a more flexible language structure and integrates multiple paradigms such as object-oriented programming and functional programming. 126 127### Module and Package Management 128 129Java allows you to use packages to organize code and import classes in other packages using the **import** statement. ArkTS also has its own module and package management mechanism, and uses the **import** statement to import functions in other modules. 130 131**Sample code in ArkTS**: 132 133```typescript 134// Import the ArkTS container set in the ArkTS standard library. 135 136import { collections } from '@kit.ArkTS'; 137``` 138 139The module system of ArkTS focuses more on modular development and code reuse, so it can conveniently manage dependencies between different functional modules. In this case, the usage is different from that of Java package management. 140 141### Class and Namespace 142 143The class system of ArkTS is similar to that of Java in syntax, but it offers more advanced features. 144 145| Feature |Java Implementation | ArkTS Implementation | Description | 146|------------|------------|------------------|-------------------------------| 147| Namespace organization | Static nested class/inner class | **namespace** keyword or module file structure | Supports the mixed mode of explicit namespace and modular organization. | 148| Inheritance mechanism | Class-based inheritance mechanism | Prototype chain-based inheritance mechanism | Similar syntax with differential underlying mechanism. | 149| Class member visibility | public/private/protected | Same as Java, but supports module-level visibility control. | Added the dimension for controlling module export.| 150 151**Namespace management** 152 153ArkTS supports explicit namespaces and modular organization. 154 155**Sample code in ArkTS**: 156 157```typescript 158namespace Models { 159 export class User { 160 // Implementation details. 161 } 162 163 export interface Repository { 164 // API definition. 165 } 166} 167``` 168 169Compared with the combination of package and static class in Java, the namespace in ArkTS can be used to implement a more intuitive code layering. 170 171### Asynchronous Programming Model 172 173**Single-threaded or multi-threaded processing** 174 175Java depends on multi-threading and **Future**/**CompletableFuture** to implement concurrency. 176 177Based on the event loop, ArkTS uses a promise/**async**/**await** to process asynchronous tasks, preventing the main thread from being blocked. 178 179**Error handling** 180 181In Java, use **try/catch** to capture exceptions in synchronous code. For asynchronous code, handle exceptions in a special manner (for example, using **Future.get()**). 182 183Uncaptured promise errors in ArkTS may cause silent failures. You need to explicitly use **try/catch** or **.catch**. 184 185### Binding of this 186 187In Java, **this** always points to the instance of the current class, which is determined by the code structure during compilation. In a method, **this** points to the object instance that calls the method. The instance pointed by this cannot be changed by calling the method. 188 189**Sample code in Java**: 190 191```java 192class MyClass { 193 void method() { 194 System.out.println(this); // Always point to the instance of MyClass. 195 } 196} 197``` 198 199In ArkTS, the instance pointed by **this** is determined by the context when the function is called. 200 201**Sample code in ArkTS**: 202 203```typescript 204class A { 205 bar: string = 'I am A'; 206 207 foo() { 208 console.info(this.bar); 209 } 210} 211 212class B { 213 bar: string = 'I am B'; 214 215 callFunction(fn: () => void) { 216 fn(); 217 } 218} 219 220function callFunction(fn: () => void) { 221 fn(); 222} 223 224let a: A = new A(); 225let b: B = new B(); 226 227callFunction(a.foo); // Program crashes. The context of this changes. 228b.callFunction(a.foo); // Program crashes. The context of this changes. 229b.callFunction(a.foo.bind(b)) // Output 'I am B'. 230``` 231 232## Type System 233 234The type system of ArkTS is different from that of Java. 235 236### Type Inference and Optional Types 237 238 239Compared with Java that requires explicit type declaration and strict null check, the type system of ArkTS provides more flexible expression modes. 240 241ArkTS has powerful type inference capabilities. The compiler can automatically infer the type of a variable based on the context. Therefore, you do not need to explicitly declare the type of a variable in most cases. 242 243**Sample code in ArkTS**: 244 245```typescript 246let num = 10; // The compiler automatically infers that num is of the number type. 247``` 248 249In addition, ArkTS supports optional types. You can add a question mark (?) to the end of a type to indicate that the variable can be **null** or **undefined**. 250 251**Sample code in ArkTS**: 252 253```typescript 254interface Person { 255 name: string; 256 age?: number; // age is an optional property. 257} 258 259const person: Person = { 260 name: "Alice", 261}; 262``` 263 264### Union Type 265 266Union type provides type combination capability for complex scenarios, which is an important innovation of the ArkTS type system. 267 268ArkTS supports union types (separated using **|**). A union type indicates that a value can be one of multiple types. 269 270**Sample code in ArkTS**: 271 272```typescript 273// Example of a union type. 274 275let value: string | number; 276value = 'hello'; 277value = 123; 278 279``` 280