Select the execution result of the following program
java.java
public class Main{
public static void main(String[] args){
for ( int i = 1,long j = 2; i < 5; i++){
System.out.print(i * j);
}
}
}
Display as A.2468 B.246810 C. Compile error D. Exception is thrown at runtime
The answer is C When initializing two variables in java at the same time, the types must be the same. In other words
java.java
public class Main{
public static void main(String[] args){
for ( int i = 1,j = 2; i < 5; i++){
System.out.print(i * j);
}
}
}
If so, it is the answer of A.
If you do this with TypeScript
TypeScript.ts
for(var i=1,j=2;i<5;i++){
console.log(i*j);
}
It will be written as. Typescript has a type declaration, but you can't explicitly declare a type in for initialization. Therefore
TypeScript.ts
for(var i=1:number,j=2:number;i<5;i++){
console.log(i*j);
}
Writing like this will result in a compile error. Type inference runs by entering an initial value and is defined with the appropriate type.
Also, on the Java side, it is divided into an integer int and a real number long. Type inference works fine even if the types are different in this way.
TypeScript.ts
for(var i=1,j="masao";i<5;i++){
console.log(i*2);
}
There is nothing wrong with writing it this way.
Recommended Posts