“Java is a programming language and a computer platform commercialized for the first time in 1995 by Sun Microsystems”, this is how easily the Java website itself summarizes what this technology is.
It was born with the objective of being a programming language with a simple structure that could be executed in several operating systems.
The similarity in name between Java and JavaScript means that they are sometimes confused. However, the two are totally different.
Showing some of their differences
Java | JavaScript |
---|---|
It is a compiled language | It is an interpreted language |
It is debugged in two phases | It is debugged in one phase |
It is a purely object-oriented language | It is prototype-based |
It is strongly typed | It is weakly typed |
Variables are not a new concept, anyone who knows mathematics is familiar with the concept of variables.
A variable is a container in which you can store any data. For example, you can have the following variable:
Variables in Java.
Java variables are a memory space in which we store a certain value (or data). To define a variable we will follow the structure:
1[privacy] variable_type identifier;
Java is a statically typed language. Therefore all variables will have a data type (either a primitive data type or a class) and an identifier name.
The data type will be assigned when defining the variable. In addition, in the case that variables are object properties they will have a privacy.
Examples of variables would be...
1int number = 2; 2String string = “Hello”; 3long decimal = 2.4; 4boolean flag = true;
Variables are used as properties within objects.
1class Triangle { 2 private long base; 3 private long height; 4}
Don't worry about the concept of object, as we will review it later when we talk about Object Oriented Programming.
Types of variables in Java
Within Java we can find the following types of variables:
1class Triangle { 2 private long base; 3 private long height; 4}
1class Triangle { 2 static long sides = 3; 3}
If we also want that the value can never change we will define it as final.
1class Mathematics { 2 final static long PI = 3.14159; 3}
1int variable = 2;
1public Triangle(long base, long height){...}
When we are going to give a name to a variable we will have to take into account a series of rules. That is to say, we cannot give any name we want to a variable.
Identifiers are unicode, case sensitive text sequences whose first character can only be a letter, number, dollar symbol $ or underscore _ . While it is true that the dollar sign is not used by convention. It is recommended that the names of the identifiers be legible and not acronyms that we cannot read. In such a way that they are self-documenting when viewed. In addition, these identifiers can never coincide with reserved words.
Some unwritten rules, but which have been assumed by convention are:
The literal values are those that we can assign to the variables. Depending on the type of variable we will be able to assign some values or others.
Integer literals
The integers we can use are byte, short, int and long. The literals we assign to them will always be an integer.
1byte variableByte = 12; 2short variableShort = 12; 3int variableInt = 12; 4long variableLong = 12;
While for the case of the long type we can create integer literals ending in L (upper or lower case, although for readability we recommend the first one)
1long variableLong = 12D;
There are other values that can be handled by the integer literals, for when we represent the number in different bases. For example when we handle them as binary or hexadecimal. For this case we will have to handle integer literals that have that format.
1int variableBinary = 011010; 2int variableHexadecimal = 0x1a;
Decimal literals
The two decimal data types we can handle are float and double. For these cases the representation of the decimal literal will be with a dot separation between the integer part and the decimal part.
1float variableFloat = 12.2; 2double variableDouble = 12.2;
In the same way we can use the letters F or f for the float data type and D or d for the double data type. Always, for readability, the uppercase letter is recommended.
1float variableFloat = 12.2F; 2double variableDouble = 12.2D;
Character literals and strings
Both characters of the char data type and strings of the String data type contain Unicode UTF-16 characters.
UTF-16 characters can be written directly in the string or if our text editor does not allow us to handle that encoding we can put them escaped in the format.
1'uCODIGOUNICODE'
For example the letter like ñ would be escaped as follows:
1'u00F1'
To use it in a text string ``Spain'' we could put
1String pais = "Espau00F1a";
For characters we will use single quotes to delimit them, while for strings we will use double quotes.
1char variableChar = 'a'; 2String variableString = 'string';
As we have already mentioned, Java is a statically typed language. That is to say, the data type of the variable is defined at the time of defining it. That is why all variables will have a data type assigned to them.
The Java language provides a series of primitive data types as a basis.
Type | Possible Values | Description | Default Value |
---|---|---|---|
byte | Numeric values from -128 to 127 (inclusive) | Represents an 8-bit signed data type that can store numeric values from -128 to 127 (inclusive). | 0 |
short | Numeric values from -32,768 to 32,767 | Represents a 16-bit signed data type that stores numeric values from -32,768 to 32,767. | 0 |
int | Numeric values | A 32-bit signed data type for storing numeric values. Its minimum value is -2³¹, and its maximum value is 2³¹-1. | 0 |
long | Numeric values between -2⁶³ to 2⁶³-1 | A 64-bit signed data type that stores numeric values between -2⁶³ and 2⁶³-1. | 0L |
float | Numeric values | A data type for storing floating-point numbers with single-precision (32-bit). | 0.0f |
double | Numeric values | A data type for storing floating-point numbers with double-precision (64-bit). | 0.0d |
char | Unicode character | A data type that represents a single 16-bit Unicode character. Note: Unicode characters must be enclosed in single quotes. | 'u0000' |
String (or any object) | Any sequence of characters | Strings are the only way to store words (sequences of characters). Note: Strings must be enclosed in double quotes. | null |
boolean | true | false | Used to define boolean data types, which have a value of either true or false. It occupies 1 bit of memory. | false |
A Java program consists of a set of statements that are executed to solve a problem. Statements are the basic element of Java program execution.
Apart from the statements, in a Java program we will find expressions and blocks.
Expressions
An expression is a set of variables, operators and method invocations that are constructed to be evaluated by returning a result.
Examples of expressions are:
1int value = 1; 2if (value 1 > value2) { ... }
When we have complex evaluation expressions it is recommended that we use parentheses to know which is the order of execution of operations.
Because if we have an expression like
12 + 10 / 5
It will not be the same if we put Since if we have an expression like:
1(2 + 10) / 5 ó 2 + (10 / 5)
In the case of not using parentheses the order of preference of operators will be executed. In this case division takes precedence over addition.
Statements
A statement is the minimum unit of execution of a program. A program is composed of a set of statements that end up solving a problem. At the end of each of the statements we will find a semicolon (;).
We have the following types of statements.
Statement statements
1int value = 2;
Assignment statements
1value = 2;
Increment or decrement statements
1value++;
Method invocations
1System.out.println(“Hello World”);
Object creations
1Circle myCircle = new Circle(2,3);
Flow control statements
1if (value>1) { ... }
Blocks
A block is a set of statements which are delimited by braces.
1if (expression) { 2 // Block 1 3} else { 4 // Block 2 5}
The simplest Java operator is the assignment operator. This operator is used to assign a value to a variable. The assignment operator is the equals sign.
The structure of the assignment operator is:
variable = value;
This way we can assign values to variables of type integer, string,...
1int number = 3; 2String string = "Hello world"; 3double decimal = 4.5; 4boolean truth = true;
Arithmetic operators in Java are the operators that allow us to perform mathematical operations: addition, subtraction, multiplication, division and remainder.
The arithmetic operators in Java are:
Operator | Description |
---|---|
+ | Sum Operator. Concatenates strings for the sum of String |
- | Subtract Operator |
* | Multiplication Operator |
/ | Division Operator |
% | Subtract Operator |
The arithmetic operators in Java are used between two literals or variables and the result is usually assigned to a variable or evaluated.
variable = (value1|variable1) operator (value2|variable2);
Thus we can have the following uses in case we want to assign its value.
1sum = 3 + 7; // Return 10 2subtraction = 5 - 2; // Returns 3 3multiplication = 3 * 2; // Returns 6 4division = 4 / 2; // Return 2 5remainder = 5 % 3; // Return 2
Note that they can be values or variables:
1sum = vble1 + 3; // We add 3 to the value of the variable vble1 2subtract = vble1 - 4; // Subtract 4 from the value of the variable vble1
Or we could use it in a condition
1if (variable > sum + 3) { ... }
In this case we don't assign the result of the sum to a variable, we just evaluate it.
Unary operators in Java are those that require only one operand to work.
The unary operators we have in Java are:
Operator | Description |
---|---|
+ | Unary addition operator. Indicates a positive number. |
- | Unary subtraction operator. Negates an expression. |
++ | Increment operator. Increases the value by 1. |
– | Decrement operator. Decreases the value by 1. |
! | Logical complement operator. Inverts the value of a boolean. |
For example we could have the following code:
1int value = 2; 2System.out.println(-value); // Will print a -2 on the screen.
Increment operators can be applied as a prefix or as a suffix.
1++ variable; 2variable ++; 3-- variable; 4variable --;
The logical complement operator is used to negate a boolean value. It is typically placed before a boolean evaluation operation, commonly in decision statements or loops.
The structure is:
! (expression)
If the expression was true
, it turns it into false
, and if it was false
, it turns it into true
.
We can see it in the following example:
1int vble1 = 2; 2int vble2 = 3; 3 4if (!(vble1 > vble2)) 5 System.out.println("variable 1 is smaller than variable 2");
As we can observe, the evaluated expression's value is inverted.
Equality and relational operators in Java allow us to compare the contents of one variable against another, checking if their values are equal or different, or if one value is greater or smaller than the other.
Operation | Syntax | Examples |
---|---|---|
Equal to | == | Is 5 == 5 ? True!Is 5 == 4 ? False!Is 5 == '5' ? True! |
Not Equal to | != | Is 5 != 5 ? False!Is 5 != '5' ? False!Is 1 != 'Hello' ? True! |
Greater than | > | Is 5 > 5 ? False!Is 6 > 3 ? True! |
Less than | < | Is 6 < 12 ? True! |
Greater or Equal to | >= | Is 6 >= 6 ? True!Is 3 >= 6 ? False! |
Less or Equal to | <= | You get the idea 🙂 |
Conditional operators in Java evaluate two boolean expressions.
Operation | Syntax | Examples |
---|---|---|
AND | && | With AND, both sides MUST BE TRUE for the whole expression to be true. Is (5 == 5 && 3 > 1) ? True!Is ('Ramon' == 'Pedro' && 2 == 2) ? False! |
OR (` | `) | |
NOT (! ) | ! | NOT gives the exact opposite of the logical operator result: Is !(5 > 5) ? True!Is !(True) ? False! |
Ternary Operator | ?: | With the ternary operator, you can write conditions in a single line: (5 == 5) ? 5 : 0 |
Now things start to get interesting! To control the flow of your application, you have several options that you will use daily. Therefore, you should feel comfortable using them.
A Java program executes sequentially from the first statement to the last.
However, control flow statements allow us to alter this flow to make decisions or repeat statements.
The main control flow statements are:
Decision statements allow us to execute one block of statements or another based on a condition.
The main decision statements are: if-then-else
and switch
.
Using if-then-else
, we can evaluate a condition and choose between two different blocks of code:
1if (expression) { 2 // Then block 3} else { 4 // Else block 5}
With switch
, we can evaluate multiple conditions and execute the corresponding block for each case:
1switch (expression) { 2 case value1: 3 block1; 4 break; 5 case value2: 6 block2; 7 break; 8 case value3: 9 block3; 10 break; 11 … 12 default: 13 default_block; 14}
Use
switch
instead ofif
when:
- You are comparing multiple possible conditions of an expression, and the expression itself is not trivial.
- You have multiple values that may require the same code.
- Some values require almost the same execution as another value with only slight differences.
Use
if
instead ofswitch
when:
- You want to test the truth value of an expression.
- You only have a single affirmative test.
- Each branch requires a different expression evaluation.
Loop statements allow us to execute a block of statements multiple times, either for a specific number of times or while a condition is met.
When the condition is no longer met, the loop exits.
The main loop statements in Java are: while
, do-while
, and for
.
With while
, the loop runs as long as the condition is true, but it may never execute if the condition is false from the start:
1while (expression) { 2 block_statements; 3}
On the other hand, do-while
ensures that the block executes at least once:
1do { 2 block_statements; 3} while (expression);
The for
loop allows a more compact structure while achieving the same result:
1for (initialization; condition; increment) { 2 block_statements; 3}
Enhanced For Loop (For-Each)
Recent Java versions introduced an enhanced version of the for
loop, called "for-each". This loop simplifies iterating through objects in a collection without needing to define the number of elements to iterate over.
The syntax is:
1for (TypeToIterate temporaryVariableName : collectionName) { 2 instructions; 3}
Branching statements allow us to break the linear execution flow of a program.
By default, Java executes statements sequentially. However, branching statements let us interrupt this sequence.
The main branching statements in Java are: break
and continue
.
break
: Exits the current block of statements.continue
: Skips to the next iteration of the loop.Java is more than just another programming language; it comes with fun instructions that we can discover throughout the course! 🚀