Saturday, 2 February 2013

if and if-else control statements in java

The most common Control Statements in Java

Control Statement if and if.. else

The if Statement:


In Java if statement is most widely used. The if statement is control statement which helps programmers in decision making. The if statement uses boolean expression in making decision whether a particular statement would execute or not. This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skips if block and rest code of program is executed. 

Introduction to Control Statements in Java


Control statements decide flow of a program

JAVA CONTROL STATEMENTS

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:

Thursday, 24 January 2013

Java Program to convert Lower Case Letter in to Uppper Case

Conversion of Lower Case letter to UpperCase in JAVA

toUpperCase(char ch) and toLowerCase(char ch) functions in Java


Syntax: public static char toUpperCase(char ch)


Converts the character argument to uppercase using case mapping information from the UnicodeData file. Note that Character.isUpperCase (Character.toUpperCase(ch)) does not always return true for some ranges of characters, particularly those that are symbols or

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

ADD TWO NUMBERS USING JAVA

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(System.in);
      //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);
   }
}

Output:

Enter two integers to calculate the sum
10
15
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
   }
}


Output:

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.

Separator
Name
Use
.
Period
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.
,
Comma
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.
;
Semicolon
It is used to terminate the statement in Java.
()
Parenthesis
This holds the list of parameters in method definition. Also used in control statements & type casting.
{}
Braces
This is used to define the block/scope of code, class, methods.
[]
Brackets
It is used in array declaration.
Separators in Java

Monday, 14 January 2013

Java Operators

Operators in Java

Operators Supported by Java Language


Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java supports a rich set of operators. Some of them are =, +, -, *. An Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical expressions. 
Java operators can be classified into a number of related categories as below:

Arithmetic Operators
+      Additive operator (also used for String concatenation)
-       Subtraction operator
*       Multiplication operator
/       Division operator
%     Remainder operator


Relational Operators
==    Equal to
!=     Not equal to
>      Greater than
>=    Greater than or equal to
<      Less than
<=    Less than or equal to


Logical Operators
&&   Logical AND
||       Logical OR
!       Logical NOT


Assignment Operators
=      Assignment

Increment and decrement Operators
++   Adds 1 to the Operand
--     Subtracts 1 from the Operand

Conditional Operators
?:    Ternary (shorthand for if-then-else statement)

Bitwise Operators
~     Unary bitwise complement
<<   Signed left shift
>>   Signed right shift
>>> Unsigned right shift
&     Bitwise AND
^      Bitwise exclusive OR
|       Bitwise inclusive OR

Special Operators
. (Dot Operator)   - To access instance variables
instanceof             - Object reference Operator

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

The basic evaluation procedure includes two left-to-right passes through the expression. During the first pass, the high priority operators (if any) are applied as they are encountered. During the second pass, the low priority operators (if any) are applied as they are encountered.

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.
Examples:

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. 

Example
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. 
              Example: 
                       average
                       sum
  • When more than one word are used in a name, the second and subsequent words are marked with a leading uppercase letters. 
              Example: 
                       dayTemperature
                       firstDayOfMonth
                       totalMarks
  • All private and local variables use only lowercase letters combined with underscores.
              Example: 
                       length
                       Batch_strength
  • All classes and interfaces start with a leading uppercase letter(and each subsequent word with a leading uppercase letter).
Example: 
                       Student
                       HelloJava
                       Vehicle
                       MotorCycle
  • Variables that represent constant values use all uppercase letters and underscores between words.
Example: 
                       TOTAL
                       F_MAX
                       PRINCIPAL_AMOUNT
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:

Valid
Invalid
HelloWorld
Hello World (uses a space)
Hi_JAVA
Hi JAVA! (uses a space and punctuation mark)
value3
3value(begins with a number)
Tall
short (this is a Java keyword)
$age
#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.


abstract
double
int
switch
assert
else
interface
synchronized
boolean
extends
long
this
break
false
native
throw
byte
final
new
transient
case
finally
package
true
catch
float
private
try
char
for
protected
void
class
goto
public
volatile
const
if
return
while
continue
implements
short
default
import
static
do
instanceof
super


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. 




Thursday, 10 January 2013

Java Tokens

Tokens used in Java Programs

Reserved Keywords, Identifiers, Literals, Operators, Separators


A Java program is basically a collection of classes. A class is defined by a set of declaration statements and methods containing executable statements. Most statements contain expressions, which describe the actions carried out on data. Smallest individual unit in a program are known as tokens. The compiler recognizes them for building up expressions and statements. 

Java Character Set


The smallest units of Java language are the characters used to write Java tokens. These characters are defined by the Unicode character set, and emerging standard that tries to create characters for a large number of scripts world wide.
The Unicode is a 16-bit character coding system and currently supports more than 34,000 defined characters derived from 24 languages from America, Europe, Middle East, Africa and Asia. However, most of us use only  the basic ASCII characters, which include letters, digits and punctuation marks, used in normal English. We therefore, have used only ASCII character character set (a subset of UNICODE character set) in developing the programs. 

Java language includes five types of tokens and they are:



Monday, 7 January 2013

Data Types in Java

Different Data Types used in Java

Data type defines a set of permitted values on which the legal operations can be performed.

There are two data types available in Java:

  • Primitive Data Types
  • Reference/Object Data Types

Primitive Data Types


     Primitive Data Types defines 8 simple types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups.

Integer:

This groups include byte, short, int, and long which are for whole valued signed number. 

Floating:

This group includes float and double, which represents numbers with fractional precision. 

Characters:

This group includes char, which respresents symbls in a character set like letters and numbers. 

Boolean:

This group includes boolean, which is a special type for representing true/false.

Data Type Default Value (for fields) Size (in bits) Minimum Range Maximum Range
 byte  0 8 bits  -128  +127
 short  0 16 bits  -32768  +32767
 int  0 32 bits  -2147483648  +2147483647
 long  0L 64 bits  -9223372036854775808  +9223372036854775807
 float  0.0f 32-bit 1.40129846432481707e-45  3.40282346638528860e+38
 double  0.0d 64-bit  4.94065645841246544e-324d  1.79769313486231570e+308d
 char  '\u0000' 16-bit  0 to 65,535
 boolean  false 1- bit  NA  NA

Reference Data Types


     Reference variables are created using defined constructors of the classes. They are used to access objects. Class objects, and various type of array variables come under reference data type. Default value of any reference variable is null. These non-primitive types are often called "reference types" because they are handled "by reference"--in other words, the address of the object or array is stored in a variable, passed to methods, and so on. By comparison, primitive types are handled "by value"--the actual primitive values are stored in variables and passed to methods. The reference data types are arrays, classes and interfaces that are made and handle according to a programmer in a java program  which can hold the three kind of values as:

    • Array Type
    • class type
    • Interface Type

        Saturday, 5 January 2013

        Creating First Java Application

        Java Simple Hello World! Program

        A program to print the Hello World! message on the Computer screen.


        You can use the notepad as an editor to write your first program. Read the below codes and carefully write on your editor as Java is case sensitive.


        Hello World! code


        class HelloWorld {
            public static void main (String args[]) {
        System.out.println(“Hello World!”);
            }
         }

        This is the simple base program of Java. I will explain you line by line to get an idea about the unique features that constitute a Java Program. 

        Class Declaration: class HelloWorld


        This line declares a class, which is an object oriented construct. We must place all codes inside a class in Java. class is a keyword and declares that a new class definition follows. HelloWorld is the Java identifier that specifies the name of the class to be defined. 

        Opening and Closing Braces :{  }


        Every class definition in Java begins wih an opening brace "{" and ends with a matching closing brace "}", appearing in the last line in the example.

        The Main Line: public static void main (String args[])


        This line defines a method named main. Conceptually, this is similar to the main() fuctnion in C and C++; Every Java application program must include main() method. This is the starting point for the interpreter to begin the execution of the program. 

        public : The keyword public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes.
        static:  Static declares this method as one that belongs to the entire class and not a part of any objects of the class. The main method must always be declared as static since the interpreter uses this method before any objects are created. 
        void: The type modifier void states that the main method does not return any value.

        The Output Line: System.out.println(“Hello World!”);


        This is similar to a printf() statement in C++. Since Java is Object Oriented, every method must be part of an object. The println() method is member of the out object, which is a static data member of System class. 

        Every Java statement must end with a semicolon.

        Note: We must save this program in a file called HelloWorld.java ensuring that the file name contains class name properly. This file is called the source file. If the program contains multiple classes, the file name must be the class name of the class containing the main method. 

        Compiling the Program


        To compile the Program, we should run the Java Compiler javac with the name of then source file on the command line as shown below:
        javac HelloWorld.java

        Running the Program


        We need to use the Java interpreter to run stand alone program. See the below line. 

        java Helloworld


        Output: 

        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        HelloWorld!

        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        Friday, 4 January 2013

        Changing the PATH Environment Variable

        Setting up PATH for Java Program


        We may have to set the PATH for environment variables for the easier execution of the Java Program. 


        We can run the JDK without setting the Environment variable. However, it is easy to compile and run the codes written in java after setting the PATH. If you do not set the PATH variable, you need to specify the full path to the executable file every time you run it. 

        Eg: C:\> "C:\Program Files\Java\jdk1.7.0\bin\javac" MyProgram.java

        To set the PATH variable permanently, add the full path of the jdk1.7.0\bin directory to the PATH variable. Typically, this full path looks something like C:\Program Files\Java\jdk1.7.0\bin. Set the PATH variable as follows on Microsoft Windows:

        1. Click Start, then Control Panel, then System.
        2. Select Advanced, then Environment Variables.
        3. Add the location of the bin folder of the JDK installation for the PATH variable in System Variables. The following is a typical value for the PATH variable:
        C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Java\jdk1.7.0\bin

        Notes: You can add multiple directories separated with semicolons(;).
              PATH Environment variables are Not Case Sensitive. 

        Installing Java

        How to Install Java on a Windows Computer


        The following instructions show how to install Java jdk to run your first Java Program


        1. Click here to open a page where you can download Java directly from Oracle. 
        2. Find the latest version, by the time I write this, the latest available on the page is "Java SE7u10". 
        3. Click on the download tab and save a known location in your Computer. 
        4. Make sure that that its byte size provided on the download page. After the download has completed, verify that you have downloaded the full, uncorrupted software file.
        5. Double Click the downloaded file to start the installer. 
        6. Follow the instructions on the Installer Wizard to complete the installation. 
        Note: The JDK installer will automatically set path for the environmental variable. No need to worry about the path as of now.

        Thursday, 3 January 2013

        Object Oriented Programming Vs Procedure Oriented Programming

        Difference between Object Oriented Programming and Procedure Oriented Programming


        What is the difference between object oriented programming and procedure oriented programming?


        Procedural Oriented Programming(POP)


        Procedural Oriented Programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. The program is divided into small parts called functions. Full importance is not given to data but to functions as well as sequence of actions to be done. It follows Top Down approach and it does not have any access specifier. When using Procedure Oriented Programming, data can move freely from function to function in the system. However, it is difficult to add data and function on a later point of time. The functions in the Procedure Oriented Programming uses Global data for sharing that can be accessed freely from function to function in the system. Hence the system does not have an option to hide the data and it leads to insecurity.

        Object Oriented Programming (OOPs)


        Object Oriented Programming is made up of many entities called objects. Objects become the fundamental units and have behavior, or a specific purpose, associated with them. Importance is given to the data rather than procedures or functions because it works as a real world. It follows Bottom Up approach and has access specifiers named Public, Private, Protected, etc. In Object Oriented Programming, objects can move and communicate with each other through member functions. This design provides easy way to add new functions. Data cannot move easily from function to function, it can be kept public or private so we can control the access of data which provides higher data security. There are so many other features available in Object Oriented Programming compared to traditional Procedure Oriented Programming; some of them are as follows. 

        The ability to create GUI (Graphical User Interface) programs

        Through inheritance, we can eliminate redundant code and extend the use of existing classes.

        We can build programs from standard working modules that communicate with one another rather than, having to start writing the code from scratch. This leads to saving of development time and higher productivity.

        Software complexity can be easily managed.