Strings and Arrays (CP:H1)
80 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What does the method indexOf() return when the substring is not found?

  • 1
  • -1 (correct)
  • 0
  • null
  • What is the starting index of the first character in a Java string?

  • 1
  • 0 (correct)
  • 2
  • Negative one
  • In the example where indexOf('t', 6) is used, which index is returned for the first occurrence of 't'?

  • 10 (correct)
  • 6
  • 12
  • 2
  • What happens when comparing the two strings 'abc' and 'abcd' using compareTo()?

    <p>Returns a negative value</p> Signup and view all the answers

    What is the purpose of the fromIndex parameter in indexOf()?

    <p>To indicate the start of the search within the string</p> Signup and view all the answers

    What is considered a string literal in Java?

    <p>A sequence of characters in double quotes</p> Signup and view all the answers

    If you use strA.indexOf('gets', 7) on the string 'It gets better', what will be the outcome?

    <p>-1</p> Signup and view all the answers

    Which of the following methods is NOT commonly used in the String class?

    <p>String[]</p> Signup and view all the answers

    What is the result of the code 'String greeting = new String();'?

    <p>It creates an empty string.</p> Signup and view all the answers

    What does the length of the string 'Hello World' represent?

    <p>The total number of characters in the string, including spaces.</p> Signup and view all the answers

    Which statement about the heap area is correct?

    <p>It contains all objects created in Java.</p> Signup and view all the answers

    What does the constructor String(char chars[]) do?

    <p>It creates a String object and stores the characters from the array.</p> Signup and view all the answers

    In the example char chars[] = {'h', 'i', 's', 't', 'o','r','y'};, what will be the output of System.out.println(s);?

    <p>story</p> Signup and view all the answers

    What is the purpose of the startIndex parameter in the constructor String(char chars[], int startIndex, int count)?

    <p>It determines where the subrange of characters begins.</p> Signup and view all the answers

    What is the output of the program that creates a String from the character array {'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l'} with a starting index of 0 and a length of 5?

    <p>peace</p> Signup and view all the answers

    Given char chars[] = { 'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l'}; and String str = new String(chars, 2, 3);, what value will str hold?

    <p>ace</p> Signup and view all the answers

    Which value corresponds to the byte that when decoded using the String constructor results in the letter 'F'?

    <p>70</p> Signup and view all the answers

    What does new String(String str) do?

    <p>Creates a new String from an existing String.</p> Signup and view all the answers

    In the String constructor String(byte byteArr[], int startIndex, int count), what does the variable 'count' represent?

    <p>4</p> Signup and view all the answers

    What is the output of the following code snippet? System.out.println(new String(new char[]{'a','b','c'}));

    <p>abc</p> Signup and view all the answers

    What will be the output of the program that decodes the byte array {70, 114, 101, 101, 100, 111, 109}?

    <p>Freedom</p> Signup and view all the answers

    In Java, what is a package?

    <p>A specified named collection of classes.</p> Signup and view all the answers

    What will happen if an invalid startIndex is provided in String(char chars[], int startIndex, int count)?

    <p>An exception will occur at runtime.</p> Signup and view all the answers

    If you only decoded the last four bytes of the byte array {66, 82, 65, 86, 69, 82, 89}, what string would you get?

    <p>RAVE</p> Signup and view all the answers

    What is the primary storage area for String objects created in Java?

    <p>Heap</p> Signup and view all the answers

    When using 'new String(chars, 0, 5)', what does the '0' signify in this context?

    <p>It is the starting position in the array.</p> Signup and view all the answers

    What is the correct syntax for creating a String from a byte array starting at a specific index with a specific count?

    <p>String str = new String(byteArr, int startIndex, int count);</p> Signup and view all the answers

    If the input byte array contains 256 elements, can you directly instantiate String using String(byte byteArr[])?

    <p>Yes, if the elements are within valid byte range.</p> Signup and view all the answers

    What does the method System.out.println(s); do in the given Java programs?

    <p>It prints the value of the String variable to the console.</p> Signup and view all the answers

    What will be the output of the following code: String strA = "Hello World"; System.out.println(strA.charAt(4));?

    <p>e</p> Signup and view all the answers

    Which method would you use to remove leading and trailing whitespace from a string?

    <p>trim()</p> Signup and view all the answers

    Given the code String strA = "Java"; String strB = "Java"; System.out.println(strA.equals(strB));, what is the output?

    <p>true</p> Signup and view all the answers

    If you execute String strA = "apple"; System.out.println(strA.replace('a', 'o'));, what will be printed?

    <p>opple</p> Signup and view all the answers

    What does the string.equals(String str) method return when the strings are not identical?

    <p>false</p> Signup and view all the answers

    What will the following code output: String strA = " Hello "; System.out.println(strA.trim());?

    <p>Hello</p> Signup and view all the answers

    What is the purpose of the replace method in a string?

    <p>To change occurrences of a character</p> Signup and view all the answers

    If you call strA.equals(strB) and both strA and strB are empty strings, what will be the output?

    <p>true</p> Signup and view all the answers

    In the context of string methods, what does the charAt() method accomplish?

    <p>Returns a character at a specific index</p> Signup and view all the answers

    If you execute String sentence = "Programming"; System.out.println(sentence.charAt(11));, what will happen?

    <p>It will throw an error</p> Signup and view all the answers

    What will be the output if you execute strA.indexOf('g') on the string 'It gets better'?

    <p>3</p> Signup and view all the answers

    If you call strA.indexOf('t', 6) on 'It gets better', what index is returned?

    <p>10</p> Signup and view all the answers

    What will be the result of strA.indexOf('gets', 7) on 'It gets better'?

    <p>-1</p> Signup and view all the answers

    Which statement is true regarding the compareTo() method?

    <p>It compares strings based on their Unicode values.</p> Signup and view all the answers

    What will strA.indexOf('t') return for the string 'It gets better'?

    <p>3</p> Signup and view all the answers

    What does the default String constructor create?

    <p>An empty string with no value</p> Signup and view all the answers

    What is the length of the string literal 'Hello World'?

    <p>11</p> Signup and view all the answers

    Which of the following best describes the purpose of the String constructor String(String str)?

    <p>To create a string identical to the original string with no changes</p> Signup and view all the answers

    How are string literals represented in Java?

    <p>They are constants enclosed in double quotes</p> Signup and view all the answers

    What will result from the execution of String strGreet = new String("Hello World!");?

    <p>It initializes a string with the value 'Hello World'</p> Signup and view all the answers

    What happens if an invalid index is provided when creating a string from a character array?

    <p>An exception is thrown</p> Signup and view all the answers

    In Java, what is considered an object of the String class?

    <p>Strings created with both direct assignment and new keyword</p> Signup and view all the answers

    What is the output of the following code snippet? String strA = "BREATHE"; System.out.println(strA.toLowerCase());

    <p>breathe</p> Signup and view all the answers

    Which of the following methods returns the total number of characters in a string?

    <p>string.length()</p> Signup and view all the answers

    What will the result be when performing this operation: strA.concat(strB) if String strA = "Java "; String strB = "Programming";?

    <p>Java Programming</p> Signup and view all the answers

    What does the method indexOf(char ch) return if the character is not found in the string?

    <p>-1</p> Signup and view all the answers

    If using String strA = "Hello World"; int len = strA.length();, what will the value of len be?

    <p>11</p> Signup and view all the answers

    Given the string String str = "JavaProgramming";, what will be the result of str.indexOf('P');?

    <p>5</p> Signup and view all the answers

    What is the purpose of the fromIndex parameter in the indexOf() method?

    <p>To start the search from a specified position</p> Signup and view all the answers

    What will be the output of this code? String strA = "Hello"; System.out.println(strA.concat(" World!"));

    <p>Hello World!</p> Signup and view all the answers

    Which method would be used to convert all characters of a string to uppercase?

    <p>toUpperCase()</p> Signup and view all the answers

    What happens when you call strA.indexOf('z') on the string 'Example'?

    <p>-1</p> Signup and view all the answers

    What character is returned by the code snippet String strA = "Java Programming"; System.out.println(strA.charAt(5));?

    <p>P</p> Signup and view all the answers

    What is the output of the code String strA = " Program with care "; System.out.println(strA.trim());?

    <p>Program with care</p> Signup and view all the answers

    If String strA = "batballing is a crime"; is used with the replace method to substitute 'b' with 'c', what will the output be?

    <p>catcalling is a crime</p> Signup and view all the answers

    What would strA.equals(strB) return if both strA and strB contain "Learn Java"?

    <p>true</p> Signup and view all the answers

    What does the charAt() method require as an argument?

    <p>An index number</p> Signup and view all the answers

    What is the purpose of the String method replace(char oldChar, char newChar)?

    <p>To replace all occurrences of a character</p> Signup and view all the answers

    Given String strA = "abc"; String strB = "abcd";, what would strA.equals(strB) evaluate to?

    <p>false</p> Signup and view all the answers

    What is returned by strC.equals(strA) if strC is "Learn Kolin" and strA is "Learn Java"?

    <p>false</p> Signup and view all the answers

    When using trim(), which part of the string is unaffected?

    <p>Spaces between words</p> Signup and view all the answers

    What is the result of System.out.println(strA.charAt(11)); in the string String strA = "Programming";?

    <p>Index out of bounds exception</p> Signup and view all the answers

    What is the result of the statement String str = new String(chars, 2, 3); if chars is defined as char chars[] = {'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l'};?

    <p>'ace'</p> Signup and view all the answers

    What does the variable s store after executing the code String s = new String(chars); with char chars[] = {'h', 'i', 's', 't', 'o', 'r', 'y'};?

    <p>'history'</p> Signup and view all the answers

    In the context of Java, what is the primary purpose of a package?

    <p>To organize classes into a specified collection</p> Signup and view all the answers

    What happens if the startIndex provided in String(char chars[], int startIndex, int count) exceeds the length of the character array?

    <p>It throws an ArrayIndexOutOfBoundsException</p> Signup and view all the answers

    When defining a string using new String(String str), what does the variable 'str' represent?

    <p>Another string as a reference</p> Signup and view all the answers

    What piece of information does the count parameter specify in String(char chars[], int startIndex, int count)?

    <p>The number of characters to copy</p> Signup and view all the answers

    If you declare char chars[] = {'h', 'i', 's', 't', 'o', 'r', 'y'}; and run System.out.println(s); after String s = new String(chars);, what will be the output?

    <p>'history'</p> Signup and view all the answers

    Which of the following correctly describes the result of using new String(char chars[])?

    <p>It creates a string object containing all characters from the array</p> Signup and view all the answers

    In the statement String str = new String(chars, 2, 3); with char chars[] = {'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l'};, which characters are included in the new string?

    <p>'ace'</p> Signup and view all the answers

    Study Notes

    Strings

    • Strings are a sequence of characters widely used in Java programming.
    • Java provides the String class using java.lang to create and manipulate strings. They are considered objects in Java and have their specific methods for working on strings.
    • String Index: Each character in a string has a specific position wherein the position of the first character starts at index 0.
    • The length of a string can be defined based on the number of characters used.

    Creating Strings

    • A String can be written in two (2) ways:
      • by directly assigning a string literal to a String object and by using the new keyword
      • and String constructor to create a String object.
    • The "Hello World!" used in the string is considered a string literal.
      • A string literal is a series of characters found enclosed in double quotes and is considered constants.
      • For the example below, a String object is created using the new keyword and a constructor.
        • String strGreet = new String("Hello World!");
    • A constructor is a block of code that initializes a newly created object.
    • The String class has 13 constructors that provide the initial value of the string using different sources.
      • Some of the most commonly used constructors in the String class include the following:
      • String() – the default constructor to create an empty string.
        • Syntax: String() = new String();
        • It creates a String object in the heap area with no value. The heap area contains all objects created and serves as a memory for objects and classes.
      • String(String str) – the most common String constructor used in Java.
      • Syntax: String st = new String(str);
      • It creates a new String object in the heap area and stores the given value in it.
      • String(char chars[]) – used to create a String object and store the array of characters in it.
        • Syntax: String str = new String(char chars[]);
        • In a program code:
          • package stringPrograms;
          • public class History {
          • public static void main(String[ ] args) {
          • char chars[] = {'h', 'i', 's', 't', 'o','r','y'};
          • String s = new String(chars);
          • System.out.println(s);
          • }
          • }
    • A package is a specified named collection of classes in Java.
    • Packages are used to organize the many classes created when creating an application.
      • String(char chars [], int startIndex, int count) – – used to create and initialize a String object with a subrange of a character array.
        • The startIndex argument defines the index at which the subrange begins, while count specifies the number of characters to be copied.
        • Syntax: String str = new String(char chars [], int startIndex, int count);
          • char chars[] = { 'p', 'e', 'a', 'c', 'e', 'f', 'u', 'l'};
          • String str = new String(chars, 2, 3);
      • String(byte byteArr[]) – used to create a new String object by decoding the given array of bytes such as by decoding ASCII values according to the system’s default character set.
        • Syntax: String str = new String(byte byteArr[]);
          • byte b[] = {70, 114, 101, 101, 100, 111, 109};
          • String s = new String(b);
          • System.out.println(s);
      • String(byte byteArr[], int startIndex, int count) – this constructor also creates a new String object by decoding the ASCII values of the current string using the system’s default character.
        • The concept of startIndex and count in the 4th String constructor also applies here.
        • Syntax: String str = new String(byte byteArr[], int startIndex, int count);
          • byte b[] = {66, 82, 65, 86, 69, 82, 89};
          • String s = new String(b, 1, 4);
          • System.out.println(s);

    String Methods

    • The String class has various methods used to perform operations on Strings. The methods below can only create and return a new String containing the result of the operation.
      • charAt() - This method returns the character present in the specified index.
        • Syntax: string.charAt(int index);
          • String strA = "Java Programming";
          • System.out.println(strA.charAt(5));
      • trim() - This method removes the leading (starting) and trailing(ending) whitespaces from a string
        • Syntax: string.trim();
          • String strA = " Program with care ";
          • System.out.println(strA.trim());
      • replace() - This method changes the matching occurrences of a text or character in the string with the new text or character.
        • Syntax: string.replace(char oldChar, char newChar);
          • String strA = "batballing is a crime";
          • System.out.println(strA.replace('b', 'c'));
      • equals() - This method returns true if two strings are identical and false if otherwise.
        • Syntax: string.equals(String str);
          • String strA = "Learn Java";
          • String strB = "Learn Java";
          • String strC = "Learn Kolin";
          • boolean result;
          • result = strA.equals(strB); // comparing strA with strB
          • System.out.println(result); // true
          • result = strA.equals(strC); // comparing strA with strC
          • System.out.println(result); // false
          • result = strC.equals(strA); // comparing strC with strA
          • System.out.println(result); // false
      • toLowerCase() - This method changes all characters in the string to lowercase or minuscule characters.
        • Syntax: string.toLowerCase();
          • String strA = "BREATHE";
          • System.out.println(strA.toLowerCase()); // convert to lowercase letters
      • toUpperCase() - can be used to convert all characters in the string to uppercase or majuscule characters.
      • Syntax: string.toUpperCase()
      • length() - This method returns the number of characters in a string
        • Syntax: string.length();
          • String strA = "Kindness is free";
          • int length = strA.length(); // returns the length of strA
          • System.out.println(strA.length()); // Output: 16
      • concat() - This method returns a new string based on two (2) concatenated or joined strings.
        • Syntax: string.concat(String str);
          • String strA = "Java ";
          • String strB = "Programming";
          • // concatenate strA and strB
          • System.out.println(strA.concat(strB)); // "Java Programming"
          • // concatenate strB and strA
          • System.out.println(strB.concat(strA)); // "ProgrammingJava "
      • indexOf() - This method returns the index or position of the first occurrence of the specified character/substring within the string.
        • To look for the index of a character, the syntax is string.indexOf(int ch, int fromIndex);
          • ch refers to the character whose starting index is to be found, while fromIndex is optional and if passed, the ch character is searched starting from this index.
        • To look for the index of a substring within the string, the syntax is string indexOf(String str, int fromIndex);
          • str refers to the string whose starting index is to be found while fromIndex, is also optional; if passed, the str string is searched starting from this index.
      • compareTo() - This method compares or matches two (2) strings based on the dictionary order. This comparison is based on the Unicode value of each character in the string.
        • Syntax: string.compareTo(String str);
          • String strA = "Learn Java";
          • String strB = "Learn Java";
          • String strC = "Learn Kolin";
          • int result;
          • result = strA.compareTo(strB); // comparing strA with strB
          • System.out.println(result); // 0
          • result = strA.compareTo(strC); // comparing strA with strC
          • System.out.println(result); // -1
          • result = strC.compareTo(strA); // comparing strC with strA
          • System.out.println(result); // 1

    Arrays (Agarwal & Bansal, 2023)

    • An array represents data in a connected space in the computer memory.
    • It is a collection of elements (a fixed number of variables) of the same data type referenced by a common name.
    • Arrays must be declared first and then initialized to create and use an array in Java
    • Like any other primitive data type variable, an array can also be initialized with specific values when declared.
    • Here are the considerations for determining an array:
      • Array elements are determined by index.
      • All elements must share the same data type.
      • Elements are accessed using an array name and index.
        • An example of how arrays work:
          • int[] num = new int [6];
            • The example creates an int array named num with six elements, accessed by indices num[0] to num[5]. Java initializes numeric arrays to 0 by default.
          • double kg[] = {2.65, 3.92, 1.85, 11.53, 14.57};
            • The initializer list contains initial values placed between braces and separated by commas.
    • There are two (2) types of arrays: one-dimensional and multi-dimensional.
      • One-dimensional Array
        • A single or one-dimensional array is a list of the same typed variables
          • Syntax
            • Data type [] variable_name; int []i;
            • Data type variable name[]; int i[];
            • Data type [] variable_name, variable_name; int [] i, j;
            • Datatype… variable_name; int…i;
          • After declaring the variables for the array, it must be created in the memory. This can be done by using the new operator
          • Initializing this array can be done using a for loop:
            • for(int var=0; var<8; var ++)
            • i[var]=var;
            • 0 i[0]
            • 1 i[1]
            • 2 i[2]
            • 3 i[3]
            • 4 i[4]
            • 5 i[5]
            • 6 i[6]
            • 7 i[7]
            • 8 i[8]
      • Multi-dimensional Array
        • A multi-dimensional array refers to an array of arrays.
        • To declare one, the additional index must be specified using another set of square brackets.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Strings and Arrays PDF

    Description

    This quiz covers fundamental concepts related to Strings in Java programming. It includes the immutability of strings, their creation, and manipulation using the String class. Test your understanding of how to work with string literals and constructors in Java.

    More Like This

    Java String: Part 1
    23 questions
    Java Strings and Methods
    17 questions

    Java Strings and Methods

    DeliciousHazel7074 avatar
    DeliciousHazel7074
    Use Quizgecko on...
    Browser
    Browser