© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_3

3. The Basics

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

In this chapter, we’ll cover the basic syntax of Java and similar languages.

Coding Terms

Source file refers to human-readable code. Binary file refers to computer-readable code (the compiled code). In Java, this binary code is called bytecode which is read by the Java Virtual Machine (JVM) .

In Java, the source files end with .java, and binary files end with .class (also called class files). You compile source files using a compiler, which gives you binary files or bytecode.

In Java, the compiler is called javac; in Groovy it is groovyc; and it is scalac in Scala (see a trend here?). All three of these languages can be compiled to bytecode and run on the JVM. The bytecode is a common format regardless of which programming language it was generated from.

However, some languages, such as JavaScript, don’t have to be compiled. These are called interpreted languages . JavaScript can run in your browser (such as Firefox or Google Chrome), or it can run on a server using Node.js, a JavaScript runtime built on Chrome’s V8 JavaScript engine.

Primitives and Reference

Primitive types in Java refer to different ways to store numbers and have practical significance. The following primitives exist in Java:
  • char: A single character, such as A (the letter A).

  • byte: A number from -128 to 127 (8 bits1). Typically, a way to store or transmit raw data.

  • short: A 16 bits signed integer. It has a maximum of about 32,000.

  • int: A 32 bits signed integer. Its maximum is about 2 to the 31st power.

  • long: A 64 bits signed integer. Maximum of 2 to the 63rd power.

  • float: A 32 bits floating-point number. This format stores fractions in base two and does not translate directly to base ten numbers (how numbers are usually written). It can be used for things such as simulations.

  • double: Like float but with 64 bits.

  • boolean: Has only two possible values: true and false (much like 1 bit).

../images/435475_2_En_3_Chapter/435475_2_En_3_Figa_HTML.jpg See Java Tutorial—Data Types2 for more information.

Groovy, Scala, and JavaScript

Groovy types are much the same as Java’s. In Scala, everything is an object, so primitives don’t exist. However, they are replaced with corresponding value types (Int, Long, etc.). JavaScript has only one type of number, Number, which is similar to Java’s float.

A variable is a value in memory referred to by a name. In Java you can declare a variable as a primitive by writing the type then any valid name. For example, to create an integer named price with an initial value of 100, write the following:
1  int price = 100;

Every other type of variable in Java is a reference. It points to some object in memory. This will be covered later on.

In Java, each primitive type also has a corresponding class type: Byte for byte, Integer for int, Long for long, and so on. Using the class type allows the variable to be null (meaning no value). However, using the primitive type can have better performance when handling a lot of values. Java can automatically wrap and unwrap primitives in their corresponding classes (this is called boxing and unboxing).

Strings/Declarations

A String is a list of characters (text). It is a very useful built-in class in Java (and most languages). To define a string, you simply surround some text in quotes. For example:
1   String hello = "Hello World!";

Here the variable hello is assigned the string "Hello World!".

In Java, you must put the type of the variable in the declaration. That’s why the first word here is String.

In Groovy and JavaScript, strings can also be surrounded by single quotes ('hello'). Also, declaring variables is different in each language. Groovy allows you to use the keyword def, while JavaScript and Scala use var. Java 10 also introduced using var to define local variables. For example:
1   def hello = "Hello Groovy!" //groovy
2   var hello = "Hello Scala/JS!" //Scala or JS

Statements

Almost every statement in Java must end in a semicolon (;). In many other languages, such as Scala, Groovy, and JavaScript, the semicolon is optional, but in Java, it is necessary. Much as how periods at the end of each sentence help you to understand the written word, the semicolon helps the compiler understand the code.

By convention, we usually put each statement on its own line, but this is not required, as long as semicolons are used to separate each statement.

Assignment

Assignment is an extremely important concept to understand, but it can be difficult for beginners. However, once you understand it, you will forget how hard it was to learn.

Let’s start with a metaphor. Imagine you want to hide something valuable, such as a gold coin. You put it in a safe place and write the address on a piece of paper. This paper is like a reference to the gold. You can pass it around and even make copies of it, but the gold remains in the same place and does not get copied. On the other hand, anyone with the reference to the gold can get to it. This is how a reference variable works.

Let’s look at an example:
1   String gold = "Au";
2   String a = gold;
3   String b = a;
4   b = "Br";

After running the preceding code, gold and a refer to the string "Au", while b refers to "Br".

