Last active 1739827712

Basic Intro to Java String class.

kristofer's Avatar kristofer revised this gist 1739827712. Go to revision

1 file changed, 4 insertions, 4 deletions

IntroJavaStrings.md

@@ -155,16 +155,16 @@ public class StringPerformance {
155 155
156 156 Important points to remember about Strings:
157 157 1. Strings are immutable - once created, they cannot be changed (and unless they are huge, they're pretty cheap to make)
158 - 2. Use StringBuilder for multiple string modifications
158 + 2. Use StringBuilder for multiple string modifications (it shows you KWYD)
159 159 3. Use equals() for string comparison, not ==
160 - 4. String methods always return a new String
160 + 4. String methods always return a new String
161 161 5. The string pool helps save memory by reusing string literals
162 - 6. Format specifiers:
162 + 6. Format specifiers: (yeah, you wanna look at these)
163 163 - %s for strings
164 164 - %d for integers
165 165 - %f for floating-point numbers
166 166 - %n for newline
167 - 7. Common methods:
167 + 7. Common methods: (start memorizing)
168 168 - length() for string length
169 169 - substring() for extracting parts
170 170 - indexOf() for finding positions

kristofer's Avatar kristofer revised this gist 1739827606. Go to revision

1 file changed, 1 insertion, 1 deletion

IntroJavaStrings.md

@@ -154,7 +154,7 @@ public class StringPerformance {
154 154 ```
155 155
156 156 Important points to remember about Strings:
157 - 1. Strings are immutable - once created, they cannot be changed
157 + 1. Strings are immutable - once created, they cannot be changed (and unless they are huge, they're pretty cheap to make)
158 158 2. Use StringBuilder for multiple string modifications
159 159 3. Use equals() for string comparison, not ==
160 160 4. String methods always return a new String

kristofer's Avatar kristofer revised this gist 1739827557. Go to revision

1 file changed, 175 insertions

IntroJavaStrings.md(file created)

@@ -0,0 +1,175 @@
1 + # Working with Strings in Java
2 +
3 + ## String Creation and Basics
4 +
5 + Strings are immutable objects in Java. Here are different ways to create them:
6 +
7 + ```java
8 + public class StringBasics {
9 + public static void main(String[] args) {
10 + // String creation
11 + String str1 = "Hello World"; // String literal
12 + String str2 = new String("Hello World"); // Using constructor
13 +
14 + // String concatenation
15 + String firstName = "John";
16 + String lastName = "Doe";
17 + String fullName = firstName + " " + lastName;
18 +
19 + // Using StringBuilder for efficient concatenation
20 + StringBuilder builder = new StringBuilder();
21 + builder.append(firstName)
22 + .append(" ")
23 + .append(lastName);
24 + String result = builder.toString();
25 +
26 + // String comparison
27 + String s1 = "hello";
28 + String s2 = "hello";
29 + String s3 = new String("hello");
30 +
31 + System.out.println(s1 == s2); // true (same string pool reference)
32 + System.out.println(s1 == s3); // false (different objects)
33 + System.out.println(s1.equals(s3)); // true (same content)
34 + System.out.println(s1.equalsIgnoreCase("HELLO")); // true
35 + }
36 + }
37 + ```
38 +
39 + ## String Methods
40 +
41 + ### Basic String Operations
42 + ```java
43 + public class StringOperations {
44 + public static void main(String[] args) {
45 + String text = "Hello, World!";
46 +
47 + // Length and case operations
48 + System.out.println(text.length()); // 13
49 + System.out.println(text.toLowerCase()); // "hello, world!"
50 + System.out.println(text.toUpperCase()); // "HELLO, WORLD!"
51 +
52 + // Trimming whitespace
53 + String padded = " text with spaces ";
54 + System.out.println(padded.trim()); // "text with spaces"
55 +
56 + // Character access
57 + char firstChar = text.charAt(0); // 'H'
58 +
59 + // Getting substring
60 + String sub1 = text.substring(0, 5); // "Hello"
61 + String sub2 = text.substring(7); // "World!"
62 +
63 + // Checking content
64 + boolean startsWithHello = text.startsWith("Hello"); // true
65 + boolean endsWithWorld = text.endsWith("World!"); // true
66 + boolean containsWorld = text.contains("World"); // true
67 + }
68 + }
69 + ```
70 +
71 + ### String Searching and Manipulation
72 + ```java
73 + public class StringSearching {
74 + public static void main(String[] args) {
75 + String text = "The quick brown fox jumps over the lazy dog";
76 +
77 + // Finding positions
78 + int firstO = text.indexOf('o'); // First 'o'
79 + int lastO = text.lastIndexOf('o'); // Last 'o'
80 + int quickPos = text.indexOf("quick"); // Position of "quick"
81 +
82 + // Replacing content
83 + String newText = text.replace('o', '0'); // Replace char
84 + String noFox = text.replace("fox", "cat"); // Replace String
85 +
86 + // Replace all occurrences using regex
87 + String noVowels = text.replaceAll("[aeiou]", "*");
88 +
89 + // Split string into array
90 + String[] words = text.split(" "); // Split by space
91 +
92 + // Join array elements
93 + String joined = String.join("-", words); // Join with hyphen
94 + }
95 + }
96 + ```
97 +
98 + ### String Formatting and Special Characters
99 + ```java
100 + public class StringFormatting {
101 + public static void main(String[] args) {
102 + String name = "John";
103 + int age = 30;
104 + double height = 1.85;
105 +
106 + // Using String.format
107 + String formatted = String.format("Name: %s, Age: %d, Height: %.2f",
108 + name, age, height);
109 +
110 + // Using printf
111 + System.out.printf("Name: %s, Age: %d, Height: %.2f%n",
112 + name, age, height);
113 +
114 + // Escape sequences
115 + String withQuotes = "He said \"Hello!\"";
116 + String withNewLine = "Line 1\nLine 2";
117 + String withTab = "Column1\tColumn2";
118 +
119 + // Unicode characters
120 + String heart = "I \u2764 Java"; // Heart symbol
121 +
122 + // Format numbers
123 + double price = 1234.5678;
124 + String formattedPrice = String.format("$%,.2f", price); // $1,234.57
125 + }
126 + }
127 + ```
128 +
129 + ### String Performance and Best Practices
130 + ```java
131 + public class StringPerformance {
132 + public static void main(String[] args) {
133 + // Bad practice: String concatenation in loop
134 + String result1 = "";
135 + for (int i = 0; i < 1000; i++) {
136 + result1 += i; // Creates new String object each time
137 + }
138 +
139 + // Good practice: StringBuilder in loop
140 + StringBuilder result2 = new StringBuilder();
141 + for (int i = 0; i < 1000; i++) {
142 + result2.append(i);
143 + }
144 + String finalResult = result2.toString();
145 +
146 + // String pool example
147 + String str1 = "hello"; // Goes to string pool
148 + String str2 = new String("hello"); // New object in heap
149 + String str3 = str2.intern(); // Gets pooled version
150 +
151 + System.out.println(str1 == str3); // true
152 + }
153 + }
154 + ```
155 +
156 + Important points to remember about Strings:
157 + 1. Strings are immutable - once created, they cannot be changed
158 + 2. Use StringBuilder for multiple string modifications
159 + 3. Use equals() for string comparison, not ==
160 + 4. String methods always return a new String
161 + 5. The string pool helps save memory by reusing string literals
162 + 6. Format specifiers:
163 + - %s for strings
164 + - %d for integers
165 + - %f for floating-point numbers
166 + - %n for newline
167 + 7. Common methods:
168 + - length() for string length
169 + - substring() for extracting parts
170 + - indexOf() for finding positions
171 + - replace() and replaceAll() for substitutions
172 + - split() for breaking into arrays
173 + - trim() for removing whitespace
174 +
175 + These String operations are fundamental to Java programming and are used extensively in text processing, data manipulation, and user interface development.
Newer Older