Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cole Rau
Cole Rau

Posted on • Edited on

     

Syntax Differences: JavaScript vs. Java

In this post I'll explain some syntactical differences between JavaScript and Java.

Declaring and assigning a variable

// JAVASCRIPTlet watermelon = "good";// JAVAString watermelon = "good";
Enter fullscreen modeExit fullscreen mode

In JavaScript, you can declare a variable withlet,const orvar. You do not need to specify the variable's data type, like you do in Java. In the Java example above, we need to say thewatermelon variable will point to theString,"good".

Printing/logging/outputting something

// JAVASCRIPTconsole.log("tomatoes are gross");// JAVASystem.out.println("tomatoes are gross");
Enter fullscreen modeExit fullscreen mode

There is just a minor difference between printing in JavaScript vs. Java. Printing the contents of an array works a bit differently in Java compared to JavaScript, which I'll cover later in this post.

Variable interpolation

// JAVASCRIPTlet fruit = "blueberry";console.log(`My favorite fruit is the ${fruit}`);// JAVAString fruit = "blueberry";System.out.println(  String.format("My favorite fruit is the %s", fruit));
Enter fullscreen modeExit fullscreen mode

To put a variable in a string:

  • In JavaScript, inside theconsole.log, write your string with back ticks; insert${variableName} where you want your variable to go.

  • In Java, inside theSystem.out.println, useString.format() to write your string; insert%s where you want your variable to go; after the ending quotation mark of the string, place a comma then write your variable name.

Declaring, invoking, and printing the return value of a function/method

// JAVASCRIPTconst isEven = (num) => {  // do something with num and return the result  return (num % 2 === 0) ? true : false;}console.log(isEven(4));// JAVApublic class Main {  static boolean isEven(int num) {    // do something with num and return the result    return (num % 2 == 0) ? true : false;  }  public static void main(String[] args) {    System.out.println(isEven(4));  }}
Enter fullscreen modeExit fullscreen mode

In both languages, we're passing an integer of4 to theisEven function/method. Then, we determine whether the remainder of the integer divided by 2 is 0. If it is, it's an even number so we returntrue; else, the integer is not even so we returnfalse.

In JavaScript, you can declare and invoke a function with the following general syntax:

// declare a function called functionNameconstfunctionName=(parameter1,parameter2,...)=>{// return something}// invoke the function called functionNamefunctionName(argument1,argument2,...);
Enter fullscreen modeExit fullscreen mode

However, in Java, every method needs to be declared within a class (in the above example, the class isMain). Every parameter to a method needs to have a data type. If the method returns something, you need to specify the return value's data type (void means nothing is returned). Every method must be invoked within themain method (The Java compiler will look for amain method before it executes any other code).

The following is the general syntax for declaring and invoking a method in Java:

publicclassMain{// declare a function called functionNamestaticreturnValueDataTypefunctionName(parameterOneDataTypeparameterOne,parameterTwoDataTypeparameterTwo,...){// return something}publicstaticvoidmain(String[]args){// invoke the function called functionNamefunctionName(argument1,argument2,...);}}
Enter fullscreen modeExit fullscreen mode

Declaring and printing an array

// #"strawberry", "orange", "lemon"];console.log(array);// JAVA:public class Main {  public static void main(String[] args) {    String[] array = {"strawberry", "orange", "lemon"};    for (int i = 0; i < array.length; i++) {      System.out.println(array[i]);    }  }}
Enter fullscreen modeExit fullscreen mode

In JavaScript, the elements in an array go inside of square [] brackets. In Java, the elements in an array go inside curly {} braces. Also in Java, you need to specify what data type the elements in the array will be. This is why we writeString[] above. TheString tells Java the array elements will beStrings. The[] tells Java you're creating an array.

Since Java doesn't natively print out the contents of an array withSystem.out.println(arrayName), you need to loop through the array, printing each element for each iteration. This is why the above example uses afor loop to print each element in the array.

Top comments(3)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
bias profile image
Tobias Nickel
German Software Engineer sharinh thoughts
  • Location
    MUNICH Germany
  • Work
    Technical Lead
  • Joined

Sometimes I wonder how much java and js code could be written intechangably. now that Java has thevar keyword and arrow functions.

CollapseExpand
 
thorstenhirsch profile image
Thorsten Hirsch
  • Joined

Not much, actually. While the syntax is rather similar the language design is very different and the runtimes are even more different.

Java is much more similar to C# in their goals and language design, so they might be what comes close to "interchangeable".

CollapseExpand
 
colerau profile image
Cole Rau
Graduate of Flatiron School in Software Engineering
  • Email
  • Location
    Seattle, WA
  • Education
    Flatiron School
  • Joined

I didn't know Java has those features now!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Graduate of Flatiron School in Software Engineering
  • Location
    Seattle, WA
  • Education
    Flatiron School
  • Joined

More fromCole Rau

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp