0% found this document useful (0 votes)
15 views

java basics-páginas-5

Uploaded by

Johnson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

java basics-páginas-5

Uploaded by

Johnson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

final int NUM_ROWS = grid.length; // 12


final int NUM_COLS = grid[0].length; // 8

// 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,

public class Array2DWithDifferentLength {


public static void main(String[] args) {
int[][] grid = {
{1, 2},
{3, 4, 5},
{6, 7, 8, 9}
};

// 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];

// Print grid - all elements init to 0


for (int y = 0; y < grid1.length; ++y) {
for (int x = 0; x < grid1[y].length; ++x) {
System.out.printf("%2d", grid1[y][x]);
}
System.out.println();
}
}

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++).

The benefits of using methods are:


1. Divide and conquer: Construct the program from simple, small pieces or components. Modularize the program into self-contained tasks.
2. Avoid repeating code: It is easy to copy and paste, but hard to maintain and synchronize all the copies.
3. Software Reuse: You can reuse the methods in other programs, by packaging them into library code (or API).

Using Methods
Two parties are involved in using a method: a caller, who calls (or invokes) the method, and the method called.

The process is:

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.

public class EgMethodGetArea {


// The entry main method
public static void main(String[] args) {
double r = 1.1, area, area2;
// Call (Invoke) method getArea() and return
area = getArea(r);
System.out.println("area is " + area);
// Call method getArea() again and return
area2 = getArea(2.2);
System.out.println("area 2 is " + area2);
// Call method getArea() one more time and return
System.out.println("area 3 is " + getArea(3.3));
}

// Method getArea() Definition.


// Compute and return the area (in double) of circle given its radius (in double).
public static double getArea(double radius) {
return radius * radius * Math.PI;
}
}

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

The expected outputs are:

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.

Tracing Method Invocation


You can trace method operations under Eclipse/NetBeans (Refer to the the Eclipse/NetBeans How-to article):
Step Over: Treat the method call as one single step.
Step Into: Step into the method, so that you can trace the operations of the method.
Step Out: Complete the current method and return to the caller.
Set "Breakpoints" inside the method, and "resume" running to the next breakpoint.

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

Method Definition Syntax


The syntax for method definition is as follows:

public static returnValueType methodName(arg-1-type arg-1, arg-2-type arg-2,... ) {


body;
}

// Examples
// Return circle's area given its radius
public static double getArea(double radius) {
return radius * radius * Math.PI;
}

// Return maximum among two given integers


public static int max(int number1, int number2) {
if (number1 > number2) {
return number1;
} else {
return number2;
}
}

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.

Method Naming Convention


A method's name shall be a verb or verb phrase (action), comprising one or more words. The first word is in lowercase, while the rest are initial-capitalized (called camel-
case). For example, getArea(), setRadius(), moveDown(), isPrime(), etc.

Another Example:

/** Example of Java Method definition and invocation */


public class EgMinMaxMethod {
// The entry main() method
public static void main(String[] args) {
int a = 6, b = 9, max, min;
max = max(a, b); // invoke method max() with arguments
min = min(a, b); // invoke method min() with arguments
System.out.println(max + "," + min);

System.out.println(max(5, 8)); // invoke method max()


System.out.println(min(5, 8)); // invoke method min()
}

// The max() method returns the maximum of two given int


public static int max(int number1, int number2) {
if (number1 > number2) {
return number1;
} else {
return number2;
}
}

// The min() method returns the minimum of two given int


public static int min(int number1, int number2) {
return (number1 < number2) ? number1 : number2;
}
}

The "return" statement

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:

return aReturnValue; // of returnValueType declared in method's signature


return; // return nothing (or void)

The "void" Return-Type


Suppose that you need a method to perform certain actions (e.g., printing) without a need to return a value to the caller, you can declare its return-value type as void. In the
method's body, you could use a "return;" statement without a return value to return control to the caller. In this case, the return statement is optional. If there is no
return statement, the entire body will be executed, and control returns to the caller at the end of the body.

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.

Actual Parameters vs. Formal Parameters


Recall that a method receives arguments from its caller, performs the actions defined in the method's body, and return a value (or nothing) to the caller.

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.

Code Example: Magic Number


The following program contains a boolean method called isMagic(int number), which returns true if the given number contains the digit 8, e.g., 18, 108, and 1288.
The signature of the method is:

public static boolean isMagic(int number);

It also provides the main() method to test the isMagic(). For example,

Enter a positive integer: 1288


1288 is a magic number

Enter a positive integer: 1234567


1234567 is not a magic number

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);

// Prompt and read input as "int"


System.out.print("Enter a positive integer: ");
number = in.nextInt();

// Call isMagic() to test the input


if (isMagic(number)) {
System.out.println(number + " is a magic number");
} else {
System.out.println(number + " is not a magic number");
}
in.close();
}

/**
* 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

// Extract and check each digit


while (number > 0) {
int digit = number % 10; // Extract the last digit
if (digit == 8) {
isMagic = true;
break; // only need to find one digit 8
}
number /= 10; // Drop the last digit and repeat
}
return isMagic;

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
}
}

Take note of the proper documentation comment for the method.

Code Example: int Array Methods


The following program contains various method for int array with signatures as follows:

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,

Enter the number of items: 5


Enter the value of all items (separated by space): 8 1 3 9 4
The values are: [8, 1, 3, 9, 4]
The min is: 1
The sum is: 25
The average (rounded to 2 decimal places) is: 5.00

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 for a non-negative integer for the number of items;


// and read the input as "int". No input validation.
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of items: ");
NUM_ITEMS = in.nextInt();

// Allocate the array


items = new int[NUM_ITEMS];
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 113/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial

// 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();

// Test the methods


System.out.print("The values are: ");
print(items);
System.out.println("The min is: " + min(items));
System.out.println("The sum is: " + sum(items));
System.out.printf("The average (rounded to 2 decimal places) is: %.2f%n", average(items));
}

/**
* 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;
}
}

Pass-by-Value for Primitive-Type Parameters


In Java, when an argument of primitive type is pass into a method, a copy is created and passed into the method. The invoked method works on the cloned copy, and
cannot modify the original copy. This is known as pass-by-value.

For example,

public class PassByValueTest {


public static void main(String[] args) {
int number = 8, result;
System.out.println("In caller, before calling the method, number is: " + number); // 8
result = increment(number); // invoke method with primitive-type parameter
System.out.println("In caller, after calling the method, number is: " + number); // 8
System.out.println("The result is " + result); // 9

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.

Pass-by-Reference for Arrays and Objects


As mentioned, for primitive-type parameters, a cloned copy is made and passed into the method. Hence, the method cannot modify the values in the caller. It is known as
pass-by-value.

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,

import java.util.Arrays; // for Arrays.toString()


public class PassByReferenceTest {
public static void main(String[] args) {
int[] testArray = {9, 5, 6, 1, 4};
System.out.println("In caller, before calling the method, array is: "
+ Arrays.toString(testArray)); // [9, 5, 6, 1, 4]
// Invoke method with an array parameter
increment(testArray);
System.out.println("In caller, after calling the method, array is: "
+ Arrays.toString(testArray)); // [10, 6, 7, 2, 5]
}

// Increment each of the element of the given int array


public static void increment(int[] array) {
System.out.println("Inside method, before operation, array is "
+ Arrays.toString(array)); // [9, 5, 6, 1, 4]
// Increment each elements

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]
}
}

Varargs - Method with Variable Number of Formal Arguments (JDK 5)


Before JDK 5, a method has to be declared with a fixed number of formal arguments. C-like printf(), which take a variable number of argument, cannot not be
implemented. Although you can use an array for passing a variable number of arguments, it is not neat and requires some programming efforts.

JDK 5 introduces variable arguments (or varargs) and a new syntax "Type...". For example,

public PrintWriter printf(String format, Object... args)


public PrintWriter printf(Local l, String format, Object... args)

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.

public class VarargsTest {


// A method which takes a variable number of arguments (varargs)
public static void doSomething(String... strs) {
System.out.print("Arguments are: ");
for (String str : strs) {
System.out.print(str + ", ");
}
System.out.println();
}

// A method which takes exactly two arguments


public static void doSomething(String s1, String s2) {
System.out.println("Overloaded version with 2 args: " + s1 + ", " + s2);
}

// Cannot overload with this method - crash with varargs version


// public static void doSomething(String[] strs)

// Test main() method

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");

String[] strs = {"apple", "orange"};


doSomething(strs); // invoke varargs version
}
}

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

Implicit Type-Casting for Method's Parameters


A method that takes a double parameter can accept any numeric primitive type, such as int or float. This is because implicit type-casting is carried out. However, a
method that take a int parameter cannot accept a double value. This is because the implicit type-casting is always a widening conversion which prevents loss of
precision. An explicit type-cast is required for narrowing conversion. Read "Type-Casting" on the conversion rules.

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 takes 2 int's


public static int average(int n1, int n2) {
System.out.println("version 1");
return (n1 + n2)/2; // int
}

// Version 2 takes 3 int's


public static int average(int n1, int n2, int n3) {
System.out.println("version 2");
return (n1 + n2 + n3)/3; // int
}

// Version 3 takes 2 doubles


public static double average(double n1, double n2) {
System.out.println("version 3");
return (n1 + n2)/2.0; // double
}
}

The expected outputs are:

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.

/** Testing Array Method Overloading */


