Note

I am a novice in the world of java programming and hope that similar learners would benefit from my learning experience. Also suggestions and corrections/revisions are highly welcomed from java programmers at any level.

Problem

Goal: Reverse a string

Pseudo-code :

  • Get a string from the command line
  • Declare new string and initialize with empty string
  • Append characters of the input value in reverse order to new string
  • Print out new string

Solution

Main class

public class TextReverser{}

Public

Classes with the keyword “public” are accessible by other classes.

Class

With classes, one can define the behaviour and properties of objects. For example, a class called “Person” would have behaviours such as walking, talking, eating, farting etc. While such a class could also have properties such as eye_color, height, weight, race, etc.

Class trigger

public static void main(String[] args) {}

Static

Another keyword like “public” is the static term. Properties or/and methods marked as static are not associated with instances or objects of the class. In Practice, one can access such members directly over the class rather than the instances. For example, [Class].method() or [Class].property.

Void

If a method is defined with the keyword “void”, it will return nothing. If you come from the world of typescript, you should have encountered or already used this keyword.

Main

Main method is the entry point of the java program.

String

In simple terms, a value of type “String” is a text or a sequence of characters.

Args

The “args” within the brackets of the static method “main” of a class is an array of strings ( String[]) called arguments. These are passed in the command line when running the java program.

package com.learnjava.beginner;

public class Person {
	String eye_color;
	int height;
	int weight;
	String race;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(String str : args) {
			System.out.println(str);
		}
		
	}
	
}

For instance, if you had a java program called Person.java above and you ran the following commands, the results below should be seen.

C:~learnjava\beginner>java Person.java

C:~learnjava\beginner>java Person.java Hello my name is
Hello
my
name
is

How to read input from command line

private static String readString() {
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		
		return line;
	}

Scanner

As quoted from W3school ( every programming learner’s first resource), the Scanner class is used to obtain input from the user. From the examples I have seen, which I currently do not completely understand honestly, when creating an instance of the scanner, the System.in method is passed as an argument. Don’t ask me why though. I am hopefully going to understand later on in the future :D. With methods such as nextLine, one could receive input until the user provides a line separator e.g. presses Enter, or nextInt, where the input is read until the user types in an integer. Interesting right ?

System

Unlike Scanner, one cannot create instances of the System class. I suppose it is static? Or maybe not. The only time I have used this class is for the in and out method, but there are other methods to explore as listed in the documentation.

sc.nextLine

Already described above 😀 .

Return

Self-explanatory, return “returns” a value or nothing really. n In the static main method, since the “void” keyword is present, the main method returns nothing. In contrast, the readString method returns a value of type “String” or an instance of the class String.

How to simply reverse a given string

private static String reverseString(String input) {
		  String r = "";
		for(int i= input.length() - 1; i >= 0; i--) {	
			r += input.charAt(i);
		}
		
	return r;
}

Iterate over string

Since an instance of the String class is a sequence of characters, it is possible to iterate or loop through each character. Based on my javascript background, there are several ways to loop through lists or sequences, namely, while, for, forEach etc. But as a java novice, I have only encountered while and for loops.

charAt

If you want to access a specific character of a String instance at a specific position, use this method. Required argument : integer, which should be between 0 and the number of characters in the string – 1.

+=

With this operator, you can update the value of either a String instance, integer or float by the value you provide after the “=”. For example

String s = "My name is"
s += " Comfort"
System.out.println(s)
My name is Comfort

Finishing touches

If the main method is empty and you ran the program, you would see nothing. So in order for you to complete this task, read the user input using the Scanner class, reverse the input string by iterating over it and print your result out using the System.out.println method.

My solution:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Please type in something");
		String s = TextReverser.readString();
		String r = TextReverser.reverseString(s);
		System.out.println("Your reversed String is: " + r);
	}

Run Program

Open your command line ( if you are using windows, open cmd and go the folder in which the java file is stored. Since I am using eclipse IDE, my program, TextReverser.java, is located within the eclipse-workspace) and run your program. Like this:

C:<path>\eclipse-workspace\com.learnjava\src\com\learnjava\beginner>java TextReverser.java
Please type in something
HELLO DARKNESS MY OLD FRIEND
Your reversed String is: DNEIRF DLO YM SSENKRAD OLLEH

TextReverser.java

This is what the entire program looks like.

package com.learnjava.beginner;

import java.util.List;
import java.util.Scanner;

public class TextReverser {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("Please type in something");
		String s = TextReverser.readString();
		String r = TextReverser.reverseString(s);
		System.out.println("Your reversed String is: " + r);
	}
	private static String readString() {
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		
		return line;
	}
	private static String reverseString(String input) {
		  String r = "";
		for(int i= input.length() - 1; i >= 0; i--) {	
			r += input.charAt(i);
		}
		
	return r;
	}

}

Extended Problem

How would you reverse a string passed in the command line when running the TextReverser program ?

Links

  1. https://stackoverflow.com/questions/15914676/how-to-get-input-via-command-line-in-java
  2. https://www.techiedelight.com/iterate-over-characters-string-java/
  3. https://en.wikibooks.org/wiki/Java_Programming/Keywords/public
  4. https://www.dummies.com/programming/java/what-is-the-static-keyword-in-java/
  5. https://en.wikibooks.org/wiki/Java_Programming/Keywords/void
  6. https://www.journaldev.com/12552/public-static-void-main-string-args-java-main-method
  7. https://www.geeksforgeeks.org/strings-in-java/
  8. https://www.quora.com/What-does-the-String-args-in-a-Java-main-method-actually-mean
  9. https://www.w3schools.com/java/java_user_input.asp
  10. https://docs.oracle.com/javase/7/docs/api/java/lang/System.html
  11. https://beginnersbook.com/2013/12/java-string-charat-method-example/
  12. https://stackoverflow.com/questions/7456462/what-does-the-operator-do-in-java/7456548
%d bloggers like this: