Friday, 22 September 2017

Java Naming Conventions

Below are some naming conventions of for java programming language. They must be followed while developing software in java for good maintenance and readability of code. Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.

Naming Conventions Table:

Camel case in Java Programming: It consists of compound words or phrases such that each word or abbreviation begins with a capital letter or first word with a lowercase letter, rest all with capital.
èClasses and Interfaces :
§  Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Interfaces name should also be capitalized just like class names.
§  Use whole words and must avoid acronyms and abbreviations.
Interface  Bicycle
Class MountainBike implements Bicyle

Interface Sport
Class Football implements Sport
    èMethods :
§  Methods should be verbs, in mixed case with the first letter lowercase and with the first letter of each internal word capitalized.
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
    è Variables: Variable names should be short yet meaningful.
§  Should not start with an underscore(‘_’) or dollar sign ‘$’ characters.
§  Should be mnemonic i.e, designed to indicate to the casual observer the intent of its use.
§  One-character variable names should be avoided except for temporary variables.
§  Common names for temporary variables are I, j, k, m, and n for integers; c, d, and e for characters.
    // variables for MountainBike class
    int speed = 0;
    int gear = 1;
    èConstant variables:
§  Should be all uppercase with words separated by underscores (“_”).
§  There are various constants used in predefined classes like Float, Long, String etc.
static final int MIN_WIDTH = 4;

// Some  Constant variables used in predefined Float class
public static final float POSITIVE_INFINITY = 1.0f / 0.0f;
public static final float NEGATIVE_INFINITY = -1.0f / 0.0f;
public static final float NaN = 0.0f / 0.0f;
   è Packages:
§  The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, Org.
§  Subsequent components of the package name vary according to an organization’s own internal naming conventions.

// java.lang packet in JDK


Thursday, 21 September 2017

Beginning Java programming with Hello World Example

The process of Java programming can be simplified in three steps:
èCreate the program by typing it into a text editor and saving it to a file –
         èCompile it by typing “javac” in the terminal window.
èExecute (or run) it by typing “java HelloWorld” in the terminal window.

The Below given program is the simplest program of Java printing “Hello World” to the screen. Let us try to understand every bit of code step by step.
/* This is a simple Java program.
 FileName : "". */
package Com.test;

public class HelloWorld {

