Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Saturday, 1 August 2015

Naming conventions in java

Java Naming Conventions

What Is a Naming Convention?

          Naming Conventions is nothing but a standard specifically used by the Java professional to represent the name of the class, interface, method, variable, package etc in a Java Program. In other words, Naming Conventions in Java is a standard rule to follow in selecting name of any identifiers in a program.

Naming Convention

          It is not mandatory to follow the Naming Conventions to run a java program. That’s why it is known as convention and not made as a rule. 

Standard Java Naming Conventions

          Standard Java Naming conventions for different identifiers are listed below


          Package names should be in all lowercase letters (small letters). 

Eg: com.packet.example, crack.analyser, name.preview


          Typical class name should be in nouns and represented by using the first letter capital method (Upper Camel Case Method). Use simple and descriptive nouns as Class name.  

Eg: class LogicalMeter, class Calculator, Class SeperateString


          Method name should be verb and use mixed case letters to represent it in programs. Mixed case letters are also knows as lower camel case letters. 

Eg: toPrint(), colorBackground()


          Constants are declared with the help of ‘static’ and ‘final’ keyword in Java. Constant variables should declare with full Upper Case letters with underscore(_) for word separation.

Eg: static final int MAX_WIDTH, static final int MAX_HEIGHT


          Interface name is also named like class name with Upper Camel Case method. 

Eg: interface ActionListener, interface Runnable


         Variable name should be in mixed case ie, naming start with small letter and use capital for internal words. It is easier to use simple one letter variable for temporary usage. Common variables used for storing integers are I, j, k and m. Common variables used for characters are c, d and e.

Eg:  float myHeight, String userName

Advantage of naming conventions in java

          Naming conventions make programs more understandable by making them easier to read. They can also give information about the function of the identifier-for example, whether it's a constant, package, or class-which can be helpful in understanding the code.

Monday, 26 January 2015

Arithmetic Compound Assignment Operators

Java Arithmetic Compound Operator

Compound Assignment Operators in Java

               Java gives special operators to combine an arithmetic operator with an assignment and which is known as Compound Assignment Operator. This session describes how it works and its benefits.

Consider the following addition and subtraction statements,

                         a = a + 5;
                         b = b - 5;

These statements can be rewritten as follows with the help of Compound Assignment Operator.

                         a += 5;
                         b -= 5;

Compound Assignment operators are available for all arithmetic and binary operators.


General Form:

                        var = var op expression;

Compound assignment Operator Form:

                         var op= expression;


 General Form  Compound Assignment Operator Form
 a = a - 5;  a -= 5;
 a = a + 5;  a += 5
 a = a % 5;  a %= 5
 a = a / 5  a /= 5
 a = a * 5  a *= 5

Advantages of Compound Assignment Operators

          The Compound Assignment Operators are used by Java Professionals to attain two major benefits.

          1. Compound Assignment Operators are shorthand and saves a few letters every time when you type Java Code.

          2. It is efficient than its equivalent long form in some cases.

Saturday, 2 February 2013

Introduction to Control Statements in Java

Control statements decide flow of a program


if, if-else, switch, nested if, switch, for, while, do-while, break, continue and return control statements

Control statements are used in programming languages to cause the flow of control to advance and branch based on changes to the state of a program. The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code.
In Java, control statements can be divided under the following three categories:

Monday, 21 January 2013

Code Comments in Java Program

Commenting Methods used in Java Program

Code comments in JAVA Source Code

Code comments are placed in source files to describe what is happening in the code to someone who might be reading the file, to comment-out lines of code to isolate the source of a problem for debugging purposes, or to generate API documentation. To these ends, the Java language supports three kinds of comments: double slashes, C-style, and doc comments.

Double Slashes

Double slashes (//) are used in the C++ programming language, and tell the compiler to treat everything from the slashes to the end of the line as text.

//A Very Simple Example

class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");

C-Style Comments

Instead of double slashes, you can use C-style comments (/* */) to enclose one or more lines of code to be treated as text.

/* These are C-style comments */
class ExampleProgram {
         public static void main(String[] args){
         System.out.println("I'm a Simple Program");

Doc Comments

To generate documentation for your program, use the doc comments (/** */) to enclose lines of text for the javadoc tool to find. The javadoc tool locates the doc comments embedded in source files and uses those comments to generate API documentation.

/** This class displays a text string at 
* the console.
class ExampleProgram {
          public static void main(String[] args){
          System.out.println("I'm a Simple Program");

Saturday, 19 January 2013

JAVA Program to Add Two Numbers


A program to accept two numbers from keyboard and calculate the sum.

//A small java program to add two numbers

import java.util.Scanner;

class AddTwoNumbers
   public static void main(String args[])
      int a, b, c;
      System.out.println("Enter two integers to calculate the sum ");
      //A simple text scanner which can parse primitive types and strings using regular                                      expressions.
      Scanner in = new Scanner(;
      //Capturing the scanned token as Int and storing it to the variables a and b.
      a = in.nextInt();
      b = in.nextInt();
      c = a + b;
      System.out.println("Sum of entered integers = "+c);


Enter two integers to calculate the sum
Sum of entered integers = 25

Thursday, 17 January 2013

Addition of Two Numbers Java Programming Code

Java program to add two numbers

Simple Program to Add two numbers in Java

//A Simple Program to Add Two Numbers in Java Program.

class AddTwoNumbers        //Class Declaration
   public static void main(String args[]) //Main Function
      int x, y, z;      // Variable Declaration
      x = 10;           //Assigning 10 to the variable x.
      y = 20;           //Assigning 20 to the variable y.
      z = x + y;        //Expression to Add two variables x, y and save the result to z
      System.out.println("Sum of x and y = "+z); //This line output the value of z on the Screen


Sum of x and y =30

Wednesday, 16 January 2013

Java Separators

Separators in Java

Separators used in Java Programming Lanuage

Separators help define the structure of a program. The separators used in HelloWorld are parentheses, ( ), braces, { }, the period, ., and the semicolon, ;. The table lists the six Java separators (nine if you count opening and closing separators as two). Following are the some characters which are generally used as the separators in Java.

It is used to separate the package name from sub-package name & class name. It is also used to separate variable or method from its object or instance.
It is used to separate the consecutive parameters in the method definition. It is also used to separate the consecutive variables of same type while declaration.
It is used to terminate the statement in Java.
This holds the list of parameters in method definition. Also used in control statements & type casting.
This is used to define the block/scope of code, class, methods.
It is used in array declaration.
Separators in Java

Sunday, 13 January 2013

Java Literals

Literals in Java

A literal is the source code representation of a fixed value.

Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables. Java language specifies five major types of literals. Literals can be any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement. While writing a source code as a character sequence, we can specify any value as a literal such as an integer.
They are:

  • Integer literals

  • Floating literals

  • Character literals

  • String literals

  • Boolean literals
Each of them has a type associated with it. The type describes how the values behave and how they are stored. 

Integer literals:

Integer data types consist of the following primitive data types: int,long, byte, and short. byte, int, long, and short can be expressed in decimal(base 
10), hexadecimal(base 16) or octal(base 8) number systems as well. 
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals.

int decimal = 100;
int octal = 0144;
int hexa =  0x64;

Floating-point literals:

Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and double. The default type when you write a floating-point literal is double, but you can designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float. We can also specify a floating-point literal in scientific notation using Exponent (short E ore), for instance: the double literal 0.0314E2 is interpreted as:

0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal

Character literals:

char data type is a single 16-bit Unicode character. We can specify a character literal as a single printable character in a pair of single quote characters such as 'a', '#', and '3'. You must know about the ASCII character set. The ASCII character set includes 128 characters including letters, numerals, punctuation etc. Below table shows a set of these special characters.

 Escape  Meaning
 \n  New line
 \t  Tab
 \b  Backspace
 \r  Carriage return
 \f  Formfeed
 \\  Backslash
 \'  Single quotation mark
 \"  Double quotation mark
 \d  Octal
 \xd  Hexadecimal
 \ud  Unicode character

If we want to specify a single quote, a backslash, or a non-printable character as a character literal use an escape sequence.  An escape sequence uses a special syntax to represents a character. The syntax begins with a single backslash character. You can see the below table to view the character literals use Unicode escape sequence to represent printable and non-printable characters.

 'u0041'  Capital letter A
 '\u0030'  Digit 0
 '\u0022'  Double quote "
 '\u003b'  Punctuation ;
 '\u0020'  Space
 '\u0009'  Horizontal Tab 

String Literals:

The set of characters in represented as String literals in Java. Always use "double quotes" for String literals. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same values.

 ""  The empty string
 "\""  A string containing
 "This is a string"  A string containing 16 characters
 "This is a " + "two-line string"  actually a string-valued constant expression, formed from two string literals

Null Literals

The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance
s = null;

Boolean Literals:

The values true and false are treated as literals in Java programming. When we assign a value to a boolean variable, we can only use these two values. Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a Boolean value. 

boolean chosen = true;

Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if its in quotation marks.

Friday, 11 January 2013

Java Identifiers

Identifiers in Java

Basics in using Identifiers in Java Programming

Identifiers are programmer-designed tokens. They are used for naming classes, methods, variables, objects, labels, packages and interfaces in a program. Java identifier’s basic rules are as follows:
  1. They can have alphabets, digits, and the underscore and dollar sign characters.
  2. They must not begin with a digit.
  3. Uppercase and lowercase letters are distinct.
  4. They can be of any length.
Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be descriptive and easily read. Java developers have followed some naming conventions.
  • Names of all public methods and instance variables start with a leading lowercase letter. 
  • When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. 
  • All private and local variables use only lowercase letters combined with underscores.
  • All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter).
  • Variables that represent constant values use all uppercase letters and underscores between words.
We may follow our own conventions as long as we do not break the basic rules of naming identifiers. 
The following table shows some valid and invalid identifiers:

Hello World (uses a space)
Hi JAVA! (uses a space and punctuation mark)
3value(begins with a number)
short (this is a Java keyword)
#age (does not begin with any other symbol except _ $ )

It is standard Java practice to name multiple-word identifiers in lowercase except for the beginning letter of words in the middle of the name.

Java Keywords

Keywords in Java

Java language has reserved 49 words as keywords.

Java Keywords also called a reserved word. Keywords are identifiers that Java reserves for its own use. These identifiers have built-in meanings that cannot change. Thus, programmers cannot use these identifiers for anything other than their built-in meanings. Technically, Java classifies identifiers and keywords as separate categories of tokens. Keywords are an essential part of a language definition. There are 49 reserved keywords currently defined in the Java language and they are shown in the below table.


The keywords const and goto are reserved but not used. In the early days of Java,several other keywords were reserved for possible future use.