java basics-páginas-5
java basics-páginas-5
// Fill in grid
for (int row = 0; row < NUM_ROWS; ++row) {
for (int col = 0; col < NUM_COLS; ++col) {
grid[row][col] = row*NUM_COLS + col + 1;
}
}
// Print grid
for (int row = 0; row < NUM_ROWS; ++row) {
for (int col = 0; col < NUM_COLS; ++col) {
System.out.printf("%3d", grid[row][col]);
}
System.out.println();
}
}
}
To be precise, Java does not support multi-dimensional array directly. That is, it does not support
syntax like grid[3, 2] like some languages. Furthermore, it is possible that the arrays in an array-
of-arrays have different length.
Take note that the right way to view the "array of arrays" is as shown, instead of treating it as a 2D
table, even if all the arrays have the same length.
For example,
// Print grid
for (int y = 0; y < grid.length; ++y) {
for (int x = 0; x < grid[y].length; ++x) {
System.out.printf("%2d", grid[y][x]);
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 105/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
System.out.println();
}
// Another 2D array
int[][] grid1 = new int[3][];
grid1[0] = new int[2];
grid1[1] = new int[3];
grid1[2] = new int[4];
Methods (Functions)
Why Methods?
At times, a certain portion of code has to be used many times. Instead of re-writing the code many times, it is better to put them into a "subroutine", and "call" this
"subroutine" many time - for ease of maintenance and understanding. Subroutine is called method (in Java) or function (in C/C++).
Using Methods
Two parties are involved in using a method: a caller, who calls (or invokes) the method, and the method called.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 106/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
1. The caller invokes a method and passes arguments to the method.
2. The method:
a. receives the arguments passed by the caller,
b. performs the programmed operations defined in the method's body, and
c. returns a result back to the caller.
3. The caller receives the result, and continue its operations.
Example: Suppose that we need to evaluate the area of a circle many times, it is better to write a method called getArea(), and re-use it when needed.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 107/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
area is 3.8013271108436504
area 2 is 15.205308443374602
area 3 is 34.21194399759284
In the above example, a reusable method called getArea() is defined, which receives an argument in double from the caller, performs the calculation, and return a
double result to the caller. In the main(), we invoke getArea() methods thrice, each time with a different parameter.
Take note that there is a transfer of control from the caller to the method called, and from the method back to the caller, as illustrated.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 108/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Examples
// Return circle's area given its radius
public static double getArea(double radius) {
return radius * radius * Math.PI;
}
Take note that you need to specify the type of the arguments and the return value in method definition.
Calling Methods
To call a method, simply use methodName(arguments). For examples, to call the above methods:
// Calling getArea()
double area1 = getArea(1.1); // with literal as argument
double r2 = 2.2;
double area2 = getArea(r2); // with variable as argument
double r3 = 3.3;
System.out.println("Area is: " + area(r3));
// Calling max()
int result1 = max(5, 8);
int i1 = 7, i2 = 9;
int result2 = max(i1, i2);
System.out.println("Max is: " + max(15, 16));
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 109/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Take note that you need to specify the type in the method definition, but not during invocation.
Another Example:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 110/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Inside the method body, you could use a return statement to return a value (of the returnValueType declared in the method's signature) to return a value back to the
caller. The syntax is:
Notice that main() is a method with a return-value type of void. main() is called by the Java runtime, perform the actions defined in the body, and return nothing back to
the Java runtime.
In the above example, the variable (double radius) declared in the signature of getArea(double radius) is known as formal parameter. Its scope is within the
method's body. When the method is invoked by a caller, the caller must supply so-called actual parameters or arguments, whose value is then used for the actual
computation. For example, when the method is invoked via "area1=getArea(radius1)", radius1 is the actual parameter, with a value of 1.1.
It also provides the main() method to test the isMagic(). For example,
import java.util.Scanner;
/**
* This program contains a boolean method called isMagic(int number), which tests if the
* given number contains the digit 8.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 111/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
*/
public class MagicNumber {
public static void main(String[] args) {
// Declare variables
int number;
Scanner in = new Scanner(System.in);
/**
* Check if the given int contains the digit 8, e.g., 18, 82, 1688.
* @param number The given integer
* @return true if number contains the digit 8
* @Precondition number > 0 (i.e., a positive integer)
*/
public static boolean isMagic(int number) {
boolean isMagic = false; // shall change to true if found a digit 8
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 112/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
}
public static void print(int[] array); // Print [a1, a2, ...., an]
public static int min(int[] array); // Return the min of the array
public static int sum(int[] array); // Return the sum of the array
public static double average(int[] array); // Return the average of the array
It also contains the main() method to test all the methods. For example,
import java.util.Scanner;
/**
* Test various int[] methods.
*/
public class IntArrayMethodsTest {
public static void main(String[] args) {
// Declare variables
final int NUM_ITEMS;
int[] items; // Declare array name, to be allocated after numItems is known
// Prompt and read the items into the "int" array, if array length > 0
if (items.length > 0) {
System.out.print("Enter the value of all items (separated by space): ");
for (int i = 0; i < items.length; ++i) {
items[i] = in.nextInt();
}
}
in.close();
/**
* Prints the given int array in the form of [x1, x2, ..., xn]
* @param array The given int array
* @Postcondition Print output as side effect
*/
public static void print(int[] array) {
System.out.print("[");
for (int i = 0; i < array.length; ++i) {
System.out.print((i == 0) ? array[i] : ", " + array[i]);
}
System.out.println("]");
}
/**
* Get the min of the given int array
* @param array The given int array
* @return The min value of the given array
*/
public static int min(int[] array) {
int min = array[0];
for (int i = 1; i < array.length; ++i) {
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 114/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
if (array[i] < min) min = array[i];
}
return min;
}
/**
* Get the sum of the given int array
* @param array The given int array
* @return The sum of the given array
*/
public static int sum(int[] array) {
int sum = 0;
for (int item: array) sum += item;
return sum;
}
/**
* Get the average of the given int array
* @param array The given int array
* @return The average of the given array
*/
public static double average(int[] array) {
return (double)(sum(array)) / array.length;
}
}
For example,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 115/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
// Return number + 1
public static int increment(int number) {
System.out.println("Inside method, before operation, number is " + number); // 8
++number; // change the parameter
System.out.println("Inside method, after operation, number is " + number); // 9
return number;
}
}
Notes:
1. Although there is a variable called number in both the main() and increment() method, there are two distinct copies - one available in main() and another
available in increment() - happen to have the same name. You can change the name of either one, without affecting the program.
For arrays (and objects - to be described in the later chapter), the array reference is passed into the method and the method can modify the contents of array's elements. It
is known as pass-by-reference. For example,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 116/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
for (int i = 0; i < array.length; ++i) ++array[i];
System.out.println("Inside method, after operation, array is "
+ Arrays.toString(array)); // [10, 6, 7, 2, 5]
}
}
JDK 5 introduces variable arguments (or varargs) and a new syntax "Type...". For example,
Varargs can be used only for the last argument. The three dots (...) indicate that the last argument may be passed as an array or as a sequence of comma-separated
arguments. The compiler automatically packs the varargs into an array. You could then retrieve and process each of these arguments inside the method's body as an array.
It is possible to pass varargs as an array, because Java maintains the length of the array in an associated variable length.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 117/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Can also use String... instead of String[]
public static void main(String... args) {
doSomething("Hello", "world", "again", "and", "again");
doSomething("Hello", "world");
Notes:
If you define a method that takes a varargs String..., you cannot define an overloaded method that takes a String[].
"varargs" will be matched last among the overloaded methods. The varargsMethod(String, String), which is more specific, is matched before the
varargsMethod(String...).
From JDK 5, you can also declare your main() method as:
public static void main(String... args) { .... } // JDK 5 varargs
Method Overloading
In Java, a method (of a particular method name) can have more than one versions, each version operates on different set of parameters - known as method overloading.
The versions shall be differentiated by the numbers, types, or orders of the parameters.
Example 1
/** Testing Method Overloading */
public class AverageMethodOverloading {
public static void main(String[] args) {
System.out.println(average(8, 6)); // invoke version 1
System.out.println(average(8, 6, 9)); // invoke version 2
System.out.println(average(8.1, 6.1)); // invoke version 3
System.out.println(average(8, 6.1));
// int 8 autocast to double 8.0, invoke version 3
//average(1, 2, 3, 4) // Compilation Error - no such method
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 118/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
version 1
7
version 2
7
version 3
7.1
version 3
7.05
Example 2: Arrays
Suppose you need a method to compute the sum of the elements for int[], short[], float[] and double[], you need to write all overloaded versions - there is no
shortcut.
Notes:
1. Unlike primitives, where int would be autocasted to double during method invocation, int[] is not casted to double[].
2. To handle all the 7 primitive number type arrays, you need to write 7 overloaded versions to handle each array types!
"boolean" Methods
A boolean method returns a boolean value to the caller.
Suppose that we wish to write a method called isOdd() to check if a given number is odd.
/**
* Testing boolean method (method that returns a boolean value)
*/
public class BooleanMethodTest {
// This method returns a boolean value
public static boolean isOdd(int number) {
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 120/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
if (number % 2 == 1) {
return true;
} else {
return false;
}
}
This seemingly correct code produces false for -5, because -5%2 is -1 instead of 1. You may rewrite the condition:
The above produces the correct answer, but is poor. For boolean method, you can simply return the resultant boolean value of the comparison, instead of using a
conditional statement, as follow:
Mathematical Methods
JDK provides many common-used Mathematical methods in a class called Math. The signatures of some of these methods are:
Math.PI // 3.141592653589793
Math.E // 2.718281828459045
To check all the available methods, open JDK API documentation ⇒ select module "java.base" ⇒ select package "java.lang" ⇒ select class "Math" ⇒ choose method
(@ https://docs.oracle.com/javase/10/docs/api/java/lang/Math.html for JDK 10).
For examples,
int x1 = 1, y1 = 1, x2 = 2, y2 = 2;
double distance = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
int dx = x2 - x1;
int dy = y2 - y1;
distance = Math.sqrt(dx*dx + dy*dy); // Slightly more efficient
Exercises on Methods
LINK
Command-Line Arguments
Java's main(String[] args) method takes an argument: String[] args, i.e., a String array named args. This is known as "command-line arguments", which
corresponds to the augments provided by the user when the java program is invoked. For example, a Java program called Arithmetic could be invoked with additional
command-line arguments as follows (in a "cmd" shell):
Each argument, i.e., "12", "3456" and "+", is a String. Java runtime packs all the arguments into a String array and passes into the main() method as args. For
this example, args has the following properties:
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 122/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
java Arithmetic 3 2 +
3+2=5
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 123/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.printf("%nError: Invalid operator!");
}
}
}
| Binary x | y Bitwise OR
Example
public class TestBitwiseOp {
public static void main(String[] args) {
int x = 0xAAAA_5555; // a negative number (sign bit (msb) = 1)
int y = 0x5555_1111; // a positive number (sign bit (msb) = 0)
System.out.printf("%d%n", x); // -1431677611
System.out.printf("%d%n", y); // 1431638289
System.out.printf("%08X%n", ~x); // 5555AAAAH
System.out.printf("%08X%n", x & y); // 00001111H
System.out.printf("%08X%n", x | y); // FFFF5555H
System.out.printf("%08X%n", x ^ y); // FFFF4444H
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 124/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
}
}
Compound operator &=, |= and ^= are also available, e.g., x &= y is the same as x = x & y.
2. The bitwise NOT (or bit inversion) operator is represented as '~', which is different from logical NOT (!).
3. The bitwise XOR is represented as '^', which is the same as logical XOR (^).
4. The operators' precedence is in this order: '~', '&', '^', '|', '&&', '||'. For example,
System.out.println(true | true & false); // true | (true & false) -> true
System.out.println(true ^ true & false); // true ^ (true & false) -> true
Bitwise operations are powerful and yet extremely efficient. [Example on advanced usage.]
Bit-Shift Operations
Bit-shift operators perform left or right shift on an operand by a specified number of bits. Right-shift can be either signed-extended (>>) (padded with signed bit) or unsigned-
extended (>>>) (padded with zeros). Left-shift is always padded with zeros (for both signed and unsigned).
>> Binary x >> count Right-shift and padded with sign bit (signed-extended right-shift)
>>> Binary x >>> count Right-shift and padded with zeros (unsigned-extended right-shift)
Since all the Java's integers (byte, short, int and long) are signed integers, left-shift << and right-shift >> operators perform signed-extended bit shift. Signed-extended right
shift >> pads the most significant bits with the sign bit to maintain its sign (i.e., padded with zeros for positive numbers and ones for negative numbers). Operator >>>
(introduced in Java, not in C/C++) is needed to perform unsigned-extended right shift, which always pads the most significant bits with zeros. There is no difference between
the signed-extended and unsigned-extended left shift, as both operations pad the least significant bits with zeros.
Example
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 125/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
As seen from the example, it is more efficient to use sign-right-shift to perform division by 2, 4, 8... (power of 2), as integers are stored in binary.
Algorithms
Before writing a program to solve a problem, you have to first develop the steps involved, called algorithm, and then translate the algorithm into programming statements.
This is the hardest part in programming, which is also hard to teach because the it involves intuition, knowledge and experience.
An algorithm is a step-by-step instruction to accomplice a task, which may involve decision and iteration. It is often expressed in English-like pseudocode, before translating
into programming statement of a particular programming language. There is no standard on how to write pseudocode - simply write something that you, as well as other
people, can understand the steps involved, and able to translate into a working program.
To test whether a number x is a prime number, we could apply the definition by dividing x by 2, 3, 4, ..., up to x-1. If no divisor is found, then x is a prime number. Since
divisors come in pair, there is no need to try all the factors until x-1, but up to √x.
TRY: translate the above pseudocode into a Java program called PrimeTest.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 127/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
TRY: translate the above pseudocode into a Java program called PerfectNumberTest.
Assume that a and b are positive integers and a >= b, the Euclidean algorithm is based on these two properties:
1. GCD(a, 0) = a
2. GCD(a, b) = GCD(b, a mod b), where "a mod b" denotes the remainder of a divides by b.
For example,
GCD(15, 5) = GCD(5, 0) = 5
GCD(99,88) = GCD(88,11) = GCD(11,0) = 11
GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 128/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// after the loop completes, i.e., b is 0, we have GCD(a, 0)
GCD is a
Before explaining the algorithm, suppose we want to exchange (or swap) the values of two variables x and y. Explain why the following code does not work.
To swap the values of two variables, we need to define a temporary variable as follows:
Let us look into the Euclidean algorithm, GCD(a, b) = a, if b is 0. Otherwise, we replace a by b; b by (a mod b), and compute GCD(b, a mod b). Repeat the process
until the second term is 0. Try this out on pencil-and-paper to convince yourself that it works.
Exercises on Algorithm
LINK
Summary
This chapter covers the Java programming basics:
Comments, Statements and Blocks.
Variables, Literals, Expressions.
The concept of type and Java's eight primitive types: byte, short, int, long, float, double, char, and boolean; and String.
Implicit and explicit type-casting.
Operators: assignment (=), arithmetic operators (+, -, *, /, %), increment/decrement (++, --) relational operators (==, !=, >, >=, <, <=), logical operators (&&, ||, !, ^)
and conditional (? :).
Three flow control constructs: sequential, condition (if, if-else, switch-case and nested-if) and loops (while, do-while, for and nested loops).
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 129/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Input (via Scanner) & Output (print(), println() and printf()) operations.
Arrays and the enhanced for-loop.
Methods and passing parameters into methods.
The advanced bitwise logical operators (&, |, ~, ^) and bit-shift operators (<<, >>, >>>).
Developing algorithm for solving problems.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 130/130