Output, Syntax, String and Int Variables, Type-Casting, Crementation, and Mathematic Statements (Math Class)
When "source code" or even just "code" is mentioned, it is implying the code in the program that is being created.
Compiler is the program that converts the source code into binary, so the computer can understand it and run it.
In Java language programming, it uses a program called Java virtual machine (J.V.M.) to also translate the programming code.
Java source files must have a .java extension.
To demonstrate the syntax, or the grammar, of the Java language, begin with a simple example of a method, System.out.println().
Compiling and Running
Make sure to compile the code before running the code. In DrJava, the file is prompted to save before compilation.
The above code is an instruction for the computer to print out the message "Hello world!" on the DrJava screen.
When pressing Compile, then Run, the following happens in Compiler Output:
Comments
Note the green-highlighted text. These are called comments. They are used for documenting code, writing notes, etc. The compiler will ignore any comments made. It will even ignore code made into a comment.
There are two types of comment formats in Java language: a block comment and a comment line.
The green-highlighted comment at the top is a comment block, which begins and terminates with /* and */, respectively. Block comments are useful when documenting long, multiple-lined comments.
The green-highlighted comment after the comment block is a line comment, which begins with //, and everything on the same line after the // is ignored by the compiler.
Program Name and File Name
The program name must be the same as the file name associated with it, and the name of the program is found in a dark blue. In this code, the program name is HelloWorldExample. The file name would then be HelloWorldExample.java.
Main Method
After the main method, public static void main(String[] args), all of the code is generally written under it.
Curly Braces and Code Blocks
Curly braces denote the start and the end of the code, which is called a code block. In this code, there are two code blocks: one is of the main method and the other is for the program, HelloWorldExample.
Indenting Code Blocks
It is always custom to indent code blocks consistently with the tab key due to making the code blocks much easier to read.
Statements
A program, and many algorithms, are made of statements. Statements are basically a line of instruction for the computer to read.
In this code, a statement of System.out.println() is present, telling the program to print a message to the screen.
Syntax
Since statements are made for the computer to follow instructions, they must be structured in a certain way for the computer to understand it. All programming languages have syntax rules.
A basic structure of a statement is the following:
command(parameter);
Since the print line statement is a command, or method, it follows this syntax.
command(parameter);
System.out.println("Hello world!");
In this case, the command is System.out.println(), and the parameter is "Hello world!".
Although we can change the parameter, we cannot change the command.
System.out.show("Hello world!") would not work, because there is no such command in Java language.
Compile-time Error
If the syntax was not typed properly, causing syntax errors, Java will give an error describing what is wrong during compile-time, however most of the time it is hard to understand the problem. This is called a compile-time error.
Case Sensitivity
Java language is case sensitive in which
System.out.println();
is not the same as
system.out.println();
In fact, S and s are completely different characters meant for completely different things in Java language.
Output
If the following statement was used:
System.out.println("...");
then a new line will start after printing the message "...".
Additionally, if the following statement was used:
System.out.print("...");
then there will be no new line after printing the message "...".
This is because "ln", or line, was not included, therefore these two statements have differences when running.
Standard Output
System.out.println() and System.out.print() are both examples of methods called standard output or console output. It is also possible to see them being called stdout, a shorthand for standard output.
Parameters
Putting something in double quotes, "", is the way of providing text to Java language. Therefore, removing these double quotes will leave a compile-time error.
String
Anything in double quotes is called a string, which is short for string of characters. It is a type of data given to the computer.
The domain for characters in Java language is letters, numbers, symbols, or even whitespace produced by the space bar.
Strings can be joined together, or concatenated, to form larger strings. This is done by using string concatenation, +.
System.out.print("Hi" + "there"); will print Hi there
Concatenation is something a programmer can always do with strings.
Variables
It is useful to store data in programs, such as usernames, passwords, bank account balances, etc. This data can be stored in variables. Consider variables like buckets that hold data.
Variables are like the mathematical variables, where a variable is assigned a value or a parameter that equals a value.
x = 1
y = 20
z = x + y
There are different types of variables that hold specific types of data. In the previous code, an example of a specific type was the string data type.
Since strings only display characters instead of calculate characters, there is a specific data type for mathematic calculations.
Variable Capabilities
There are three ways that a variable could be used.
1. Creating a variable.
In mathematics, creating a variable is assigning a value to a character, such as x = 1.
2. Assigning a value to a variable.
In mathematics, assigning a variable to a value is the same as creating the variable.
x = 1
Not only did it create the variable, x, but it was assigned the value 1.
This is why variables are called variables: they can vary in value.
If a value was assigned to the variable the first time, then it is called initializing the variable.
Another way of assigning is assigning variables to other values, even to themselves.
Given the following variable declaration:
String name;
name = "Joe";
There can be another variable involved, such as lastname...
String name;
String lastname;
name = "Joe";
lastname = "Smith";
However, if someone was named Smith, we could use the string variable, lastname, to input this value.
String name;
String lastname;
lastname = "Smith";
name = lastname;
If it were the print the variable, name, then its value should be Smith.
System.out.println(name);
Just because we set name to lastname in value, it does not change the initial value of lastname; assigning variables is merely copying the variable.
Assigning variables is actually an operator, and a good way to show this is the following statements:
int x;
System.out.println(3 + (x = 4));
System.out.println(x);
Two outputs will happen: 7 and 4. The first output indicates that the integer 3 will be added to the value of x, which is 4. The second output indicates that the integer variable, x, is equal to 4.
3. Retrieving the value of a variable.
In mathematics, retrieving the value of a variable means to find the value of the variable to perform the instruction.
if x = 4, then 4x = 16
The above statement had to retrieve the variable value, 4, to determine 4x.
4. Declaring variables.
Declaring variables in Java language has the following syntax rules:
variableType variableName;
A string variable called "name" would look like this:
String name;
It is saying to create a String variable and name it "name".
Once the variable is created, it does not need to be created again.
If the variableName had a value, the following syntax rules would be used:
variableName = data;
Therefore, the variableName above, name, can be assigned a value.
name = "Joe";
Remember that the variable type is a String, so double quotes are used for the data. These double quotes are called string literal. Because whatever is inside the double quotes is what will be literally stored in the string variable.
Therefore, the string "Joe" is stored into the string variable name.
Another way to write the following:
String name;
name = "Joe";
is
String name = "Joe";
This is both declaring the variable and initializing the variable all on one line.
5. Accessing variables.
Variables can be accessed at any time.
If the variable name was assigned the value "Joe", then the variable can be used to access the value during an instruction statement.
Since the variable is a string type, then the instruction statement must be a string command.
String name;
name = "Joe";
System.out.println("Joe");
can be written as
String name;
name = "Joe";
System.out.println(name);
The following demonstrates how to access variables:
When Compile is pressed, and Run is pressed, the following output should result:
Escape Sequences
If a double quote, or other special characters, is desired in the string, it cannot be simply placed inside the double quotes without a compile-time error. Instead, there are some escape sequences to allow such characters in string variables.
They always begin with a back slash, \.
For double quote, ", it's \"
For a new line, it's \n
For a tab indent, it's \t
For a back slash, it's \\
Naming Variables
A few rules to naming variables in order for Java language to understand:
1. No spaces.
2. No special characters, except underscores.
3. Numbers can be used but cannot start with a number.
4. Cannot be named as Java language's reserved words.
Numbers and Variables
If we used a string variable and its concatenated operator, +, to add numbers, it would literally add the number characters together and not actually create a sum.
That means this:
This is why string literals are called string literals. Because they literally string values together.
Instead, another type of variable would have to be used; a variable that deals with number characters for arithmetic operations.
There are many types of these variables, but the common ones are the following:
int
Stands for integer. Only deals with whole number values.
Has 4 bytes of memory, which is 32 bits in total.
Range: +- 2,147,483,647
long
64 bits.
Range: +- 9,223,372,036,854,775,807
short
16 bits.
Range: +- 32,767
byte
8 bits.
Range: +- 127
There are also variable types for decimals.
float
32 bits.
Range: ~7 significant digits
double
64 bits. Used more for better precision.
Range: ~15 significant digits
When using integer variables, do not use commas to separate place value.
Note that the floating-point values are not always accurate, which is considered normal and will not really affect the program.
String Variables and Integer Variables
Concatenating a string and an int will always make a string output, never an integer output.
Combining a string data with numeric data
String course = "comp" + 1010;
will result in "comp1010".
Written differently:
int num = 1010;
String course = "comp" + num;
Type Casting
Certain data types, like int and double, are very closely related. With this relation, similar data types can be type-casted into each other.
What if the data value of the following statement
double someDecimal = 5.7;
was to be an integer instead of a decimal?
To type-cast this, you create another variable and insert (int) before the variable you want type-casted.
double someDecimal = 5.7;
double val = (int)someDecimal;
This will return the value of 5, meaning the decimal portion, 7, is truncated, or dropped. This does not mean the number was rounded.
Rounding Numbers
In order to round a floating-point number rather than truncating the number, add 0.5 and then truncate.
To round the floating-point number 5.7, the following code is used:
When compiled and ran, the compiler output should give 6.0.
Operators
Operators are the things we can do to different data types. Operators include concatenating strings and adding numbers.
There are either unary operators or binary operators.
Unary, or monadic, operators have a single one operand:
int val = -5;
In this case, the negation of the five is the operand.
Binary (dyadic) operators have two operands:
int sum = a + b;
In this case, a is the first operand, and b is the second operand.
Five Standard Arithmetic Operators
Addition (+): int val = x + y;
Subtraction (-): int val = x - y;
Multiplication (*): int val = x * y;
Division (/): int val = x / y;
Modulus (%): int val = x % y;
If a number was to be divided by another number with a remainder, truncation will occur.
Therefore, to store the result in a floating-point number, it is important to type-cast the variable type double for each operand.
int a = 5;
int b = 2;
double divide = (double) a / (double) b;
The output result should then be 2.5.
double divide = a / b;
would result in 5/2 truncated: 2.0, which is the wrong answer.
Order of Operation
The following the order of operation for statement calculation.
1. Casting.
2. Bracket calculations.
3. Multiplication.
4. Division.
5. Addition.
6. Subtraction.
7. Variable assignment happens.
Therefore, using parentheses to clean up the mathematical expressions is required.
Math Library
Java language has another built-in library that allows programmers to do a lot of additional mathematics. This library is called the Math Class.
In Math Class, there are many functions for square roots, trigonometry, absolute value, random numbers, minimum and maximum, and more.
Maximum and Minimum
A way of finding what the maximum or minimum of 2 numbers is to use the method Math.min(a,b);
Using 2 numbers:
int a = 5;
int b = 10;
int minimum = Math.min(a,b);
The output will return the lowest number of 5 and 10, which is 5.
With maximums and minimums, the parameters are two instead of one. Some methods have more than two parameters.
If it was desired to determine the maximum or minimum of more than two numbers, the following should be applied:
int a = 1;
int b = 2;
int c = 3;
int d = 4;
int highest = Math.max( Math.max(a,b), Math.max(cd) );
System.out.println(highest);
Notice that, since maximum and minimum methods can only work in two parameters at a time, the first two int values, a and b, are compared in one parameter, and the second two int values, c and d, are compared in the other parameter. After those are compared, the maximum value for the first parameter and the maximum value for the second parameter are then compared.
In the end, the maximum value is 4, which would be the compiler output.
Increment and Decrement
Incrementation and decrementation are used to keep track of the number of a certain value at any given time in the program, such as the number of bullets your gun has in the video game or how much time has passed.
If the number of seconds increased by 1 each time, the following statement can apply to this increment:
numSec = numSec + 1;
This may also be expressed the same way with the following statements:
numSec ++; (This statement, called postfix increment, only increases by 1.)
numSec += 1;
Decrementation, if time were to count down instead of up, would have similar statements:
numSec = numSec - 1;
numSec --; (This statement only decreases by 1.)
numSec -= 1;
Postfix Crementation and Prefix Crementation
Recall that ++; or --; increases and decreases by 1, respectively.
However, this can be placed behind the variable, postfix, or in front of the variable, prefix. They crement in different ways.
numSec ++;
int numSec = 2;
int secondsAdded = numSec++;
int seconds = numSec;
The output of the variable seconds would result in 3.
This postfix incrementation means to use the variable, numSec, then increment by 1, showing the increase in the next statement regarding that cremented variable.
++numsec;
This prefix incrementation means to increment numSec by 1, then use numSec.
int numSec = 2;
int seconds = ++numSec;
The output would result in 3.
Expressions
Any statement that can be evaluated is known as an expression.
Such expressions are like this:
int a = 5;
int b = 10;
int c = 15;
int x = (a + b) * c;
x --;
String str = "result = " + x;
In this case, the expressions are 5, 10, 15, (a + b) * c, x --, and "result = " + x.
Variables, and other things, are always assigned values from expressions.
Random Numbers
Another method that the Math Class has is a method to generate a random number in the range of [0,1).
Math.random();
To make the number not inside this range, we simply place the expression (min + (max - min + 1) with the method.
int min = 1;
int max = 6;
int diceRoll = (int)(min + (max - min + 1) * Math.random());
Remember to cast the value as an int, because Math.random() is a decimal value.
Although Math.random() can be zero, the min added on to the value after the multiplication causes the output to be in the minimum, 1, and maximum, 6, range.
Floating-Point Syntax
There many different values that indicate a floating-point number. The common are the following:
double v1 = 5.0; (regular double)
float v2 = 5.0F; (F specifies a float)
double v3 = 2.1E-3 (scientific notation)
double v4 = .1; (omitting 0)