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:
  1. They are also known as: Reference data type.
  2. They are not defined in the core of Java programming language; they are defined in distinct class blocks.
  3. They possess method implementations which enrich them with robust capabilities and/or functionalities.
  4. Examples include: String, Array, ArrayList, etc.

On the other hand, Primitive data types possess the following attributes, viz:
  1. They are also known as: Non-Derived data type.
  2. They are defined in the core of Java programming language.
  3. They do not possess method implementations; hence, they are relatively lesser robust in terms of capabilities and/or functionalities.
  4. Examples include: byte, short, double, etc.

Now, focusing on the String data type:
  1. It is essentially an immutable collection of characters. Thus, it is a derivative of the char data type.
  2. A String collection of characters begins with index-number: 0.
  3. Basically, a String is used for storing text, sentences, words, special characters, etc., in Java programming.
  4. Its declaration follows this syntax: String <variableIdentifier>;
  5. Its initialization follows this syntax: <variableIdentifier> = "<value>"; (note that the value must be enclosed within double-quotation marks).
  6. Alternatively, its initialization can be in this syntax: <variableIdentifier> = new String("<value>"); (note that the value must be enclosed within double-quotation marks).
  7. 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.
  1. The addition (+) operator is a binary operator, and must always operate upon only two (2) operands at a time.
  2. The addition (+) operator transitions into a concatenation (+) operator whenever any of its operand is a String value.
  3. 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.
  4. 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
  1. A variable of String (data) type can be declared and initialized as follows: String course = "ProgLessons";
  2. A variable of char (data) type can be declared and initialized as follows: char initial = 'P';
  3. Notice the use of double-quotation marks around a String value; and the use of single-quotation marks around a char value.
  4. As mentioned earlier, a String as an immutable collection of characters has index numbering beginning at: 0.
  5. 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

Referencing and copying a character 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
  1. A substring is simply a String value existing as a subset within a reference String value.
  2. 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.
  3. The start index is a compulsory argument with regard to the substring(start, stop) method.
  4. 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

Referencing and copying a substring from a String value
Caption: s1=courseTitle.substring(0,4);   s2=courseTitle.substring(4,10);

Referencing and copying a substring from a String value
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
  1. A prewritten class block that is packaged and available in the java.util package.
  2. 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.
  3. 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;
  4. Some of the method implementations in this class include: nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), nextDouble(), nextBoolean(), next(), nextLine(), etc.
  5. 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>
    Scanner buffer and the associated Scanner methods
    Caption: <User Keyboard>—→<Scanner Buffer>←→Scanner methods()—→<Java's Console>
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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);
  1. Each unit of the formatSpecifier is a String value which employs the following syntax: %<fieldWidth><.floatRange>dataType
  2. Each unit of the formatSpecifier must begin with this symbol: %
  3. 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).
  4. 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.
  5. 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.
  6. 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.
  7. 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

printf() method based on regular text-output alignment
Code Snippet 1 (Line 15 and Line 18): System.out.printf("%.2f", var1);

printf() method based on right text-output alignment
Code Snippet 1 (Line 19): System.out.printf("%12.2f%n", var1);

printf() method based on left text-output alignment
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:
  1. Simply, it implements a Non-Primitive (or Derived) data-type variant for a corresponding Primitive data type.
  2. 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.
  3. 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.
  4. 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
  1. 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

Sponsored Ads