Class and Object

A class is the basic building block of code in object-oriented languages. A class typically defines state and behavior. The following class is named SmallClass:
1   package com.example.mpme;
2   public class  SmallClass  {
3   }

Class names always begin with an uppercase letter in Java. It’s common practice to use CamelCase to construct the names. This means that instead of using spaces (or anything else) to separate words, we uppercase the first letter of each word.

The first line is the package of the class. A package is like a directory on the file system. In fact, in Java, the package must actually match the path to the Java source file. So, the preceding class would be located in the path com/example/mpme/ in the source file system. Packages help to organize code and allow multiple classes to have the same name as long as they are in different packages.

An object is an instance of a class in memory. Because a class can have multiple values within it, an instance of a class will store those values.

../images/435475_2_En_3_Chapter/435475_2_En_3_Figb_HTML.jpg Create a Class 
  • Open your IDE (NetBeans).

  • Note the common organizational structure of a typical Java project in the file system:
    • src/main/java: Java classes

    • src/main/resources: Non-Java resources

    • src/test/java: Java test classes

    • src/test/resources: Non-Java test resources

  • Right-click your Java project and choose New ➤ Java Class. Under “Class-Name” put “SmallClass”. Put “com.example.mpme” for the package name.

Fields, Properties, and Methods

Next you might want to add some properties and methods to your class. A field is a value associated with a particular value or object. A property is essentially a field which has a “getter” or “setter” or both (a getter gets the value and a setter sets the value of a property). A method is a block of code on a class which can be called later on (it doesn’t do anything until called).
1   package  com.example.mpme;
2   public  class  SmallClass  {
3       String name; //field
4       String getName() {return  name;} //getter
5       void print() {System.out.println(name);} //method
6   }

In the preceding code, name is a property, getName is a special method called a getter, and print is a method which does not return anything (this is what void means). Here, name is defined to be a String. System.out is built into the JDK and links to “standard out” which we discuss later, and println prints text and appends a newline to the output.

Methods can have parameters (values passed into the method), modify fields of the class, and can have return values (a value returned by the method) using the return statement. For example, modify the preceding method, print, to the following:
1   public String print(String value) {
2     name = "you gave me " + value;
3     System.out.println(name);
4     return name;
5   }
This method changes the name field, prints out the new value, and then returns that value. Try this new method out in the groovyConsole by defining the class and then executing the following:
1  new SmallClass().print("you gave me dragons")

Groovy Classes

Groovy is extremely similar to Java but always defaults to public (we will cover what public means in a later chapter).
1   package com.example.mpme;
2   class SmallClass {
3       String name //property
4       def print() { println(name) } //method
5   }

Groovy also automatically gives you “getter” and “setter” methods for properties, so writing the getName method would have been redundant.

JavaScript Prototypes

Although JavaScript has objects, it doesn’t have a class keyword (prior to ECMAScript 2015). Instead, it uses a concept called prototype . For example, creating a class can look like the following:
1   function SmallClass() {}
2   SmallClass.prototype.name = "name"
3   SmallClass.prototype.print = function() { console.log(this.name) }

Here name is a property and print is a method.

Scala Classes

Scala has a very concise syntax, which puts the properties of a class in parentheses. Also, types come after the name and a colon. For example:
1   class SmallClass(var name:String) {
2       def  print =  println(name)
3   }

Creating a New Object

In all four languages, creating a new object uses the new keyword. For example:
1   sc = new  SmallClass();

Comments

As a human, it is sometimes useful for you to leave notes in your source code for other humans—and even for yourself, later. We call these notes comments. You write comments thus:
1   String gold = "Au"; // this is a comment
2   String a = gold; // a is now "Au"
3   String b = a; // b is now  "Au"
4   b = "Br";
5   /* b is now "Br".
6      this is still a comment */
Those last two lines demonstrate multiline comments. So, in summary:
  • Two forward slashes denote the start of a single-line comment.

  • Slash-asterisk marks the beginning of a multiline comment.

  • Asterisk-slash marks the end of a multiline comment.

Comments are the same in all languages covered in this book.

Summary

In this chapter, you learned the basic concepts of programming:
  • Compiling source files into binary files

  • How objects are instances of classes

  • Primitive types, references, and strings

  • Fields, methods, and properties

  • Variable assignment

  • How source code comments work

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset