0% found this document useful (0 votes)
35 views

all jav programs of string

All about Java string
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

all jav programs of string

All about Java string
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

STRING

What are Strings in Java?


Strings are the type of objects that can store the character of values and in Java
Example:
String name = "Geeks";
// Java Program to demonstrate
// String
public class StringExample {

// Main Function
public static void main(String args[])
{
String str = new String("example");

System.out.println(str);
}
}
Output
Example

Here's a list of commonly used String functions in Java, each with a simple example, its
definition, and a brief explanation of its use:

1. length()

Definition: Returns the length of the string.


Use: To determine the number of characters in a string.

String str = "Hello";


System.out.println(str.length()); // Output: 5

2. charAt(index)

Definition: Returns the character at the specified index.


Use: To access individual characters in a string.

String str = "Hello";


System.out.println(str.charAt(1)); // Output: e
3. substring(start, end)

Definition: Extracts a portion of the string from start index to end index (exclusive).
Use: To get a specific part of a string.

String str = "Hello World";


System.out.println(str.substring(0, 5)); // Output: Hello

4. toUpperCase()

Definition: Converts all characters in the string to uppercase.


Use: To standardize text to uppercase.

String str = "hello";


System.out.println(str.toUpperCase()); // Output: HELLO

5. toLowerCase()

Definition: Converts all characters in the string to lowercase.


Use: To standardize text to lowercase.

String str = "HELLO";


System.out.println(str.toLowerCase()); // Output: hello

6. trim()

Definition: Removes leading and trailing whitespace from the string.


Use: To clean up unnecessary spaces in input.

String str = " Hello ";


System.out.println(str.trim()); // Output: Hello

7. replace(oldChar, newChar)

Definition: Replaces all occurrences of oldChar with newChar.


Use: To modify a string by replacing characters.

String str = "Java";


System.out.println(str.replace('a', 'o')); // Output: Jovo

8. equals(otherString)

Definition: Compares two strings for equality.


Use: To check if two strings are identical.
String str1 = "Hello";
String str2 = "Hello";
System.out.println(str1.equals(str2)); // Output: true

9. contains(sequence)

Definition: Checks if the string contains a specified sequence of characters.


Use: To search for substrings in a string.

String str = "Hello World";


System.out.println(str.contains("World")); // Output: true

10. split(delimiter)

Definition: Splits the string into an array of substrings based on the delimiter.
Use: To break a string into parts for processing.

String str = "Java,Python,C++";


String[] languages = str.split(",");
for (String lang : languages) {
System.out.println(lang);
}
// Output:
// Java
// Python
// C++

11. indexOf(char)

Definition: Returns the index of the first occurrence of the specified character.
Use: To locate a character in a string.

String str = "Hello";


System.out.println(str.indexOf('e')); // Output: 1

12. isEmpty()

Definition: Checks if the string is empty (length is 0).


Use: To validate user input or check if a string is blank.

String str = "";


System.out.println(str.isEmpty()); // Output: true

Would you like explanations for other functions or deeper examples? 😊


1. Which of the following is not a type of inheritance in Java?
a) Single inheritance b) Multiple inheritance using classes
c) Multilevel inheritance d) Hierarchical inheritance
2. In Java, when an array is initialized, what is the default value of elements for an integer
array?
a) 0 b) null c) undefined d) garbage value
3. What is method overloading?
a) Having multiple methods with the same name but different parameters
b) Having multiple methods with different names
c) Changing the return type of a method
d) Writing a method inside another method
4. Which keyword is used in Java to inherit a class?
a) extends b) implements c) inherits d) this
5. What is the size of an array in Java?
a) It can be dynamically changed after initialization b) It is fixed once initialized c) It
must be initialized later in the code d) It has no size limit
6. Write a method prototype name check() which takes an integer argument and returns a
char:
a)char check() b)void check (int x) c)check (int x) d)char check (int x)
7. The number of values that a method can return is:
a)1 b)2c)3 d)4
8. The String class method to join two strings is:
a)concat(String) b)<string>.joint(string) c)concat(char) d)Concat()
9. The output of the function "COMPOSITION".substring(3, 6):
a)POSI b)POS c)MPO d)MPOS
10. The code obtained after compilation is known as:
a)source code b)object code c)machine code d)java byte code
11. Missing a semicolon in a statement is what type of error?
a) Logical b) Syntax c)Runtime d)No error
12. When an object of a Wrapper class is converted to its corresponding primitive data
type, it is called as ............... .

a)Boxing b)Explicit type conversion c)Unboxing d)Implicit type conversion


13. The number of bits occupied by the value ‘a’ are:
a)1 bit b)2 bits c)4 bits d)16 bits
14. Method which is a part of a class rather than an instance of the class is termed as:
a)Static method b)Non static method c)Wrapper class d)String method
15. Which of the following is a reserved keyword in Java?
A) main B) goto C) label D) constant
16. Which of these operators is used to allocate memory for an object?
A) malloc B) alloc C) new D) create
17. Which of the following is the correct way to declare an array in Java?
A) int arr[] = new int[5]; B) int arr = int[5]; C) int[] arr = int[5]; D) arr = new int(5);
18. Which keyword is used to prevent a method from being overridden?
A) final B) static C) const D) abstract
19. Which of these cannot be used for a switch statement parameter?
A) int B) float C) char D) byte

