Java Summary#

Programming languages are generally huge and redundant, and Java is no exception. As you are learning to program, you should learn just enough Java to get you through each task. By the time you have completed each of the chapters, you will be a Java programmer – but there may still be parts of Java that remain untouched. For example, there are many Java libraries that may be imported and used to create programs faster. Furthermore, you will quickly adopt your own subset of Java. For example, “while” and “for” loops are redundant. If you use only a “while” loop then you can still do all computing. Do not get caught in the mindset of thinking “I can’t solve this problem until I know more Java.” In reality, there is very little Java you need to know to be able to solve all solvable[1] problems.

When starting out in Java, in my opinion, the four most important things to know are:

  1. File structure matters.

  2. Execution and instructions in Java, as in all programming languages, are very particular.

  3. Brackets are necessary.

  4. Variables are used to store data into the computer’s memory.

File Structure#

File structure matters and your code must be organized into classes, normally one class per file. The file name must match the class name. Within each class, your code is organized into methods, where each method does a specific thing (or multiple things, but this is not preferred).

Java requires you to have this class structure, and this is the basis of object-oriented programming (OOP). When you follow the object-oriented paradigm, where a file becomes an abstract data type, your classes may have data associated with each class (class and instance variables). However, especially on starting to program, you will not always want to follow an object-oriented paradigm. Sometimes, you just want to “do something”, that is, follow a procedural paradigm, where you focus on listing the steps the program should do. When you are programming in Java in the procedural paradigm, your file must still have the class structure, but it becomes a container to hold your code. Your file contains code to just do something; there are no class or instance variables and you should avoid “global” variables, which are those variables declared just below the class declaration and outside of any method.

Java code starts executing at the first line of the main method, i.e. the method named “main.” Execution proceeds sequentially down the page unless the execution order is explicitly changed by a method call or return or by a control structure such as a loop or conditional.



Code Can’t Just Be Anywhere

Java requires extreme structure. Your code should be inside the main method to start with (and then in other methods as you progress). Java starts executing at the first line of the main method.



Execution and Instructions in Java#

Execution means “to do” or “make happen.” The only instructions the computer can do are those that are pre-wired into the machine. Java provides you with a list of commands or instructions that can be converted into machine code to access the instructions that are pre-wired into the computer. Use only the Java commands – do not use other English words and assume something great will happen. A full list of Java commands, which are reserved words, appears in the Appendix Java At A Glance, near the end of this textbook.

A Java program is made up of statements: each contains a command, or commands, and zero or more arguments, and ends with a semicolon.

Some statements look like arithmetic, for example, x = y + 3; which adds 3 to y and stores the result under the name of x in the computer’s memory. Note that we cannot say y + 3 = x;. Java instructions are very particular with only a single name allowed on the left side of the equals sign (=) and calculations on the right side. The assignment statement always places the value from the right into memory at the name on the left. Another important observation is that the equality symbol is not used for checking equality but rather for setting a variable’s value. A statement to check for equality would require two equals signs (==), thus to check whether x and y contain the same value, we would write x == y.

Some statements look like method or function calls, for example, System.out.print("Hi"); which displays the word “Hi” to standard output, your screen.

Some statements are just a command, for example, return; which causes execution to leave a particular method.

Some statements are just a declaration, for example, int x; which allocates room for an integer in the computer’s memory. This integer goes by the name of x.

Here is a single statement that contains a function call that operates on an arithmetic expression and concatenates the result to a string: System.out.println("fe fi fo fum" + (3 + x));. If x contained the value 5 then the output would be fe fi fo fum8.



Some statements may be put together into a more complex structure, with curly brackets to make a block. For example,

{
    int x;
    int y;
    x = 4;
    y = 3 * x;
    System.out.println("Banana" + (x + y));
}
Banana16

In Java, execution is sequential, from top to bottom,[2] starting at the main method. Some special Java commands – control structures, method calls, or exception handling – allow us to change the execution path to jump around. We can create conditionals where instructions are sometimes executed, using the if or switch commands. We can cause repetition where instructions may be executed multiple times, the real power of computing, with the while and for commands. Bizarre situations may be encountered, and dealt with by the exception handling facility in the language.



