Skip to content

Instantly share code, notes, and snippets.

@kenorb
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save kenorb/499bfebba5525277c04d to your computer and use it in GitHub Desktop.

Select an option

Save kenorb/499bfebba5525277c04d to your computer and use it in GitHub Desktop.
String Handling Demo
/*
* StringDemo.java
*
* String Handling.
* - String is fixed and immutable class object.
* - Strings are stored in Java heap memory.
* -
*
* Usage:
* javac StringDemo.java && java StringDemo
*/
class StringDemo {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static void main(String args[]) {
String s1 = "hello";
String s2 = new String("hello");
String s3 = "hello";
s1.toUpperCase(); // String is fixed and immutable
System.out.println(s1); // Output: hello
s1 = s1.toUpperCase(); // s1 is replaced by the new object.
System.out.println(s1); // Output: HELLO
// Color test
// It generally works for Unix shell prompts,
// however it doesn't work for Windows command prompt
// (although it does work for Cygwin).
// See: http://stackoverflow.com/questions/5762491/how-to-print-color-in-console-using-system-out-println
System.out.println(ANSI_RED + s1 + ANSI_RESET); // Output: HELLO
// Compare the object references
System.out.println(s1 == s2);
String a1 = "hello";
String a2 = "hello";
String a3 = new String("hello");
System.out.println(a1 == a3); // False, comparison of different objects.
System.out.println(a1 == a2); // True, as "hello" is the same object.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment