Coding conventions in java with example

In previous post we have discussed about the data types in java. Now, we will discuss about the coding standards in java. Whenever we are writing code that is highly recommended to follow coding conventions. The name of the method or class should reflect the purpose of functionality of that component.

Packages:
Package declaration should start with Lowercase letters. If you have tried creating the package with the Uppercase letter's, eclipse will show you the below warning message. 

But, you can create the package by using uppercase letter also. For small projects that only have few packages, it's okay to just give them simple names which are meaningful.

Ex: package com.javatbrains.sample;
    package com.sun.java;

Classes:
Class names should be nouns in “Capital Camel Case” . with the first letter of every word capital. After the first letter in the word you should use lower case letters. We can also create the class names which start with the small letter's. But, that will be a bad practice and eclipse warn us.

For Ex: See the difference between the two class names in below,

1. class Hello{
   }

2. class HelloWorld{
   } 

Methods:
Method names should be in “lower Camel Case” . First letter in the first word must be small. After the first word every word start with capital letter.

For Ex: see the difference in the below examples,

1. run();
2. runFast();
3. getBackground();

Variables:
Local variable, instance variables, Class variables names should be in lower Camel Case Variable names also start with underscore(_) and dollar($) symbols. The name should represent what the value should represents the variable.

For Ex: see the below lines,

1. String firstName;
2. int orderNumber;
3. float avg;

Only use short names where the variable lives short. Like

for(int i=0;i<10;i++){
    // only I lives here
}

Constants:
Constants names should be in Upper case only.

For Ex:

static final int DEFAULT_WIDTH
static final int TEAM_SIZE

Interface: 
        Usually interfaces names are adjectives should start with uppercase letters & if it contains multiple words every inner word should starts with uppercase letter.

Ex: Runnable, Cloneable, Movable,...etc. 

    Comments

    Popular posts from this blog

    Hibernate auto increment with example

    how to count the page views by using JSP

    Multithreading in java with example

    How to retrieve data from table by using JDBC with example

    Prime, Fibonacci and Factorial number with example in java

    How to insert images into database using JDBC?

    How to sort list of objects in java with examples

    String interview questions and answers

    Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

    Store file into table by using JDBC with example