A Computer Does Not Work by Magic

Only specific commands are available. Each command does one and only one thing. There should be no ambiguity in a command. Just because one command looks English-like, do not assume that another simple English word will do anything at all.



Practice Questions#

  1. Label the parts of the Java file:

    1.  public class JavaWelcome {
    2.
    3.      /**
    4.       * Prints three welcoming sentences.
    5.       * @param args the command line arguments - none
    6.       */
    7.      public static void main(String[] args) {
    8.          System.out.println("Hello Computing Students!");
    9.          System.out.println("Hope you like this course.");
    10.         System.out.println("Programming is a lot of fun.");
    11.      }//main
    12. }
    
  2. Without running the program, explain what the above program likely does.

  3. What would happen if we switched the following lines in the original program:

    1. 8 and 9?
    2. 8 and 10?
    3. 7 and 8?
    4. 1 and 7?
    5. 10 and 11?
  4. From your observations in the previous question, describe what sequential execution means.

  5. What is the difference between syntax and semantics? Use your knowledge of a natural language such as English, as well as your observations from question 3, to answer this.

  6. What is the name of the file in which the code from question 1 must reside?

To Solutions

Brackets#

Java is a bracketed language, more so than a whitespace language, but you should still make your code with appropriate whitespace, starting by keeping the indentation you learned in Python. You could write every Java program on one line, with few spaces, and it will execute just fine. Here is such an example:

/*SimpleProgram.java*byR.Heise*May26,2021*/import java.util.Scanner;public class SimpleProgram{public static void main(String[] args){int userEntry;Scanner keyboard=new Scanner(System.in);System.out.println("Please enter an integer: ");userEntry=keyboard.nextInt();System.out.println("You have entered: "+userEntry);}//main}//class

Notice, however, how difficult it is to read this program. This program simply asks the user for a number and places that number onto the screen. Was that clear? Justasitisbetter to put space and indentation into English, so it is important to make Java code readable. Here is a much better version of the same code:

/* SimpleProgram.java
 * by R. Heise
 * May 26, 2021
 */
import java.util.Scanner;

public class SimpleProgram{
    public static void main(String[] args){
        int userEntry;
        Scanner keyboard=new Scanner(System.in);
        System.out.println("Please enter an integer: ");
        userEntry = keyboard.nextInt();
        System.out.println("You have entered: " + userEntry);
    }//main
}//class

Notice how every statement - instruction - is on its own line, and indentation shows the relationship to the level of the code. Some statements are put together with squiggly brackets, into blocks. Use a “{” to open a set of related statements and a “}” to the block. Squiggly brackets are also used to put statements together for a method or in control structures such as loops and conditionals. Indent all statements inside of a method or a control structure by 2 to 3 spaces, not to help the computer but to make your code clear to the human reading it.



Write Code for People

If you are writing for the machine, you should be using binary (machine code). If you want to be tricky, you likely won’t remember your own trick in two weeks, never mind a year later.



Variables#

When you, personally, are solving a problem, you might use paper or your phone to write the information you need to remember – information you will use later to continue working towards a solution. As you write code, you will do a similar thing. You will need the computer “to remember” information or data by having the computer store this data in memory. Programming languages provide variables, named memory locations, for this purpose. A typical pattern that is followed in programming is to assign a few variables to values, manipulate them, and output a result. Here is a simple example of this in Java:

1.  public class UseVariables {
2.
3.      /**
4.       * Prints the average of three numbers
5.       * @param args the command line arguments - none
6.       */
7.      public static void main(String[] args) {
8.          int number1;
9.          int number2;
10.         int number3;
11.  
12.         number1 = 10;
13.         number2 = 25;
14.         number3 = 15;
15.                 
16.         double number4 = (number1 + number2 + number3) / 3.0;
17.         System.out.print("The average of the three numbers is: ");
18.         System.out.println(number4);
19.      }//main
20.  }

There are four variables: number1, number2, and number3 are integers, while number4 is a floating point number with double precision. A variable provides access to a computer’s memory and has three important components: name, value, and data type.

The name is something you, as a programmer, create, based on the rules for Java names. Any variable name must start with a letter (or an underscore), followed by any number of letters, digits, or underscores, and can be any length, but must not be a reserved word. The name you choose for your data has a substantial effect on the readability of your program. When people are first programming, myself included, it is tempting to just use single letters such as x, y, z, i, and j because it feels like we are programming faster and we can temporarily remember what x or y contain. However, as our code gets longer, or if someone else needs to read our code, or if we come back to our code weeks later, this is no longer true – it takes time to remember or figure out what those single letters were. Because code readability is so important, there are standards for naming variables. We will use the following conventions:

  1. Most names will be in camelCase, which means that when words are put together, no underscores are used but the beginning of each word within the name is capitalized. Whether the first letter is capitalized or not portrays information to the programmer, as noted in the next two points.

  2. Class names start with a capital letter.

  3. Variable and method names start with a lowercase letter.

  4. Constant names and generic classes are entirely capital letters, with underscores to separate words.

Remember, you are writing code for people, therefore create names to reflect the meaning of your variables.



Create Meaningful Variable Names

After proper indentation, a good variable name has the next biggest effect on better readability of your code. Even if you write code with short names, always use the “refactor” option of your IDE to make better names.



Before you can use a variable in Java, you must declare it. This is done by stating the data type of the variable so that the computer knows how much space in memory should be set aside for the information you want to put there, how to translate your data into machine code, and which operations may be valid on that data. Lines 8-10 of the previous program show examples of declarations. Before a variable is used, we have stated the data type (int) for each of number1, number2, and number3. If you come into Java programming from a language such as Python, you may find data types unsettling. However, when Python is translated into machine code, the interpreter must still assign a data type to each of your variables. The Python interpreter would “assume” that data type (and may not always match what the programmer really wanted). In Java, the programmer leaves no room for doubt; the programmer specifies the data type directly.

Finally, the third component of a variable is its value. Values are put into memory with an assignment statement, which, in Java, is created with a single equals sign. Be very careful here, because you may be coming into the world of programming thinking that an equals sign means equality, but in Java, an equals sign is an assignment. The equals sign must have a single variable on the left-hand side and may have any (type-matched) expression on the right-hand side. Variables that appear on the right-hand side are evaluated for their value (their value does not normally change[3]), and those values are used to determine a new value which is put into memory for the name on the left-hand side.

You may be wondering what happens when different programmers use the same variable name or when you might use the same name in different parts of your program. This is not a problem because variables have a limited time in which they are accessible within a program. A variable is alive only within the block in which it is declared. If the same name is used inside a nested block, that produces a syntax error, so is not allowed. Consider the following example:

{//BLOCK A starts =======================================================
   int x = 5;
   int y = 7;
   
   {//BLOCK B starts =====================================================
      int x = 3; //Causes syntax error: the name 'x' is already used
      System.out.println(y); //This will print 7

      int z = 6;
   }//BLOCK B ends, access to z ends here ================================
   
   System.out.println(x); //Will print 5
   System.out.println(y); //Will print 7
   System.out.println(z); //Causes syntax error: no access to z
}//BLOCK A ends ========================================================== 

Note that I have used poor, single-letter variable names. This is because I have no meaning associated with these variables. They are used only to illustrate the concept of when a variable is alive. Adding meaning to them in this case could only create confusion.

Practice Questions#

  1. Which of the following are valid names for variables in Java?

    1. _x
    2. hello
    3. Hello
    4. numChildrenOfClient
    5. i^2
    6. _CLIENT_AGE_
    7. 7thDay
    8. day7
    9. switch
  2. Which is the best variable name to represent the number of students in a database?
    x n number numStudents students num numStud numS

  3. Write the Java statement to declare a variable for a mortgage interest rate and put the value of 12.5% into memory for that variable.

  4. Assuming all variables are declared as integers, what is the value of each variable after execution of the Java code snippets:
    a.

    banana = 4;
    papaya = -32;
    banana = papaya + 8;
    

    b.

    banana = 4;
    papaya = -32;
    papaya = 8 * banana + papaya;
    

    c.

    banana = 4;
    papaya = -32;
    banana = papaya++ + 8;
    

    d.

    banana = 4;
    papaya = -32;
    banana = --papaya + 8;
    

To Solutions