          public static void main(String[] args) {
                   // Your program begins with a call to main().
              // Prints "Hello, World" to the terminal window

                   System.out.println("Hello World");


Hello World
The “Hello World!” program consists of three primary components: the HelloWorld class definition, the method main and source code comments. The following explanation will provide you with a basic understanding of the code:

èClass definition: This line uses the keyword class to declare that a new class is being defined.

1.     class HelloWorld 
HelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace  {  and the closing curly brace  }.
2.     main method: In Java programming language, every application must contain a main method whose signature is:
3.     public static void main(String[] args)
5.     public: So that JVM can execute the method from anywhere.
6.     static: Main method is to be called without object. 
7.     The modifiers public and static can be written in either order.
8.     void: The main method doesn't return anything.
9.     main(): Name configured in the JVM.
10.            String[]: The main method accepts a single argument: an array of elements of type String.
Like in C/C++, the main method is the entry point for your application and will subsequently invoke all the other methods required by your program.
11.      The next line of code is shown here. Notice that it occurs inside main( ).
12.            System.out.println("Hello World");
This line outputs the string “Hello World” followed by a new line on the screen. The output is actually accomplished by the built-in print( ) method. The system is a predefined class that provides access to the system, and out is the variable of type output stream that is connected to the console.
13.      Comments: They can either be multi-line or single line comments.
14.            /* This is a simple Java program. 
15.            Call this file "". */
This is a multiline comment. This type of comment must begin with /* and end with */. For single line you may directly use // as in C/C++.
Important Points :
èThe name of the class defined by the program is HelloWorld, which is same as name of file( This is not a coincidence. In Java, all codes must reside inside a class and there is at most one public class which contains main() method.
èBy convention, the name of the main class( a class which contains main method) should match the name of the file that holds the program.

Compiling the program :

èAfter successfully setting up the environment, we can open the terminal in both Windows/Unix and can go to the directory where the file – is present.

èNow, to compile the HelloWorld program, execute the compiler – javac , specifying the name of the source file on the command line, as shown:
èThe compiler creates a file called HelloWorld.class (in present working directory) that contains the bytecode version of the program. Now, to execute our program, JVM(Java Virtual Machine) needs to be called using java, specifying the name of the class file on the command line, as shown:
èjava HelloWorld
This will print “Hello, World” to the terminal screen.

In Windows
In Linux

Setting up the environment in Java

Introduction to Java, Class, and Object :

Java is a general-purpose computer programming language that is concurrent, class-based object-oriented etc. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture. The latest version is Java 8.

èWhat is a class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is a blueprint from which individual objects are created.
The following Bicycle class is one possible implementation of a bicycle:
public class Bicycle {

       int cadence = 0;
       int speed = 0;
       int gear = 1;

       void changeCadence(int newValue) {
              cadence = newValue;

       void changeGear(int newValue) {
              gear = newValue;

       void speedUp(int increment) {
              speed = speed + increment;

       void applyBrakes(int decrement) {
              speed = speed - decrement;

       void printStates() {
              System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear);

èWhat Is an Object?
Objects are key to understanding Object-Oriented Technology. Look around right now and you’ll find many examples of real-world Objects: Your dog, your desk, your television set your bicycle.

Example :
èReal-world objects share two characteristics: They all have state and behavior. Dogs have state(name,color,breed,hungry) and behavior (barking ,fetching ,wagging tail).
èBicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior of real-world objects is a great way to begin thinking in terms of object-oriented programming.

Setting up the environment in Java

Below are the environment settings for both Linux and Windows. JVM, JRE, and JDK  all three are platform dependent because the configuration of each Operating System is different. But, Java is platform independent.
There are few things which must be clear before setting up the environment
1.JDK(Java Development Kit): JDK is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.
2.     JRE(Java Runtime Environment): JRE contains the parts of the Java libraries required to run Java programs and is intended for end users. JRE can be view as a subset of JDK.
3.     JVM: JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides the runtime environment in which Java bytecode can be executed. JVMs are available for many hardware and software platforms. 
4.     JIT: The JIT Compiler is enable by default and is activated when a Java method is called. The JIT compiler compiles the bytecodes of that method into native machine code, compiling it “”Just in time” to run.When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it.

Steps for Setting up Java Environment for Windows

1.    Java8 JDK is available at :

Click the below link to find the JDK:

2.    After download, run the .exe file and follow the instructions to install Java on your machine. Once you installed Java on your machine, you have to setup environment variable.
3.    Go to Control Panel -> System and Security -> System.
Under Advanced System Setting option click on Environment Variables as highlighted below.

4.    Now, you have to alter the “Path” variable under System variables so that it also contains the path to the Java environment. Select the “Path” variable and click on Edit button as highlighted below.
5.    You will see a list of different paths, click on New button and then add the path where java is installed. By default, Java is installed in “C:\Program Files\Java\jdk\bin” folder OR “C:\Program Files(x86)\Java\jdk\bin”. In case, you have installed java at any other location, then add that path.
6.    Click OK, Save the settings and you are done !! Now to check whether the installation is done correctly, open command prompt and type java -version. You will see that java is running on your machine.

7.    In order to make sure whether the compiler is set up, type javac in command prompt. You will see a list related to javac.

Steps for Linux
In Linux, there are several ways to install java. But we will refer to simplest and easy way to install java using the terminal. For Linux we will install OpenJDK. OpenJDK is a free and open source implementation of the Java programming language.
1.    Go to Application -> Accessories -> Terminal.
2.    Type command as below.
3.    sudo apt-get install OpenJDK-8-jdk
4.    For “JAVA_HOME” (Environment Variable) type command as shown below, in “Terminal” using your installation path…(Note: The default path is as shown, but if you have to install OpenJDK at other location then set that path.)
5.    export JAVA_HOME = /usr/lib/jvm/java-8-openjdk
6.    For “PATH” (Environment Value) type command as shown below, in “Terminal” using your installation path…Note: the default path is as shown, but if you have to install OpenJDK at other location then set that path.)
7.    export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin
8.    You are done !! Now to check whether the installation is done correctly, type java -version in the Terminal.You will see that java is running on your machine.

Popular Java Editors/IDE :
§  Notepad/gedit : They are simple text-editor for writing java programs. Notepad is available on Windows and gedit is available on Linux.
§  Eclipse IDE: It is most widely used IDE(Integrated Development Environment) for developing software in java. You can download Eclipse from here.
§  Netbeans: NetBeans IDE provides Java developers with all the tools needed to create professional desktop, mobile and enterprise applications.

Related Posts: