[go: up one dir, main page]

0% found this document useful (0 votes)
17 views26 pages

java basics-páginas-4

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views26 pages

java basics-páginas-4

Uploaded by

Johnson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
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

for (int number = 2; number <= UPPERBOUND; ++number) {


// Not a prime, if there is a factor between 2 and sqrt(number)
int maxFactor = (int)Math.sqrt(number);
boolean isPrime = true; // boolean flag to indicate whether number is a prime
for (int factor = 2; factor <= maxFactor; ++factor) {
if (number % factor == 0) { // Factor?
isPrime = false; // number is not a prime
break; // A factor found, no need to search for more factors
}
}
if (isPrime) System.out.println(number + " is a prime");
}
}
}

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

// Sum 1 to upperbound, exclude 11, 22, 33,...


final int UPPERBOUND = 100;
int sum = 0;
for (int number = 1; number <= UPPERBOUND; ++number) {
if (number % 11 == 0) continue; // Skip the rest of the loop body, continue to the next iteration
sum += number;
}

// It is better to re-write the loop as:


for (int number = 1; number <= UPPERBOUND; ++number) {
if (number % 11 != 0) sum += number;
}

Example (break and continue): Study the following program.

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

level1: // define a label for the level-1 loop


for (.....) {
level2: // define a label for the level-2 loop
for (.....) {
for (......) { // level-3 loop
if (...) break level1; // break all loops, continue after the loop
if (...) break level2: // continue into the next statement of level-1 loop
......
}
}
}

Labeled continue
In a nested loop, similar to labeled break, you can use labeled continue to continue into a specified loop. For example,

level1: // define a label (with : suffix) for the level-1 loop


for (.....) {
level2: // define a label (with : suffix) for the level-2 loop
for (.....) {
for (......) { // level-3 loop
if (...) continue level1; // continue the next iteration of level-1 loop
if (...) continue level2: // continue the next iteration of level-2 loop
......
}
}
}

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.

public class TestLabeledBreak {


public static void main(String[] args) {
int[][] testArray = {
{1, 2, 3, 4},
{4, 3, 1, 4},

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

final int MAGIC_NUMBER = 8;


boolean found = false;
mainLoop:
for (int i = 0; i < testArray.length; ++i) {
for (int j = 0; j < testArray[i].length; ++j) {
if (testArray[i][j] == MAGIC_NUMBER) {
found = true;
break mainLoop;
}
}
}
System.out.println("Magic number " + (found ? "found" : "NOT found"));
}
}

String and char operations

char Arithmetic Operations


Recall that:
In Java, each char is represented by a 16-bit Unicode number. For examples, char '0' is represented by code number 48 (30H), char '1' by 49 (31H), char 'A'
by 65 (41H). char 'a' by 97 (61H). Take note that char '0' is NOT int 0, char '1' is NOT int 1.
chars can take part in arithmetic operations. A char is treated as its underlying int (in the range of [0, 65535]) in arithmetic operations. In other words, char and
int are interchangeable. char '0' ⇔ int 48, char '1' ⇔ int 49, char 'A' ⇔ int 65, char 'a' ⇔ int 97. For examples,

char c1 = '0'; // Code number 48


char c2 = 'A'; // Code number 65
char c3;

// char <-> int (interchangeable)


System.out.println((int)c1); // Print int 48
System.out.println((int)c2); // Print int 65
c3 = 97; // Code number for 'a'

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,

char c1 = '0'; // Code number 48


char c2 = 'A'; // Code number 65
char c3;

// char + char -> int + int -> int


//c3 = c1 + c2; // error: RHS evaluated to "int", cannot assign to LHS of "char"
c3 = (char)(c1 + c2); // Need explicit type casting, return char 'q' (code number 113)
System.out.println(c3); // Print 'q', as c3 is a char
System.out.println(c1 + c2); // Print int 113
System.out.println((char)(c1 + c2)); // Print char 'q'

Similar, char ⊕ int ⇒ int ⊕ int ⇒ int. You may need to explicitly cast the resultant int back to char. For examples,

char c1 = '0'; // Code number 48


char c2 = 'A'; // Code number 65
char c3;

// char + int -> int + int -> int


//c3 = c1 + 5; // error: RHS evaluated to "int", cannot assign to LHS of "char"
c3 = (char)(c1 + 5); // Need explicit type casting, return char '5' (code number 53)
System.out.println(c3); // Print '5', as c3 is a char
System.out.println(c1 + 5); // Print int 53

// Print the code number for 'a' to 'z'


for (int codeNum = 'a'; codeNum <= 'z'; ++codeNum) {
System.out.println((char)codeNum + ": " + codeNum);
}

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,

// Print char '0' to '9' via increment


for (char c = '0'; c <= '9'; ++c) { // ++c remains as "char"
System.out.println(c);
}

Converting char to int


You can convert char '0' to '9' to int 0 to 9 by subtracting the char with the base '0', e.g., '8' - '0' ⇒ 8.

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.

// Converting a hex char (0-9|A-F|a-f) to its equivalent decimal (0-15)


char hexChar = 'a';
int dec;

if (hexChar >= '0' && hexChar <= '9') {


dec = hexChar - '0'; // int 0-9
} else if (hexChar >= 'A' && hexChar <= 'F') {
dec = hexChar - 'A' + 10; // int 10-15
} else if (hexChar >= 'a' && hexChar <= 'f') {
dec = hexChar - 'a' + 10; // int 10-15
} else {
dec = -1; // to overcome variable have not been initialized error
System.out.println("Invalid hex char");
}
System.out.println(hexChar + ": " + dec);

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

String str = "Java is cool!";


System.out.println(str.length()); // return int 13
System.out.println(str.charAt(2)); // return char 'v'
System.out.println(str.charAt(5)); // return char 'i'

// Comparing two Strings


String anotherStr = "Java is COOL!";
System.out.println(str.equals(anotherStr)); // return boolean false
System.out.println(str.equalsIgnoreCase(anotherStr)); // return boolean true
System.out.println(anotherStr.equals(str)); // return boolean false
System.out.println(anotherStr.equalsIgnoreCase(str)); // return boolean true
// (str == anotherStr) to compare two Strings is WRONG!!!

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 str = "Java is cool!";


System.out.println(str.length()); // return int 13
System.out.println(str.charAt(2)); // return char 'v'
System.out.println(str.substring(0, 3)); // return String "Jav"
System.out.println(str.indexOf('a')); // return int 1
System.out.println(str.lastIndexOf('a')); // return int 3
System.out.println(str.endsWith("cool!")); // return boolean true
System.out.println(str.toUpperCase()); // return a new String "JAVA IS COOL!"
System.out.println(str.toLowerCase()); // return a new String "java is cool!"

Converting String to Primitive

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,

String inStr = "5566";


int number = Integer.parseInt(inStr); // number <- 5566
// Input to Integer.parseInt() must be a valid integer literal
//number = Integer.parseInt("abc"); // Runtime Error: NumberFormatException

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 inStr = "55.66";


float aFloat = Float.parseFloat(inStr); // aFloat <- 55.66f
double aDouble = Double.parseDouble("1.2345"); // aDouble <- 1.2345
aDouble = Double.parseDouble("1.2e-3"); // aDouble <- 0.0012
// Input to Integer.parseInt() must be a valid double literal
//aDouble = Double.parseDouble("abc"); // Runtime Error: NumberFormatException

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

// Extract each char


String msg = "Hello, world";
char msgChar;
for (int idx = 0; idx < msg.length(); ++idx) {
msgChar = msg.charAt(idx);
// Do something about the extracted char
.......
}

String to boolean
You can use method Boolean.parseBoolean(aBooleanStr) to convert string of "true" or "false" to boolean true or false, e.g.,

String boolStr = "true";


boolean done = Boolean.parseBoolean(boolStr); // done <- true
boolean valid = Boolean.parseBoolean("false"); // valid <- false

Converting Primitive to String


To convert a primitive to a String, you can:
1. Use the '+' operator to concatenate the primitive with an empty String "".
2. Use the JDK built-in methods String.valueOf(aPrimitive), which is applicable to all primitives.
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 86/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
3. Use the toString() methods of the respective wrapper class, such as Integer.toString(anInt), Double.toString(aDouble),
Character.toString(aChar), Boolean.toString(aBoolean), etc.

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"

// Using String.valueOf(aPrimitive) (applicable to ALL primitive types)


String str5 = String.valueOf(12345); // int 12345 -> String "12345"
String str6 = String.valueOf(true); // boolean true -> String "true"
String str7 = String.valueOf(55.66); // double 55.66 -> String "55.66"

// Using toString() for each primitive type


String str8 = Integer.toString(1234); // int 1234 -> String "1234"
String str9 = Double.toString(1.23); // double 1.23 -> String "1.23"
String str10 = Character.toString('z'); // char 'z' -> String "z"

Formatting Strings - String.format()


Recall that you can use printf() to create a formatted string and send it to the display console, e.g.,

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)

String.format() has the same form as printf().

Code Example: Reverse String


The following program prompts user a string, and prints the input string in the reverse order. For examples,

Enter a String: abcdefg


The reverse is: gfedcba

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

// Prompt and read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a String: ");
inStr = in.next();
inStrLen = inStr.length();
in.close();

System.out.print("The reverse is: ");


// Use a for-loop to extract each char in reverse order
for (int inCharIdx = inStrLen - 1; inCharIdx >= 0; --inCharIdx) {
System.out.print(inStr.charAt(inCharIdx));
}
System.out.println();
}
}

Code Example: Validating Binary String


The following program prompts user for a string, and checks if the input is a valid binary string, consisting of '0' and '1' only. For example,

Enter a binary string: 1011000


"1011000" is a binary string

Enter a binary string: 10001900


"10001900" is NOT a binary string

Version 1: With a boolean flag


import java.util.Scanner;
/**
* Check if the input string is a valid binary string.
*/
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 88/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
public class ValidateBinString {
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
boolean isValid; // "is" or "is not" a valid binary string?

// Prompt and read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a binary string: ");
inStr = in.next();
inStrLen = inStr.length();
in.close();

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

// Prompt and read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a binary string: ");
inStr = in.next();
inStrLen = inStr.length();
in.close();

for (int inCharIdx = 0; inCharIdx < inStrLen; ++inCharIdx) {


inChar = inStr.charAt(inCharIdx);
if (!(inChar == '0' || inChar == '1')) {
System.out.println("\"" + inStr + "\" is NOT a binary string");
return; // exit the program upon the first error detected
}
}
// for-loop completed. No error detected.
System.out.println("\"" + inStr + "\" is a binary string");
}
}

This version, although shorter, are harder to read, and harder to maintain.

Code Example: Binary to Decimal (Bin2Dec)


The following program prompts user for a binary string, and converts into its equivalent decimal number. For example,

Enter a binary string: 10001001


The equivalent decimal for "10001001" is 137

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

// Prompt and read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a binary string: ");
binStr = in.next();
binStrLen = binStr.length();
in.close();

// Process char by char from the right (i.e. Least-significant bit)


// using exponent as loop index.
for (int exp = 0; exp < binStrLen ; ++exp) {
binChar = binStr.charAt(binStrLen - 1 - exp);
// 3 cases: '1' (add to dec), '0' (valid but do nothing), other (error)
if (binChar == '1') {
dec += (int)Math.pow(2, exp); // cast the double result back to int
} else if (binChar == '0') {
} else {
System.out.println("error: invalid binary string \"" + binStr + "\"");
return; // or System.exit(1);
}
}

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

dec = bn-1×2n-1 + bn-2×2n-2 + ... + b2×22 + b1×21 + b0×20

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,

number = in.nextInt(2); // Input in binary e.g., 10110100


System.out.println(number); // 180

Code Example: Hexadecimal to Decimal (Hex2Dec)


The following program prompts user for a hexadecimal string and converts into its equivalent decimal number. For example,

Enter a Hexadecimal string: 10aB


The equivalent decimal for "10aB" is 4267

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

// Prompt and Read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a Hexadecimal string: ");
hexStr = in.next();
hexStrLen = hexStr.length();
in.close();

// Process char by char from the left (most-significant digit)


for (int charIdx = 0; charIdx < hexStrLen; ++charIdx) {
char hexChar = hexStr.charAt(charIdx);
int expFactor = (int)Math.pow(16, hexStrLen - 1 - charIdx);
// 23 cases: '0'-'9', 'a'-'f', 'A'-'F', other (error)
if (hexChar == '0') {
// Valid but do nothing
} else if (hexChar >= '1' && hexChar <= '9') {
dec += (hexChar - '0') * expFactor; // Convert char '0'-'9' to int 0-9
} else if (hexChar >= 'a' && hexChar <= 'f') {
dec += (hexChar - 'a' + 10) * expFactor; // Convert char 'a'-'f' to int 10-15
} else if (hexChar >= 'A' && hexChar <= 'F') {
dec += (hexChar - 'A' + 10) * expFactor; // Convert char 'A'-'F' to int 10-15
} else {
System.out.println("error: invalid hex string \"" + hexStr + "\"");
return; // or System.exit(1);
}
}
System.out.println("The equivalent decimal for \"" + hexStr + "\" is " + dec);
}
}

Notes:
1. The conversion formula is:

hexStr = hn-1hn-2....h2b1h0 hi∈{0,..,9,A,..,F} where h0 is the least-significant digit

dec = hn-1×16n-1 + hn-2×16n-2 + ... + h2×162 + h1×161 + h0×160

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

Exercises on String and char operations


LINK

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

int[] marks; // Declare an int array named "marks"


// "marks" is assigned to a special value called "null" before allocation
int marks[]; // Same as above, but the above syntax recommended
marks = new int[5]; // Allocate 5 elements via the "new" operator
// Declare and allocate a 20-element array in one statement via "new" operator
int[] factors = new int[20];
// Declare, allocate a 6-element array thru initialization
int[] numbers = {11, 22, 33, 44, 55, 66}; // size of array deduced from the number of items

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

The index of an array is between 0 and arrayName.length - 1.

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.

Array and Loop


Arrays works hand-in-hand with loops. You can process all the elements of an array via a loop, for example,

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

// Compute sum and square-sum using loop


for (int i = 0; i < marks.length; ++i) {
sum += marks[i];
sumSq += marks[i] * marks[i];
}
mean = (double)sum / marks.length;
stdDev = Math.sqrt((double)sumSq / marks.length - mean * mean);

// Print results
System.out.printf("Mean is: %.2f%n", mean);
System.out.printf("Standard deviation is: %.2f%n", stdDev);
}
}

Enhanced for-loop (or "for-each" Loop) (JDK 5)


JDK 5 introduces a new loop syntax known as enhanced for-loop (or for-each loop) to facilitate processing of arrays and collections. It takes the following syntax:

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.

Code Example: Read and Print Array


The following program prompts user for the length and all the elements of an array, and print the array in the form of [a0, a1, ..., an]. For examples,

Enter the number of items: 5


Enter the value of all items (separated by space): 7 9 1 6 2
The values are: [7, 9, 1, 6, 2]

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

Scanner in = new Scanner(System.in);


// Prompt for a non-negative integer for the number of items;
// and read the input as "int". No input validation.
System.out.print("Enter the number of items: ");
NUM_ITEMS = in.nextInt();

// Allocate the array


items = new int[NUM_ITEMS];

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

import java.util.Arrays; // Needed to use Arrays.toString()


