In this tutorial, you will explore two important Java concepts: Array in String and Multithreading. These play a vital role in efficient data handling and concurrent programming.
In Java, a String can be converted into an Array and vice-versa. This conversion is useful when you want to process, analyze, or modify string data effectively.
toCharArray() method converts a String into a character array.
2. The split() method splits a String into an array of substrings based on a given delimiter.
String str = "Bhau Automation";
char[] charArray = str.toCharArray();
String[] words = str.split(" ");
System.out.println("Character Array:");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println("\nWord Array:");
for (String w : words) {
System.out.println(w);
}
String sentence = "Java is awesome";
String[] wordsList = sentence.split(" ");
System.out.println("First word: " + wordsList[0]);
System.out.println("Total words: " + wordsList.length);
Multithreading allows Java programs to perform multiple operations simultaneously by dividing a program into small threads. It enhances efficiency and improves CPU utilization.
Thread class or implementing the Runnable interface.
2. Override the run() method to define thread logic.
3. Start the thread using the start() method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class Demo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread-1");
Thread t2 = new Thread(new MyRunnable(), "Thread-2");
t1.start();
t2.start();
}
}