public class SumArrayMethodOverloading {
public static void main(String[] args) {
int[] a1 = {9, 1, 2, 6, 5};
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 119/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println(sum(a1)); // invoke version 1
double[] a2 = {1.1, 2.2, 3.3};
System.out.println(sum(a2)); // invoke version 2
float[] a3 = {1.1f, 2.2f, 3.3f};
//System.out.println(sum(a3)); // error - float[] is not casted to double[]
}

// Version 1 takes an int[]


public static int sum(int[] array) {
System.out.println("version 1");
int sum = 0;
for (int item : array) sum += item;
return sum; // int
}

// Version 2 takes a double[]


public static double sum(double[] array) {
System.out.println("version 2");
double sum = 0.0;
for (double item : array) sum += item;
return sum; // double
}
}

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;
}
}

public static void main(String[] args) {


System.out.println(isOdd(5)); // true
System.out.println(isOdd(6)); // false
System.out.println(isOdd(-5)); // false
}
}

This seemingly correct code produces false for -5, because -5%2 is -1 instead of 1. You may rewrite the condition:

public static boolean isOdd(int number) {


if (number % 2 == 0) {
return false;
} else {
return true;
}
}

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:

public static boolean isEven(int number) {


return (number % 2 == 0);
}
public static boolean isOdd(int number) {
return !(number % 2 == 0);
}

Mathematical Methods
JDK provides many common-used Mathematical methods in a class called Math. The signatures of some of these methods are:

double Math.pow(double x, double y) // returns x raises to power of y


double Math.sqrt(double x) // returns the square root of x
double Math.random() // returns a random number in [0.0, 1.0)
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 121/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
double Math.sin()
double Math.cos()

The Math class also provide two constants:

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 secretNumber = (int)Math.random()*100; // Generate a random int between 0 and 99

double radius = 5.5;


double area = radius*radius*Math.PI;
area = Math.pow(radius, 2)*Math.PI; // Not as efficient as above

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):

java Arithmetic 12 3456 +

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

args = {"12", "3456", "+"} // "args" is a String array


args.length = 3 // length of the array args
args[0] = "12" // Each element of the array is a String
args[1] = "3456"
args[2] = "+"
args[0].length() = 2 // length of the String
args[1].length() = 4
args[2].length() = 1

Code Example: Arithmetic


The program Arithmetic reads three parameters form the command-line, two integers and an arithmetic operator ('+', '-', '*', or '/'), and performs the arithmetic
operation accordingly. For example,

java Arithmetic 3 2 +
3+2=5
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1

public class Arithmetic {


public static void main (String[] args) {
int operand1, operand2;
char theOperator;
operand1 = Integer.parseInt(args[0]); // Convert String to int
operand2 = Integer.parseInt(args[1]);
theOperator = args[2].charAt(0); // Consider only 1st character
System.out.print(args[0] + args[2] + args[1] + "=");
switch(theOperator) {
case ('+'):
System.out.println(operand1 + operand2); break;
case ('-'):
System.out.println(operand1 - operand2); break;
case ('*'):
System.out.println(operand1 * operand2); break;
case ('/'):
System.out.println(operand1 / operand2); break;
default:

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!");
}
}
}

Exercises on Command-Line Arguments


LINK

(Advanced) Bitwise Operations

Bitwise Logical Operations


Bitwise operators perform operations on one or two operands on a bit-by-bit basis, as follows, in descending order of precedences.

Operator Mode Usage Description Example


~ Unary ~x Bitwise NOT (inversion)

& Binary x & y Bitwise AND

| Binary x | y Bitwise OR

^ Binary x ^ y Bitwise XOR

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.

Take note that:


1. '&', '|' and '^' are applicable when both operands are integers (int, byte, short, long and char) or booleans. When both operands are integers, they perform
bitwise operations. When both operands are booleans, they perform logical AND, OR, XOR operations (i.e., same as logical &&, || and ^). They are not applicable to
float and double. On the other hand, logical AND (&&) and OR (||) are applicable to booleans only.

System.out.println(true & true); // logical -> true


System.out.println(0x1 & 0xffff); // bitwise -> 1
System.out.println(true && true); // logical -> true

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).

Operator Mode Usage Description Example


<< Binary x << count Left-shift and padded with zeros