/**
* Use Arrays.toString() to print an array in the form of [a1, a2, ..., an]
*/
public class TestArrayToString {
public static void main(String[] args) {
// Declare and allocate test arrays
int[] a1 = {6 ,1, 3, 4, 5}; // Allocate via initialization
int[] a2 = {}; // Empty array with length = 0
double[] a3 = new double[1]; // One-Element array, init to 0.0

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

Code Example: Horizontal and Vertical Histograms


https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 98/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
The following program prompts user for the number of students, and the grade of each student. It then print the histogram, in horizontal and vertical forms, as follows:

Enter the grade for student 1: 98


Enter the grade for student 2: 100
Enter the grade for student 3: 9
Enter the grade for student 4: 3
Enter the grade for student 5: 56
Enter the grade for student 6: 58
Enter the grade for student 7: 59
Enter the grade for student 8: 87

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

Scanner in = new Scanner(System.in);

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

// Allocate the array


grades = new int[numStudents];

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

// Print array for debugging


System.out.println(Arrays.toString(grades));

// Populate the histogram bins


for (int grade : grades) {
if (grade == 100) { // Need to handle 90-100 separately as it has 11 items.
++bins[9];
} else {
++bins[grade/10];
}
}
// Print array for debugging
System.out.println(Arrays.toString(bins));

// Print the horizontal histogram


// Rows are the histogram bins[0] to bins[9]
// Columns are the counts in each bins[i]
for (int binIdx = 0; binIdx < bins.length; ++binIdx) {
// Print label
if (binIdx != 9) { // Need to handle 90-100 separately as it has 11 items
System.out.printf("%2d-%3d: ", binIdx*10, binIdx*10+9);
} else {
System.out.printf("%2d-%3d: ", 90, 100);
}
// Print columns of stars

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

// Find the max value among the bins


int binMax = bins[0];
for (int binIdx = 1; binIdx < bins.length; ++binIdx) {
if (binMax < bins[binIdx]) binMax = bins[binIdx];
}

// Print the Vertical histogram


// Columns are the histogram bins[0] to bins[9]
// Rows are the levels from binMax down to 1
for (int level = binMax; level > 0; --level) {
for (int binIdx = 0; binIdx < bins.length; ++binIdx) {
if (bins[binIdx] >= level) {
System.out.print(" * ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
// Print label
for (int binIdx = 0; binIdx < bins.length; ++binIdx) {
System.out.printf("%3d-%-3d", binIdx*10, (binIdx != 9) ? binIdx * 10 + 9 : 100);
// Use '-' flag for left-aligned
}
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

Code Example: Hexadecimal to Binary (Hex2Bin)


The following program prompts user for a hexadecimal string and convert it to its binary equivalence. For example,

Enter a Hexadecimal string: 1bE3


The equivalent binary for "1bE3" is "0001101111100011"

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

// Prompt and read input as "String"


Scanner in = new Scanner(System.in);
System.out.print("Enter a Hexadecimal string: ");
hexStr = in.next();
hexStrLen = hexStr.length();
in.close();

// Process the string from the left (most-significant hex digit)


for (int charIdx = 0; charIdx < hexStrLen; ++charIdx) {
hexChar = hexStr.charAt(charIdx);
if (hexChar >= '0' && hexChar <= '9') {
binStr += BIN_STRS[hexChar - '0']; // index into the BIN_STRS array and concatenate
} else if (hexChar >= 'a' && hexChar <= 'f') {
binStr += BIN_STRS[hexChar - 'a' + 10];
} else if (hexChar >= 'A' && hexChar <= 'F') {

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.

Code Example: Decimal to Hexadecimal (Dec2Hex)


The following program prompts user for an integer, reads as int, and prints its hexadecimal equivalent. For example,

Enter a decimal number: 1234


The equivalent hexadecimal number is 4D2

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

// Prompt and read input as "int"


Scanner in = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
https://www3.ntu.edu.sg/home/ehchua/programming/java/J2_Basics.html 103/130
1/9/25, 3:48 PM Java Basics - Java Programming Tutorial
dec = in.nextInt();
in.close();

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

int grid[][] = new int[12][8]; // a 12×8 grid of int


grid[0][0] = 8;
grid[1][1] = 5;
System.out.println(grid.length); // 12
System.out.println(grid[0].length); // 8
System.out.println(grid[11].length); // 8

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.

public class Array2DTest {


public static void main(String[] args) {
int[][] grid = new int[12][8]; // A 12x8 grid, in [row][col] or [y][x]

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

You might also like