-
Notifications
You must be signed in to change notification settings - Fork 0
/
array in java
55 lines (47 loc) · 1.99 KB
/
array in java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class ArrayAndStringExample {
public static void main(String[] args) {
// Example of arrays
// Declaration and initialization of an integer array
int[] intArray = {1, 2, 3, 4, 5};
// Accessing elements of the array
System.out.println("Elements of the integer array:");
for (int i = 0; i < intArray.length; i++) {
System.out.println("Element at index " + i + ": " + intArray[i]);
}
// Example of strings
// Declaration and initialization of a string
String myString = "Hello, world!";
// Accessing characters of the string
System.out.println("\nCharacters of the string:");
for (int i = 0; i < myString.length(); i++) {
System.out.println("Character at index " + i + ": " + myString.charAt(i));
}
// Splitting the string into an array of substrings
String[] words = myString.split(" ");
System.out.println("\nSplitting the string into words:");
for (int i = 0; i < words.length; i++) {
System.out.println("Word " + (i + 1) + ": " + words[i]);
}
// Concatenating strings
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println("\nFull Name: " + fullName);
// String comparison
String str1 = "hello";
String str2 = "Hello";
if (str1.equals(str2)) {
System.out.println("Strings are equal.");
} else {
System.out.println("Strings are not equal.");
}
// Searching within a string
String sentence = "The quick brown fox jumps over the lazy dog";
String searchWord = "fox";
if (sentence.contains(searchWord)) {
System.out.println("The word '" + searchWord + "' was found in the sentence.");
} else {
System.out.println("The word '" + searchWord + "' was not found in the sentence.");
}
}
}