Java Fundamentals 23.0
3.1Non-Primitive (or Derived) Data Types
Consequently, as earlier mentioned in the previous Lesson or Chapter, Non-Primitive (or Derived) data types are data types which are derivatives of one or more Primitive data types; and they are uniquely defined in separate
class
blocks existing within Java's plugin library.
On one hand, Non-Primitive (or Derived) data types possess the following attributes, viz:
- They are also known as: Reference data type.
- They are not defined in the core of Java programming language; they are defined in distinct class blocks.
- They possess method implementations which enrich them with robust capabilities and/or functionalities.
- Examples include:
String
, Array
, ArrayList
, etc.
On the other hand, Primitive data types possess the following attributes, viz:
- They are also known as: Non-Derived data type.
- They are defined in the core of Java programming language.
- They do not possess method implementations; hence, they are relatively lesser robust in terms of capabilities and/or functionalities.
- Examples include:
byte
, short
, double
, etc.
Now, focusing on the
String
data type:
- It is essentially an immutable collection of characters. Thus, it is a derivative of the
char
data type.
- A
String
collection of characters begins with index-number: 0.
- Basically, a
String
is used for storing text, sentences, words, special characters, etc., in Java programming.
- Its declaration follows this syntax:
String <variableIdentifier>;
- Its initialization follows this syntax:
<variableIdentifier> = "<value>";
(note that the value must be enclosed within double-quotation marks).
- Alternatively, its initialization can be in this syntax:
<variableIdentifier> = new String("<value>");
(note that the value must be enclosed within double-quotation marks).
- Possesses lots of methods() functionality.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
String str1;
str1 = "This is String 1";
String str2 = new String("This is String 2");
int len1 = str1.length(); //Computes the length of str1
System.out.println(len1);
String str3 = str2.toUpperCase(); //Converst str2 to uppercase characters
System.out.println(str3);
String str4 = str2.toLowerCase(); //Converst str2 to lowercase characters
System.out.println(str4);
int idx1 = str1.indexOf('i'); //Returns the index position for the 1st occurrence of the argument
System.out.println(idx1); //Index numbering begins from 0
int idx2 = str1.lastIndexOf('i'); //Returns the index position for the last occurrence of the argument
System.out.println(idx2); //Index numbering begins from 0
String str5 = " I am padded with both leading and trailing white-spaces ";
String str6 = str5.trim(); //Trims a String value of both its leading and trailing white-spaces
System.out.println(str6);
String str7 = str5.strip(); //Alternative for trimming a String value of both its leading & trailing white-spaces
System.out.println(str7);
String str8 = str5.stripLeading(); //Trims a String value of its leading white-spaces
System.out.println(str8);
String str9 = str5.stripTrailing(); //Trims a String value of its leading white-spaces
System.out.println(str9);
}
}
Code Snippet: Declaring, initializing, and manipulating String
values
Additionally, a comprehensive list of all the methods available in the
String
class can be found at the Java official documentation
here.
Also, to invoke any
method()
implementation within a Java code, simply employ the dot-notation syntax:
<String Identifier>
.
<Method Identifier>()
3.2String Concatenation in Java
Generally, in programming, concatenation refers to the process of linearly or serially joining together any two (2)
String
values. In Java programming, the addition (
+
) operator doubles as the concatenation operator depending on the (data) type of the operands.
- The addition (
+
) operator is a binary operator, and must always operate upon only two (2) operands at a time.
- The addition (
+
) operator transitions into a concatenation (+
) operator whenever any of its operand is a String
value.
- Operation(s) evaluation with respect to the addition and concatenation (
+
) operator begins from the left-hand-side to the right-hand-side of any expression and/or operation.
-
For example:
2 + 2 + "Streets"
should yield "4Streets" and not "22Streets".
This is because, evaluating this expression from the left-hand-side, the first two (2) operands are numeric; therefore, it performs an arithmetic-addition operation and yields: 4.
Thereafter, we now have: 4 + "Streets". Thus, because one (1) of the operands here is a String
value; therefore, it does a concatenation operation and yields: "4Streets".
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
String str11 = new String("Programming");
String str12 = new String("Lessons");
System.out.println(str11 + str12); //ProgrammingLessons
System.out.println(str11 + " " + str12); //Programming Lessons
System.out.println(2 + str12); //2Lessons
System.out.println(str12 + 2); //Lessons2
}
}
Code Snippet: Concatenation operations involving String
values
3.3Copying a Character from a String in Java
- A variable of
String
(data) type can be declared and initialized as follows: String course = "ProgLessons";
- A variable of
char
(data) type can be declared and initialized as follows: char initial = 'P';
- Notice the use of double-quotation marks around a
String
value; and the use of single-quotation marks around a char
value.
- As mentioned earlier, a
String
as an immutable collection of characters has index numbering beginning at: 0.
- Therefore, the
charAt(index)
method returns the char
value existing at the index specified in the argument (to this method).
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
String course = "ProgLessons";
char c1 = course.charAt(0); //RETURN: 'P'
char c2 = course.charAt(5); //RETURN: 'e'
char c3 = course.charAt(10); //RETURN: 's'
char c4 = course.charAt(11); //Runtime Error (out-of-boundary error)
System.out.println("c1: " + c1);
System.out.println("c2: " + c2);
System.out.println("c3: " + c3);
}
}
Code Snippet: Referencing and copying a character (char
value) from a String
value
Caption: c1=course.charAt(0);
c2=course.charAt(5);
c3=course.charAt(10);
3.4Copying a Substring from a String in Java
- A substring is simply a
String
value existing as a subset within a reference String
value.
- The
substring(start, stop)
method returns the String
value starting at the start index and ending at the index just before the specified stop index.
- The start index is a compulsory argument with regard to the
substring(start, stop)
method.
- The stop index is not a compulsory argument with regard to the
substring(start, stop)
method. Thus, if this argument is omitted, the length of the String
value is automatically used as a replacement.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
String courseTitle = "ProgLessons";
String s1 = courseTitle.substring(0, 4); //RETURN: "Prog"
String s2 = courseTitle.substring(4, 10); //RETURN: "Lesson"
String s3 = courseTitle.substring(4); //RETURN: "Lessons" {equivalent to: courseTitle.substring(4, 11)}
String s4 = courseTitle.substring(4, 12); //Runtime Error (out-of-boundary error for the stop index)
System.out.println("s1: " + s1);
System.out.println("s2: " + s2);
System.out.println("s3: " + s3);
}
}
Code Snippet: Referencing and copying a substring from a String
value
Caption: s1=courseTitle.substring(0,4);
s2=courseTitle.substring(4,10);
Caption: s3=courseTitle.substring(4);
s3=courseTitle.substring(4,11);
3.5Data Input in Java Programming
To request and/or read input data from a user, we shall be employing one or more methods which have already been prewritten and resident in the
Scanner
class block of Java's API Library.
Scanner
class
- A prewritten
class
block that is packaged and available in the java.util
package.
- The
Scanner
class block encapsulates several method
implementations which are very useful with regard to the extraction of console input (from the user) via the user keyboard.
- To import the Scanner class into any Java program (or source code), the following explicit statement of code is required, viz:
import java.util.Scanner;
- Some of the
method
implementations in this class include: nextByte()
, nextShort()
, nextInt()
, nextLong()
, nextFloat()
, nextDouble()
, nextBoolean()
, next()
, nextLine()
, etc.
-
Technically, the aforementioned methods of the
Scanner
class directly read from a Scanner
buffer which sits as an intermediary between the user's keyboard and the Java console.
<User Keyboard>
—→<Scanner Buffer>
←→Scanner methods()
—→<Java's Console>
Caption: <User Keyboard>
—→<Scanner Buffer>
←→Scanner methods()
—→<Java's Console>
- The
Scanner
buffer only prompts the user for input via the keyboard whenever it is empty; otherwise, the Scanner
buffer keeps relaying input(s) to the Scanner methods()
for corresponding output(s) to the Java console.
nextByte()
: reads in any value of byte
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextShort()
: reads in any value of short
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextInt()
: reads in any value of int
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextLong()
: reads in any value of long
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextFloat()
: reads in any value of float
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextDouble()
: reads in any value of double
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextBoolean()
: reads in any value of boolean
(data) type, from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
next()
: reads in any sequence of characters (String
data type), from the Scanner
buffer, until a white-space (' ') character or end-of-line ('\r\n') character.
nextLine()
: reads in an entire line of mixed characters/text (String
data type), from the Scanner
buffer, until end-of-line ('\r\n') character.
Below are some code snippets with respect to the usage of the methods implemented within the
Scanner
class.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
/* Create an instance-variable of the "Scanner" class.
"System.in" is passed as an argument to the instantiation of the "Scanner" class.
Tells the Java compiler that system input will be provided via standard input (or console) buffer. */
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your year of birth: ");
short birthYr = usrInput.nextShort();
int age = 2023 - birthYr;
System.out.println("In 2023, your age should be: " + age);
/* Always close the instantiation of the "Scanner" class upon completion of input task(s).
This action directly flushes and closes the "Scanner" buffer so as to prevent resource leakage and/or wastage. */
usrInput.close();
}
}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your full name: ");
String fName = usrInput.next(); //ENTER: "Bonaventure Chidube Molokwu"
/*
BUFFER now contains: "Bonaventure Chidube Molokwu"
next(): extracts sequence of characters until white-space (' ') or end-of-line ('\r\n')
next() returns: "Bonaventure"
BUFFER now contains: " Chidube Molokwu"
*/
System.out.println("Your first name is: " + fName);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your full name: ");
String fName = usrInput.nextLine(); //ENTER: "Bonaventure Chidube Molokwu"
/*
BUFFER now contains: "Bonaventure Chidube Molokwu"
nextLine(): extracts an entire line of text until end-of-line ('\r\n')
nextLine() returns: "Bonaventure Chidube Molokwu"
BUFFER now contains: ""
*/
System.out.println("Your full name is: " + fName);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your Age and your Weight: ");
byte age = usrInput.nextByte(); //ENTER: "25"
/*
BUFFER now contains: "25"
nextByte(): extracts 'byte' value until white-space (' ') or end-of-line ('\r\n')
nextByte() returns: "25"
BUFFER now contains: ""
*/
double weight = usrInput.nextDouble(); //ENTER: "88.55 ProgLessons"
/*
BUFFER now contains: "88.55 ProgLessons"
nextDouble(): extracts 'double' value until white-space (' ') or end-of-line ('\r\n')
nextDouble() returns: "88.55"
BUFFER now contains: " ProgLessons"
*/
System.out.println("Please enter your Name: ");
String fName = usrInput.nextLine(); //No input prompt, from "Scanner" buffer to user, because buffer still has non-whitespace characters.
/*
BUFFER now contains: " ProgLessons"
nextLine(): extracts an entire line of text until end-of-line ('\r\n')
nextLine() returns: " ProgLessons"
BUFFER now contains: ""
*/
System.out.println("Your Age is: " + age + "; your Weight is: " + weight + "; your Name is: " + fName);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your Age and your Weight: ");
byte age = usrInput.nextByte(); //ENTER: "25 88.55 ProgLessons"
/*
BUFFER now contains: "25 88.55 ProgLessons"
nextByte(): extracts 'byte' value until white-space (' ') or end-of-line ('\r\n')
nextByte() returns: "25"
BUFFER now contains: " 88.55 ProgLessons"
*/
double weight = usrInput.nextDouble(); //No input prompt, from "Scanner" buffer to user, because buffer still has non-whitespace characters.
/*
BUFFER now contains: " 88.55 ProgLessons"
nextDouble(): extracts 'double' value until white-space (' ') or end-of-line ('\r\n')
nextDouble() returns: "88.55"
BUFFER now contains: " ProgLessons"
*/
System.out.println("Please enter your Name: ");
String fName = usrInput.nextLine(); //No input prompt, from "Scanner" buffer to user, because buffer still has non-whitespace characters.
/*
BUFFER now contains: " ProgLessons"
nextLine(): extracts an entire line of text until end-of-line ('\r\n')
nextLine() returns: " ProgLessons"
BUFFER now contains: ""
*/
System.out.println("Your Age is: " + age + "; your Weight is: " + weight + "; your Name is: " + fName);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your Age and your Weight: ");
byte age = usrInput.nextByte(); //ENTER: "25 88.55 Programming Lessons"
/*
BUFFER now contains: "25 88.55 Programming Lessons"
nextByte(): extracts 'byte' value until white-space (' ') or end-of-line ('\r\n')
nextByte() returns: "25"
BUFFER now contains: " 88.55 Programming Lessons"
*/
double weight = usrInput.nextDouble(); //No input prompt, from "Scanner" buffer to user, because buffer still has non-whitespace characters.
/*
BUFFER now contains: " 88.55 Programming Lessons"
nextDouble(): extracts 'double' value until white-space (' ') or end-of-line ('\r\n')
nextDouble() returns: "88.55"
BUFFER now contains: " Programming Lessons"
*/
System.out.print("Please enter your Name: ");
String trashCan = usrInput.nextLine(); //No input prompt, from "Scanner" buffer to user, because buffer still has non-whitespace characters.
/*
BUFFER now contains: " Programming Lessons"
nextLine(): extracts an entire line of text until end-of-line ('\r\n')
nextLine() returns: " Programming Lessons"
BUFFER now contains: ""
*/
String fName = usrInput.nextLine(); //ENTER: "John Doe" ("Scanner" buffer prompt to user)
/*
BUFFER now contains: "John Doe"
nextLine(): extracts an entire line of text until end-of-line ('\r\n')
nextLine() returns: "John Doe"
BUFFER now contains: ""
*/
System.out.println("Your Age is: " + age + "; your Weight is: " + weight + "; your Name is: " + fName);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
Code Snippet: Operations involving several methods of the Scanner
class
3.6Formatting Data Output in Java Programming
Screen outputs in Java programming can be formatted for appropriate display using the
printf()
method that is already implemented and encapsulated in the
System
class block
(packaged within the
java.lang
package). Like we mentioned in the earlier chapter, the
java.lang
package is automatically imported into any Java program (or source code); therefore,
there exist no need for any explicit import statement with regard to this package and its constituent class block implementations.
Thus, to invoke the
printf()
method, we can use the following statement of code:
System.out.printf(formatSpecifier, arguments);
- Each unit of the
formatSpecifier
is a String
value which employs the following syntax: %<fieldWidth><.floatRange>dataType
- Each unit of the
formatSpecifier
must begin with this symbol: %
- Each unit of the
formatSpecifier
must end with a data-type character: d (byte
, short
, int
, and long
); f (float
and double
); s (String
, char
, and/or boolean
); n (\r\n
newline character).
- The <fieldWidth> subunit (of the
formatSpecifier
) is an optional portion which is usually used in reference to a numeric argument. It is an integer which specifies how many characters should be used to represent the entire length of the numeric value.
- The <.floatRange> subunit (of the
formatSpecifier
) is an optional portion which is also used in reference to a numeric argument. It is a floating-point value which specifies how many decimal places the numeric value should be rounded up to.
- By default, each unit of the
formatSpecifier
formats its corresponding output to be right-aligned on the display screen. However, if the <fieldWidth> subunit (of the formatSpecifier
) is a negative integer, then the corresponding output is formatted to be left-aligned on the display screen.
- Every unit of the
formatSpecifier
should be associated with a corresponding argument/value from left-to-right in arguments' portion.
Below are some code snippets with respect to the usage of the
printf()
method implemented within the
System
class.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
double var1 = 123456.098745;
System.out.printf("%.2f", var1); //123456.10
System.out.println();
System.out.printf("%.2f%n", var1); //"%n": newline character for use in format specifier(s)
System.out.printf("%12.2f%n", var1); //___123456.10
System.out.printf("%-12.2f%n", var1); //123456.10___
System.out.printf("The car milage is: %12.2f%n", var1); //The car milage is: ___123456.10
System.out.printf("My name is: %-12s%n", "Jane Doe"); //My name is: Jane Doe____
System.out.printf("My name is: %12s", "John Doe"); //My name is: ____John Doe
}
}
Code Snippet 1: Operations involving the printf()
method of the System
class
Code Snippet 1 (Line 15 and Line 18): System.out.printf("%.2f", var1);
Code Snippet 1 (Line 19): System.out.printf("%12.2f%n", var1);
Code Snippet 1 (Line 20): System.out.printf("%-12.2f%n", var1);
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
//My first name is: John, my last name is: Doe
System.out.printf("%nMy first name is: %4s, my last name is: %3s", "John", "Doe");
//User 1: John Doe
//User 2: Jane Doe
//User 3: Tom Harry
System.out.printf("User 1: %8s%nUser 2: %8s%nUser 3: %8s%n", "John Doe", "Jane Doe", "Tom Harry");
}
}
Code Snippet 2: Operations involving the printf()
method of the System
class
3.7Wrapper Class(es) in Java
Wrapper Class: This can be defined in terms of the following, viz:
- Simply, it implements a Non-Primitive (or Derived) data-type variant for a corresponding Primitive data type.
- It is a class that essentially implements a Non-Primitive data type by means of mimicking and encapsulating a specific Primitive data type with the goal of providing robust capabilities and/or functionalities for the data type, in terms of method implementations, through the corresponding Non-Primitive data type implemented by a Wrapper class.
- Input prompts/requests, from the
Scanner
buffer to the user, are usually entered in String
format via the keyboard. Thus, a Wrapper class provides method implementations for converting (or parsing) String
data-type inputs into data in their corresponding primitive data types.
- Moreover, a Wrapper class aids in ensuring some level of equity in terms of robustness and/or functionalities between Primitive (data) types and Non-Primitive (data) types.
Primitive (Data) Type |
Non-Primitive (Data) Type |
Method() implementations for Parsing/Conversion |
Implemented into Java core |
Implemented via Wrapper class |
byte |
Byte |
Byte.parseByte() |
short |
Short |
Short.parseShort() |
int |
Integer |
Integer.parseInteger() |
long |
Long |
Long.parseLong() |
float |
Float |
Float.parseFloat() |
double |
Double |
Double.parseDouble() |
boolean |
Boolean |
Boolean.parseBoolean() |
char |
Character |
Character.toString() |
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
public class JavaFundamentals2 {
public static void main(String[] args) {
int primitiveIntVar = 22; //Primitive
Integer derivedIntVar = 22; //Non-Primitive
primitiveIntVar.compareTo(27); //Throws a Syntax Error because a Primitive (data) type has no method() implementation
Integer res = derivedIntVar.compareTo(27);
/*
Returns a negative value because 22 is lesser than 27 (22 < 27)
Returns a positive value if 22 were to be greater
Returns zero (0) if 22 and the argument passed were to be equal
*/
System.out.println(res);
}
}
Code Snippet: Non-Primitive data-type variant of a Primitive data type
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
// Create an instance-variable of the "Scanner" class.
Scanner usrInput = new Scanner(System.in);
System.out.print("Please enter your Age: ");
String ageStr = usrInput.nextLine();
int ageNum = Integer.parseInt(ageStr);
ageNum = ageNum + 1;
System.out.println("Your Age is: " + ageNum);
//Flushes and closes the "Scanner" buffer so as to prevent resource leakage/wastage.
usrInput.close();
}
}
Code Snippet: Parsing (or Converting) String
data-type user input(s)
3.8Escape Sequence(s) in Java
Escape Sequence: In simple terms, this is an alternative interpretation associated with a given series of characters in Java programming. Thus, below is a list of Escape Sequences used in Java programming, viz:
Escape Sequence |
Definition |
Screen Output |
\t |
Horizontal tab |
{tab} |
\n |
Line break |
{new line} |
\r |
Sends the cursor to the leftmost (index) position in a line of text |
{carriage return} |
\' |
Single quotation mark |
' |
\" |
Double quotation mark |
" |
\\ |
Back slash |
\ |
3.9Practice Exercise
-
Which one of the following statements appropriately declares and initializes a
float
data-type variable with some random numeric value?
- float randFloat = 10;
- float randFloat = 10.00;
- Float randFloat = 10.00F;
- float randFloat = 10.0e-4;
- float randFloat;
- Float randFloat;
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
Integer v1 = 123;
int v2 = 123;
int v3 = v1 + v2;
System.out.println(v3 + "123");
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
Integer v7 = 2;
double v8 = 123.123;
int v9 = v7 * v8;
System.out.println("v9: " + v9);
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
Integer v10;
v10 = 3.142;
System.out.println("v10: " + v10);
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
import java.util.Scanner;
public class JavaFundamentals2 {
public static void main(String[] args) {
Scanner usrInput = new Scanner(System.in);
System.out.print("Enter cost of the item: ");
double itemCost = usrInput.nextDouble(); //ENTER: "20"
System.out.print("Enter the tax rate: ");
double taxRate = usrInput.nextDouble(); //ENTER: "10"
System.out.println("Total cost is: " + (itemCost + (taxRate / 100) * itemCost));
usrInput.close();
}
}
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
System.out.printf("+%014.3f", 12345.12345);
-
Which one of the following statements generates the following screen output:
'123go\
- System.out.println("\"123go\");
- System.out.println("\'123go\\");
- System.out.println("'123go\");
- System.out.println("'123go/\");
- System.out.println("\'123go\\\");
-
Which one of the following statements return the sixth character within a
String
(strVal
) value?
- strVal.charAt(5);
- strVal.charAt(6);
- strVal[5];
- strVal[6];
- strVal.substring(5);
-
What is the expected output with reference to the code snippet below?
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
String strVal = "ProgLessons";
System.out.println(strVal.substring(0,4) + strVal.substring(strVal.length()-1));
-
Which one of the following statements is used to convert a
String
(strVal
) input value str to an int
value?
- int.parseInt(strVal);
- (int) strVal;
- (Integer) strVal;
- Integer.parseInt(strVal);
- strVal.parseInt(strVal);
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
int i1 = 4;
float f1 = 123.456F;
String s1 = "Thank you for your patronage!";
System.out.printf("The total cost of %2d items is: %8.2f%n%n%s", i1, f1, s1);
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
short v11 = 100;
int v12 = 1000;
v11 = v12;
System.out.printf("%nThe total cost of all items is: %d", v11);
-
Consider the code snippet below, if the code compiles then what is the expected output; otherwise, state the expected error.
/**
* @copyright © www.proglessons.com 2024. ALL RIGHTS RESERVED.
* @course ProgrammingLessons (proglessons).
* @title Java Fundamentals 2.
* @author Dr. Bonaventure Chidube Molokwu.
*/
short v11 = 100;
int v12 = 1000;
v12 = v11;
System.out.printf("%nThe total cost of all items is: %d", v12);
-
Consider these data types in Java programming, viz:
double
and Double
. Thus, these data types are exactly same, equivalent, and posses same capabilities.
If the aforementioned proposition is FALSE then state with concrete reason(s) why it is so; otherwise, the proposition should be TRUE.