Updates

Friday, 16 August 2013

How To Read Input From Console in Java (Part 1)

Accepting Input from the Keyboard

A stream is required to accept input from the keyboard. A stream represents flow of data from one
Place to another place. It is like a water-pipe where water flows.  Like a water-pipe carries water from
One place to another, a stream carries data from one place to another place .A stream can carry
Data . From keyboard to memory or from memory to printer or from memory to a file. A stream is
Always required if we want to move data from one place to another.

 Basically, there are two types of streams: input streams and output streams.

 Input streams are those streams which receive or read data coming from some other place. Output streams  are those Streams which sender write data to some other place.
All streams are represented by classes in java.io (input and output) package. This package
Contains a lot of classes, all of which can be classified into two basic categories :input streams and
Outputs treams.
Keyboard  is represented by a field, called in System class. When we write System.in, we are
Representing a standard input device, i.e. keyboard ,by default. System class is found in java.lang
(language) package and has three fields' as shown below. All these fields represent some type of
stream:
    System.in: This represents Ii1putStream object ,which by default represents standard input       Device. eg. keyboard.
    System.out: This represents PrintStream object ,which by default represents standard output device, eg. monitor.
     System.err: This field also represents PrintStream object, which by default represents monitor.
Note: that both System.out and System.err can be used to represent the monitor rand hence any of
These two can be used to send data to the monitor.

What is the difference between System.out and System.err?

System.out and System.err both represent the monitor by default and hence can be used to send
Data or results to the monitor .But System.out is used to display normal messages and results whereas
System.err is used to display error messages.
 System.out.println("A normal message");
 System.err.println("An error Message");

To accept data from the keyboard ,eg . System.in , we need to connect it to an input stream as some
. inputstream is needed to read data.


We will discuss the ways to input a String, an integer, and a real number. System.in is a pre-defined InputStream used with the console. Unfortunately this class does not have a method for simple input. But there is a java.io.BufferedReader class that has a method readLine(). A buffer is a region in memory where input from the terminal is stored until needed by the program. If you want to perform buffered input on the System.in stream you would pass the System.in object into the constructor

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.
For top efficiency, consider wrapping an InputStreamReader within a BufferedReader.
BufferedReader input = new
BufferedReader (new InputStreamReader (System.in));

Once we have created a BufferedReader we can use its method readLine() to read one line of characters at a time from the keyboard and store it as a

String object.
String inputString = input.readLine(); 
Once we have the input data in a String object we can use the various methods
available to a String object to manipulate the data.  Since data can get lost/corrupted
during an input operation the method readLine() canalert the user by
throwing an exception. There are several ways that Java allows
a user to handle exceptions. For the time being we will add the phrase "throws
IOException" and let the system to do the error handling.

Reading
an integerOne way to read an integer is to read the input as a String and then use the method parseInt() of the wrapper class Integer to convert the String to an integer.
int num = Integer.parseInt ( inputString);

a real numberThere is a wrapper class java.lang.Double that can take
the input as a String and a method parseDouble() to convert the String
to a real number.

double d = Double.parseDouble (inputString );

An Example :

import java.io.*;
public class CalcArea
{
  public static void main ( String args[] ) throws IOException
  {
    System.out.print ( "Enter the radius: " );
    BufferedReader input = new BufferedReader ( new InputStreamReader ( System.in ) );
    String inputString = input.readLine();

    double radius = Double.parseDouble ( inputString );
    double area = 3.14159 * radius * radius;

    System.out.println ( "Area is: " + area );
  }
}

Difference Between Interface and Abstract Class

Difference between Interface and Abstract Class

What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.
So Is there any other major differences ?
Yes…They are as follows:
·         An Abstract class can have a combination of abstract and other normal methods Whereas in Interface it must have only methods (abstract) without definition i.e. Without body.
·         An Abstract class can have any combinations of member variables i.e. public int, private
String, final int etc but in case of Interface all the variables must have default access specifier as public and of type static and final. So Even if you didn’t declare it explicitly it will be always public.
·         As all the member variables are declared public that is why an Interface must also need to
Be declared default as public. While in case Abstract class such conditions are not mandatory.


When to use abstract class and interface in Java
Here are some guidelines on when to use an abstract class and interface in Java:
1.    An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
2.    An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
3.    If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
4.    Interfaces are a good choice when you think that the API will not change for a while.
5.    Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.

Tuesday, 30 July 2013

How to Install JDK 7 in different operating System

How to Install and
Get Started with Java Programming 
(on Windows, Mac & Ubuntu)

