Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Object Oriented Programming - JAVA - Strings

Uploaded by

kumarvinayakchms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Object Oriented Programming - JAVA - Strings

Uploaded by

kumarvinayakchms
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Object Oriented Programming - JAVA

Strings
Agenda
● Exploring the String class
● String buffer class
● Command-line arguments
● Library:
○ StringTokenizer
○ Random class
○ Wrapper classes
● Encapsulation: Abstraction
● Creating User defined Data Structures:
○ Array of Objects
○ User defined Linked List
Exploring the String class
The String class is one of the most commonly used classes in Java and represents a sequence of characters.

Here are some key points and methods to explore:

1. Immutability: Strings in Java are immutable, meaning once a string object is created, its content cannot be changed.
This property ensures that strings are thread-safe and can be safely shared across multiple threads.
2. Creating Strings: You can create a string in Java using either a string literal or by using the new keyword with the String
Constructor.

String str1 = "Hello"; // String created using a string literal

String str2 = new String("World"); // String created using the constructor

1. String Concatenation: Strings in Java can be concatenated using the + operator or the concat() method.

String greeting = str1 + " " + str2; // Using +

String fullGreeting = str1.concat(" ").concat(str2); // Using concat method

1. String Length: You can get the length of a string using the length() method.

int length = greeting.length();


Exploring the String class continue
5. Accessing Characters: Individual characters in a string can be accessed using the charAt() method.

char firstChar = greeting.charAt(0); // 'H'

6. Substring: You can extract a substring from a string using the substring() method.

String sub = greeting.substring(6); // "World"

7. Equality and Comparison: You can compare strings for equality using the equals() method or for lexicographical order using
compareTo() method. boolean isEqual = str1.equals(str2);

int comparison = str1.compareTo(str2); // Returns a negative value if str1 < str2

8. String Manipulation: The String class provides various methods for manipulating strings, such as toUpperCase(), toLowerCase(), replace(
), trim(), startsWith(), endsWith(), contains(), etc.

String upperCaseGreeting = greeting.toUpperCase();

String replacedGreeting = greeting.replace("World", "Universe");

9. Splitting: You can split a string into an array of substrings using the split() method.

String[] words = greeting.split(" "); // Splits the string at spaces


String buffer class
The StringBuffer class in Java is similar to the String class, but with one key difference: it is mutable. This means you can modify the content of a StringBuffer
object after it has been created. This class is particularly useful when you need to perform a lot of modifications on a string without creating a new object
each time, which can be inefficient due to the immutability of strings.
1. Creating a StringBuffer: You can create a StringBuffer object using its constructor. Optionally, you can specify an initial capacity for the buffer.
StringBuffer buffer = new StringBuffer(); // Creates an empty StringBuffer
StringBuffer bufferWithCapacity = new StringBuffer(20); // Creates a StringBuffer
with an initial capacity of 20
1. Appending and Inserting:
● The append() method is used to add characters or other data types to the end of the StringBuffer.
● insert() method inserts characters or other data types at a specified position.
buffer.append("Hello"); // Appends "Hello" to the buffer
buffer.insert(5, ", World"); // Inserts ", World" at index 5
1. Deleting and Replacing:
● The delete() method removes characters from the buffer starting at the specified start index (inclusive) to the specified end index (exclusive).
● The replace() method replaces characters from the buffer starting at the specified start index to the specified end index with the specified
string.
buffer.delete(5, 11); // Deletes characters from index 5 to 10
buffer.replace(0, 5, "Hi"); // Replaces characters from index 0 to 4 with "Hi"
1. Capacity Management:
● The capacity() method returns the current capacity of the buffer.
● The ensureCapacity() method ensures that the buffer has at least the specified capacity.
int capacity = buffer.capacity();
buffer.ensureCapacity(30); // Ensures capacity is at least 30
1. Converting to String: The toString() method converts the content of the StringBuffer into a string.
String result = buffer.toString(); // Converts StringBuffer to String
Command-line arguments

command-line arguments can be passed to a program when it is executed from the command line. These arguments are
provided after the name of the Java class file and are passed as strings to the main method of the class.

Example:

public class MyClass {


public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
}
else {
System.out.println("Command-line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}

Compile the Java source file: javac MyClass.java

Execute the compiled bytecode file: java MyClass arg1 arg2 arg3
Library
1. StringTokenizer:
● StringTokenizer class in Java is used to break a string into tokens based on a specified delimiter.
● It provides methods to retrieve individual tokens and to check whether there are more tokens left.
Example:
import java.util.StringTokenizer;
public class StringToken{
public static void main(String[] args) {
String str = "Hello,World,Java";
StringTokenizer tokenizer = new StringTokenizer(str, ",");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
}
}
Library Continue
2. Random class:
● Random class in Java is used to generate random numbers of different data types.
● It provides methods to generate random integers, doubles, floats, longs, and more.
Example:
import java.util.Random;

public class RandamClass{


public static void main(String[] args) {
Random random = new Random();

int randomNumber = random.nextInt(100); // Generates a random integer between 0 and 99


double randomDouble = random.nextDouble(); // Generates a random double between 0.0 and 1.0

System.out.println("Random integer: " + randomNumber);


System.out.println("Random double: " + randomDouble);
}
}
Library Continue

3. Wrapper classes:
● Wrapper classes in Java are used to represent primitive data types as objects.
● They provide methods to convert between primitive data types and their corresponding object representations.
Example:
public class Main {
public static void main(String[] args) {
Integer intValue = Integer.valueOf("123"); // Convert string to Integer
int intValuePrimitive = intValue.intValue(); // Convert Integer to int
Double doubleValue = Double.valueOf("3.14"); // Convert string to Double
double doubleValuePrimitive = doubleValue.doubleValue(); // Convert Double to
double
System.out.println("Integer value: " + intValue);
System.out.println("Double value: " + doubleValue);
}
}
Encapsulation: Abstraction
Creating User defined Data Structures:

Array of Objects:

User defined Linked List

You might also like