>> 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

public class BitShiftTest {


public static void main(String[] args) {
int x = 0xAAAA5555; // a negative number (sign bit (msb) = 1)
int y = 0x55551111; // 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<<1); // 5554AAAAH
System.out.printf("%08X%n", x>>1); // D5552AAAH
System.out.printf("%d%n", x>>1); // negative
System.out.printf("%08X%n", y>>1); // 2AAA8888H
System.out.printf("%08d%n", y>>1); // positive
System.out.printf("%08X%n", x>>>1); // 55552AAAH
System.out.printf("%d%n", x>>>1); // positive
System.out.printf("%08X%n", y>>>1); // 2AAA8888
System.out.printf("%d%n", y>>>1); // positive

// More efficient to use signed-right-right to perform division by 2, 4, 8,...


int i1 = 12345;
System.out.println("i1 divides by 2 is " + (i1 >> 1));
System.out.println("i1 divides by 4 is " + (i1 >> 2));
System.out.println("i1 divides by 8 is " + (i1 >> 3));
int i2 = -12345;
System.out.println("i2 divides by 2 is " + (i2 >> 1));
System.out.println("i2 divides by 4 is " + (i2 >> 2));
System.out.println("i2 divides by 8 is " + (i2 >> 3));
}
}

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.

[More example on advanced usage.]

Types and Bitwise Operations


The bitwise operators are applicable to integral primitive types: byte, short, int, long and char. char is treated as unsigned 16-bit integer. There are not applicable to
float and double. The '&', '|', '^', when apply to two booleans, perform logical operations. Bit-shift operators are not applicable to booleans.

Like binary arithmetic operations:


byte, short and char operands are first promoted to int.
If both the operands are of the same type (int or long), they are evaluated in that type and returns a result of that type.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 126/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
If the operands are of different types, the smaller operand (int) is promoted to the larger one (long). It then operates on the larger type (long) and returns a result in
the larger type (long).

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.

Algorithm for Prime Testing


Ancient Greek mathematicians like Euclid and Eratosthenes (around 300-200 BC) had developed many algorithms (or step-by-step instructions) to work on prime numbers.
By definition, a prime is a positive integer that is divisible by one and itself only.

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.

// To test whether an int x is a prime


int maxFactor = (int)Math.sqrt(x); // find the nearest integral square root of x
assume x is a prime;
for (int factor = 2; factor <= maxFactor; ++factor) {
if (x is divisible by factor) {
x is not a prime;
break; // a factor found, no need to find more factors
}
}

TRY: translate the above pseudocode into a Java program called PrimeTest.

Algorithm for Perfect Numbers


A positive integer is called a perfect number if the sum of all its proper divisor is equal to its value. For example, the number 6 is perfect because its proper divisors are 1, 2,
and 3, and 6=1+2+3; but the number 10 is not perfect because its proper divisors are 1, 2, and 5, and 10≠1+2+5. Other perfect numbers are 28, 496, ...

The following algorithm can be used to test for perfect number:

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

// To test whether int x is a perfect number


int sum = 0;
for (int i = 1; i < x; ++i) {
if (x is divisible by i) {
i is a proper divisor;
add i into the sum;
}
}
if (sum == x)
x is a perfect number
else
x is not a perfect number

TRY: translate the above pseudocode into a Java program called PerfectNumberTest.

Algorithm on Computing Greatest Common Divisor (GCD)


Another early algorithm developed by ancient Greek mathematician Euclid (300 BC) is to find the Greatest Common Divisor (GCD) (or Highest Common Factor (HCF)) of
two integers. By definition, GCD(a,b) is the largest factor that divides both a and b.

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

The Euclidean algorithm is as follows:

GCD(a, b) // assume that a >= b


while (b != 0) {
// Change the value of a and b: a ← b, b ← a mod b, and repeat until b is 0
temp ← b
b ← a mod b
a ← temp
}

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.

int x = 55, y=66;


// swap the values of x and y
x = y;
y = x;

To swap the values of two variables, we need to define a temporary variable as follows:

int x = 55, y=66;


int temp;
// swap the values of x and y
temp = y;
y = x;
x = temp;

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.

TRY: Write a program called GCD, based on the above algorithm.

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.

Link to Java References and Resources

More References and Resources


1. (MUST READ) "Code Conventions for the Java Programming Language" @ https://www.oracle.com/technetwork/java/codeconvtoc-136057.html, or google the title, Sun
Microsystems (now Oracle), 1999.

Latest version tested: JDK 15.0.2


Last modified: February, 2021

https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 130/130

You might also like