Java Development Kit (JDK) 1.7 (officially named Java SE 7), which is freely available from Sun Microsystems (now part of Oracle), is needed for writing Java programs. JDK can be downloaded from the Java mother site @ http://java.sun.com (or http://www.oracle.com/technetwork/java/javase/downloads/index.html).
JDK or JRE?
JRE (Java Runtime) is needed for running Java programs. JDK (Java Development Kit), which includes JRE plus the development tools (such as compiler and debugger), is need for writing as well as running Java programs. Since you are supposed to write Java Programs, you should install JDK, which includes JRE.
JDK Versions
The various JDK versions are:
  1. JDK Alpha and Beta (1995): Sun announced Java in September 23, 1995.
  2. JDK 1.0 (January 23, 1996): Originally called Oak (named after the oak tree outside James Gosling's office). Renamed to Java 1 in JDK 1.0.2.
  3. JDK 1.1 (February 19, 1997): Introduced AWT event model, inner class, JavaBean, JDBC, and RMI.
  4. J2SE 1.2 (codename Playground) (December 8, 1998): Rebranded as "Java 2" and renamed JDK to J2SE (Java 2 Standard Edition). Also released J2EE (Java 2 Enterprise Edition) and J2ME (Java 2 Micro Edition). Included JFC (Java Foundation Classes - Swing, Accessibility API, Java 2D, Pluggable Look and Feel and Drag and Drop). Introduced Collection Framework and JIT compiler.
  5. J2SE 1.3 (codename Kestrel) (May 8, 2000): Introduced Hotspot JVM.
  6. J2SE 1.4 (codename Merlin) (February 6, 2002): Introduced assert, non-blocking IO (nio), logging API, image IO, Java webstart, regular expression support.
  7. J2SE 5.0 (codename Tiger) (September 30, 2004): Officially called 5.0 instead of 1.5. Introduced generics, autoboxing/unboxing, annotation, enum, varargs, for-each loop, static import.
  8. Java SE 6 (codename Mustang) (December 11, 2006): Renamed J2SE to Java SE (Java Standard Edition).
  9. Java SE 7 (codename Dolphin) (July 28, 2011): First version after Oracle purchased Sun (called Orcale JDK).
  10. Java SE 8: expected in summer 2013.Originally slated for release in September, Java 8 has been delayed until March of next year, 

1.  How To Install JDK on Windows

Step 1: Download JDK
  1. Goto JavaSE download site @ http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Click the "Download" button under "JDK" of "Java SE 7".
  3. Choose your operating platform, e.g., Windows x86 for 32-bit Windows OS or Windows x64 for 64-bit Windows OS. You can check whether your Windows OS is 32-bit or 64-bit via "Control Panel" ⇒ System ⇒ Under the "System Type".
Step 2: Install JDK and JRE
Run the downloaded installer (e.g., "jdk-7uxx-windows-i586.exe"), which installs both the JDK (Java Development Kit) and JRE (Java Runtime). By default, the JDK will be installed in directory "C:\Program Files\Java\jdk1.7.0_{xx}", where {xx} denotes the latest upgrade number; and JRE in "C:\Program Files\Java\jre7".
For novices, accept the defaults. Simply click "next"..."next"... to install JDK in "C:\Program Files\Java\jdk1.7.0_{xx}" and JRE in "C:\Program Files\Java\jre7". Take note of you JDK installed directory. I shall refer to the JDK installed directory as <JAVA_HOME>, hereafter, in this article.
(For Advanced Users Only) The default JDK/JRE directories work but I recommend avoiding "Program Files" directory because of thatblank character in the directory name. You may change the installed directories for JDK and JRE during installation. I personally installed JDK and all my programming tools in "d:\bin" (instead of "C:\Program Files") for ease of maintenance.
Step 3: Include JDK's "bin" Directory in the PATH
Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK's programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory "<JAVA_HOME>\bin" (where <JAVA_HOME> denotes the JDK installed directory, e.g., C:\Program Files\Java\jdk1.7.0_{xx}). You need to include the "<JAVA_HOME>\bin" directory in the PATH.
To edit the PATH environment variable in Windows 2000/XP/Vista/7/8:
  1. Click "Start" button ⇒ "Control Panel" ⇒ "System" ⇒ (Vista/7/8 only) "Advanced system settings".
  2. Switch to "Advanced" tab ⇒ "Environment Variables..."
  3. In "System Variables" box, scroll down to select "PATH" ⇒ "Edit..."
  4. (CAUTION: Read this paragraph 3 times before doing this step! There is no UNDO) In "Variable value" field, INSERT "c:\Program Files\Java\jdk1.7.0_{xx}\bin" (VERIFY that this is your JDK's binary directory) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK's binary directory from the rest of the existing directories. DO NOT DELETE any existing entries; otherwise, some existing applications may not run.
    Variable name  : PATH
    Variable value : c:\Program Files\Java\jdk1.7.0_{xx}\bin;[exiting entries]
(For Advanced Users Only)
I suggested that you place the JDK bin directory in front of "c:\windows\system32" and "c:\windows". This is because some Windows systems may have an out-dated copy of JDK/JRE in these directories. Do a search for "java.exe", and you will be amazed by the findings.
You could read "Java Applications and Environment Variable" for more discussions about PATH environment variable.
I also recommend that you define an environment variable called JAVA_HOME, which contains the JDK installed directory, and include the JDKbin directory in the PATH via JAVA_HOME, i.e., PATH=%JAVA_HOME%\bin;.....
Step 4: Verify the JDK Installation
Launch a CMD shell (Click "Start" button ⇒ run... ⇒ enter "cmd"; or "Start" button ⇒ All Programs ⇒ Accessories ⇒ Command Prompt).
  1. Issue a "path" command to list the contents of the PATH environment variable. Check the output and make sure that <JAVA_HOME>\bin is listed in the PATH.
    prompt> path
    PATH=c:\Program Files\Java\jdk1.7.0_{xx}\bin;[other entries]
  2. Issue the following commands to verify that JDK/JRE are properly installed and display their version:
    prompt> java -version
    java version "1.7.0_{xx}"
    Java(TM) SE Runtime Environment (build 1.7.0_{xx}-b11)
    Java HotSpot(TM) Client VM (build 23.3-b01, mixed mode, sharing)
     
    prompt> javac -version
    javac 1.7.0_{xx}
Step 5: Write a Hello-World Java Program
  1. Create a directory to keep all your works, e.g., d:\myproject, or any directory of your choice. Do NOT save your works in "Desktop" or "Documents" as they are hard to locate. The directory name shall not contain blank or special characters. Use meaningful but short name as it is easier to type.
  2. Launch a programming text editor (such as TextPad or NotePad++). Begin with a new file and enter the following source code. Save the file as "Hello.java", under your work directory (e.g., d:\myproject).
    /*
     * First Java program to say Hello
     */
    public class Hello {   // Save as "Hello.java" under "d:\myproject"
       public static void main(String[] args) {
          System.out.println("Hello, world!");
       }
    }
Step 6: Compile and Run the Hello-World Java Program
JavaBasics_GettingStarted.png
  1. To run the program, invoke the Java Runtime "java":
    D:\myproject> java Hello
    Hello, world!

    2.  How to Install JDK on Macs

    Step 1: Check if JDK has been Pre-Installed
    In some Mac systems (earlier than Mac OS X 10.7 (Lion)), JDK has been pre-installed. To check if JDK has been installed, open a "Terminal" (Go ⇒ Utilities ⇒ Terminal) and issue these commands:
    $ javac -version
    • If a JDK version number is returned (e.g., JDK {1.x.x}), then JDK has already been installed. Proceed to "Step 3: Write a Hello-world Java program".
    • If message "command not found" appears, JDK is NOT installed. Proceed to the "Step 2: Install JDK".
    • If message "To open javac, you need a Java runtime" appears, select "Install" and follow the instructions to install JDK. Then, proceed to "Step 3: Write a Hello-world Java program".
    Step 2: Download and Install JDK
    1. Goto http://connect.apple.com.
    2. Login with your AppleID.
    3. Download "Java for Mac OS X {10.x} Update {u} Developer Package (DMG)". Choose {10.x} according to your Mac OS X version and the latest{u}.
    4. Double-click to install the downloaded Disk Image (DMG) file.
    5. Eject the DMG file.
    6. To verify your installation, open a "Terminal" and issue these commands:
      // Check the version of "javac" (Java Compiler) and "java" (Java Runtime)
      $ javac -version
      javac {1.x.x_xx}
       
      $ java -version
      java version "{1.x.x_xx}"
      Java(TM) SE Runtime Environment (build {1.x.x_xx-xxx})
      Java HotSpot(TM) Client VM (build 22.1-b02, mixed mode, sharing)
       
      // Find the location of "javac" (Java Compiler) and "java" (Java Runtime)
      $ which javac
      /usr/bin/javac
       
      $ which java
      /usr/bin/java
    Step 3: Write a Hello-World Java Program
    1. Create a directory called "myproject" under your home directory (Finder ⇒ Go ⇒ Home; File ⇒ New Folder ⇒ "myproject").
      In Macs under the Terminal, the home directory of the current login user is denoted as "~". Hence, this new directory is represented as "~/myproject".
    2. Use a programming text editor (such as jEditgedit) to input the following source code and save as "Hello.java" under the directory "~/myproject" created earlier.
      If you use "TextEdit" (NOT encouraged, as it is a plain text editor, NOT a programming text editor), you need to open a new file ⇒ choose "Format" ⇒ "Make Plain Text" ⇒ Enter the source code ⇒ Save as "Hello.java" (without the ".txt").
      /*
       * My First Java program to say Hello
       */
      public class Hello {   // Save as "Hello.java" under "~/myproject"
         public static void main(String[] args) {
            System.out.println("Hello, world from Mac!");
         }
      }
    Step 4: Compile and Run the Hello-World Java Program
    MacJavaCompile.png
    1. To compile the source code "Hello.java", open a new "Terminal" (Go ⇒ Utilities ⇒ Terminal) and issue these commands (as illustrated):
      // Change Directory (cd) to where "Hello.java" resides
      // i.e., sub-directory "myproject" under home (~)
      $ cd ~/myproject
       
      // Check if "Hello.java" exists using list (ls) command
      $ ls
      Hello.java   ......
       
      // Compile "Hello.java" using JDK compiler "javac"
      $ javac Hello.java
      // If error message appears, debug your source code
       
      // Check for the output "Hello.class"
      $ ls
      Hello.class   Hello.java   ......
    2. To run the Hello-world, invoke the Java Runtime "java" as follows:
      // Run "Hello.class"
      $ java Hello
      Hello, world from Mac!
  2. To compile the source code "Hello.java":
    1. Start a CMD Shell (Click "Start" button ⇒ Select "run..." ⇒ Enter "cmd"; or "Start" button ⇒ All Programs ⇒ Accessories ⇒ Command Prompt).
    2. Set the Current Drive to the drive where you saved your source file "Hello.java". For example, suppose that your source file is saved in drive "d", enter "d:" as follow:
      prompt> d:
      D:\xxx>
    3. Set the Current Working Directory to the directory that you saved your source file via the cd (Change Directory) command. For example, suppose that your source file is saved in directory "d:\myproject".
      D:\xxx> cd \myproject
      D:\myproject>
    4. Issue a dir (List Directory) command to confirm that your source file is present in the current directory.
      D:\myproject> dir
      ......
      08-May-XX  06:25 PM               277 Hello.java
      ......
    5. Invoke the JDK compiler "javac" to compile the source code "Hello.java".
      D:\myproject> javac Hello.java
      The compilation is successful if the command prompt returns. Otherwise, error messages would be shown. Correct the errors in your source file and re-compile. Check "Common JDK Installation Errors", if you encounter problem compiling your program.
    6. The output of the compilation is a Java class called "Hello.class". Issue a dir (List Directory) command again to check for the output.
      D:\myproject> dir
      ......
      xx-xxx-xx  01:53 PM               416 Hello.class
      xx-xxx-xx  06:25 PM               277 Hello.java
      ......
      Step 1: Download and Install JDK
      1. Goto JDK (Java SE) download site @ http://www.oracle.com/technetwork/java/javase/downloads/index.html. Select "Java SE 7ux" ⇒ JDK ⇒ Download ⇒ "Accept Licence Agreement" ⇒ Select Linux x86 (for 32-bit system) or Linux x64 (for 64-bit system) "tar.gz" package, e.g., "jdk-7ux-linux-i586.tar.gz". (Check Settings ⇒ Details or issue command "file /sbin/init" to check your OS version.) The tarball will be stored in folder "~/Downloads", by default.
      2. We shall install JDK under "/usr/local/java". First, create a directory "java" under "/usr/local". Open a Terminal and issue these commands:
        $ cd /usr/local
        $ sudo mkdir java
        Extract the downloaded package (Check your downloaded filename!)
        $ cd /usr/local/java
        $ sudo tar xzvf ~/Downloads/jdk-7u{xx}-linux-x64.tar.gz
        JDK shall be extracted in a folder "/usr/local/java/jdk1.7.0_{xx}", where {xx} is the upgrade number.
      3. Add JDK's binary directory ("bin") to the PATH by editing "/etc/profile":
        $ cd /etc
        $ gksudo gedit profile   // OR "sudo nano profile" to use the console-based nano editor
        Add these lines at the end of the file "/etc/profile", replace "{xx}" with the actual number:
        export JAVA_HOME=/usr/local/java/jdk1.7.0_{xx}
        export PATH=$PATH:$JAVA_HOME/bin
        Rerun the configuaration file by:
        $ source /etc/profile
         
        // Check the new settings for JAVA_HOME and PATH
        $ echo $JAVA_HOME
        /usr/local/java/jdk1.7.0_{xx}
         
        $ echo $PATH
        .....:/usr/local/java/jdk1.7.0_{xx}/bin
      4. To use Java under Firefox, you need to enable the so-called "Java Plugin for web browser".
        $ cd /usr/lib/mozilla/plugins
        // if this directory does not exist, create it
        $ sudo mkdir -p /usr/lib/mozilla/plugins
        Then, create a symbolic link to your Mozilla plugins folder, (check your JDK folder)
        $ cd /usr/lib/mozilla/plugins
        $ sudo ln -s /usr/local/java/jdk1.7.0_{xx}/jre/lib/amd64/libnpjp2.so
        To verify the installation, restart your Firefox and issue URL "about:plugins" to view the status of the plugins (check for java plugins with the correct version).
      5. To verify the JDK installation, issue these commands:
        // Show the Java Compiler (javac) version
        $ javac -version
        JDK 1.7.0_07
         
        // Show the Java Runtime (java) version
        $ java -version
        ......
         
        // Show the location of javac and java
        $ which javac
        /usr/local/java/jdk1.7.0_{xx}/bin/javac
        $ which java
        /usr/local/java/jdk1.7.0_{xx}/bin/java
      6. Inform the Ubuntu about the Oracle JDK/JRE:
        // Setup the location of java, javac and javaws
        $ sudo update-alternatives --install "/usr/bin/java" "java" "/usr/local/java/jdk1.7.0_17/jre/bin/java" 1
              // --install link name path priority
        $ sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/local/java/jdk1.7.0_17/bin/javac" 1
        $ sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/local/java/jdk1.7.0_17/jre/bin/javaws" 1
         
        // Use this Oracle JDK/JRE as the default
        $ sudo update-alternatives --set java /usr/local/java/jdk1.7.0_17/jre/bin/java
        $ sudo update-alternatives --set javac /usr/local/java/jdk1.7.0_17/bin/javac
        $ sudo update-alternatives --set javaws /usr/local/java/jdk1.7.0_17/jre/bin/javaws
      Step 2: Compile and Run a Hello-world Java Program
      1. Open "Folder" and create a new directory called "myproject" under your home directory to keep all your works.
      2. Open "Text Editor" (gedit). Enter the following source code and save as "Hello.java" under the "~/myproject" directory created eariler.
        public class Hello {   // To save as "Hello.java" under "~/myproject"
           public static void main(String[] args) {
              System.out.println("Hello, world from Ubuntu!");
           }
        }
      3. To compile the Hello-world Java program, launch a Terminal and issue these commands:
        // Change directory to where the source code resides
        $ cd ~/myproject
         
        // List the contents of current directory. Check for "Hello.java"
        $ ls
        ...... Hello.java ....
         
        // Compile "Hello.java" into "Hello.class"
        $ javac Hello.java
         
        // Check for "Hello.class"
        $ ls
        ...... Hello.class ....
      4. Run the Hello-world Java program:
        // Run "Hello.class"
        $ java Hello
        Hello, world from Ubuntu!

Friday, 26 July 2013

The most used statement in java "System.out.println()"

What is System.out.println

I didn't like it when I'm using it at first time and do you guys know the reasons why ? I need to write a huge statement to  print a single line rather than simple printf and cout in C and C++ respectively.Later on, I fell in deep love with it. Didn’t you? How many times have we used it till now? It is one of the most number of times compiled statement in the History of java.

System.out.println prints the argument passed, into the System.out which is generally stdout.
  • System – is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities provided by theSystem class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…”
  • out – is a static member field of System class and is of type PrintStream. Itsaccess specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data. When running a program from windows command line, it is the standard console.
  • println – println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that.

Change out of System.out.println

‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior usingsetOut method as below. In the following example, I have redirected the output to a text file in the same directory.
public class ChangeOut {
  public static void main(String args[]) {
    try {
      System.setOut(new PrintStream(new FileOutputStream("log.txt")));
      System.out.println("Now the output is redirected!");
    } catch(Exception e) {}
  }
}