java basics-páginas-4
java basics-páginas-4
Let's rewrite the above program without using break statement. A while loop is used (which is controlled by the boolean flag) instead of for loop with break.
/**
* List all prime numbers between 2 and an upperbound
*/
public class PrimeList {
public static void main(String[] args) {
final int UPPERBOUND = 100;
for (int number = 2; number <= UPPERBOUND; ++number) {
// Not prime, if there is a factor between 2 and sqrt of number
int maxFactor = (int)Math.sqrt(number);
boolean isPrime = true;
int factor = 2;
while (isPrime && factor <= maxFactor) {
if (number % factor == 0) { // Factor of number?
isPrime = false;
}
++factor;
}
if (isPrime) System.out.println(number + " is a prime");
}
}
}
Example (continue):
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 79/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
/**
* A mystery series created using break and continue
*/
public class MysterySeries {
public static void main(String[] args) {
int number = 1;
while(true) {
++number;
if ((number % 3) == 0) continue;
if (number == 133) break;
if ((number % 2) == 0) {
number += 3;
} else {
number -= 3;
}
System.out.print(number + " ");
}
}
}
// Can you figure out the output?
// break and continue are hard to read, use it with great care!
Labeled break
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 80/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
In a nested loop, the break statement breaks out the innermost loop and continue into the outer loop. At times, there is a need to break out all the loops (or multiple loops).
This is clumsy to achieve with boolean flag, but can be done easily via the so-called labeled break. You can add a label to a loop in the form of labelName: loop. For
example,
Labeled continue
In a nested loop, similar to labeled break, you can use labeled continue to continue into a specified loop. For example,
Again, labeled break and continue are not structured and hard to read. Use them only if absolutely necessary.
Example (Labeled break): Suppose that you are searching for a particular number in a 2D array.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 81/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
{9, 2, 3, 4}
};
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 82/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.println(c3); // Print char 'a'
System.out.println((char)97); // Print char 'a'
In arithmetic operations, char (and byte, and short) is first converted to int. In Java, arithmetic operations are only carried out in int, long, float, or double;
NOT in byte, short, and char.
Hence, char ⊕ char ⇒ int ⊕ int ⇒ int, where ⊕ denotes an binary arithmetic operation (such as +, -, *, / and %). You may need to explicitly cast the resultant
int back to char. For examples,
Similar, char ⊕ int ⇒ int ⊕ int ⇒ int. You may need to explicitly cast the resultant int back to char. For examples,
However, for compound operators (such as +=, -=, *=, /=, %=), the evaluation is carried out in int, but the result is casted back to the LHS automatically. For
examples,
char c4 = '0'; // Code number 48
c4 += 5; // Automatically cast back to char '5'
System.out.println(c4); // Print char '5'
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 83/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
For increment (++) and decrement (--) of char (and byte, and short), there is no promotion to int. For examples,
That is, suppose c is a char between '0' and '9', (c - '0') is the corresponding int 0 to 9.
The following program illustrates how to convert a hexadecimal character (0-9, A-F or a-f) to its decimal equivalent (0-15), by subtracting the appropriate base char.
String Operations
The most commonly-used String methods are as follows, suppose that str, str1, str2 are String variables:
str.length(): return the length of the str.
str.charAt(int index): return the char at the index position of the str. Take note that index begins at 0, and up to str.length()-1.
str1.equals(str2): for comparing the contents of str1 and str2. Take note that you cannot use "str1 == str2" to compare two Strings. This is because
"==" is only applicable to primitive types, but String is not a primitive type.
For examples,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 84/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
To check all the available methods for String, open JDK Documentation ⇒
Select "API documentation" ⇒
Click "FRAMES" (top menu) ⇒ From "Modules" (top-left pane),
select "java.base" ⇒
From "java.base Packages" (top-left pane), select "java.lang" ⇒
From "Classes" (bottom-left pane), select "String" ⇒choose "SUMMARY"
"METHOD" (right pane) (@ https://docs.oracle.com/javase/10/docs/api/java/lang/String.html for JDK 10).
For examples,
String to int/byte/short/long
You could use the JDK built-in methods Integer.parseInt(anIntStr) to convert a String containing a valid integer literal (e.g., "1234") into an int (e.g., 1234). The
runtime triggers a NumberFormatException if the input string does not contain a valid integer literal (e.g., "abc"). For example,
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 85/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Similarly, you could use methods Byte.parseByte(aByteStr), Short.parseShort(aShortStr), Long.parseLong(aLongStr) to convert a String containing a
valid byte, short or long literal to the primitive type.
String to double/float
You could use Double.parseDouble(aDoubleStr) or Float.parseFloat(aFloatStr) to convert a String (containing a floating-point literal) into a double or
float, e.g.
String to char
You can use aStr.charAt(index) to extract individual character from a String, where index begins at 0 and up to aStr.length()-1, e.g.,
String to boolean
You can use method Boolean.parseBoolean(aBooleanStr) to convert string of "true" or "false" to boolean true or false, e.g.,
For examples,
// Using String concatenation operator '+' with an empty String (applicable to ALL primitive types)
String str1 = 123 + ""; // int 123 -> String "123"
String str2 = 12.34 + ""; // double 12.34 -> String "12.34"
String str3 = 'c' + ""; // char 'c' -> String "c"
String str4 = true + ""; // boolean true -> String "true"
System.out.printf("Hi, %d, %.1f%n", 11, 22.22); // Send the formatted String to console
There is a similar function called String.format() which returns the formatted string, instead of sending to the console, e.g.,
String str = String.format("%.1f", 1.234); // Returns a String "1.2" (for further operations)
import java.util.Scanner;
/**
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 87/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
* Prompt user for a string; and print the input string in reverse order.
*/
public class ReverseString {
public static void main(String[] args) {
// Declare variables
String inStr; // input String
int inStrLen; // length of the input String
isValid = true; // Assume that the input is valid, unless our check fails
for (int inCharIdx = 0; inCharIdx < inStrLen; ++inCharIdx) {
inChar = inStr.charAt(inCharIdx);
if (!(inChar == '0' || inChar == '1')) {
isValid = false;
break; // break the loop upon first error, no need to continue for more errors
// If this is not encountered, isValid remains true after the loop.
}
}
System.out.println("\"" + inStr + "\" is " + (isValid ? "" : "NOT ") + "a binary string");
}
}
Version 2
import java.util.Scanner;
/**
* Check if the input string is a valid binary string.
*/
public class ValidateBinStringV2 {
public static void main(String[] args) {
// Declare variables
String inStr; // The input string
int inStrLen; // The length of the input string
char inChar; // Each char of the input string
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 89/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
This version, although shorter, are harder to read, and harder to maintain.
import java.util.Scanner;
/**
* Prompt user for a binary string, and convert into its equivalent decimal number.
*/
public class Bin2Dec {
public static void main(String[] args) {
// Declare variables
String binStr; // The input binary string
int binStrLen; // The length of binStr
int dec = 0; // The decimal equivalent, to accumulate from 0
char binChar; // Each individual char of the binStr
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 90/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Print result
System.out.println("The equivalent decimal for \"" + binStr + "\" is " + dec);
}
}
Notes:
1. The conversion formula is:
binStr = bn-1bn-2....b2b1b0 hi∈{0,1} where b0 is the least-significant bit
2. We use binStr.charAt(idx) to extract each individual char from the binStr. The idx begins at zero, and increases from left-to-right. On the other hand, the
exponent number increases from right-to-left, as illustrated in the following example:
binStr : 1 0 1 1 1 0 0 1
charAt(idx) : 0 1 2 3 4 5 6 7 (idx increases from the left)
Math.pow(2, exp) : 7 6 5 4 3 2 1 0 (exp increases from the right)
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 91/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
binStr.length() = 8
idx + exp = binStr.length() - 1
3. This code uses exp as the loop index, and computes the idx for charAt() using the relationship idx + exp = binStr.length() - 1. You could also use the
idx as the loop index (see next example).
4. We use the built-in function Math.pow(x, y) to compute the exponent, which takes two doubles and return a double. We need to explicitly cast the resultant
double back to int for dec.
5. There are 3 cases to handle: '1' (add to dec), '0' (valid but do nothing for multiply by 0) and other (error). We can write the nested-if as follows, but that is harder to
read:
if (binChar == '1') {
dec += (int)Math.pow(2, exp); // cast the double result back to int
} else if (binChar != '0') {
System.out.println("error: invalid binary string \"" + binStr + "\"");
return; // or System.exit(1);
} // else (binChar == '0') do nothing
6. You can use Scanner's nextInt(int radix) method to read an int in the desired radix. Try reading a binary number (radix of 2) and print its decimal equivalent.
For example,
import java.util.Scanner;
/**
* Prompt user for the hexadecimal string, and convert to its equivalent decimal number
*/
public class Hex2Dec {
public static void main(String[] args) {
// Declare variables
String hexStr; // The input hexadecimal String
int hexStrLen; // The length of hexStr
int dec = 0; // The decimal equivalent, to accumulate from 0
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 92/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
Notes:
1. The conversion formula is:
2. In this example, we use the charIdx as the loop index, and compute the exponent via the relationship charIdx + exp = hexStr.length() - 1 (See the
illustration in the earlier example).
3. You could write a big switch of 23 cases (0-9, A-F, a-f, and other). But take note how they are reduced to 5 cases.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 93/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
a. To convert hexChar '1' to '9' to int 1 to 9, we subtract the hexChar by the base '0'.
b. Similarly, to convert hexChar 'a' to 'f' (or 'A' to 'F') to int 10 to 15, we subtract the hexChar by the base 'a' (or 'A') and add 10.
4. You may use str.toLowerCase() to convert the input string to lowercase to further reduce the number of cases. But You need to keep the original String for output
in this example (otherwise, you could use in.next().toLowerCase() directly).
Arrays
Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1, mark2, ..., mark30. Instead, You
could use a single variable, called an array, with 30 elements (or items).
An array is an ordered collection of elements of the same type, identified by a pair of square brackets [ ]. To use an array, you need to:
1. Declare the array with a name and a type. Use a plural name for array, e.g., marks, rows, numbers. All elements of the array belong to the same type.
2. Allocate the array using new operator, or through initialization, e.g.,
When an array is constructed via the new operator, all the elements are initialized to their default value, e.g., 0 for int, 0.0 for double, false for boolean, and null for
objects. [Unlike C/C++, which does NOT initialize the array contents.]
When an array is declared but not allocated, it has a special value called null.
Array Index
You can refer to an element of an array via an index (or subscript) enclosed within the square bracket [ ]. Java's array index begins with zero (0). For example, suppose
that marks is an int array of 5 elements, then the 5 elements are: marks[0], marks[1], marks[2], marks[3], and marks[4].
int[] marks = new int[5]; // Declare & allocate a 5-element int array
// Assign values to the elements
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 94/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
// Retrieve elements of the array
System.out.println(marks[0]);
System.out.println(marks[3] + marks[4]);
Array's length
To create an array, you need to known the length (or size) of the array in advance, and allocate accordingly. Once an array is created, its length is fixed and cannot be
changed during runtime. At times, it is hard to ascertain the length of an array (e.g., how many students?). Nonetheless, you need to estimate the length and allocate an
upper bound. Suppose you set the length to 30 (for a class of students) and there are 31 students, you need to allocate a new array (of length 31), copy the old array to the
new array, and delete the old array. In other words, the length of an array cannot be dynamically adjusted during runtime. This is probably the major drawback of using an
array. (There are other structures that can be dynamically adjusted.)
In Java, the length of array is kept in an associated variable called length and can be retrieved using "arrayName.length", e.g.,
int[] factors = new int[5]; // Declare and allocate a 5-element int array
int numFactors = factors.length; // numFactor is 5
Unlike languages like C/C++, Java performs array index-bound check at the runtime. In other words,
for each reference to an array element, the index is checked against the array's length. If the index
is outside the range of [0, arrayName.length-1], Java Runtime will signal an exception called
ArrayIndexOutOfBoundException. It is important to note that checking array index-bound
consumes computation power, which inevitably slows down the processing. However, the benefits
gained in terms of good software engineering out-weight the slow down in speed.
/**
* Find the mean and standard deviation of numbers kept in an array
*/
public class MeanSDArray {
public static void main(String[] args) {
// Declare variable
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 95/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
int[] marks = {74, 43, 58, 60, 90, 64, 70};
int sum = 0;
int sumSq = 0;
double mean, stdDev;
// Print results
System.out.printf("Mean is: %.2f%n", mean);
System.out.printf("Standard deviation is: %.2f%n", stdDev);
}
}
Syntax Example
for (type item : anArray) { int[] numbers = {8, 2, 6, 4, 3};
body; int sum = 0, sumSq = 0;
} for (int number : numbers) { // for each int number in int[] numbers
// type must be the same as the sum += number;
// anArray's type sumSq += number * number;
}
System.out.println("The sum is: " + sum);
System.out.println("The square sum is: " + sumSq);
This loop shall be read as "for each element in the array...". The loop executes once for each element in the array, with the element's value copied into the declared variable.
The for-each loop is handy to transverse all the elements of an array. It requires fewer lines of code, eliminates the loop counter and the array index, and is easier to read.
However, for array of primitive types (e.g., array of ints), it can read the elements only, and cannot modify the array's contents. This is because each element's value is
copied into the loop's variable, instead of working on its original copy.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 96/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
In many situations, you merely want to transverse thru the array and read each of the elements. For these cases, enhanced for-loop is preferred and recommended over
other loop constructs.
import java.util.Scanner;
/**
* Prompt user for the length and all the elements of an array; and print [a1, a2, ..., an]
*/
public class ReadPrintArray {
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, only 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();
// Print array contents, need to handle first item and subsequent items differently
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 97/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
System.out.print("The values are: [");
for (int i = 0; i < items.length; ++i) {
if (i == 0) {
// Print the first item without a leading commas
System.out.print(items[0]);
} else {
// Print the subsequent items with a leading commas
System.out.print(", " + items[i]);
}
}
System.out.println("]");
}
}
Arrays.toString() (JDK 5)
JDK 5 provides an built-in methods called Arrays.toString(anArray), which returns a String in the form [a0, a1, ..., an]. You need to import
java.util.Arrays. For examples,
System.out.println(Arrays.toString(a1)); //[6, 1, 3, 4, 5]
System.out.println(Arrays.toString(a2)); //[]
System.out.println(Arrays.toString(a3)); //[0.0]
a3[0] = 2.2;
System.out.println(Arrays.toString(a3)); //[2.2]
}
}
0- 9: **
10- 19:
20- 29:
30- 39:
40- 49:
50- 59: ***
60- 69:
70- 79:
80- 89: *
90-100: **
*
* * *
* * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
import java.util.Scanner;
import java.util.Arrays; // for Arrays.toString()
/**
* Print the horizontal and vertical histograms of grades.
*/
public class GradesHistograms {
public static void main(String[] args) {
// Declare variables
int numStudents;
int[] grades; // Declare array name, to be allocated after numStudents is known
int[] bins = new int[10]; // int array of 10 histogram bins for 0-9, 10-19, ..., 90-100
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 99/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
// Prompt and read the number of students as "int"
System.out.print("Enter the number of students: ");
numStudents = in.nextInt();
// Prompt and read the grades into the int array "grades"
for (int i = 0; i < grades.length; ++i) {
System.out.print("Enter the grade for student " + (i + 1) + ": ");
grades[i] = in.nextInt();
}
in.close();
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 100/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
for (int itemNo = 0; itemNo < bins[binIdx]; ++itemNo) { // one star per item
System.out.print("*");
}
System.out.println();
}
Notes:
1. We use two arrays in this exercise, one for storing the grades of the students (of the length numStudents) and the other to storing the histogram counts (of length 10).
2. We use a 10-element int arrays called bins, to keep the histogram counts for grades of [0, 9], [10, 19], ..., [90, 100]. Take note that there are 101 grades
between [0, 100], and the last bin has 11 grades (instead of 10 for the rest). The bins's index is grade/10, except grade of 100.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 101/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
import java.util.Scanner;
/**
* Prompt user for a hexadecimal string, and print its binary equivalent.
*/
public class Hex2Bin {
public static void main(String[] args) {
// Define variables
String hexStr; // The input hexadecimal String
int hexStrLen; // The length of hexStr
char hexChar; // Each char in the hexStr
String binStr =""; // The equivalent binary String, to accumulate from an empty String
// Lookup table for the binary sub-string corresponding to Hex digit '0' (index 0) to 'F' (index 15)
final String[] BIN_STRS =
{"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 102/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
binStr += BIN_STRS[hexChar - 'A' + 10];
} else {
System.err.println("error: invalid hex string \"" + hexStr + "\"");
return; // or System.exit(1);
}
}
System.out.println("The equivalent binary for \"" + hexStr + "\" is \"" + binStr + "\"");
}
}
Notes
1. We keep the binary string corresponding to hex digit '0' to 'F' in an array with indexes of 0-15, used as look-up table.
2. We extract each hexChar, find its array index (0-15), and retrieve the binary string from the array based on the index.
a. To convert hexChar '1' to '9' to int 1 to 9, we subtract the hexChar by the base '0'.
b. Similarly, to convert hexChar 'a' to 'f' (or 'A' to 'F') to int 10 to 15, we subtract the hexChar by the base 'a' (or 'A') and add 10.
import java.util.Scanner;
/**
* Prompt user for an int, and print its equivalent hexadecimal number.
*/
public class Dec2Hex {
public static void main(String[] args) {
// Declare variables
int dec; // The input decimal number in "int"
String hexStr = ""; // The equivalent hex String, to accumulate from an empty String
int radix = 16; // Hex radix
final char[] HEX_CHARS = // Use this array as lookup table for converting 0-15 to 0-9A-F
{'0','1','2','3', '4','5','6','7', '8','9','A','B', 'C','D','E','F'};
// Repeated modulus/division and get the hex digits (0-15) in reverse order
while (dec > 0) {
int hexDigit = dec % radix; // 0-15
hexStr = HEX_CHARS[hexDigit] + hexStr; // Append in front of the hex string corresponds to reverse order
dec = dec / radix;
}
System.out.println("The equivalent hexadecimal number is " + hexStr);
}
}
Notes
1. We use modulus/divide algorithm to get the hex digits (0-15) in reserve order. See "Number System Conversion".
2. We look up the hex digit '0'-'F' from an array using index 0-15.
Exercises on Arrays
LINK
Multi-Dimensional Array
In Java, you can declare an array of arrays. For examples:
In the above example, grid is an array of 12 elements. Each of the elements (grid[0] to grid[11]) is an 8-element int array. In other words, grid is a "12-element
array" of "8-element int arrays". Hence, grid.length gives 12 and grid[0].length gives 8.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 104/130