Which of the following is not a feature of Java?


A) Object-Oriented B) Platform-Independent C) Pointer Manipulation D) Secure
Here are 10 additional MCQs for Java:

21. Which of the following is not a valid access modifier in Java?


a) public
b) protected
c) private
d) internal
22. What is the default access level of a class in Java if no modifier is specified?
a) public
b) private
c) protected
d) package-private
23. Which exception is thrown when an array index is accessed out of its bounds?
a) NullPointerException
b) ArrayIndexOutOfBoundsException
c) IndexError
d) ArithmeticException
24. In Java, the keyword this refers to:
a) The parent class of the current class
b) The current instance of the class
c) The main method
d) A static member of the class
25. What is the output of Math.ceil(5.2)?
a) 5
b) 6
c) 5.2
d) 5.0
26. What does the finally block do in Java?
a) Executes only when an exception is thrown
b) Executes only when no exception is thrown
c) Executes after the try and catch blocks, regardless of an exception
d) Prevents exceptions from occurring
27. Which of these is used to create an immutable object in Java?
a) final class
b) final method
c) synchronized method
d) private constructor
28. What is the return type of the compareTo() method in Java?
a) int
b) boolean
c) double
d) String
29. Which method is used to convert a string to a lowercase in Java?
a) toLowerCase()
b) lower()
c) toLower()
d) convertLower()
30. What does the keyword super refer to in Java?
a) A superclass constructor
b) A subclass method
c) A static method
d) A local variable in the method

Answer

1. b) Multiple inheritance using classes


2. a) 0
3. a) Having multiple methods with the same name but different parameters
4. a) extends
5. b) It is fixed once initialized
6. d) char check(int x)
7. a) 1
8. a) concat(String)
9. b) POS
10. d) java byte code
11. b) Syntax
12. c) Unboxing
13. d) 16 bits
14. a) Static method
15. b) goto
16. c) new
17. a) int arr[] = new int[5];
18. a) final
19. b) float
20. c) Pointer Manipulation
21. d) internal
22. d) package-private
23. b) ArrayIndexOutOfBoundsException
24. b) The current instance of the class
25. b) 6
26. c) Executes after the try and catch blocks, regardless of an exception
27. a) final class
28. a) int
29. a) toLowerCase()
30. a) A superclass constructor

1. Write the Java expression for (p + q)2


2. Evaluate the expression when the value of x = 2:
x = x++ + ++x + x
3. How is a constructor different from a method in Java?
4. Define polymorphism and its types in Java.
5. How does the final keyword affect variables, methods, and classes in Java?
6. What is inheritance, and why is it used in Java?
7. Describe the purpose of the static keyword in Java.
8. What are wrapper classes in Java? Give an example.
9. Name any two jump statements.
10. Write two characteristics of a constructor.

1. Write a Java program to accept a string from the user and perform the following operations:

 Count the number of vowels and consonants.


 Reverse the string.
 Check if the string is a palindrome.

2. Write a Java program that demonstrates the use of the following Math class methods:

 Math.pow()
 Math.sqrt()
 Math.abs()
 Math.ceil()
 Math.floor()

3.Write a Java program to accept an array of integers from the user. The program should
calculate and display the following:

 The largest and smallest elements in the array.


 The sum of all elements.
 The average of the array elements.

4. Design a class RailwayTicket with following description:


String name — To store the name of the customer
String coach — To store the type of coach customer wants to travel
long mobno — To store customer’s mobile number
int amt — To store basic amount of ticket
int totalamt — To store the amount to be paid after updating the original amount
Member methods:
void accept() — To take input for name, coach, mobile number and amount.
void update() — To update the amount as per the coach selected (extra amount to be added in the amount
as follows)
Type of Coaches Amount
First_AC 700
Second_AC 500
Third_AC 250
sleeper none
void display() — To display all details of a customer such as name, coach, total amount and mobile
number.

Write a main method to create an object of the class and call the above member methods.

5. Write a Java program to print the below pyramid pattern for n rows.
*
***
*****
*******
*********

1. Reverse a String:
Write a Java program to reverse a given string without using built-in functions.
Example:
Input: "hello"
Output: "olleh"
2. Find the Largest Element in an Array:
Write a Java program to find the largest element in an array of integers.
Example:
Input: [3, 7, 1, 8, 4]
Output: 8
3. Check if a Number is Prime:
Write a Java program to check if a given number is prime.
Example:
Input: 7
Output: Prime
4. Factorial of a Number:
Write a Java program to calculate the factorial of a given number using recursion.
Example:
Input: 5
Output: 120
5. Fibonacci Series:
Write a Java program to print the first n numbers of the Fibonacci series.
Example:
Input: n = 5
Output: 0, 1, 1, 2, 3

You might also like