C Programming

C is a general-purpose high level language that was originally developed by Dennis Ritchie for the Unix operating system. It was first implemented on the Digital Eqquipment Corporation PDP-11 computer in 1972.


Learn more

C programming is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers.

why to Learn C Programming?


C programming language is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Software Development Domain. I will list down some of the key advantages of learning C Programming: Easy to learn Structured language It produces efficient programs It can handle low-level activities It can be compiled on a variety of computer platforms

Facts about C


C was invented to write an operating system called UNIX. C is a successor of B language which was introduced around the early 1970s. The language was formalized in 1988 by the American National Standard Institute (ANSI). The UNIX OS was totally written in C. Today C is the most widely used and popular System Programming Language. Most of the state-of-the-art software have been implemented using C. Today's most popular Linux OS and RDBMS MySQL have been written in C.

Hello World using C Programming.

Just to give you a little excitement about C programming, I'm going to give you a small conventional C Programming Hello World program, You can try it using Demo link.
Live Demo
#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");
return 0;
}

Applications of C Programming

C was initially used for system development work, particularly the programs that make-up the operating system. C was adopted as a system development language because it produces code that runs nearly as fast as the code written in assembly language. Some examples of the use of C are -
  • Operating Systems
  • Language Compilers
  • Assemblers
  • Text Editors
  • Print Spoolers
  • Network Drivers
  • Modern Programs
  • Databases
  • Language Interpreters
  • Utilities

You have seen the basic structure of a C program, so it will be easy to understand other basic building blocks of the C programming language.

Tokens in C


A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following C statement consists of five tokens − printf("Hello, World! \n");
The individual tokens are − printf ( "Hello, World! \n" ) ;

Semicolons


In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity. Given below are two different statements − printf("Hello, World! \n"); return 0;

Comments


Comments are like helping text in your C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below − /* my first program in C */ You cannot have comments within comments and they do not occur within a string or character literals.

Identifiers


A C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z, a to z, or an underscore '_' followed by zero or more letters, underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers − mohd zara abc move_name a_123 myname50 _temp j a23b9 retVal

Keywords


The following list shows the reserved words in C. These reserved words may not be used as constants or variables or any other identifier names.
auto, else, long, switch, break, enum, register, typedef, case, extern, return, union, char, float, shor, unsigned, const, for, signed, void, continue, goto, sizeof, volatile, default, if, static, while, do, int, struct, _Packed, double.

Whitespace in C


A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement − int age; there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement − fruit = apples + oranges; // get the total fruit no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish to increase readability.

Input and Output

In C programming you can use scanf() and printf() predefined function to read and print data respectively.
Example:

                      
                          #include<stdio.h>
                          void main()
                          {
                              int a,b,c;
                              printf("please enter any two number:");
                              scanf("%d %d",&a,&b);
                              c=a+b;
                              printf("the addition is:%d",c);
                          }
                      
                      

Output:
Please enter any two number: 2 5
the addition is:7


While dealing with the input/output operation in C,there are two important stream that play there role.These are:

  • standard input(stdin)
  • standard output(stdout)


Reading Character in C:
The easiest and simplest of all I/O operations are taking a character as input by reading that character from standard input (keybord). getchar() function can be used to read a single character.this function is alternate to scanf() function.
Syntax:
var_name=getchar();
Example:

                          
                              #include<stdio.h>
                              void main()
                              {
                                  char title;
                                  title=getchar();
                              }
                          
                      

There is another function to do that task for file:getc which is used to accept a character from standard input.


Syntax:
int getc(FILE *stream);


Writing Character in c:
Similar to getchar() there is another function used to write character,but on at a time.
Syntax:
putchar(var_name);
Example:


                          
                              #include<stdio.h>
                              void main()
                              {
                                  char result='p';
                                  putchar(result);
                                  putchar('\n');
                              }
                          
                      

Similarly there is another function putc which is used for sending a single character to the standard output.
Syntax:
int putc(int c,FILE *stream);


Formatted Input
it refer to the input data which can be arranged in specific format.this is possible in C using scanf().we have already encountered this and familier with this function.
Syntax:
scanf("control string",arg1,arg2,....,argn);
The field specification for reading integer nputted number is:%w sd
heres the % sign denote the conversion specification ;w specifies the integer number that defines no. to be read in integer format.
Example:

                           
                               #include<stdio.h>
                               void main()
                               {
                                   int var1=60;
                                   int var2=1234;
                                   scanf("%2d %5d",var1,var2);
                               }
                           
                       

Reading and Writing string in c:
There are two popular library functions gets() and puts() provides to deal with the string in C.
- gets:The char *gets(char *str) read the line from stdin and keeps the string pointed to by the the str and is terminated when the new line is read or EOF is reached.the declaration of gets() function is:
Syntax:
int puts(const char *str)
where str is the string to be written in c.

Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows −

Sr.No. Types & Description
1

Basic Types

They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types.

2

Enumerated types

They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program.

3

The type void

The type specifier void indicates that no value is available.

4

Derived types

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

The array types and structure types are referred collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see the basic types in the following section, where as other types will be covered in the upcoming chapters.

Integer Types

The following table provides the details of standard integer types with their storage sizes and value ranges −

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes -9223372036854775808 to 9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size of various type on a machine using different constant defined in limits.h header file −

                        #include <stdio.h>
                        #include <stdlib.h>
                        #include <limits.h>
                        #include <float.h>

                        int main(int argc, char** argv) {

                            printf("CHAR_BIT    :   %d\n", CHAR_BIT);
                            printf("CHAR_MAX    :   %d\n", CHAR_MAX);
                            printf("CHAR_MIN    :   %d\n", CHAR_MIN);
                            printf("INT_MAX     :   %d\n", INT_MAX);
                            printf("INT_MIN     :   %d\n", INT_MIN);
                            printf("LONG_MAX    :   %ld\n", (long) LONG_MAX);
                            printf("LONG_MIN    :   %ld\n", (long) LONG_MIN);
                            printf("SCHAR_MAX   :   %d\n", SCHAR_MAX);
                            printf("SCHAR_MIN   :   %d\n", SCHAR_MIN);
                            printf("SHRT_MAX    :   %d\n", SHRT_MAX);
                            printf("SHRT_MIN    :   %d\n", SHRT_MIN);
                            printf("UCHAR_MAX   :   %d\n", UCHAR_MAX);
                            printf("UINT_MAX    :   %u\n", (unsigned int) UINT_MAX);
                            printf("ULONG_MAX   :   %lu\n", (unsigned long) ULONG_MAX);
                            printf("USHRT_MAX   :   %d\n", (unsigned short) USHRT_MAX);

                            return 0;
                        }
                        

When you compile and execute the above program, it produces the following result on Linux −

                        CHAR_BIT    :   8
                        CHAR_MAX    :   127
                        CHAR_MIN    :   -128
                        INT_MAX     :   2147483647
                        INT_MIN     :   -2147483648
                        LONG_MAX    :   9223372036854775807
                        LONG_MIN    :   -9223372036854775808
                        SCHAR_MAX   :   127
                        SCHAR_MIN   :   -128
                        SHRT_MAX    :   32767
                        SHRT_MIN    :   -32768
                        UCHAR_MAX   :   255
                        UINT_MAX    :   4294967295
                        ULONG_MAX   :   18446744073709551615
                        USHRT_MAX   :   65535
                        

Floating-Point Types

The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision −

Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. The following example prints the storage space taken by a float type and its range values −

                        #include <stdio.h>
                        #include <stdlib.h>
                        #include <limits.h>
                        #include <float.h>

                        int main(int argc, char** argv) {

                            printf("Storage size for float : %d \n", sizeof(float));
                            printf("FLT_MAX     :   %g\n", (float) FLT_MAX);
                            printf("FLT_MIN     :   %g\n", (float) FLT_MIN);
                            printf("-FLT_MAX    :   %g\n", (float) -FLT_MAX);
                            printf("-FLT_MIN    :   %g\n", (float) -FLT_MIN);
                            printf("DBL_MAX     :   %g\n", (double) DBL_MAX);
                            printf("DBL_MIN     :   %g\n", (double) DBL_MIN);
                            printf("-DBL_MAX     :  %g\n", (double) -DBL_MAX);
                            printf("Precision value: %d\n", FLT_DIG );

                            return 0;
                        }
                        

When you compile and execute the above program, it produces the following result on Linux −

                        Storage size for float : 4 
                        FLT_MAX      :   3.40282e+38
                        FLT_MIN      :   1.17549e-38
                        -FLT_MAX     :   -3.40282e+38
                        -FLT_MIN     :   -1.17549e-38
                        DBL_MAX      :   1.79769e+308
                        DBL_MIN      :   2.22507e-308
                        -DBL_MAX     :  -1.79769e+308
                        Precision value: 6
                        

The void Type

The void type specifies that no value is available. It is used in three kinds of situations −

Sr.No. Types & Description
1

Function returns as void

There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);

2

Function arguments as void

There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, int rand(void);

3

Pointers to void

A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

Basic Structure of A program

A C program involves the following section:

  • Documentations(Documentation section).
  • Preprocessor statements(Link section).
  • Global Declarations(Defination section).
  • The main() function
    -local Declarations
    -Program statements & Expressions
  • User Defined functions

Let's begin with the simple C program code:

Sample code of C "Hello World" Program
Example:

  1. /*Write the words "Hello World" on the screen*/
  2. #include<stdio.h>
  3. #include<conio.h>
  4. void main()
  5. {
  6. printf("Hello World");
  7. return;
  8. }

Program Output:

Hello World //in Command Prompt


Let's look into various part of the above above C program:

  1. /*Comments*/
  2. Comments are a way of explaining what makes a program,the compilers ignore the comments and used by other to understand the code or

    this is a comment block,which is ignore by the compilers.Comment can be used anywhere in the program to add info about the program or code block,which will be useful for developers to understand the existing code in the future easily.


  3. #include <stdio.h>
  4. stdio is a standard for input/output,this allow us to use some commands which include a file called stdio.h
    or
    this is a Preprocessor command. that notify the compiler to include the header file stdio.h in the program before compiling the source code.


  5. int/void main()
  6. int/void is the return value which will be explain in a while.


  7. main()
  8. the main() is the main function where program execute begin.every c program must contains only one main function.
    or
    thos is the main function,which is default entry point for every c program and the void in front of it indicates that it does not return a value.


  9. braces
  10. Two curley brackets "{...}" are used to group all the statements.
    or
    Curley braces which shows how much the main() function has it's scope.


  11. printf()
  12. It is a function in c ,which prints text on the screen
    or
    This is another predefined function of c which is used to be displayed text string on the screen.


  13. return 0
  14. At the end of the main() return the value 0.



    The example discussed above illustrate hoe the simple C program looks like and how the program segment works.A C program may contains one or many section which discussed above.


    The documentation section usually contain the collection of comment line giving the name of the pogram,author's or programmer name and few othere details.
    The second part is the link section which instruct the compiler to connect to the various function from the system library.The defination section describe all the symbolic constants. The global declaration section is used to define those variable that are used globally within the entire program and is used in more than one functions.then comes the main() function.All c program must have main() which have two parts:

    • Declaration part
    • Execution part

    The Declaration part is used to declare all the variable that will be used within the program.There needs to be atleast one statement in the executable part, and this two parts will be declared within the opening and closing braces of the main().The execution of the program begins at the opening brace '{' and ends with the closing brace'}' .Also,it has to be noted that all the statement of these two parts need to be terminated with the semicolon.

    The sub-program section deal with all user-define functions that are called from main().These user defined functions are declared and usually defined after the main() function.

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. Based on the basic types explained in the previous chapter, there will be the following basic variable types −

