Advertisement
wtmhahagd

From JS to Java

Nov 29th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.41 KB | None | 0 0
  1. FROM JAVASCRIPT TO JAVA: A GUIDE
  2.  
  3. You're not looking to reinvent the programming wheel; you just know some JS and are looking to get into some Java. Sound like you? Then this tutorial was written for and is dedicated with love to you.
  4.  
  5. First thing to note: Java is a lot stricter than JavaScript. So if you've been writing messy JS, time to get your act together, son, because Java won't allow any other way.
  6.  
  7. COMPILING
  8.  
  9. You have .java files, where you store your code, and you have .class files, where you store code for the computer. You get .class files from compiling .java files (most IDEs will have a button just for this.) Compiling also checks for errors in your code- and there will be lots of them! And if there are errors, you'll get a compiler error, and no .class file.
  10.  
  11. And the computer runs the .class, not the .java, so you can't run the file, either. Sassy.
  12.  
  13. DYNAMIC TYPING: THOSE WERE THE DAYS
  14.  
  15. One of the most important things to note here: Java has strict typing. What this means: in Java, it's super important whether something is a number, or a string, or whatever. Once a variable is created, its type will never be able to change; unlike in Javascript, where a var x = 5; and a subsequent x = "wow! dynamic typing"; won't raise an eyebrow. We'll look at a few of the differences this makes:
  16.  
  17. DATA TYPES
  18. Here are the primitives you'll be using:
  19. - int - Integers. Duh.
  20. - double, float - Used for decimals. Float is more precise, but double is used more often.
  21. - boolean - True/false, just like JS.
  22. - char - One character. Use single quotes, like 'c', to delimit. Strings must be delimited with double quotes exclusively.
  23.  
  24. There are more, but those are only used for special, very large or very small data. So don't bother unless you have to. Oh yes! String, too, although it's an object, not a primitive.
  25.  
  26. All primitives have corresponding object classes as part of Java's standard library; that's right, you can do a new Integer(5). You'll probably never use it, but just know about it.
  27.  
  28. VARIABLE INITIALIZATION: Instead of a var or const keyword, your new keywords are the data type of the variable.
  29.  
  30. int x = 5;
  31. String y = "variable!"
  32. Object z = null;
  33. SomeCustomClass theycallmezeal = new SomeCustomClass();
  34.  
  35. This applies to the counter variable you use in a for-loop:
  36.  
  37. for (int i = 0; i < 5; i++) {
  38. System.out.println("Hello, world!");
  39. }
  40.  
  41. By the way- System.out.print() and System.out.println() (this one prints on a new line) print to the console, and are used very often. They're a pain to type out, but you get used to it.
  42.  
  43. And (here's the real kicker) to the arguments you define in a function header:
  44.  
  45. public int addNumbers (int x, int y) {
  46. return x + y;
  47. }
  48.  
  49. Notice how it was public int addNumbers(), not function addNumbers()- more on this later.
  50.  
  51. CASTING: Casting is an operation that, instead of altering a value, alters the value's type. Use it like this, when you need one type out of a variable that's another type:
  52.  
  53. double x = 5.0; //When initializing values that are integers into doubles, the .0 is customary.
  54. int y = (int)(x); //This turns the value of x into an int. Any decimal portions are cut off.
  55.  
  56. DIVISION: Division with doubles works as expected. Division with ints is a bit different, since ints don't support decimal points. When working with ints, division will chop off any excess decimal points, meaning that int 1 divided by int 3 equals 0, not 0.333.
  57.  
  58. ARRAY INITIALIZATION: The syntax looks a bit different, but what you really need to concern yourself with: arrays have type, too, and they can only hold objects or primitives of the same type. Meaning: you can only have arrays of all ints, or arrays of all Strings, or arrays of all SomeCustomClass objects, but you can't mix them up. There are data structures like ArrayList in Java's standard library that let you do this, but let's focus on arrays for now:
  59.  
  60. There's a shorthand notation, similar to that which is used in Java, but with curly brackets:
  61.  
  62. int[] array = {1, 2, 3};
  63.  
  64. The other way looks like this:
  65.  
  66. int[] array = new int[3];
  67.  
  68. Weird syntax, I know. The array is blank; you then populate it with a for-loop or something similar. But make sure you fill it with ints!
  69.  
  70. FUNCTION HEADERS: First of all, say goodbye to function literals. We just don't have them; besides, you don't really need them for the stuff for which Java is made. Second of all, say goodbye to the simplicity of a function keyword- you've got a bit more that needs to be specified:
  71.  
  72. -Privacy. The two big ones: public, accessible by outside classes, and private, accessible only within the class. (Classes are very important in Java. More on this later.)
  73.  
  74. -Return type. That's right, your functions can return one type, and one type only. Want your function to return ints? You gotta specify it. Does your function not return anything? That's a void return type. And guess what! If you try to return something in the method body that isn't the specified return type, the compiler gets pissed! Isn't Java FUN‽
  75.  
  76. Looking back at our example addNumbers():
  77.  
  78. public int addNumbers (int x, int y) {
  79. return x + y;
  80. }
  81.  
  82. The public means that addNumbers() could be called outside of the file (we'll see exactly how later); the int means that addNumbers() will always return an int. The reason for the strictness? If you know anything about return, you'll know that it lets you use function calls almost like variables- and you know how strict Java is with its variables.
  83.  
  84. Confused? Ha! I haven't even gotten to the good stuff yet:
  85.  
  86. EVERYTHING IS A CLASS
  87. Also, MEET MAIN
  88.  
  89. Yup. Every single thing in Java must be within a class. It's customary for each class to be in its own file. Here's how to create a class:
  90.  
  91. public class ClassName {
  92.  
  93. Isn't that simple. You've got a dedicated class keyword this time around- much more explicit than JS, where you really only have a constructor.
  94.  
  95. By the way, say goodbye to object literals. Wonderful as they are, you'll find they're just not Java's style. Java is quite highly organized, albeit a tad clunky, although there is admittedly a certain elegance to it. And the everything-is-a-class rule permeates the entire workings of the language. Get used to the damn thing.
  96.  
  97. Every class is given a default constructor. It takes no args and contains nothing in its body, so it just returns a plain instance of the object. If you use it out of the box like that, I hope you have some getters and setters ready.
  98.  
  99. But if everything is in a class- how do you get things to run? With a main() method, which you put (of course) in a class with the purpose of starting off the program, known as the driver. Whatever's defined in main() will be what's actually run upon running of the program. No main() defined? Nothing will happen, and that would be dumb. Let's look at the method header for main():
  100.  
  101. public static void main(String[] args)
  102.  
  103. You should understand most of this- it's a void method, it's public so other stuff can access it, and it takes in an argument of an array of Strings. The array in question: in a terminal, when a command is run, it's possible to provide a series of parameters after the command. If the command involves Java, the parameters are passed to main() through the args array. You can name it anything you want, but args is so strong of a convention I highly discourage anything else.
  104.  
  105. And then the static keyword- the static keyword, which is optional, defines a class method, as opposed to an instance method. That's right- one of the few things where Java is actually simpler! Java has true class methods, which means that you can define them right there in the class with a static keyword. Isn't that great? Enjoy this brief moment of Java superiority. It won't last long, let me tell you.
  106.  
  107. INHERITANCE GETS AN UPGRADE
  108.  
  109. Inheritance is kind of an obscure concept in Javascript, and its implementation, while functional, isn't exactly elegant- first you gotta create the subclass, then you gotta set its prototype to an entire instance of the superclass, then mess with the constructor... However, in Java, it's one of the core concepts when it comes to classes. Instead of doing weird things with prototype, Java lets you do this:
  110.  
  111. public class Subclass extends Superclass
  112.  
  113. What this does, if you don't know- Subclass is now automatically given a copy of all the properties and methods that are defined in Superclass, meaning if Superclass has a foo() implemented, Subclass will receive a copy of the same exact foo() method. If you want, you can override the foo() implementation with your own, but if you don't, the same it shall remain.
  114.  
  115. Great news here: you can simply call inherited methods directly; no more clunky Function.call()!
  116.  
  117. One thing that doesn't get inherited is the constructor. When you construct a Subclass, you have to first construct a Superclass, then add on all the extra stuff in Subclass. You do this with a special method called super(), which simply acts as a constructor of the superclass. Use whatever arguments you see necessary.
  118.  
  119. Now- typing. An important thing to know is that not only is Subclass of type Subclass (duh), Subclass is also of type Superclass. Which means that you can instantiate a Subclass object to a variable declared as type Subclass or type Superclass. Get it?
  120.  
  121. And that's the basics! Is that all? Of course not, but you've trudged through 1,684 words and that is damn near enough reading for anyone to do. Go take a break. Drink some ginger ale. Then get yourself a book and start programming the hell outta Java.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement