• Home
  • Courses
  • School
  • Programs
  • Problems
  • Contact Us
  • My account
  • Register

Have any question?

(+91) 98222 16647
info@simplycoding.in
RegisterLogin
Simply Coding
  • Home
  • Courses
  • School
  • Programs
  • Problems
  • Contact Us
  • My account
  • Register

Strings in Java

What is Java String?

  • Categories Strings in Java, String, Java

To understand what is Java String watch our playlist – click here

1. What is String class?
Ans. 

  • A String is a collection of characters in a sequence; for example a word can be a String and a sentence can also be a String.
  • A String is treated as object which is constant i.e. a String can not be changed once it created in a program.
  • String objects are immutable that is ones String object is created it cannot be modified or changed.

Q. 2 How do you create a String Object?
Ans. New String can be created by any of these methods

  1. Using String Default Constructor: String h0 = new String();
  2. Using String parameterized Constructor: String h1 = new String(“Hello”);
  3. Using character array in String parameterized Constructor:
                  char[] h3 = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ };
                  String h4 = new String(h3);
  4. Assigning a String literal directly: String h2 = “Hello “;

Q. 3 Explain what do you mean when you say String in immutable in Java?
Ans. When you create a new string object for e.g. ch in the diagram, Java has something called as String constant pool in heap which stores the value and ch refers to it.
If you create a second variable referring to the same string, it creates only a new reference variable and it points to the same string.

String ch = “Hello”;
String ch1=ch;
String ch2="Hello";
String

Suppose if we try to use a function toUpperCase on ch. It does not change ch. VM creates a new string with upper case and returns a reference to that.
ch2 = ch.toUpperCase();

String1

So once a String object is created, if you change it, it creates a new String object. This shows than the String is immutable. So it is critical that you have the return value assigned to a new String variable otherwise your string is lost.

Q. 4 What do you mean by a package? Give three examples.
Ans.
A package in java is a group of logically related classes together in the form of java class libraries in which all related functions and information are pre-stored which helps in executing a program.
Example. Java.io, java.util, java.lang 

Q. 5 What is String Buffer? How we create a String Buffer?
Ans.

  • Any string or sequence of character created using StringBuffer class is considered as mutable i.e the characters that the string contain can be modified or changed.
  • It represents flexible length of mutable sequence of characters in which various characters and substrings can be inserted.
  • String Buffer is created as follows:
    StringBuffer p=new StringBuffer(“SimplyCoding”);

Q. 6 In which package is String class included?
Ans.
String Class is included in java.lang.

Q. 7 Why we do not need to import any library for using String class?
Ans. String Class is included in java.lang. Since Java imports java.lang by default, we do not need to explicitly include it in our program.

Q. 8 Which Scanner class function is used to input String?
Ans. We can use next() or nextLine() to input a String from a user. next() function is used to read only one word or till first newline. While nextLine() can read complete line till EOL.

Q. 9 How do you convert a String to primitive type like int, double etc.?
Ans. To convert String to primitive type, we can use Wrapper class functions. There are two methods.

  1. Every Wrapper class except character class contains a method parseXxx() method to find primitive for the given String object.
    • E.g. int i = Integer.parseInt(“10”);
    • double d – Double.parseDouble(“12.45”);
  2. Every Wrapper class contains a method valueOf() to create a Wrapper object for the given String.
    • E. g. int I = Integer.valueOf(“10”);
    • float f =valeOf(“3.14”);

Q. 10 How do you convert a primitive type to String?
Ans. To convert primitive type to String, we can use Wrapper class functions.
We can use toString() method to convert Wrapper object or primitive to String.
E.g. String s = Double.toString(10.5);

Q. 11 List of different String Functions
Ans.

MethodReturnparameter
char charAt(int index)charint
int length()int–
int compareTo(String) CompareToIgnoreCase()intString
int lastIndexOf()/ indexOf(int ch/ String str)intint, String
boolean equals() equalsIgnoreCase ()booleanString
boolean StartsWith() endsWith()booleanString
Boolean contains(str)booleanString
String concat(String str)StringString
String replace(char old, char new)StringChar, string
String substring(int beginI, int endI):Stringint
String toLowerCase() toUpperCase()String–
String trim()String–

Q. 12 What is the Difference between equals() and compareTo() method.
Ans.

equals()compareTo()
This function is used to check only the equality of two strings and return a boolean result in the form of true or false.This is a sting function and used to compare two strings “lexicographically” and returns integer result in the form of positive (>0), negative(<0) or zero (=0)
boolean res= “Simply”.equals(“Simply”)
//return ‘true’
boolean res= “Simply”.equals(“SIMPLY”)
//return ‘false’
boolean res= “SIMPLY”.equals(“SIMPLY”)
//it gives result zero

Q. 13 Write a short note on contains() method.
Ans. The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
       Syntax: public boolean contains(CharSequence chars)

Q. 14 State the data type and value of res after the following is executed:

char ch=‘n’;
res=Character.toUpperCase(ch);

Ans. res is of char type is value is ‘N’.

Q. 15 Give the use of trim() and length(). Explain with example. 
Ans.
trim(): String trim() method is used to avoid the white space before of any String. Trim method does not have any parameters.
Example:

String s1= “simply”;
String s2= new String(s1, trim());
System.out.println(s1.trim());

length(): This method returns the length of sequence of characters as an int value.
Example:

String s1=”simply”;
System.out.println(s1.length());

Q. 16 What is the difference between indexOf() and charAt() function?
Ans.

indexOf()charAt()
It returns the character at the specific indexReturns of the index within the this string (current string object) of the first occurrence of the specified character.
Example:
String s= new String(“SimplyCoding”);
System.out.println(s.indexOf(‘m’));
Output: 2
Example:
String s= new String(“SimplyCoding”);
System.out.println(s.charAt(6));
Output: C

Q. 17 Describe equalsignorecase() method.
Ans. It compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and it represents an equivalent String ignoring case, else false.
Syntax: str2.equalsIgnoreCase(str1);

Q. 18 Write the output of the following:
     (i) System.out.println (Character.isUpperCase(‘D’));
     (ii) System.out.println(Character.toUpperCase(‘l’));
Ans.
      (i) true
      (ii) L

Q. 19 What is the use of substring()?
Ans. it extract a substring from the given string by using the index values passed as an argument. In case of substring() method startIndex is inclusive and endIndex is exclusive.

  • Share:
author avatar
Simply Coding

Previous post

Constructor Programs
July 3, 2021

Next post

Python function
July 3, 2021

You may also like

Questions on Encapsulation
Questions on Encapsulation
4 July, 2021
Questions on Library classes
Questions on Library classes
4 July, 2021
for loop
Loops in Java
23 June, 2021

Leave A Reply Cancel reply

You must be logged in to post a comment.

Categories

  • Uncategorized
  • Programs
    • Python
    • Java
  • Problems
    • Python
    • Java
    • Web Development
      • Internet
    • Emerging Technologies
  • Notes
    • General
    • QBasic
    • MS Access
    • Web Development
      • XML
      • HTML
      • JavaScript
      • Internet
    • Database
    • Logo Programming
    • Scratch
    • Emerging Trends
      • Artificial Intelligence
      • Internet of Things
      • Cloud Computing
      • Machine Learning
    • Computer Fundamentals
      • Computer Networks
      • E-Services
      • Computer Hardware
    • Python
    • Java
  • School
    • ICSE
      • Computers Class 9
        • Java Introduction
        • Tokens & Data Types
        • Java Operators
        • Math Library
        • if & switch
        • For & While
        • Nested loops
      • Computer Class 10
        • Sample Papers
        • OOPS concepts
        • Functions in Java
        • Constructors
        • Arrays in Java
        • Strings in Java
    • SSC
      • IT Class 11
        • IT Basics
        • DBMS
        • Web Designing
        • Cyber Laws
      • IT Class 12
        • Web Designing
        • SEO
        • Advanced JavaScript
        • Emerging Tech
        • Server Side Scripting
        • E-Com & E-Gov
      • Computer Science 11
      • Computer Science 12
    • CBSE
      • Computer 9
        • Basics of IT
        • Cyber Safety
        • Scratch
        • Python
      • Computer 10
        • Sample Papers
        • Networking
        • HTML
        • Cyber Ethics
        • Scratch
        • Python
      • Computer Science 11
        • Computer Systems
        • Python 11
          • Python Basics
          • Python Tokens
          • Python Operators
          • Python if-else
          • Python loops
          • Python Strings
          • Python List
          • Python Tuple
          • Python Dictionary
          • Python Modules
        • Data Management
      • Computer Science 12
        • Sample Papers
        • Python 12
          • Python Functions
          • Python File Handling
          • Python Libraries
          • Python Recursion
          • Data Structures
        • Computer Networks
        • Data Management
    • ISC
      • Computer Science 11
        • Introduction to Java
        • Values & Data Types
        • Operators
        • if & switch
        • Iterative Statements
        • Functions
        • Arrays
        • String
        • Data Structures
        • Cyber Ethics
      • Computer Science 12
        • Sample Papers
        • Boolean Algebra
        • OOPS
        • Wrapper Classes
        • Functions
        • Arrays
        • String
Simply Coding Computer Courses for School                Privacy Policy     Terms of Use     Contact Us

© 2021 Simply Coding

Login with your site account

Lost your password?

Not a member yet? Register now

Register a new account

Are you a member? Login now