Sr.No. Type & Description
1

char

Typically a single octet(one byte). It is an integer type.

2

int

The most natural size of integer for the machine.

3

float

A single-precision floating point value.

4

double

A double-precision floating point value.

5

void

Represents the absence of type.

C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.

Variable Definition in C

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −

                    type variable_list;
                    

Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −

                    int    i, j, k;
                    char   c, ch;
                    float  f, salary;
                    double d;
                    

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −

                    type variable_name = value;
                    

Some examples are −

                    extern int d = 3, f = 5;    // declaration of d and f. 
                    int d = 3, f = 5;           // definition and initializing d and f. 
                    byte z = 22;                // definition and initializes z. 
                    char x = 'x';               // the variable x has the value 'x'.
                    

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.

A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

Example

Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −

                    #include <stdio.h>

                    // Variable declaration:
                    extern int a, b;
                    extern int c;
                    extern float f;

                    int main () {

                      /* variable definition: */
                      int a, b;
                      int c;
                      float f;
                    
                      /* actual initialization */
                      a = 10;
                      b = 20;
                      
                      c = a + b;
                      printf("value of c : %d \n", c);

                      f = 70.0/3.0;
                      printf("value of f : %f \n", f);
                    
                      return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    value of c : 30
                    value of f : 23.333334
                    

The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −

                    // function declaration
                    int func();

                    int main() {

                      // function call
                      int i = func();
                    }

                    // function definition
                    int func() {
                      return 0;
                    }
                    

Lvalues and Rvalues in C

There are two kinds of expressions in C −

  • lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.

  • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

                    int g = 20; // valid statement

                    10 = 20; // invalid statement; would generate compile-time error
                  

Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.

Constants are treated just like regular variables except that their values cannot be modified after their definition.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals −

                    212         /* Legal */
                    215u        /* Legal */
                    0xFeeL      /* Legal */
                    078         /* Illegal: 8 is not an octal digit */
                    032UU       /* Illegal: cannot repeat a suffix */
                    

Following are other examples of various types of integer literals −

                    85         /* decimal */
                    0213       /* octal */
                    0x4b       /* hexadecimal */
                    30         /* int */
                    30u        /* unsigned int */
                    30l        /* long */
                    30ul       /* unsigned long */
                    

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.

While representing decimal form, you must include the decimal point, the exponent, or both; and while representing exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals −

                    3.14159       /* Legal */
                    314159E-5L    /* Legal */
                    510E          /* Illegal: incomplete exponent */
                    210f          /* Illegal: no decimal or exponent */
                    .e55          /* Illegal: missing integer or fraction */
                    

Character Constants

Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type.

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').

There are certain characters in C that represent special meaning when preceded by a backslash for example, newline (\n) or tab (\t).

Following is the example to show a few escape sequence characters −

                    #include <stdio.h>

                    int main() {
                      printf("Hello\tWorld\n\n");

                      return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Hello World
                    

String Literals

String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.

You can break a long line into multiple lines using string literals and separating them using white spaces.

Here are some examples of string literals. All the three forms are identical strings.

                    "hello, dear"

                    "hello, \

                    dear"

                    "hello, " "d" "ear"
                    

Defining Constants

There are two simple ways in C to define constants −

  • Using #define preprocessor.

  • Using const keyword.

The #define Preprocessor

Given below is the form to use #define preprocessor to define a constant −

                    #define identifier value
                    

The following example explains it in detail −

                    #include <stdio.h>

                    #define LENGTH 10   
                    #define WIDTH  5
                    #define NEWLINE '\n'

                    int main() {
                      int area;  
                      
                      area = LENGTH * WIDTH;
                      printf("value of area : %d", area);
                      printf("%c", NEWLINE);

                      return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    value of area : 50
                    

The const Keyword

You can use const prefix to declare constants with a specific type as follows −

                    const type variable = value;
                    

The following example explains it in detail −

                    #include <stdio.h>

                    int main() {
                      const int  LENGTH = 10;
                      const int  WIDTH = 5;
                      const char NEWLINE = '\n';
                      int area;  
                      
                      area = LENGTH * WIDTH;
                      printf("value of area : %d", area);
                      printf("%c", NEWLINE);

                      return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    value of area : 50
                  

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −

Loop Architecture

C programming language provides the following types of loops to handle looping requirements.

Sr.No. Loop Type & Description
1 while loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 do...while loop

It is more like a while statement, except that it tests the condition at the end of the loop body.

4 nested loops

You can use one or more loops inside any other while, for, or do..while loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C supports the following control statements.

Sr.No. Control Statement & Description
1 break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 goto statement

Transfers control to the labeled statement.

The Infinite Loop

A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty.

                    #include <stdio.h>
                    
                    int main () {

                      for( ; ; ) {
                          printf("This loop will run forever.\n");
                      }

                      return 0;
                    }
                    

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.

A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function

The general form of a function definition in C programming language is as follows −

                    return_type function_name( parameter list ) {
                       body of the function
                    }
                    

A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −

  • Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

  • Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

  • Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

  • Function Body − The function body contains a collection of statements that define what the function does.

Example

Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two −

                    /* function returning the max between two numbers */
                    int max(int num1, int num2) {
                    
                       /* local variable declaration */
                       int result;
                     
                       if (num1 > num2)
                          result = num1;
                       else
                          result = num2;
                     
                       return result; 
                    }
                    

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

                    return_type function_name( parameter list );
                    

For the above defined function max(), the function declaration is as follows −

                    int max(int num1, int num2);
                    

Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −

                    int max(int, int);
                    

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example −

                    #include <stdio.h>
                     
                    /* function declaration */
                    int max(int num1, int num2);
                     
                    int main () {
                    
                       /* local variable definition */
                       int a = 100;
                       int b = 200;
                       int ret;
                     
                       /* calling a function to get max value */
                       ret = max(a, b);
                     
                       printf( "Max value is : %d\n", ret );
                     
                       return 0;
                    }
                     
                    /* function returning the max between two numbers */
                    int max(int num1, int num2) {
                    
                       /* local variable declaration */
                       int result;
                     
                       if (num1 > num2)
                          result = num1;
                       else
                          result = num2;
                     
                       return result; 
                    }
                    

We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result −

                    Max value is : 200
                    

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways in which arguments can be passed to a function −

Sr.No. Call Type & Description
1 Call by value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2 Call by reference

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.

target="_blank" rel="nofollow" class="demo"> Live Demo
                  #include <stdio.h>
                   
                  int main () {
                  
                     int n[ 10 ]; /* n is an array of 10 integers */
                     int i,j;
                   
                     /* initialize elements of array n to 0 */         
                     for ( i = 0; i < 10; i++ ) {
                        n[ i ] = i + 100; /* set element at location i to i + 100 */
                     }
                     
                     /* output each array element's value */
                     for (j = 0; j < 10; j++ ) {
                        printf("Element[%d] = %d\n", j, n[j] );
                     }
                   
                     return 0;
                  }
                  

When the above code is compiled and executed, it produces the following result −

                  Element[0] = 100
                  Element[1] = 101
                  Element[2] = 102
                  Element[3] = 103
                  Element[4] = 104
                  Element[5] = 105
                  Element[6] = 106
                  Element[7] = 107
                  Element[8] = 108
                  Element[9] = 109
                  

Arrays in Detail

Arrays are important to C and should need a lot more attention. The following important concepts related to array should be clear to a C programmer −

Sr.No. Concept & Description
1 Multi-dimensional arrays

C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

3 Return array from a function

C allows a function to return an array.

4 Pointer to an array

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.

As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined −

                    #include <stdio.h>
                    
                    int main () {
                    
                       int  var1;
                       char var2[10];
                    
                       printf("Address of var1 variable: %x\n", &var1  );
                       printf("Address of var2 variable: %x\n", &var2  );
                    
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Address of var1 variable: bff5a400
                    Address of var2 variable: bff5a3f6
                    

What are Pointers?

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −

                    type *var-name;
                    

Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations −

                    int    *ip;    /* pointer to an integer */
                    double *dp;    /* pointer to a double */
                    float  *fp;    /* pointer to a float */
                    char   *ch     /* pointer to a character */
                    

The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.

How to Use Pointers?

There are a few important operations, which we will do with the help of pointers very frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. The following example makes use of these operations −

                    #include <stdio.h>
                    
                    int main () {
                    
                       int  var = 20;   /* actual variable declaration */
                       int  *ip;        /* pointer variable declaration */
                    
                       ip = &var;  /* store address of var in pointer variable*/
                    
                       printf("Address of var variable: %x\n", &var  );
                    
                       /* address stored in pointer variable */
                       printf("Address stored in ip variable: %x\n", ip );
                    
                       /* access the value using the pointer */
                       printf("Value of *ip variable: %d\n", *ip );
                    
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Address of var variable: bffd8b3c
                    Address stored in ip variable: bffd8b3c
                    Value of *ip variable: 20
                    

NULL Pointers

It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.

The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program −

                    #include <stdio.h>
                    
                    int main () {
                    
                       int  *ptr = NULL;
                    
                       printf("The value of ptr is : %x\n", ptr  );
                     
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    The value of ptr is 0
                    

In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.

To check for a null pointer, you can use an 'if' statement as follows −

                    if(ptr)     /* succeeds if p is not null */
                    if(!ptr)    /* succeeds if p is null */
                    

Pointers in Detail

Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer −

Sr.No. Concept & Description
1 Pointer arithmetic

There are four arithmetic operators that can be used in pointers: ++, --, +, -

2 Array of pointers

You can define arrays to hold a number of pointers.

3 Pointer to pointer

C allows you to have pointer on a pointer and so on.

4 Passing pointers to functions in C

Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function.

5 Return pointer from functions in C

C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well.

Arrays allow to define type of variables that can hold several data items of the same kind. Similarly structure is another user defined data type available in C that allows to combine data items of different kinds.

Structures are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −

  • Title
  • Author
  • Subject
  • Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member. The format of the struct statement is as follows −

                    struct [structure tag] {
                    
                       member definition;
                       member definition;
                       ...
                       member definition;
                    } [one or more structure variables];  
                    

The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure's definition, before the final semicolon, you can specify one or more structure variables but it is optional. Here is the way you would declare the Book structure −

                    struct Books {
                       char  title[50];
                       char  author[50];
                       char  subject[100];
                       int   book_id;
                    } book;  
                    

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use the keyword struct to define variables of structure type. The following example shows how to use a structure in a program −

                    #include <stdio.h>
                    #include <string.h>
                     
                    struct Books {
                       char  title[50];
                       char  author[50];
                       char  subject[100];
                       int   book_id;
                    };
                     
                    int main( ) {
                    
                       struct Books Book1;        /* Declare Book1 of type Book */
                       struct Books Book2;        /* Declare Book2 of type Book */
                     
                       /* book 1 specification */
                       strcpy( Book1.title, "C Programming");
                       strcpy( Book1.author, "Nuha Ali"); 
                       strcpy( Book1.subject, "C Programming Tutorial");
                       Book1.book_id = 6495407;
                    
                       /* book 2 specification */
                       strcpy( Book2.title, "Telecom Billing");
                       strcpy( Book2.author, "Zara Ali");
                       strcpy( Book2.subject, "Telecom Billing Tutorial");
                       Book2.book_id = 6495700;
                     
                       /* print Book1 info */
                       printf( "Book 1 title : %s\n", Book1.title);
                       printf( "Book 1 author : %s\n", Book1.author);
                       printf( "Book 1 subject : %s\n", Book1.subject);
                       printf( "Book 1 book_id : %d\n", Book1.book_id);
                    
                       /* print Book2 info */
                       printf( "Book 2 title : %s\n", Book2.title);
                       printf( "Book 2 author : %s\n", Book2.author);
                       printf( "Book 2 subject : %s\n", Book2.subject);
                       printf( "Book 2 book_id : %d\n", Book2.book_id);
                    
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Book 1 title : C Programming
                    Book 1 author : Nuha Ali
                    Book 1 subject : C Programming Tutorial
                    Book 1 book_id : 6495407
                    Book 2 title : Telecom Billing
                    Book 2 author : Zara Ali
                    Book 2 subject : Telecom Billing Tutorial
                    Book 2 book_id : 6495700
                    

Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other variable or pointer.

                    #include <stdio.h>
                    #include <string.h>
                     
                    struct Books {
                       char  title[50];
                       char  author[50];
                       char  subject[100];
                       int   book_id;
                    };
                    
                    /* function declaration */
                    void printBook( struct Books book );
                    
                    int main( ) {
                    
                       struct Books Book1;        /* Declare Book1 of type Book */
                       struct Books Book2;        /* Declare Book2 of type Book */
                     
                       /* book 1 specification */
                       strcpy( Book1.title, "C Programming");
                       strcpy( Book1.author, "Nuha Ali"); 
                       strcpy( Book1.subject, "C Programming Tutorial");
                       Book1.book_id = 6495407;
                    
                       /* book 2 specification */
                       strcpy( Book2.title, "Telecom Billing");
                       strcpy( Book2.author, "Zara Ali");
                       strcpy( Book2.subject, "Telecom Billing Tutorial");
                       Book2.book_id = 6495700;
                     
                       /* print Book1 info */
                       printBook( Book1 );
                    
                       /* Print Book2 info */
                       printBook( Book2 );
                    
                       return 0;
                    }
                    
                    void printBook( struct Books book ) {
                    
                       printf( "Book title : %s\n", book.title);
                       printf( "Book author : %s\n", book.author);
                       printf( "Book subject : %s\n", book.subject);
                       printf( "Book book_id : %d\n", book.book_id);
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Book title : C Programming
                    Book author : Nuha Ali
                    Book subject : C Programming Tutorial
                    Book book_id : 6495407
                    Book title : Telecom Billing
                    Book author : Zara Ali
                    Book subject : Telecom Billing Tutorial
                    Book book_id : 6495700
                    

Pointers to Structures

You can define pointers to structures in the same way as you define pointer to any other variable −

                    struct Books *struct_pointer;
                    

Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the '&'; operator before the structure's name as follows −

                    struct_pointer = &Book1;
                    

To access the members of a structure using a pointer to that structure, you must use the → operator as follows −

                    struct_pointer->title;
                    

Let us re-write the above example using structure pointer.

                    #include <stdio.h>
                    #include <string.h>
                     
                    struct Books {
                       char  title[50];
                       char  author[50];
                       char  subject[100];
                       int   book_id;
                    };
                    
                    /* function declaration */
                    void printBook( struct Books *book );
                    int main( ) {
                    
                       struct Books Book1;        /* Declare Book1 of type Book */
                       struct Books Book2;        /* Declare Book2 of type Book */
                     
                       /* book 1 specification */
                       strcpy( Book1.title, "C Programming");
                       strcpy( Book1.author, "Nuha Ali"); 
                       strcpy( Book1.subject, "C Programming Tutorial");
                       Book1.book_id = 6495407;
                    
                       /* book 2 specification */
                       strcpy( Book2.title, "Telecom Billing");
                       strcpy( Book2.author, "Zara Ali");
                       strcpy( Book2.subject, "Telecom Billing Tutorial");
                       Book2.book_id = 6495700;
                     
                       /* print Book1 info by passing address of Book1 */
                       printBook( &Book1 );
                    
                       /* print Book2 info by passing address of Book2 */
                       printBook( &Book2 );
                    
                       return 0;
                    }
                    
                    void printBook( struct Books *book ) {
                    
                       printf( "Book title : %s\n", book->title);
                       printf( "Book author : %s\n", book->author);
                       printf( "Book subject : %s\n", book->subject);
                       printf( "Book book_id : %d\n", book->book_id);
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Book title : C Programming
                    Book author : Nuha Ali
                    Book subject : C Programming Tutorial
                    Book book_id : 6495407
                    Book title : Telecom Billing
                    Book author : Zara Ali
                    Book subject : Telecom Billing Tutorial
                    Book book_id : 6495700
                    

Bit Fields

Bit Fields allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium. Typical examples include −

  • Packing several objects into a machine word. e.g. 1 bit flags can be compacted.

  • Reading external file formats -- non-standard file formats could be read in, e.g., 9-bit integers.

C allows us to do this in a structure definition by putting :bit length after the variable. For example −

                    struct packed_struct {
                       unsigned int f1:1;
                       unsigned int f2:1;
                       unsigned int f3:1;
                       unsigned int f4:1;
                       unsigned int type:4;
                       unsigned int my_int:9;
                    } pack;
                    

Here, the packed_struct contains 6 members: Four 1 bit flags f1..f3, a 4-bit type and a 9-bit my_int.

C automatically packs the above bit fields as compactly as possible, provided that the maximum length of the field is less than or equal to the integer word length of the computer. If this is not the case, then some compilers may allow memory overlap for the fields while others would store the next field in the next word.

Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.

                    void recursion() {
                       recursion(); /* function calls itself */
                    }
                    
                    int main() {
                       recursion();
                    }
                    

The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.

Number Factorial

The following example calculates the factorial of a given number using a recursive function −

                    #include <stdio.h>
                    
                    unsigned long long int factorial(unsigned int i) {
                    
                       if(i <= 1) {
                          return 1;
                       }
                       return i * factorial(i - 1);
                    }
                    
                    int  main() {
                       int i = 12;
                       printf("Factorial of %d is %d\n", i, factorial(i));
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    Factorial of 12 is 479001600
                    

Fibonacci Series

The following example generates the Fibonacci series for a given number using a recursive function −

                    #include <stdio.h>
                    
                    int fibonacci(int i) {
                    
                       if(i == 0) {
                          return 0;
                       }
                      
                       if(i == 1) {
                          return 1;
                       }
                       return fibonacci(i-1) + fibonacci(i-2);
                    }
                    
                    int  main() {
                    
                       int i;
                      
                       for (i = 0; i < 10; i++) {
                          printf("%d\t\n", fibonacci(i));
                       }
                      
                       return 0;
                    }
                    

When the above code is compiled and executed, it produces the following result −

                    0	
                    1	
                    1	
                    2	
                    3	
                    5	
                    8	
                    13	
                    21	
                    34
                    


CPP Programming

C++ (/ˌsiːˌplʌsˈplʌs/) is a general-purpose programming language created by Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significantly over time, and modern C++ now has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation. It is almost always implemented as a compiled language, and many vendors provide C++ compilers, including the Free Software Foundation, LLVM, Microsoft, Intel, Oracle, and IBM, so it is available on many platforms.


Learn more

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.

C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.

C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.

C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

Note − A programming language is said to use static typing when type checking is performed during compile-time as opposed to run-time.

Object-Oriented Programming

C++ fully supports object-oriented programming, including the four pillars of object-oriented development −

  • Encapsulation
  • Data hiding
  • Inheritance
  • Polymorphism

Standard Libraries

Standard C++ consists of three important parts −

  • The core language giving all the building blocks including variables, data types and literals, etc.

  • The C++ Standard Library giving a rich set of functions manipulating files, strings, etc.

  • The Standard Template Library (STL) giving a rich set of methods manipulating data structures, etc.

The ANSI Standard

The ANSI standard is an attempt to ensure that C++ is portable; that code you write for Microsoft's compiler will compile without errors, using a compiler on a Mac, UNIX, a Windows box, or an Alpha.

The ANSI standard has been stable for a while, and all the major C++ compiler manufacturers support the ANSI standard.

Learning C++

The most important thing while learning C++ is to focus on concepts.

The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.

C++ supports a variety of programming styles. You can write in the style of Fortran, C, Smalltalk, etc., in any language. Each style can achieve its aims effectively while maintaining runtime and space efficiency.

Use of C++

C++ is used by hundreds of thousands of programmers in essentially every application domain.

C++ is being highly used to write device drivers and other software that rely on direct manipulation of hardware under realtime constraints.

C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts.

Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.

When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean.

  • Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors - wagging, barking, eating. An object is an instance of a class.

  • Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support.

  • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

C++ Program Structure

Let us look at a simple code that would print the words Hello World.

                      #include <iostream>
                      using namespace std;
                      
                      // main() is where program execution begins.
                      int main() {
                         cout << "Hello World"; // prints Hello World
                         return 0;
                      }
                      

Let us look at the various parts of the above program −

  • The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.

  • The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.

  • The next line '// main() is where program execution begins.' is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.

  • The line int main() is the main function where program execution begins.

  • The next line cout << "Hello World"; causes the message "Hello World" to be displayed on the screen.

  • The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

Compile and Execute C++ Program

Let's look at how to save the file, compile and run the program. Please follow the steps given below −

  • Open a text editor and add the code as above.

  • Save the file as: hello.cpp

  • Open a command prompt and go to the directory where you saved the file.

  • Type 'g++ hello.cpp' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.

  • Now, type 'a.out' to run your program.

  • You will be able to see ' Hello World ' printed on the window.

                      $ g++ hello.cpp
                      $ ./a.out
                      Hello World
                      

Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.

You can compile C/C++ programs using makefile. For more details, you can check our 'Makefile Tutorial'.

Semicolons and Blocks in C++

In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.

For example, following are three different statements −

                      x = y;
                      y = y + 1;
                      add(x, y);
                      

A block is a set of logically connected statements that are surrounded by opening and closing braces. For example −

                      {
                         cout << "Hello World"; // prints Hello World
                         return 0;
                      }
                      

C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where you put a statement in a line. For example −

                      x = y;
                      y = y + 1;
                      add(x, y);
                      

is the same as

                      x = y; y = y + 1; add(x, y);
                      

C++ Identifiers

A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).

C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case-sensitive programming language. Thus, Manpower and manpower are two different identifiers in C++.

Here are some examples of acceptable identifiers −

                      mohd       zara    abc   move_name  a_123
                      myname50   _temp   j     a23b9      retVal
                      

C++ Keywords

The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.

asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template  

Trigraphs

A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks.

Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives.

Following are most frequently used trigraph sequences −

Trigraph Replacement
??= #
??/ \
??' ^
??( [
??) ]
??! |
??< {
??> }
??- ~

All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.

Whitespace in C++

A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.

Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins.

Statement 1

                      int age;
                      

In the above statement there must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them.

Statement 2

                      fruit = apples + oranges;   // Get the total fruit
                      

In the above statement 2, no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive −

There are following basic types of variable in C++ as explained in last chapter −

Sr.No Type & Description
1

bool

Stores either value true or false.

2

char

Typically a single octet (one byte). This is an integer type.

3

int

The most natural size of integer for the machine.

4

float

A single-precision floating point value.

5

double

A double-precision floating point value.

6

void

Represents the absence of type.

7

wchar_t

A wide character type.

C++ also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.

Following section will cover how to define, declare and use various types of variables.

Variable Definition in C++

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −

                      type variable_list;
                      

Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any user-defined object, etc., and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −

                      int    i, j, k;
                      char   c, ch;
                      float  f, salary;
                      double d;
                      

The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −

                      type variable_name = value;
                      

Some examples are −

                      extern int d = 3, f = 5;    // declaration of d and f. 
                      int d = 3, f = 5;           // definition and initializing d and f. 
                      byte z = 22;                // definition and initializes z. 
                      char x = 'x';               // the variable x has the value 'x'.
                      

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.

Variable Declaration in C++

A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program.

A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.

Example

Try the following example where a variable has been declared at the top, but it has been defined inside the main function −

                      #include <iostream>
                      using namespace std;
                      
                      // Variable declaration:
                      extern int a, b;
                      extern int c;
                      extern float f;
                        
                      int main () {
                         // Variable definition:
                         int a, b;
                         int c;
                         float f;
                       
                         // actual initialization
                         a = 10;
                         b = 20;
                         c = a + b;
                       
                         cout << c << endl ;
                      
                         f = 70.0/3.0;
                         cout << f << endl ;
                       
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      30
                      23.3333
                      

Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −

                      // function declaration
                      int func();
                      int main() {
                         // function call
                         int i = func();
                      }
                      
                      // function definition
                      int func() {
                         return 0;
                      }
                      

Lvalues and Rvalues

There are two kinds of expressions in C++ −

  • lvalue − Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.

  • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.

Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement −

                      int g = 20;
                      

But the following is not a valid statement and would generate compile-time error −

                      10 4
                    

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program

  • auto
  • register
  • static
  • extern
  • mutable

The auto Storage Class

The auto storage class is the default storage class for all local variables.

                      {
                         int mount;
                         auto int month;
                      }
                      

The example above defines two variables with the same storage class, auto can only be used within functions, i.e., local variables.

The register Storage Class

The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).

                      {
                         register int  miles;
                      }
                      

The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.

In C++, when static is used on a class data member, it causes only one copy of that member to be shared by all objects of its class.

                      #include <iostream>
                       
                      // Function declaration
                      void func(void);
                       
                      static int count = 10; /* Global variable */
                       
                      main() {
                         while(count--) {
                            func();
                         }
                         
                         return 0;
                      }
                      
                      // Function definition
                      void func( void ) {
                         static int i = 5; // local static variable
                         i++;
                         std::cout << "i is " << i ;
                         std::cout << " and count is " << count << std::endl;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      i is 6 and count is 9
                      i is 7 and count is 8
                      i is 8 and count is 7
                      i is 9 and count is 6
                      i is 10 and count is 5
                      i is 11 and count is 4
                      i is 12 and count is 3
                      i is 13 and count is 2
                      i is 14 and count is 1
                      i is 15 and count is 0
                      

The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.

When you have multiple files and you define a global variable or function, which will be used in other files also, then extern will be used in another file to give reference of defined variable or function. Just for understanding extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

First File: main.cpp

                      #include <iostream>
                      int count ;
                      extern void write_extern();
                       
                      main() {
                         count = 5;
                         write_extern();
                      }
                      

Second File: support.cpp

                      #include <iostream>
                      
                      extern int count;
                      
                      void write_extern(void) {
                         std::cout << "Count is " << count << std::endl;
                      }
                      

Here, extern keyword is being used to declare count in another file. Now compile these two files as follows −

                      $g++ main.cpp support.cpp -o write
                      

This will produce write executable program, try to execute write and check the result as follows −

                      $./write
                      5
                      

The mutable Storage Class

The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provide the following types of operators −

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by C++ language −

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiplies both operands A * B will give 200
/ Divides numerator by de-numerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

Relational Operators

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

Logical Operators

There are following logical operators supported by C++ language.

Assume variable A holds 1 and variable B holds 0, then −

Show Examples

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows −

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A  = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −

Show Examples

Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 0000 1111

Assignment Operators

There are following assignment operators supported by C++ language −

Show Examples

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Misc Operators

The following table lists some other operators that C++ supports.

Sr.No Operator & Description
1

sizeof

sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4.

2

Condition ? X : Y

Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.

3

,

Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.

4

. (dot) and -> (arrow)

Member operators are used to reference individual members of classes, structures, and unions.

5

Cast

Casting operators convert one data type to another. For example, int(2.2000) would return 2.

6

&

Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable.

7

*

Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples

Category  Operator  Associativity 
Postfix  () [] -> . ++ - -   Left to right 
Unary  + - ! ~ ++ - - (type)* & sizeof  Right to left 
Multiplicative   * / %  Left to right 
Additive   + -  Left to right 
Shift   << >>  Left to right 
Relational   < <= > >=  Left to right 
Equality   == !=  Left to right 
Bitwise AND  Left to right 
Bitwise XOR  Left to right 
Bitwise OR  Left to right 
Logical AND  &&  Left to right 
Logical OR  ||  Left to right 
Conditional  ?:  Right to left 
Assignment  = += -= *= /= %=>>= <<= &= ^= |=  Right to left 
Comma  Left to right 

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −

Loop Architecture

C++ programming language provides the following type of loops to handle looping requirements.

Sr.No Loop Type & Description
1 while loop

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

2 for loop

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 do...while loop

Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

4 nested loops

You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C++ supports the following control statements.

Sr.No Control Statement & Description
1 break statement

Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 goto statement

Transfers control to the labeled statement. Though it is not advised to use goto statement in your program.

The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless loop by leaving the conditional expression empty.

                      #include <iostream>
                      using namespace std;
                       
                      int main () {
                         for( ; ; ) {
                            printf("This loop will run forever.\n");
                         }
                      
                         return 0;
                      }
                      

When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the ‘for (;;)’ construct to signify an infinite loop.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

Normally, when we work with Numbers, we use primitive data types such as int, short, long, float and double, etc. The number data types, their possible values and number ranges have been explained while discussing C++ Data Types.

Defining Numbers in C++

You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++ −

                      #include <iostream>
                      using namespace std;
                       
                      int main () {
                         // number definition:
                         short  s;
                         int    i;
                         long   l;
                         float  f;
                         double d;
                         
                         // number assignments;
                         s = 10;      
                         i = 1000;    
                         l = 1000000; 
                         f = 230.47;  
                         d = 30949.374;
                         
                         // number printing;
                         cout << "short  s :" << s << endl;
                         cout << "int    i :" << i << endl;
                         cout << "long   l :" << l << endl;
                         cout << "float  f :" << f << endl;
                         cout << "double d :" << d << endl;
                       
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      short  s :10
                      int    i :1000
                      long   l :1000000
                      float  f :230.47
                      double d :30949.4
                      

Math Operations in C++

In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.

C++ has a rich set of mathematical operations, which can be performed on various numbers. Following table lists down some useful built-in mathematical functions available in C++.

To utilize these functions you need to include the math header file <cmath>.

Sr.No Function & Purpose
1

double cos(double);

This function takes an angle (as a double) and returns the cosine.

2

double sin(double);

This function takes an angle (as a double) and returns the sine.

3

double tan(double);

This function takes an angle (as a double) and returns the tangent.

4

double log(double);

This function takes a number and returns the natural log of that number.

5

double pow(double, double);

The first is a number you wish to raise and the second is the power you wish to raise it t

6

double hypot(double, double);

If you pass this function the length of two sides of a right triangle, it will return you the length of the hypotenuse.

7

double sqrt(double);

You pass this function a number and it gives you the square root.

8

int abs(int);

This function returns the absolute value of an integer that is passed to it.

9

double fabs(double);

This function returns the absolute value of any decimal number passed to it.

10

double floor(double);

Finds the integer which is less than or equal to the argument passed to it.

Following is a simple example to show few of the mathematical operations −

                      #include <iostream>
                      #include <cmath>
                      using namespace std;
                       
                      int main () {
                         // number definition:
                         short  s = 10;
                         int    i = -1000;
                         long   l = 100000;
                         float  f = 230.47;
                         double d = 200.374;
                      
                         // mathematical operations;
                         cout << "sin(d) :" << sin(d) << endl;
                         cout << "abs(i)  :" << abs(i) << endl;
                         cout << "floor(d) :" << floor(d) << endl;
                         cout << "sqrt(f) :" << sqrt(f) << endl;
                         cout << "pow( d, 2) :" << pow(d, 2) << endl;
                       
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      sign(d)     :-0.634939
                      abs(i)      :1000
                      floor(d)    :200
                      sqrt(f)     :15.1812
                      pow( d, 2 ) :40149.7
                      

Random Numbers in C++

There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.

Following is a simple example to generate few random numbers. This example makes use of time() function to get the number of seconds on your system time, to randomly seed the rand() function −

                      #include <iostream>
                      #include <ctime>
                      #include <cstdlib>
                      
                      using namespace std;
                       
                      int main () {
                         int i,j;
                       
                         // set the seed
                         srand( (unsigned)time( NULL ) );
                      
                         /* generate 10  random numbers. */
                         for( i = 0; i < 10; i++ ) {
                            // generate actual random number
                            j = rand();
                            cout <<" Random Number : " << j << endl;
                         }
                      
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      Random Number : 1748144778
                      Random Number : 630873888
                      Random Number : 2134540646
                      Random Number : 219404170
                      Random Number : 902129458
                      Random Number : 920445370
                      Random Number : 1319072661
                      Random Number : 257938873
                      Random Number : 1256201101
                      Random Number : 580322989
                    

A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

A function is known with various names like a method or a sub-routine or a procedure etc.

Defining a Function

The general form of a C++ function definition is as follows −

                      return_type function_name( parameter list ) {
                         body of the function
                      }
                      

A C++ function definition consists of a function header and a function body. Here are all the parts of a function −

  • Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

  • Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

  • Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

  • Function Body − The function body contains a collection of statements that define what the function does.

Example

Following is the source code for a function called max(). This function takes two parameters num1 and num2 and return the biggest of both −

                      // function returning the max between two numbers
                       
                      int max(int num1, int num2) {
                         // local variable declaration
                         int result;
                       
                         if (num1 > num2)
                            result = num1;
                         else
                            result = num2;
                       
                         return result; 
                      }
                      

Function Declarations

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts −

                      return_type function_name( parameter list );
                      

For the above defined function max(), following is the function declaration −

                      int max(int num1, int num2);
                      

Parameter names are not important in function declaration only their type is required, so following is also valid declaration −

                      int max(int, int);
                      

Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function

While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.

When a program calls a function, program control is transferred to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example −

                      #include <iostream>
                      using namespace std;
                       
                      // function declaration
                      int max(int num1, int num2);
                       
                      int main () {
                         // local variable declaration:
                         int a = 100;
                         int b = 200;
                         int ret;
                       
                         // calling a function to get max value.
                         ret = max(a, b);
                         cout << "Max value is : " << ret << endl;
                       
                         return 0;
                      }
                       
                      // function returning the max between two numbers
                      int max(int num1, int num2) {
                         // local variable declaration
                         int result;
                       
                         if (num1 > num2)
                            result = num1;
                         else
                            result = num2;
                       
                         return result; 
                      }
                      

I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result −

                      Max value is : 200
                      

Function Arguments

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

While calling a function, there are two ways that arguments can be passed to a function −

Sr.No Call Type & Description
1 Call by Value

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2 Call by Pointer

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

3 Call by Reference

This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

Default Values for Parameters

When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.

This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example −

                      #include <iostream>
                      using namespace std;
                       
                      int sum(int a, int b = 20) {
                         int result;
                         result = a + b;
                        
                         return (result);
                      }
                      int main () {
                         // local variable declaration:
                         int a = 100;
                         int b = 200;
                         int result;
                       
                         // calling a function to add the values.
                         result = sum(a, b);
                         cout << "Total value is :" << result << endl;
                      
                         // calling a function again as follows.
                         result = sum(a);
                         cout << "Total value is :" << result << endl;
                       
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      Total value is :300
                      Total value is :120
                    

C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Declaring Arrays

To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −

                      type arrayName [ arraySize ];
                      

This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement −

                      double balance[10];
                      

Initializing Arrays

You can initialize C++ array elements either one by one or using a single statement as follows −

                      double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
                      

The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −

If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −

                      double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
                      

You will create exactly the same array as you did in the previous example.

                      balance[4] = 50.0;
                      

The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −

Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −

                      double salary = balance[9];
                      

The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −

                      #include <iostream>
                      using namespace std;
                       
                      #include <iomanip>
                      using std::setw;
                       
                      int main () {
                      
                         int n[ 10 ]; // n is an array of 10 integers
                       
                         // initialize elements of array n to 0          
                         for ( int i = 0; i < 10; i++ ) {
                            n[ i ] = i + 100; // set element at location i to i + 100
                         }
                         cout << "Element" << setw( 13 ) << "Value" << endl;
                       
                         // output each array element's value                      
                         for ( int j = 0; j < 10; j++ ) {
                            cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
                         }
                       
                         return 0;
                      }
                      

This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result −

                      Element        Value
                            0          100
                            1          101
                            2          102
                            3          103
                            4          104
                            5          105
                            6          106
                            7          107
                            8          108
                            9          109
                      

Arrays in C++

Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer −

Sr.No Concept & Description
1 Multi-dimensional arrays

C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2 Pointer to an array

You can generate a pointer to the first element of an array by simply specifying the array name, without any index.

3 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

4 Return array from functions

C++ allows a function to return an array.

C++ provides following two types of string representations −

  • The C-style character string.
  • The string class type introduced with Standard C++.

The C-Style Character String

The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

                      char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
                      

If you follow the rule of array initialization, then you can write the above statement as follows −

                      char greeting[] = "Hello";
                      

Following is the memory presentation of above defined string in C/C++ −

String Presentation in C/C++

Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −

                      #include <iostream>
                      
                      using namespace std;
                      
                      int main () {
                      
                         char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
                      
                         cout << "Greeting message: ";
                         cout << greeting << endl;
                      
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces the following result −

                      Greeting message: Hello
                      

C++ supports a wide range of functions that manipulate null-terminated strings −

Sr.No Function & Purpose
1

strcpy(s1, s2);

Copies string s2 into string s1.

2

strcat(s1, s2);

Concatenates string s2 onto the end of string s1.

3

strlen(s1);

Returns the length of string s1.

4

strcmp(s1, s2);

Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.

5

strchr(s1, ch);

Returns a pointer to the first occurrence of character ch in string s1.

6

strstr(s1, s2);

Returns a pointer to the first occurrence of string s2 in string s1.

Following example makes use of few of the above-mentioned functions −

                      #include <iostream>
                      #include <cstring>
                      
                      using namespace std;
                      
                      int main () {
                      
                         char str1[10] = "Hello";
                         char str2[10] = "World";
                         char str3[10];
                         int  len ;
                      
                         // copy str1 into str3
                         strcpy( str3, str1);
                         cout << "strcpy( str3, str1) : " << str3 << endl;
                      
                         // concatenates str1 and str2
                         strcat( str1, str2);
                         cout << "strcat( str1, str2): " << str1 << endl;
                      
                         // total lenghth of str1 after concatenation
                         len = strlen(str1);
                         cout << "strlen(str1) : " << len << endl;
                      
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces result something as follows −

                      strcpy( str3, str1) : Hello
                      strcat( str1, str2): HelloWorld
                      strlen(str1) : 10
                      

The String Class in C++

The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example −

                      #include <iostream>
                      #include <string>
                      
                      using namespace std;
                      
                      int main () {
                      
                         string str1 = "Hello";
                         string str2 = "World";
                         string str3;
                         int  len ;
                      
                         // copy str1 into str3
                         str3 = str1;
                         cout << "str3 : " << str3 << endl;
                      
                         // concatenates str1 and str2
                         str3 = str1 + str2;
                         cout << "str1 + str2 : " << str3 << endl;
                      
                         // total length of str3 after concatenation
                         len = str3.size();
                         cout << "str3.size() :  " << len << endl;
                      
                         return 0;
                      }
                      

When the above code is compiled and executed, it produces result something as follows −

                      str3 : Hello
                      str1 + str2 : HelloWorld
                      str3.size() :  10
                    


Java Object-Oriented

Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It is intended to let application developers write once, run anywhere (WORA),[17] meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.


Learn more

Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).

The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.

Java is −

  • Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model.

  • Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

  • Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.

  • Secure − With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

  • Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system.

  • Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.

  • Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

  • Multithreaded − With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly.

  • Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process.

  • High Performance − With the use of Just-In-Time compilers, Java enables high performance.

  • Distributed − Java is designed for the distributed environment of the internet.

  • Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

History of Java

James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ‘Oak’ after an oak tree that stood outside Gosling's office, also went by the name ‘Green’ and ended up later being renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright.

Tools You Will Need

For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended).

You will also need the following softwares −

  • Linux 7.1 or Windows xp/7/8 operating system
  • Java JDK 8
  • Microsoft Notepad or any other text editor

This tutorial will provide the necessary skills to create GUI, networking, and web applications using Java.

What is Next?

The next chapter will guide you to how you can obtain Java and its documentation. Finally, it instructs you on how to install Java and prepare an environment to develop Java applications.

When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods, and instance variables mean.

  • Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.

  • Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.

  • Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

  • Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

First Java Program

Let us look at a simple code that will print the words Hello World.

Example

                      public class MyFirstJavaProgram {
                      
                         /* This is my first java program.
                          * This will print 'Hello World' as the output
                          */
                      
                         public static void main(String []args) {
                            System.out.println("Hello World"); // prints Hello World
                         }
                      }
                      

Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −

  • Open notepad and add the code as above.

  • Save the file as: MyFirstJavaProgram.java.

  • Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.

  • Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set).

  • Now, type ' java MyFirstJavaProgram ' to run your program.

  • You will be able to see ' Hello World ' printed on the window.

Output

                      C:\> javac MyFirstJavaProgram.java
                      C:\> java MyFirstJavaProgram 
                      Hello World
                      

Basic Syntax

About Java programs, it is very important to keep in mind the following points.

  • Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.

  • Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.

    Example: class MyFirstJavaClass

  • Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.

    Example: public void myMethodName()

  • Program File Name − Name of the program file should exactly match the class name.

    When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile).

    But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file.

    Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'

  • public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program.

Java Identifiers

All Java components require names. Names used for classes, variables, and methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows −

  • All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_).

  • After the first character, identifiers can have any combination of characters.

  • A key word cannot be used as an identifier.

  • Most importantly, identifiers are case sensitive.

  • Examples of legal identifiers: age, $salary, _value, __1_value.

  • Examples of illegal identifiers: 123abc, -salary.

Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers −

  • Access Modifiers − default, public , protected, private

  • Non-access Modifiers − final, abstract, strictfp

We will be looking into more details about modifiers in the next section.

Java Variables

Following are the types of variables in Java −

  • Local Variables
  • Class Variables (Static Variables)
  • Instance Variables (Non-static Variables)

Java Arrays

Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters.

Java Enums

Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.

With the use of enums it is possible to reduce the number of bugs in your code.

For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.

Example

                      class FreshJuice {
                         enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
                         FreshJuiceSize size;
                      }
                      
                      public class FreshJuiceTest {
                      
                         public static void main(String args[]) {
                            FreshJuice juice = new FreshJuice();
                            juice.size = FreshJuice.FreshJuiceSize.MEDIUM ;
                            System.out.println("Size: " + juice.size);
                         }
                      }
                      

The above example will produce the following result −

Output

                      Size: MEDIUM
                      

Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well.

Java Keywords

The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names.

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

Comments in Java

Java supports single-line and multi-line comments very similar to C and C++. All characters available inside any comment are ignored by Java compiler.

Example

                      public class MyFirstJavaProgram {
                      
                         /* This is my first java program.
                          * This will print 'Hello World' as the output
                          * This is an example of multi-line comments.
                          */
                      
                         public static void main(String []args) {
                            // This is an example of single line comment
                            /* This is also an example of single line comment. */
                            System.out.println("Hello World");
                         }
                      }
                      

Output

                      Hello World
                      

Using Blank Lines

A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.

Inheritance

In Java, classes can be derived from classes. Basically, if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code.

This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.

Interfaces

In Java language, an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance.

An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass.

What is Next?

The next section explains about Objects and classes in Java programming. At the end of the session, you will be able to get a clear picture as to what are objects and what are classes in Java.

Java is an Object-Oriented Language. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts −

  • Polymorphism
  • Inheritance
  • Encapsulation
  • Abstraction
  • Classes
  • Objects
  • Instance
  • Method
  • Message Passing

In this chapter, we will look into the concepts - Classes and Objects.

  • Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of a class.

  • Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type support.

Objects in Java

Let us now look deep into what are objects. If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging the tail, running.

If you compare the software object with a real-world object, they have very similar characteristics.

Software objects also have a state and a behavior. A software object's state is stored in fields and behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

Classes in Java

A class is a blueprint from which individual objects are created.

Following is a sample of a class.

Example

                      public class Dog {
                         String breed;
                         int age;
                         String color;
                      
                         void barking() {
                         }
                      
                         void hungry() {
                         }
                      
                         void sleeping() {
                         }
                      }
                      

A class can contain any of the following variable types.

  • Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

  • Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

  • Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above example, barking(), hungry() and sleeping() are methods.

Following are some of the important topics that need to be discussed when looking into classes of the Java Language.

Constructors

When discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

Following is an example of a constructor −

Example

                      public class Puppy {
                         public Puppy() {
                         }
                      
                         public Puppy(String name) {
                            // This constructor has one parameter, name.
                         }
                      }
                      

Java also supports Singleton Classes where you would be able to create only one instance of a class.

Note − We have two different types of constructors. We are going to discuss constructors in detail in the subsequent chapters.

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

  • Declaration − A variable declaration with a variable name with an object type.

  • Instantiation − The 'new' keyword is used to create the object.

  • Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

Following is an example of creating an object −

Example

                      public class Puppy {
                         public Puppy(String name) {
                            // This constructor has one parameter, name.
                            System.out.println("Passed Name is :" + name );
                         }
                      
                         public static void main(String []args) {
                            // Following statement would create an object myPuppy
                            Puppy myPuppy = new Puppy( "tommy" );
                         }
                      }
                      

If we compile and run the above program, then it will produce the following result −

Output

                      Passed Name is :tommy
                      

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path −

                      /* First create an object */
                      ObjectReference = new Constructor();
                      
                      /* Now call a variable as follows */
                      ObjectReference.variableName;
                      
                      /* Now you can call a class method as follows */
                      ObjectReference.MethodName();
                      

Example

This example explains how to access instance variables and methods of a class.

                      public class Puppy {
                         int puppyAge;
                      
                         public Puppy(String name) {
                            // This constructor has one parameter, name.
                            System.out.println("Name chosen is :" + name );
                         }
                      
                         public void setAge( int age ) {
                            puppyAge = age;
                         }
                      
                         public int getAge( ) {
                            System.out.println("Puppy's age is :" + puppyAge );
                            return puppyAge;
                         }
                      
                         public static void main(String []args) {
                            /* Object creation */
                            Puppy myPuppy = new Puppy( "tommy" );
                      
                            /* Call class method to set puppy's age */
                            myPuppy.setAge( 2 );
                      
                            /* Call another class method to get puppy's age */
                            myPuppy.getAge( );
                      
                            /* You can access instance variable as follows as well */
                            System.out.println("Variable Value :" + myPuppy.puppyAge );
                         }
                      }
                      

If we compile and run the above program, then it will produce the following result −

Output

                      Name chosen is :tommy
                      Puppy's age is :2
                      Variable Value :2
                      

Source File Declaration Rules

As the last part of this section, let's now look into the source file declaration rules. These rules are essential when declaring classes, import statements and package statements in a source file.

  • There can be only one public class per source file.

  • A source file can have multiple non-public classes.

  • The public class name should be the name of the source file as well which should be appended by .java at the end. For example: the class name is public class Employee{} then the source file should be as Employee.java.

  • If the class is defined inside a package, then the package statement should be the first statement in the source file.

  • If import statements are present, then they must be written between the package statement and the class declaration. If there are no package statements, then the import statement should be the first line in the source file.

  • Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.

Classes have several access levels and there are different types of classes; abstract classes, final classes, etc. We will be explaining about all these in the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special classes called Inner classes and Anonymous classes.

Java Package

In simple words, it is a way of categorizing the classes and interfaces. When developing applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a must as well as makes life much easier.

Import Statements

In Java if a fully qualified name, which includes the package and the class name is given, then the compiler can easily locate the source code or classes. Import statement is a way of giving the proper location for the compiler to find that particular class.

For example, the following line would ask the compiler to load all the classes available in directory java_installation/java/io −

                      import java.io.*;
                      

A Simple Case Study

For our case study, we will be creating two classes. They are Employee and EmployeeTest.

First open notepad and add the following code. Remember this is the Employee class and the class is a public class. Now, save this source file with the name Employee.java.

The Employee class has four instance variables - name, age, designation and salary. The class has one explicitly defined constructor, which takes a parameter.

Example

                      import java.io.*;
                      public class Employee {
                      
                         String name;
                         int age;
                         String designation;
                         double salary;
                      
                         // This is the constructor of the class Employee
                         public Employee(String name) {
                            this.name = name;
                         }
                      
                         // Assign the age of the Employee  to the variable age.
                         public void empAge(int empAge) {
                            age = empAge;
                         }
                      
                         /* Assign the designation to the variable designation.*/
                         public void empDesignation(String empDesig) {
                            designation = empDesig;
                         }
                      
                         /* Assign the salary to the variable	salary.*/
                         public void empSalary(double empSalary) {
                            salary = empSalary;
                         }
                      
                         /* Print the Employee details */
                         public void printEmployee() {
                            System.out.println("Name:"+ name );
                            System.out.println("Age:" + age );
                            System.out.println("Designation:" + designation );
                            System.out.println("Salary:" + salary);
                         }
                      }
                      

As mentioned previously in this tutorial, processing starts from the main method. Therefore, in order for us to run this Employee class there should be a main method and objects should be created. We will be creating a separate class for these tasks.

Following is the EmployeeTest class, which creates two instances of the class Employee and invokes the methods for each object to assign values for each variable.

Save the following code in EmployeeTest.java file.

                      import java.io.*;
                      public class EmployeeTest {
                      
                         public static void main(String args[]) {
                            /* Create two objects using constructor */
                            Employee empOne = new Employee("James Smith");
                            Employee empTwo = new Employee("Mary Anne");
                      
                            // Invoking methods for each object created
                            empOne.empAge(26);
                            empOne.empDesignation("Senior Software Engineer");
                            empOne.empSalary(1000);
                            empOne.printEmployee();
                      
                            empTwo.empAge(21);
                            empTwo.empDesignation("Software Engineer");
                            empTwo.empSalary(500);
                            empTwo.printEmployee();
                         }
                      }
                      

Now, compile both the classes and then run EmployeeTest to see the result as follows −

Output

                      C:\> javac Employee.java
                      C:\> javac EmployeeTest.java
                      C:\> java EmployeeTest
                      Name:James Smith
                      Age:26
                      Designation:Senior Software Engineer
                      Salary:1000.0
                      Name:Mary Anne
                      Age:21
                      Designation:Software Engineer
                      Salary:500.0
                    

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other start-up procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.

Syntax

Following is the syntax of a constructor −

                      class ClassName {
                         ClassName() {
                         }
                      }
                      

Java allows two types of constructors namely −

  • No argument Constructors
  • Parameterized Constructors

No argument Constructors

As the name specifies the no argument constructors of Java does not accept any parameters instead, using these constructors the instance variables of a method will be initialized with fixed values for all objects.

Example

                      Public class MyClass {
                         Int num;
                         MyClass() {
                            num = 100;
                         }
                      }
                      

You would call constructor to initialize objects as follows

                      public class ConsDemo {
                         public static void main(String args[]) {
                            MyClass t1 = new MyClass();
                            MyClass t2 = new MyClass();
                            System.out.println(t1.num + " " + t2.num);
                         }
                      }
                      

This would produce the following result

                      100 100
                      

Parameterized Constructors

Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name.

Example

Here is a simple example that uses a constructor −

                      // A simple constructor.
                      class MyClass {
                         int x;
                         
                         // Following is the constructor
                         MyClass(int i ) {
                            x = i;
                         }
                      }
                      

You would call constructor to initialize objects as follows −

                      public class ConsDemo {
                         public static void main(String args[]) {
                            MyClass t1 = new MyClass( 10 );
                            MyClass t2 = new MyClass( 20 );
                            System.out.println(t1.x + " " + t2.x);
                         }
                      }
                    

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.

Syntax

                      class Super {
                         .....
                         .....
                      }
                      class Sub extends Super {
                         .....
                         .....
                      }
                      

Sample Code

Following is an example demonstrating Java inheritance. In this example, you can observe two classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of Calculation class.

Copy and paste the following program in a file with name My_Calculation.java

Example

                      class Calculation {
                         int z;
                        
                         public void addition(int x, int y) {
                            z = x + y;
                            System.out.println("The sum of the given numbers:"+z);
                         }
                        
                         public void Subtraction(int x, int y) {
                            z = x - y;
                            System.out.println("The difference between the given numbers:"+z);
                         }
                      }
                      
                      public class My_Calculation extends Calculation {
                         public void multiplication(int x, int y) {
                            z = x * y;
                            System.out.println("The product of the given numbers:"+z);
                         }
                        
                         public static void main(String args[]) {
                            int a = 20, b = 10;
                            My_Calculation demo = new My_Calculation();
                            demo.addition(a, b);
                            demo.Subtraction(a, b);
                            demo.multiplication(a, b);
                         }
                      }
                      

Compile and execute the above code as shown below.

                      javac My_Calculation.java
                      java My_Calculation
                      

After executing the program, it will produce the following result −

Output

                      The sum of the given numbers:30
                      The difference between the given numbers:10
                      The product of the given numbers:200
                      

In the given program, when an object to My_Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass.

Inheritance

The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.

If you consider the above program, you can instantiate the class as given below. But using the superclass reference variable ( cal in this case) you cannot call the method multiplication(), which belongs to the subclass My_Calculation.

                      Calculation demo = new My_Calculation();
                      demo.addition(a, b);
                      demo.Subtraction(a, b);
                      

Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

The super keyword

The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used.

  • It is used to differentiate the members of superclass from the members of subclass, if they have same names.

  • It is used to invoke the superclass constructor from subclass.

Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.

                      super.variable
                      super.method();
                      

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.

In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass.

Copy and paste the program in a file with name Sub_class.java.

Example

                      class Super_class {
                         int num = 20;
                      
                         // display method of superclass
                         public void display() {
                            System.out.println("This is the display method of superclass");
                         }
                      }
                      
                      public class Sub_class extends Super_class {
                         int num = 10;
                      
                         // display method of sub class
                         public void display() {
                            System.out.println("This is the display method of subclass");
                         }
                      
                         public void my_method() {
                            // Instantiating subclass
                            Sub_class sub = new Sub_class();
                      
                            // Invoking the display() method of sub class
                            sub.display();
                      
                            // Invoking the display() method of superclass
                            super.display();
                      
                            // printing the value of variable num of subclass
                            System.out.println("value of the variable named num in sub class:"+ sub.num);
                      
                            // printing the value of variable num of superclass
                            System.out.println("value of the variable named num in super class:"+ super.num);
                         }
                      
                         public static void main(String args[]) {
                            Sub_class obj = new Sub_class();
                            obj.my_method();
                         }
                      }
                      

Compile and execute the above code using the following syntax.

                      javac Super_Demo
                      java Super
                      

On executing the program, you will get the following result −

Output

                      This is the display method of subclass
                      This is the display method of superclass
                      value of the variable named num in sub class:10
                      value of the variable named num in super class:20
                      

Invoking Superclass Constructor

If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as shown below.

                      super(values);
                      

Sample Code

The program given in this section demonstrates how to use the super keyword to invoke the parametrized constructor of the superclass. This program contains a superclass and a subclass, where the superclass contains a parameterized constructor which accepts a integer value, and we used the super keyword to invoke the parameterized constructor of the superclass.

Copy and paste the following program in a file with the name Subclass.java

Example

                      class Superclass {
                         int age;
                      
                         Superclass(int age) {
                            this.age = age; 		 
                         }
                      
                         public void getAge() {
                            System.out.println("The value of the variable named age in super class is: " +age);
                         }
                      }
                      
                      public class Subclass extends Superclass {
                         Subclass(int age) {
                            super(age);
                         }
                      
                         public static void main(String args[]) {
                            Subclass s = new Subclass(24);
                            s.getAge();
                         }
                      }
                      

Compile and execute the above code using the following syntax.

                      javac Subclass
                      java Subclass
                      

On executing the program, you will get the following result −

Output

                      The value of the variable named age in super class is: 24
                      

IS-A Relationship

IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

                      public class Animal {
                      }
                      
                      public class Mammal extends Animal {
                      }
                      
                      public class Reptile extends Animal {
                      }
                      
                      public class Dog extends Mammal {
                      }
                      

Now, based on the above example, in Object-Oriented terms, the following are true −

  • Animal is the superclass of Mammal class.
  • Animal is the superclass of Reptile class.
  • Mammal and Reptile are subclasses of Animal class.
  • Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say −

  • Mammal IS-A Animal
  • Reptile IS-A Animal
  • Dog IS-A Mammal
  • Hence: Dog IS-A Animal as well

With the use of the extends keyword, the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.

Example

                      class Animal {
                      }
                      
                      class Mammal extends Animal {
                      }
                      
                      class Reptile extends Animal {
                      }
                      
                      public class Dog extends Mammal {
                      
                         public static void main(String args[]) {
                            Animal a = new Animal();
                            Mammal m = new Mammal();
                            Dog d = new Dog();
                      
                            System.out.println(m instanceof Animal);
                            System.out.println(d instanceof Mammal);
                            System.out.println(d instanceof Animal);
                         }
                      }
                      

This will produce the following result −

Output

                      true
                      true
                      true
                      

Since we have a good understanding of the extends keyword, let us look into how the implements keyword is used to get the IS-A relationship.

Generally, the implements keyword is used with classes to inherit the properties of an interface. Interfaces can never be extended by a class.

Example

                      public interface Animal {
                      }
                      
                      public class Mammal implements Animal {
                      }
                      
                      public class Dog extends Mammal {
                      }
                      

The instanceof Keyword

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal.

Example

                      interface Animal{}
                      class Mammal implements Animal{}
                      
                      public class Dog extends Mammal {
                      
                         public static void main(String args[]) {
                            Mammal m = new Mammal();
                            Dog d = new Dog();
                      
                            System.out.println(m instanceof Animal);
                            System.out.println(d instanceof Mammal);
                            System.out.println(d instanceof Animal);
                         }
                      }
                      

This will produce the following result −

Output

                      true
                      true
                      true
                      

HAS-A relationship

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets look into an example −

Example

                      public class Vehicle{}
                      public class Speed{}
                      
                      public class Van extends Vehicle {
                         private Speed sp;
                      } 
                      

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So, basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

Types of Inheritance

There are various types of inheritance as demonstrated below.

Types of Inheritance

A very important fact to remember is that Java does not support multiple inheritance. This means that a class cannot extend more than one class. Therefore following is illegal −

Example

                      public class extends Animal, Mammal{} 
                      

However, a class can implement one or more interfaces, which has helped Java get rid of the impossibility of multiple inheritance.

In the previous chapter, we talked about superclasses and subclasses. If a class inherits a method from its superclass, then there is a chance to override the method provided that it is not marked final.

The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method.

Example

Let us look at an example.

                      class Animal {
                         public void move() {
                            System.out.println("Animals can move");
                         }
                      }
                      
                      class Dog extends Animal {
                         public void move() {
                            System.out.println("Dogs can walk and run");
                         }
                      }
                      
                      public class TestDog {
                      
                         public static void main(String args[]) {
                            Animal a = new Animal();   // Animal reference and object
                            Animal b = new Dog();   // Animal reference but Dog object
                      
                            a.move();   // runs the method in Animal class
                            b.move();   // runs the method in Dog class
                         }
                      }
                      

This will produce the following result −

Output

                      Animals can move
                      Dogs can walk and run
                      

In the above example, you can see that even though b is a type of Animal it runs the move method in the Dog class. The reason for this is: In compile time, the check is made on the reference type. However, in the runtime, JVM figures out the object type and would run the method that belongs to that particular object.

Therefore, in the above example, the program will compile properly since Animal class has the method move. Then, at the runtime, it runs the method specific for that object.

Consider the following example −

Example

                      class Animal {
                         public void move() {
                            System.out.println("Animals can move");
                         }
                      }
                      
                      class Dog extends Animal {
                         public void move() {
                            System.out.println("Dogs can walk and run");
                         }
                         public void bark() {
                            System.out.println("Dogs can bark");
                         }
                      }
                      
                      public class TestDog {
                      
                         public static void main(String args[]) {
                            Animal a = new Animal();   // Animal reference and object
                            Animal b = new Dog();   // Animal reference but Dog object
                      
                            a.move();   // runs the method in Animal class
                            b.move();   // runs the method in Dog class
                            b.bark();
                         }
                      }
                      

This will produce the following result −

Output

                      TestDog.java:26: error: cannot find symbol
                            b.bark();
                             ^
                        symbol:   method bark()
                        location: variable b of type Animal
                      1 error
                      

This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.

Rules for Method Overriding

  • The argument list should be exactly the same as that of the overridden method.

  • The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass.

  • The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overridding method in the sub class cannot be either private or protected.

  • Instance methods can be overridden only if they are inherited by the subclass.

  • A method declared final cannot be overridden.

  • A method declared static cannot be overridden but can be re-declared.

  • If a method cannot be inherited, then it cannot be overridden.

  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.

  • A subclass in a different package can only override the non-final methods declared public or protected.

  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

  • Constructors cannot be overridden.

Using the super Keyword

When invoking a superclass version of an overridden method the super keyword is used.

Example

                      class Animal {
                         public void move() {
                            System.out.println("Animals can move");
                         }
                      }
                      
                      class Dog extends Animal {
                         public void move() {
                            super.move();   // invokes the super class method
                            System.out.println("Dogs can walk and run");
                         }
                      }
                      
                      public class TestDog {
                      
                         public static void main(String args[]) {
                            Animal b = new Dog();   // Animal reference but Dog object
                            b.move();   // runs the method in Dog class
                         }
                      }
                      

This will produce the following result −

Output

                      Animals can move
                      Dogs can walk and run
                    

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.

Example

Let us look at an example.

                      public interface Vegetarian{}
                      public class Animal{}
                      public class Deer extends Animal implements Vegetarian{}
                      

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −

  • A Deer IS-A Animal
  • A Deer IS-A Vegetarian
  • A Deer IS-A Deer
  • A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal −

Example

                      Deer d = new Deer();
                      Animal a = d;
                      Vegetarian v = d;
                      Object o = d;
                      

All the reference variables d, a, v, o refer to the same Deer object in the heap.

Virtual Methods

In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

Example

                      /* File name : Employee.java */
                      public class Employee {
                         private String name;
                         private String address;
                         private int number;
                      
                         public Employee(String name, String address, int number) {
                            System.out.println("Constructing an Employee");
                            this.name = name;
                            this.address = address;
                            this.number = number;
                         }
                      
                         public void mailCheck() {
                            System.out.println("Mailing a check to " + this.name + " " + this.address);
                         }
                      
                         public String toString() {
                            return name + " " + address + " " + number;
                         }
                      
                         public String getName() {
                            return name;
                         }
                      
                         public String getAddress() {
                            return address;
                         }
                      
                         public void setAddress(String newAddress) {
                            address = newAddress;
                         }
                      
                         public int getNumber() {
                            return number;
                         }
                      }
                      

Now suppose we extend Employee class as follows −

                      /* File name : Salary.java */
                      public class Salary extends Employee {
                         private double salary; // Annual salary
                         
                         public Salary(String name, String address, int number, double salary) {
                            super(name, address, number);
                            setSalary(salary);
                         }
                         
                         public void mailCheck() {
                            System.out.println("Within mailCheck of Salary class ");
                            System.out.println("Mailing check to " + getName()
                            + " with salary " + salary);
                         }
                         
                         public double getSalary() {
                            return salary;
                         }
                         
                         public void setSalary(double newSalary) {
                            if(newSalary >= 0.0) {
                               salary = newSalary;
                            }
                         }
                         
                         public double computePay() {
                            System.out.println("Computing salary pay for " + getName());
                            return salary/52;
                         }
                      }
                      

Now, you study the following program carefully and try to determine its output −

                      /* File name : VirtualDemo.java */
                      public class VirtualDemo {
                      
                         public static void main(String [] args) {
                            Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
                            Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
                            System.out.println("Call mailCheck using Salary reference --");   
                            s.mailCheck();
                            System.out.println("\n Call mailCheck using Employee reference--");
                            e.mailCheck();
                         }
                      }
                      

This will produce the following result −

Output

                      Constructing an Employee
                      Constructing an Employee
                      
                      Call mailCheck using Salary reference --
                      Within mailCheck of Salary class
                      Mailing check to Mohd Mohtashim with salary 3600.0
                      
                      Call mailCheck using Employee reference--
                      Within mailCheck of Salary class
                      Mailing check to John Adams with salary 2400.0
                      

Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.

While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send.

Likewise in Object-oriented programming, abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.

  • Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )

  • But, if a class has at least one abstract method, then the class must be declared abstract.

  • If a class is declared abstract, it cannot be instantiated.

  • To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.

  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Example

This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration.

                      /* File name : Employee.java */
                      public abstract class Employee {
                         private String name;
                         private String address;
                         private int number;
                      
                         public Employee(String name, String address, int number) {
                            System.out.println("Constructing an Employee");
                            this.name = name;
                            this.address = address;
                            this.number = number;
                         }
                         
                         public double computePay() {
                           System.out.println("Inside Employee computePay");
                           return 0.0;
                         }
                         
                         public void mailCheck() {
                            System.out.println("Mailing a check to " + this.name + " " + this.address);
                         }
                      
                         public String toString() {
                            return name + " " + address + " " + number;
                         }
                      
                         public String getName() {
                            return name;
                         }
                       
                         public String getAddress() {
                            return address;
                         }
                         
                         public void setAddress(String newAddress) {
                            address = newAddress;
                         }
                       
                         public int getNumber() {
                            return number;
                         }
                      }
                      

You can observe that except abstract methods the Employee class is same as normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor.

Now you can try to instantiate the Employee class in the following way −

                      /* File name : AbstractDemo.java */
                      public class AbstractDemo {
                      
                         public static void main(String [] args) {
                            /* Following is not allowed and would raise error */
                            Employee e = new Employee("George W.", "Houston, TX", 43);
                            System.out.println("\n Call mailCheck using Employee reference--");
                            e.mailCheck();
                         }
                      }
                      

When you compile the above class, it gives you the following error −

                      Employee.java:46: Employee is abstract; cannot be instantiated
                            Employee e = new Employee("George W.", "Houston, TX", 43);
                                         ^
                      1 error
                      

Inheriting the Abstract Class

We can inherit the properties of Employee class just like concrete class in the following way −

Example

                      /* File name : Salary.java */
                      public class Salary extends Employee {
                         private double salary;   // Annual salary
                         
                         public Salary(String name, String address, int number, double salary) {
                            super(name, address, number);
                            setSalary(salary);
                         }
                         
                         public void mailCheck() {
                            System.out.println("Within mailCheck of Salary class ");
                            System.out.println("Mailing check to " + getName() + " with salary " + salary);
                         }
                       
                         public double getSalary() {
                            return salary;
                         }
                         
                         public void setSalary(double newSalary) {
                            if(newSalary >= 0.0) {
                               salary = newSalary;
                            }
                         }
                         
                         public double computePay() {
                            System.out.println("Computing salary pay for " + getName());
                            return salary/52;
                         }
                      }
                      

Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class as shown below.

                      /* File name : AbstractDemo.java */
                      public class AbstractDemo {
                      
                         public static void main(String [] args) {
                            Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
                            Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
                            System.out.println("Call mailCheck using Salary reference --");
                            s.mailCheck();
                            System.out.println("\n Call mailCheck using Employee reference--");
                            e.mailCheck();
                         }
                      }
                      

This produces the following result −

Output

                      Constructing an Employee
                      Constructing an Employee
                      Call mailCheck using Salary reference --
                      Within mailCheck of Salary class 
                      Mailing check to Mohd Mohtashim with salary 3600.0
                      
                       Call mailCheck using Employee reference--
                      Within mailCheck of Salary class 
                      Mailing check to John Adams with salary 2400.0
                      

Abstract Methods

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract.

  • abstract keyword is used to declare the method as abstract.

  • You have to place the abstract keyword before the method name in the method declaration.

  • An abstract method contains a method signature, but no method body.

  • Instead of curly braces, an abstract method will have a semoi colon (;) at the end.

Following is an example of the abstract method.

Example

                      public abstract class Employee {
                         private String name;
                         private String address;
                         private int number;
                         
                         public abstract double computePay();
                         // Remainder of class definition
                      }
                      

Declaring a method as abstract has two consequences −

  • The class containing it must be declared as abstract.

  • Any class inheriting the current class must either override the abstract method or declare itself as abstract.

Note − Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.

Suppose Salary class inherits the Employee class, then it should implement the computePay() method as shown below −

                      /* File name : Salary.java */
                      public class Salary extends Employee {
                         private double salary;   // Annual salary
                        
                         public double computePay() {
                            System.out.println("Computing salary pay for " + getName());
                            return salary/52;
                         }
                         // Remainder of class definition
                      }
                    

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding.

To achieve encapsulation in Java −

  • Declare the variables of a class as private.

  • Provide public setter and getter methods to modify and view the variables values.

Example

Following is an example that demonstrates how to achieve Encapsulation in Java −

                      /* File name : EncapTest.java */
                      public class EncapTest {
                         private String name;
                         private String idNum;
                         private int age;
                      
                         public int getAge() {
                            return age;
                         }
                      
                         public String getName() {
                            return name;
                         }
                      
                         public String getIdNum() {
                            return idNum;
                         }
                      
                         public void setAge( int newAge) {
                            age = newAge;
                         }
                      
                         public void setName(String newName) {
                            name = newName;
                         }
                      
                         public void setIdNum( String newId) {
                            idNum = newId;
                         }
                      }
                      

The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed using the following program −

                      /* File name : RunEncap.java */
                      public class RunEncap {
                      
                         public static void main(String args[]) {
                            EncapTest encap = new EncapTest();
                            encap.setName("James");
                            encap.setAge(20);
                            encap.setIdNum("12343ms");
                      
                            System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
                         }
                      }
                      

This will produce the following result −

Output

                      Name : James Age : 20
                      

Benefits of Encapsulation

  • The fields of a class can be made read-only or write-only.

  • A class can have total control over what is stored in its fields.

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways −

  • An interface can contain any number of methods.

  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.

  • The byte code of an interface appears in a .class file.

  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including −

  • You cannot instantiate an interface.

  • An interface does not contain any constructors.

  • All of the methods in an interface are abstract.

  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

  • An interface is not extended by a class; it is implemented by a class.

  • An interface can extend multiple interfaces.

Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an interface −

Example

Following is an example of an interface −

                      /* File name : NameOfInterface.java */
                      import java.lang.*;
                      // Any number of import statements
                      
                      public interface NameOfInterface {
                         // Any number of final, static fields
                         // Any number of abstract method declarations\
                      }
                      

Interfaces have the following properties −

  • An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface.

  • Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

  • Methods in an interface are implicitly public.

Example

                      /* File name : Animal.java */
                      interface Animal {
                         public void eat();
                         public void travel();
                      }
                      

Implementing Interfaces

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Example

                      /* File name : MammalInt.java */
                      public class MammalInt implements Animal {
                      
                         public void eat() {
                            System.out.println("Mammal eats");
                         }
                      
                         public void travel() {
                            System.out.println("Mammal travels");
                         } 
                      
                         public int noOfLegs() {
                            return 0;
                         }
                      
                         public static void main(String args[]) {
                            MammalInt m = new MammalInt();
                            m.eat();
                            m.travel();
                         }
                      } 
                      

This will produce the following result −

Output

                      Mammal eats
                      Mammal travels
                      

When overriding methods defined in interfaces, there are several rules to be followed −

  • Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

  • The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.

  • An implementation class itself can be abstract and if so, interface methods need not be implemented.

When implementation interfaces, there are several rules −

  • A class can implement more than one interface at a time.

  • A class can extend only one class, but implement many interfaces.

  • An interface can extend another interface, in a similar way as a class can extend another class.

Extending Interfaces

An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

Example

                      // Filename: Sports.java
                      public interface Sports {
                         public void setHomeTeam(String name);
                         public void setVisitingTeam(String name);
                      }
                      
                      // Filename: Football.java
                      public interface Football extends Sports {
                         public void homeTeamScored(int points);
                         public void visitingTeamScored(int points);
                         public void endOfQuarter(int quarter);
                      }
                      
                      // Filename: Hockey.java
                      public interface Hockey extends Sports {
                         public void homeGoalScored();
                         public void visitingGoalScored();
                         public void endOfPeriod(int period);
                         public void overtimePeriod(int ot);
                      }
                      

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as −

Example

                      public interface Hockey extends Sports, Event
                      

Tagging Interfaces

The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as −

Example

                      package java.util;
                      public interface EventListener
                      {}
                      

An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces −

Creates a common parent − As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario.

Adds a data type to a class − This situation is where the term, tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.

Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations ) providing access protection and namespace management.

Some of the existing packages in Java are −

  • java.lang − bundles the fundamental classes

  • java.io − classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Creating a Package

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

To compile the Java programs with package statements, you have to use -d option as shown below.

                      javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.

Example

Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.

Following package example contains interface named animals

                      /* File name : Animal.java */
                      package animals;
                      
                      interface Animal {
                         public void eat();
                         public void travel();
                      }
                      

Now, let us implement the above interface in the same package animals

                      package animals;
                      /* File name : MammalInt.java */
                      
                      public class MammalInt implements Animal {
                      
                         public void eat() {
                            System.out.println("Mammal eats");
                         }
                      
                         public void travel() {
                            System.out.println("Mammal travels");
                         } 
                      
                         public int noOfLegs() {
                            return 0;
                         }
                      
                         public static void main(String args[]) {
                            MammalInt m = new MammalInt();
                            m.eat();
                            m.travel();
                         }
                      } 
                      

Now compile the java files as shown below −

                      $ javac -d . Animal.java 
                      $ javac -d . MammalInt.java
                      

Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.

Packages

You can execute the class file within the package and get the result as shown below.

                      Mammal eats
                      Mammal travels
                      

The import Keyword

If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax.

Example

Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class.

                      package payroll;
                      public class Boss {
                         public void payEmployee(Employee e) {
                            e.mailCheck();
                         }
                      }
                      

What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package.

  • The fully qualified name of the class can be used. For example −
                      payroll.Employee
                      
  • The package can be imported using the import keyword and the wild card (*). For example −

                      import payroll.*;
                      
  • The class itself can be imported using the import keyword. For example −
                      import payroll.Employee;
                      

Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration.

The Directory Structure of Packages

Two major results occur when a class is placed in a package −

  • The name of the package becomes a part of the name of the class, as we just discussed in the previous section.

  • The name of the package must match the directory structure where the corresponding bytecode resides.

Here is simple way of managing your files in Java −

Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java.

For example −

                      // File Name :  Car.java
                      package vehicle;
                      
                      public class Car {
                         // Class implementation.   
                      }
                      

Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −

                      ....\vehicle\Car.java
                      

Now, the qualified class name and pathname would be as follows −

  • Class name → vehicle.Car
  • Path name → vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names.

Example − A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.

Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −

                      ....\com\apple\computers\Dell.java
                      

At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.

For example −

                      // File Name: Dell.java
                      package com.apple.computers;
                      
                      public class Dell {
                      }
                      
                      class Ups {
                      }
                      

Now, compile this file as follows using -d option −

                      $javac -d . Dell.java
                      

The files will be compiled as follows −

                      .\com\apple\computers\Dell.class
                      .\com\apple\computers\Ups.class
                      

You can import all the classes or interfaces defined in \com\apple\computers\ as follows −

                      import com.apple.computers.*;
                      

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −

                      <path-one>\sources\com\apple\computers\Dell.java
                      
                      <path-two>\classes\com\apple\computers\Dell.class
                      

By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, <path-two>\classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in <path-two>\classes\com\apple\computers.

A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.

Set CLASSPATH System Variable

To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −

  • In Windows → C:\> set CLASSPATH
  • In UNIX → % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use −

  • In Windows → C:\> set CLASSPATH =
  • In UNIX → % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable −

  • In Windows → set CLASSPATH = C:\users\jack\java\classes
  • In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH