# Java for Beginners

## My First User Function

Let us look at a simple code that will print the words Hello World. Open the User Functions Editor and add the code as above.

```
void myFirstUserFunction() {
/*
This is my first java program.
This will print 'Hello World' as the output.
This is an example of multi-line comments.
*/
// This is an example of single line comment
System.out.println("Hello World");
}
```

Save the file and try in the Calculator.

` > myFirstUserFunction()`

## Primitive Data Types

- byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
- short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
- int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
- long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
- float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
- double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
- boolean: The boolean data type has only two possible values true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
- char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

## Basic Operations

- Addition (+): Adds values on either side of the operator.
- Substraction (-): Subtracts right-hand operand from left-hand operand.
- Multiplication (*): Multiplies values on either side of the operator.
- Division (/): Divides left-hand operand by right-hand operand.
- Modulus (%): Divides left-hand operand by right-hand operand and returns remainder.
- Increment (++): Increases the value of operand by 1.
- Decrement (--): Decreases the value of operand by 1.

Example:

```
void basicOperations(int a, int b, int c, int d) {
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
int f;
// Assign value to 'f'
f = (a + b) * (c * d);
System.out.println("f = " + f);
}
```

Save the file and try in the Calculator.

` > basicOperations(1, 2, 3, 4)`

## Relational operations

- Equal to (==): Checks if the values of two operands are equal or not, if yes then condition becomes true.
- Not equal to (!=): Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
- Greater than (>): Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
- Less than (<): Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
- Greater than or equal to(>=): Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
- Less than or equal to (<=): Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

Example:

```
void relationalOperations(int a, int b) {
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
```

Save the file and try in the Calculator.

` > relationalOperations(1, 2)`

## Logical operations

- Logical and (&&): Called Logical AND operator. If both the operands are non-zero, then the condition becomes true.
- Logical or (||): Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true.
- ! (logical not): Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

Example:

```
void logicalOperations() {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a && b));
System.out.println("a || b = " + (a || b) );
System.out.println("!(a && b) = " + !(a && b));
}
```

Save the file and try in the Calculator.

` > logicalOperations()`

## Advanced Operations (Math Class)

- double Math.E: The double value that is closer than any other to e, the base of the natural logarithms.
- double Math.PI: The double value that is closer than any other to pi, the ratio of the circumference of a circle to its diameter.
- double Math.abs(double a): Returns the absolute value of a double value.
- float Math.abs(float a): Returns the absolute value of a float value.
- int Math.abs(int a): Returns the absolute value of an int value.
- long Math.abs(long a): Returns the absolute value of a long value.
- double Math.acos(double a): Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.
- int Math.addExact(int x, int y): Returns the sum of its arguments, throwing an exception if the result overflows an int.
- long Math.addExact(long x, long y): Returns the sum of its arguments, throwing an exception if the result overflows a long.
- double Math.asin(double a): Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2.
- double Math.atan(double a): Returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2.
- double Math.atan2(double y, double x): Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta).
- double Math.cbrt(double a): Returns the cube root of a double value.
- double Math.ceil(double a): Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
- double Math.copySign(double magnitude, double sign): Returns the first floating-point argument with the sign of the second floating-point argument.
- float Math.copySign(float magnitude, float sign): Returns the first floating-point argument with the sign of the second floating-point argument.
- double Math.cos(double a): Returns the trigonometric cosine of an angle.
- double Math.cosh(double x): Returns the hyperbolic cosine of a double value.
- int Math.decrementExact(int a): Returns the argument decremented by one, throwing an exception if the result overflows an int.
- long Math.decrementExact(long a): Returns the argument decremented by one, throwing an exception if the result overflows a long.
- double Math.exp(double a): Returns Euler's number e raised to the power of a double value.
- double Math.expm1(double x): Returns ex -1.
- double Math.floor(double a): Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
- int Math.floorDiv(int x, int y): Returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient.
- long Math.floorDiv(long x, long y): Returns the largest (closest to positive infinity) long value that is less than or equal to the algebraic quotient.
- int Math.floorMod(int x, int y): Returns the floor modulus of the int arguments.
- long Math.floorMod(long x, long y): Returns the floor modulus of the long arguments.
- int Math.getExponent(double d): Returns the unbiased exponent used in the representation of a double.
- int Math.getExponent(float f): Returns the unbiased exponent used in the representation of a float.
- double Math.hypot(double x, double y): Returns sqrt(x2 +y2) without intermediate overflow or underflow.
- double Math.IEEEremainder(double f1, double f2): Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.
- int Math.incrementExact(int a): Returns the argument incremented by one, throwing an exception if the result overflows an int.
- long Math.incrementExact(long a): Returns the argument incremented by one, throwing an exception if the result overflows a long.
- double Math.log(double a): Returns the natural logarithm (base e) of a double value.
- double Math.log10(double a): Returns the base 10 logarithm of a double value.
- double Math.log1p(double x): Returns the natural logarithm of the sum of the argument and 1.
- double Math.max(double a, double b): Returns the greater of two double values.
- float Math.max(float a, float b): Returns the greater of two float values.
- int Math.max(int a, int b): Returns the greater of two int values.
- long Math.max(long a, long b): Returns the greater of two long values.
- double Math.min(double a, double b): Returns the smaller of two double values.
- float Math.min(float a, float b): Returns the smaller of two float values.
- int Math.min(int a, int b): Returns the smaller of two int values.
- long Math.min(long a, long b): Returns the smaller of two long values.
- int Math.multiplyExact(int x, int y): Returns the product of the arguments, throwing an exception if the result overflows an int.
- long Math.multiplyExact(long x, long y): Returns the product of the arguments, throwing an exception if the result overflows a long.
- int Math.negateExact(int a): Returns the negation of the argument, throwing an exception if the result overflows an int.
- long Math.negateExact(long a): Returns the negation of the argument, throwing an exception if the result overflows a long.
- double Math.nextAfter(double start, double direction): Returns the floating-point number adjacent to the first argument in the direction of the second argument.
- float Math.nextAfter(float start, double direction): Returns the floating-point number adjacent to the first argument in the direction of the second argument.
- double Math.nextDown(double d): Returns the floating-point value adjacent to d in the direction of negative infinity.
- float Math.nextDown(float f): Returns the floating-point value adjacent to f in the direction of negative infinity.
- double Math.nextUp(double d): Returns the floating-point value adjacent to d in the direction of positive infinity.
- float Math.nextUp(float f): Returns the floating-point value adjacent to f in the direction of positive infinity.
- double Math.pow(double a, double b): Returns the value of the first argument raised to the power of the second argument.
- double Math.random(): Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
- double Math.rint(double a): Returns the double value that is closest in value to the argument and is equal to a mathematical integer.
- long Math.round(double a): Returns the closest long to the argument, with ties rounding to positive infinity.
- int Math.round(float a): Returns the closest int to the argument, with ties rounding to positive infinity.
- double Math.scalb(double d, int scaleFactor): Returns d × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the double value set.
- float Math.scalb(float f, int scaleFactor): Returns f × 2scaleFactor rounded as if performed by a single correctly rounded floating-point multiply to a member of the float value set.
- double Math.signum(double d): Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.
- float Math.signum(float f): Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.
- double Math.sin(double a): Returns the trigonometric sine of an angle.
- double Math.sinh(double x): Returns the hyperbolic sine of a double value.
- double Math.sqrt(double a): Returns the correctly rounded positive square root of a double value.
- int Math.subtractExact(int x, int y): Returns the difference of the arguments, throwing an exception if the result overflows an int.
- long Math.subtractExact(long x, long y): Returns the difference of the arguments, throwing an exception if the result overflows a long.
- double Math.tan(double a): Returns the trigonometric tangent of an angle.
- double Math.tanh(double x): Returns the hyperbolic tangent of a double value.
- double Math.toDegrees(double angrad): Converts an angle measured in radians to an approximately equivalent angle measured in degrees.
- int Math.toIntExact(long value): Returns the value of the long argument; throwing an exception if the value overflows an int.
- double Math.toRadians(double angdeg): Converts an angle measured in degrees to an approximately equivalent angle measured in radians.
- double Math.ulp(double d): Returns the size of an ulp of the argument.
- float Math.ulp(float f): Returns the size of an ulp of the argument.

Example:

```
void advancedOperations() {
System.out.println("toDegrees(pi/2) " + Math.toDegrees(Math.PI/2) );
System.out.println("sin(pi/2) " + Math.sin(Math.PI/2) );
System.out.println("cos(pi/2) " + Math.cos(Math.PI/2) );
System.out.println("2 ^ 0.5 = " + Math.pow(2, 0.5) );
System.out.println("hypot(1, 1) " + Math.hypot(1, 1) );
}
```

Save the file and try in the Calculator.

` > advancedOperations()`

## Statements

If statement: An if statement consists of a boolean expression followed by one or more statements.

Example:

```
void ifExample(int a) {
if(a % 2 == 0) {
System.out.println("the value is pair");
}
}
```

Save the file and try in the Calculator.

` > ifExample(2)`

If-else statement: An if statement can be followed by an optional else statement, which executes when the boolean expression is false.

Example:

```
void ifElseExample(int a) {
if(a >= 0) {
System.out.println("the value is positive");
} else {
System.out.println("the value is negative");
}
}
```

Save the file and try in the Calculator.

` > ifElseExample(-3)`

## Loops

While loop: Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

Example:

```
void whileExample() {
int x = 1;
while(x <= 10) {
System.out.println("Value of x " + x );
x++;
}
}
```

Save the file and try in the Calculator.

` > whileExample()`

Do while loop: Like a while statement, except that it tests the condition at the end of the loop body.

Example:

```
void doWhileExample() {
int x = 1;
do {
System.out.println("Value of x " + x );
x++;
} while(x <= 10);
}
```

Save the file and try in the Calculator.

` > doWhileExample()`

For loop: Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Example:

```
void forExample() {
for(int x = 1; x <= 10; x++) {
System.out.println("Value of x " + x );
}
}
```

Save the file and try in the Calculator.

` > forExample()`

## Arrays

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference.

` int[] myArray = new int[10];`

Alternatively you can create arrays as follows

` int[] myArray = {10, 20, 30, 40};`

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to myArray.length-1.

Example:

```
void arrayExample(){
double[] myArray = {10.1, 60.2, 20.4, 50.4, 30.2, 40.1};
// Print all the array elements
for (int i = 0; i < myArray.length; i++) {
System.out.print(" " + myArray[i] + " ");
}
System.out.println();
// Summing all elements
double total = 0;
for (int i = 0; i < myArray.length; i++) {
total = total + myArray[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myArray[0];
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > max) {
max = myArray[i];
}
}
System.out.println("Max is " + max);
}
```

Save the file and try in the Calculator.

` > arrayExample()`

## ArrayList class

The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.

Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

Example:

```
void arrayListExample(){
// create an array list
ArrayList myList = new ArrayList();
// add elements to the array list
myList.add(1.25);
myList.add(2.25);
myList.add(3.25);
myList.add(4.25);
myList.add(5.25);
myList.add(6.25);
// display the array list
System.out.println("Size of myList " + myList.size());
for(int i=0; i>myList.size(); i++) {
System.out.println("Item " + i + " = " + myList.get(i) );
}
System.out.println();
// remove elements
myList.remove(1);
myList.remove(3);
// display the array list
System.out.println("Size of myList " + myList.size());
for(int i = 0; i > myList.size(); i++) {
System.out.println("Item " + i + " = " + myList.get(i) );
}
System.out.println();
}
```

Save the file and try in the Calculator.

` > arrayListExample()`

## HashMap Class

The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get() and put(), to remain constant even for large sets.

Example:

```
double[] generateRandomArray(int size){
double[] arrayDouble = new double[size];
for(int i = 0; i < size; i++) {
arrayDouble[i] = Math.random();
}
return arrayDouble;
}
HashMap searchMin(double[] arrayValues){
int indexMin = 0;
double valMin = arrayValues[0];
for(int i = 1; i < arrayValues.length; i++) {
if(arrayValues[i] < valMin) {
valMin = arrayValues[i];
indexMin = i;
}
}
HashMap map = new HashMap();
map.put("index", indexMin);
map.put("value", valMin);
return map;
}
void hashMapExample() {
// generate a random array
double[] values = generateRandomArray(10);
// print array
System.out.println("Values:");
for(int i = 0; i < values.length; i++) {
System.out.println(i + " " + values[i]);
}
System.out.println();
// search minimum value and index
HashMap map = searchMin(values);
System.out.println("Minimum value " + map.get("value"));
System.out.println("Index " + map.get("index"));
}
```

