Sunday, March 24, 2013

Java / immutable objects - example: String object

What are immutable objects?
Immutable object are objects whose state cannot be changed.

Example of immutable object (String):

public class MyImmutable 
{
 public static void main(String[] args) 
 {
  String myString = new String( "my string" );
  
  myString.replace("my", "my new");
  System.out.println("Original String (immutable): " + myString);
  
  String newMyString = myString.replace("my", "my new");
  System.out.println("New String: " + newMyString);  
 }
}
Java official immutable tutorial

Java / Scanner class. Simple example of Sanner.in

How to read something from console?
Java provides Scanner class to read from input.

Example:

import java.util.Scanner;

public class MyScanner 
{
 public static void main(String[] args) 
 {
  Scanner in = new Scanner( System.in );
  boolean isExit = false;
  
  while( !isExit )
  {
   System.out.println( "Write something to me" );
   String line = in.nextLine();
   
   System.out.println( "Your text: " + line );
   
   if( line.equals("exit") )
   {
    isExit = true;
    System.out.println( "You have choosen exit. Bye bye." );
   }
  }
  in.close();
 }
}


In this loop you can read everything you want from console and your text will be displayed in line #15..
If you type "exit" the program will terminate.

More about Scanner class you can read from official documentation here. (Java 1.6)