|
| 1 | +In this lesson, I explored the differences between Java and JavaScript. Despite their similar names, these languages have distinct features. |
| 2 | + |
| 3 | +- ## Key Differences |
| 4 | +- ### Document Preparation: |
| 5 | + |
| 6 | + - Java requires preparation before defining variables and functions. |
| 7 | +JavaScript has more flexibility with variable definitions. |
| 8 | + |
| 9 | +- ### User Input: |
| 10 | + |
| 11 | + - In Java, I used the Scanner class to prompt the user for number input. |
| 12 | +This required importing Java's Scanner class. |
| 13 | +In JavaScript, there is no built-in Scanner class, so I used Node.js as a workaround. |
| 14 | +With Node.js, I utilized process.stdin for input and process.stdout for output (similar to console.log). |
| 15 | + |
| 16 | +- ### Loop Control: |
| 17 | + |
| 18 | + - Both languages allow for loops to be exited early, but the methods differ: |
| 19 | +In Java, using a break statement within the loop will terminate it. |
| 20 | +In JavaScript, I opted for read.close(), which achieves a similar effect. |
| 21 | + |
| 22 | +- ### Variable Declaration: |
| 23 | + |
| 24 | + - Java requires explicit declaration of variable types. |
| 25 | +JavaScript automatically assigns variable types. |
| 26 | +- ## Loop Behavior |
| 27 | +Both languages share similarities in loop functionality: |
| 28 | + |
| 29 | +- **For Loops**: |
| 30 | + - Take three expressions. |
| 31 | + |
| 32 | +- **If Statements**: |
| 33 | + - Accept a condition and can be nested. |
| 34 | + |
| 35 | +- **Java Example** |
| 36 | +```java |
| 37 | +for (int i = 2; i < userInput; i++) { |
| 38 | + if ((userInput / i) == (int) (userInput / i)) { |
| 39 | + System.out.println(userInput + " is not a prime number."); |
| 40 | + isConditionMet = true; |
| 41 | + break; |
| 42 | + } |
| 43 | + } if (!isConditionMet) { |
| 44 | + System.out.println(userInput + " is a prime number."); |
| 45 | + } |
| 46 | +``` |
| 47 | +- **JavaScript Example** |
| 48 | +```javascript |
| 49 | +for (let i = 2; i < answer; i++) { |
| 50 | + if ((answer / i) == parseInt(answer / i)) { |
| 51 | + console.log(answer + " is not a prime number."); |
| 52 | + isConditionMet = true; |
| 53 | + read.close(); |
| 54 | + } |
| 55 | + } if (!isConditionMet) { |
| 56 | + console.log(answer + " is a prime number."); |
| 57 | + read.close(); |
| 58 | + } |
| 59 | +``` |
0 commit comments