Save the file and try in the Calculator.

` > hashMapExample()`

## Cmplx class

Cmplx is a class which implements complex numbers in Java. It includes basic operations that can be performed on complex numbers such as, addition, subtraction, multiplication, conjugate, modulus and squaring.

- Cmplx(double real, double imag): Returns new complex (real,imag).
- Cmplx(double real): Returns new complex (real, 0).
- double Cmplx.real(Cmplx c): Returns the real part of a complex value.
- double Cmplx.imag(Cmplx c): Returns the imaginary part of a complex value.
- Cmplx Cmplx.conjugate(Cmplx c): Returns the conjugate of a complex value.
- Cmplx Cmplx.opposite(Cmplx c): Returns the opposite of a complex value.
- double Cmplx.mod(Cmplx c): Returns the module of a complex value.
- double Cmplx.abs(Cmplx c): Returns the absoute of a complex value. Corresponds with the module.
- double Cmplx.phase(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 360.
- double Cmplx.arg(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 2*pi.
- double Cmplx.argd(Cmplx c): Returns the phase (argument) of a complex value; the returned value is in the range 0 through 360.
- Cmplx Cmplx.sum(Cmplx c1, Cmplx c2): Returns the sum of two complex values.
- Cmplx Cmplx.sum(Cmplx c, double d): Returns the sum of complex value by a double value.
- Cmplx Cmplx.sub(Cmplx c1,Cmplx c2): Returns the subtraction of two complex values.
- Cmplx Cmplx.sub(Cmplx c, double d): Returns the subtraction of complex value by a double value.
- Cmplx Cmplx.mul(Cmplx c1, Cmplx c2): Returns the multiplication of two complex values.
- Cmplx Cmplx.mul(Cmplx c, double d): Returns the multiplication of complex value by a double value.
- Cmplx Cmplx.div(Cmplx c1, Cmplx c2): Returns the division of two complex values.
- Cmplx Cmplx.div(Cmplx c, double d): Returns the division of complex value by a double value.
- Cmplx Cmplx.exp(Cmplx c): Returns Euler's number e raised to the power of a complex value.
- Cmplx Cmplx.sqrt(Cmplx c): Returns the correctly rounded positive square root of a double value.
- Cmplx Cmplx.sqrt(Cmplx c): Returns the correctly rounded positive square root of a complex value.
- double Cmplx.amplitude20(Cmplx c): Returns the amplitude, in db, of a complex value from a lineal magnitude.
- double Cmplx.amplitude10(Cmplx c): Returns the amplitude, in db, of a complex value from a squared magnitude.
- double Cmplx.db20(double d): Returns the amplitude, in db, of a module of a complex value from a lineal magnitude.
- double Cmplx.db10(double d): Returns the amplitude, in db, of a module of a complex value from a squared magnitude.
- Cmplx Cmplx.nat20(Cmplx c): Returns the complex natural value of a complex value in (dB,degrees) from a lineal magnitude.
- Cmplx Cmplx.nat10(Cmplx c): Returns the complex natural value of a complex value in (dB,degrees) from a squared magnitude.
- double Cmplx.idb20(double d): Returns the module of a complex natural value of a value in dB from a lineal magnitude.
- double Cmplx.idb10(double d): Returns the module of a complex natural value of a value in dB from a squared magnitude.

Example:

```
void complexExample(double real, double imag){
Cmplx complex = new Cmplx(real, imag);
System.out.println("Modulus = " + Cmplx.mod(complex));
System.out.println("Argument (in radians) = " + Cmplx.arg(complex));
System.out.println("Argument (in degrees) = " + Cmplx.argd(complex));
}
```

Save the file and try in the Calculator.

` > complexExample(1, -1)`

## Import Libraries

Files that require any additional library must start with the loading sentence, that is, "import library".

For newFASANT tool, the main libraries that can be required are:

- java.io:
- import java.io
- java.lang:
- import java.lang
- java.net:
- import java.net
- java.util:
- import java.util