Reverse a String Using Java import java.util.Scanner; public class ReverseStringDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a string: "); String input = sc.nextLine(); // Convert string to char array char[] chars = input.toCharArray(); int left = 0; int right = chars.length - 1; // Swap characters from both ends while (left < right) { char temp = chars[left]; chars[left] = chars[right]; chars[right] = temp; left++; right--; } // Convert char array back to string String reversed = new String(chars); System.out.println("Reversed String: " + reversed); sc.close(); } }
How to Reverse a String in Java
More Relevant Posts
-
package com.frequency.characters; import java.util.Map; import java.util.HashMap; public class CountCharacters { public static void main(String[] args) { String input = "Automation Testing"; // Create a HashMap to store character frequencies Map<Character, Integer> freqMap = new HashMap<>(); // Iterate through each character in the string using a traditional for loop for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); // If character is already in map, increment its count, else initialize with 1 if (freqMap.containsKey(ch)) { freqMap.put(ch, freqMap.get(ch) + 1); } else { freqMap.put(ch, 1); } } // Print the frequency of each character for (Map.Entry<Character, Integer> entry : freqMap.entrySet()) { System.out.println("Character: '" + entry.getKey() + "' Frequency: " + entry.getValue()); } } }
To view or add a comment, sign in
-
🧩 Day 12: String Methods in Java (In Depth) Today I explored some powerful built-in methods that make string handling efficient and flexible. These are the real tools behind text manipulation in Java! 💡 What I Learned Today substring(start, end) → Extracts part of a string replace(oldChar, newChar) → Replaces characters equalsIgnoreCase() → Compares strings ignoring case trim() → Removes extra spaces indexOf() → Finds position of a character or substring contains() → Checks if substring exists split() → Splits string into parts based on a delimiter 🧩 Example Code public class StringMethods { public static void main(String[] args) { String text = " Java Programming "; System.out.println("Original: '" + text + "'"); System.out.println("Trimmed: '" + text.trim() + "'"); System.out.println("Substring: " + text.substring(2, 6)); System.out.println("Replace: " + text.replace("a", "@")); System.out.println("Contains 'Java': " + text.contains("Java")); System.out.println("Index of 'P': " + text.indexOf("P")); } }
To view or add a comment, sign in
-
-
a Java code to count the frequency of characters in a string using Traditional for loops and arrays—without using a HashMap or any other collection: package com.frequency.characters; public class CountCharacters { public static void main(String[] args) { String input = "Automation Testing"; // Convert string to lower case if you want case-insensitive count // input = input.toLowerCase(); int[] freq = new int[256]; // Assuming ASCII character set // Count frequency of each character using traditional for loop for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); freq[ch]++; } // Print frequency of each character using another for loop for (int i = 0; i < freq.length; i++) { if (freq[i] > 0) { System.out.println("Character '" + (char) i + "' appears " + freq[i] + " times"); } } } } Explanation An integer array freq of size 256 is used to cover all ASCII characters. The first for loop iterates over each character in the input string and increments the frequency in freq at the index corresponding to the character's ASCII value. The second for loop goes through the freq array and prints all characters that appeared (with frequency > 0). This method avoids using HashMap or collections and relies purely on arrays and loops. It works efficiently for strings containing ASCII characters only. This is a classic and simple way to count character frequencies using only traditional loops and arrays.
To view or add a comment, sign in
-
Digital clock example:- import java.time.LocalTime; import java.time.format.DateTimeFormatter; class DigitalClock extends Thread { public void run() { for (int i = 1; i <= 10; i++) { LocalTime time = LocalTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm:ss"); System.out.println("Current Time: " + time.format(format)); try { Thread.sleep(1000); } catch (InterruptedException e) { } } System.out.println("Clock stopped"); } public static void main(String[] args) { DigitalClock clock = new DigitalClock(); clock.setName("Digital Clock"); clock.start(); } } output:- Current Time: 02:53:04 Current Time: 02:53:05 Current Time: 02:53:06 Current Time: 02:53:07 Current Time: 02:53:08 Current Time: 02:53:09 Current Time: 02:53:10 Current Time: 02:53:11 Current Time: 02:53:12 Current Time: 02:53:13 Clock stopped
To view or add a comment, sign in
-
import java.util.Scanner; class Recursion { public static void main(String []args) { Scanner sc = new Scanner(System.in); System.out.println("Enter The Number : "); int num = sc.nextInt(); //long result = factorial(num); long result = factorialRecursive(num); System.out.println("Result : "+ result); } public static long factorial(int num) { long fact = 1; for(int i=1;i<=num;i++) { fact *= i; } return fact; } public static long factorialRecursive(int num) { if(num == 1) { return 1; } return num * factorialRecursive(num-1); } }
To view or add a comment, sign in
-
Can you explain the difference between `static` and `non-static` members in Java? --->🧩 1️⃣ Static Members These belong to the class itself, not to any specific object. 🔹 Examples: static variables (class variables) static methods static blocks static nested classes 🔹 Characteristics: Shared among all objects of the class. Can be accessed without creating an object using ClassName.member. Memory allocated only once — when the class is loaded. Can access only other static members directly (no instance data). 🔹 Example: class Demo { static int count = 0; // static variable static void displayCount() { // static method System.out.println("Count: " + count); } public static void main(String[] args) { Demo.displayCount(); // Access without object } } 🧩 2️⃣ Non-static (Instance) Members These belong to each object of the class. 🔹 Examples: Instance variables Instance methods 🔹 Characteristics: Each object gets its own copy of instance variables. Must be accessed through an object. Can access both static and non-static members. Memory allocated when the object is created. 🔹 Example: class Demo { int id; // non-static variable void show() { // non-static method System.out.println("ID: " + id); } public static void main(String[] args) { Demo obj = new Demo(); obj.id = 101; obj.show(); // Access using object } }
To view or add a comment, sign in
-
-
Method overloading in Java is when a class has multiple methods with the same name but different parameters (either in number or type). This allows you to perform similar but slightly different tasks using the same method name, improving code readability and reducing redundancy. java example : class Calculator { // Adds two integers public int add(int a, int b) { return a + b; } // Adds three integers public int add(int a, int b, int c) { return a + b + c; } // Adds two double values public double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls add(int, int) System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int) System.out.println(calc.add(5.5, 3.2)); // calls add(double, double) } } Here, the add method name is overloaded with different parameter lists. The compiler decides which method to call based on arguments given. Summary: Method overloading means same method name, different parameters.Improves code clarity; no need for different method names for similar actions.Compiler selects correct method based on argument types/count. #Java #MethodOverloading #ProgrammingConcepts #CodingTips #JavaBasics #JavaDevelopment #100DaysOfCode #Day6ofcoding
To view or add a comment, sign in
-
🚀 Mastering Strings in Java – The Backbone of Text Handling! 🧵 In Java, Strings are more than just text — they’re objects that make text manipulation powerful and efficient. Let’s break it down 👇 🔹 1. What is a String? A String in Java is an object that represents a sequence of characters. Example: String name = "Java"; Yes, even though it looks simple — it’s backed by the String class in java.lang package! 🔹 2. Immutable by Nature 🧊 Once created, a String cannot be changed. If you modify it, Java creates a new object in memory. String s = "Hello"; s = s + " World"; // Creates a new String object ✅ Immutability ensures security, caching, and thread-safety. 🔹 3. String Pool 🏊♂️ Java optimizes memory by storing String literals in a special area called the String Constant Pool. If two Strings have the same literal value, they point to the same memory! 🔹 4. Common String Methods 🛠️ s.length(); // Returns length s.charAt(0); // Returns first character s.toUpperCase(); // Converts to uppercase s.equals("Java"); // Compares values s.substring(0, 3);// Extracts substring 🔹 5. Mutable Alternatives 🧱 For performance-heavy string manipulations, use: StringBuilder (non-thread-safe, faster) StringBuffer (thread-safe) 💡 Pro Tip: Use StringBuilder inside loops for better performance instead of concatenating Strings repeatedly. #Java #Programming #Coding #100DaysOfCode #JavaDeveloper #StringsInJava #SoftwareDevelopment #TechLearning
To view or add a comment, sign in
-
Is the below code the scariest thing in Java to execute an asynchronous task? class CompletableFuture { static<U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) } Could we have just something more readable like: class AsyncTask { static <TValue> Eventual<TValue> AsyncTask.create(Supplier<TValue> valueSupplier) } public static void main(String[] args) { Supplier<String> fetchGreeting = () -> { return "Hello"; } var eventualGreeting = AsyncTask.create(fetchGreeting) eventualGreeting.mapException(exception -> { return "<Default greeting>" }); var eventualMessage = eventualGreeting.map(greeting -> { return greeting + ", World"; }); eventualMessage.for(System.out::println) // Keep main thread alive for async tasks to complete try { Thread.sleep(1000); } catch (InterruptedException e) {} }
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development