The Association of the method call to the method body is known as binding. There are two types of binding in java:
Static binding.
Dynamic bindinng.
1. Static Binding or Early Binding in Java:
The binding that resolved at compile time is known as Static Binding or Early Binding. There are three methods that cannot be overridden and the type of the class is determined at the compile time.
They are static, private and final methods. They are bind at compile time. In this type, the compiler knows the type of object or class to which object belongs to during the execution.
Example of Static Binding or Early Binding in Java:
class SuperClass
{
static void display()
{
System.out.println("Displaying superclass.");
}
}
class SubClass extends SuperClass
{
static void display()
{
System.out.println("Displaying subclass.");
}
}
public class StaticTest
{
public static void main(String[] args)
{
//Reference is of SuperClass type and object is SuperClass type
SuperClass sup = new SuperClass();
//Reference is of SuperClass type and object is SubClass type
SuperClass sub = new SubClass();
sup.display();
sub.display();
}
}
Output of Static Binding:
Displaying superclass.
Displaying superclass.
In this above example, two objects are created (sup, sub) of different types referring to the same class type(SuperClass type). Here the display() method of SuperClass is static, and therefore compiler knows that it will not be overridden in subclasses and also knows which display() method to call and hence no ambiguity.
2. Dynamic Binding or Late Binding in Java:
The binding that resolved at run time is known as Static Binding or Late Binding. The perfect example of this would be Overriding. Consider a method overriding where parent class and child class has the same method.
Example Dynamic Binding in Java: In the following example, the overriding of a method is possible because no methods are declared static, private, and final.
class SuperClass
{
void display()
{
System.out.println("Displaying superclass.");
}
}
class SubClass extends SuperClass
{
void display()
{
System.out.println("Displaying subclass.");
}
}
public class StaticTest
{
public static void main(String[] args)
{
//Reference is of SuperClass typ and object is SuperClass type
SuperClass sup = new SuperClass();
//Reference is of SuperClass typ and object is SubClass type
SuperClass sub = new SubClass();
sup.display();
sub.display();
}
}
A string is defined as a series of characters or an array of characters in java. They are present within the double quote.
Create a String:
One way to create a String is to directly declare it within the double quote that is by String Literal:
String s = "SimpleToCode";
Like any other object, it is possible to create a string object with the help of a new keyword. such as:
char[] s = {'S','i','m','p','l','e','T','o','C','o','d','e'};
String obj = new String(s);
Example:
public class StringTest
{
public static void main(String args[])
{
String s = "Simple To Code";
System.out.println( s );
}
}
Output:
Simple To Code
Example of string with object in Java:
public class StringTest
{
public static void main(String args[])
{
char[] s = {'S','i','m','p','l','e',' ','T','o',' ','C','o','d','e'};
String obj = new String(s);
System.out.println( obj );
}
}
Output:
Simple To Code
Note that: it also takes blank space as a character. Also, string objects are immutable that is their values are unchangeable once the object is created.
String Methods:
Java provides Various String Methods for String Operation such as compare(), concat(), equals(), length(), compareTo() and amany more.
List of some string Methods supported by Java are:
char charAt(int index): This method returns the character at the specified index.
int compareTo(String secondString): The method compares the two strings depending upon their Unicode Value.
int compareTo(Object o): Compares the present String to another object.
String concat(String str): This method concatenates the String ‘str’ at the end of the string.
boolean equals(Object obj): This method compares the string to the specified object.
boolean endsWith(String suffix): This method checks or tests whether the string ends with the specified suffix or not.
boolean startsWith(String prefix): It checks for the string to have a specified prefix and depending on that it returns a true or false boolean value.
int compareToIgnoreCase(String str): It compares the string the same as compareTo() but here it ignores the case of the string.
int hashCode(): This method returns the hash code of the string.
int indexOf(int ch): The index of the first occurrence of the specified character ‘ch’ is returned in the string.
int lastIndexOf(int ch): This one returns the last occurrence ‘ch’ in the string.
int indexOf(String str): The index of the first occurrence of the specified substring ‘str’ is returned through this method.
int lastindexOf(String str): similarly, this method returns the last occurrence of the string ‘str’.
String intern(): This method first searches for the particular string and returns the reference of it otherwise it allocates the memory to the particular string and assigns the reference to it.
int length(): This method returns the length of the string.
char[] toCharArray(): It is used to convert the string to a new array.
String toString(): This already present string is itself return.
String toLowerCase(): It is used to all the characters of the string to lower case by the default locale.
String toUpperCase(): It is used to all the characters of the string to upper case by the default locale.
String trim(): It returns the substring of the original string after omitting leading and trailing white spaces.
There are many more String methods such as, static String copyValueOf(char[] data), static String valueOf(), byte[] getBytes(), boolean matches(String regex), static String copyValueOf(char[] data, int offset, int count), string[] split(String regex) and so on.
The decision-making statement in Java is used when the user wants a specific block of code to be executed when the given condition is fulfilled.
Java programming language provides the following types of decision-making statements:
if statement
if-else statement
nested-if statement
if-else-if ladder statement
switch-case statement
if statement
Among the decision making statements, it is the most simple one. It checks if the condition is true or not, and if it is true then it executes the block of code inside if otherwise, it will not. The block that is executed is placed within the curly braces({}).
Syntax of if statement in Java:
if (boolean expression)
{
/* if expression is true */
statements... ; /* Execute statements */
}
There are two-part in this statement. First is the if statement, here it checks for the condition to be true and if it is true then it will execute the code present inside the if. But if the condition is false then the code inside the else statement will be executed.
Syntax of if-else statement in Java:
if (condition)
{
//code executed if condition true
}
else
{
//code executed if condition false
}
This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be bypassed. if none of the conditions is true then the final else statement at the end will be executed.
Syntax of if-else-if ladder statement in java:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//final else if all the above condition are false
}
A switch statement allows a variable to be tested for equality against multiple values. It provides the case for the different blocks of code to be executed. Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values.
In the end, it can have a default case which is optional that is executed if no cases are matched. It can also have an optional break that is useful to exit the switch otherwise it continues to the next case.
Syntax of switch statements in Java:
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
.
.
.
.
case valueN:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
}
Operators are the mathematical symbols that are used to perform a mathematical operation on operands. These symbols tell the compiler to perform respective operations. An expression is formed by joining constants and variables in C programming.
Example:
int a = 10 + 5;
In the above example, 10 and 5 are operands and + is the operation performed between these two operands.
Types of Operator in C:
Arithmetic Operator
Increment and Decrement Operators
Relational Operator
Assignment Operators
Logical Operators
Bitwise Operators
sizeof Operator
Other Operators
C Arithmetic Operator
These are used to perform mathematical operations on operands such as addition, subtraction, multiplication, division etc.
Addition: ‘+’ operator adds two operands. eg, a+b.
Subtraction: ‘-‘ operator subtracts two operands. eg, a-b.
Multiplication: ‘*’ operator multiplies two operands. eg, a*b.
Division: ’/’ operator divides the operand by the second. eg, a/b.
Modulus: ’%’ operator returns the remainder when the first operand is divided by the second. For example, a%b.
Example of Arithmetic Operator
#include <stdio.h>
int main()
{
int a = 24;
int b = 12;
int result;
result = a + b;
printf("Addition: %d\n", result);
result = a - b;
printf("Subtraction: %d\n", result);
result = a * b;
printf("Multiplication: %d\n", result);
result = a / b;
printf("Division: %d\n", result);
result = a % b;
printf("Modulus %d\n", result);
return 0;
}
These are the Unary Operators as they operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.
Post-Increment or Post-Decrement: First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
Pre-Increment Pre-Decrement: Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.
Example of Increment and Decrement Operator
#include <stdio.h>
void main()
{
int x = 5;
//post increment
printf("%d\n", x++);
printf("%d\n\n", x);
x = 10;
//preincrement
printf("%d\n", ++x);
printf("%d\n", x);
}
The output of Increment and Decrement Operator.
5
6
11
11
C Relational Operator
Relational operators are used to compare two values and return boolean results. These operators are used to check for relations like equality, greater than, less than between two values. They are used with a loop statement and also with if-else statements.
List of relational operators in C:
Operator
Name
Example
==
Equal to.
A == B
!=
Not equal.
A != B
>
Greater than.
A > B
<
Less than.
A < B
>=
Greater than or equal to.
A >= B
<=
Less than or equal to.
A <= B
Example of Relational Operator
#include <stdio.h>
int main()
{
int a = 10, b = 10, c = 20;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d > %d is %d \n", a, b, a> b);
printf("%d > %d is %d \n", a, c, a> c);
printf("%d<%d is %d \n", a, b, a < b);
printf("%d<%d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d != %d is %d \n", a, c, a != c);
printf("%d >= %d is %d \n", a, b, a>= b);
printf("%d >= %d is %d \n", a, c, a>= c);
printf("%d <= %d is %d \n", a, b, a <= b);
printf("%d <= %d is %d \n", a, c, a <= c);
return 0;
}
The output of Relational Operator.
10 == 10 is 1
10 == 20 is 0
10 > 10 is 0
10 > 20 is 0
10 < 10 is 0
10 < 20 is 1
10 != 10 is 0
10 != 20 is 1
10 >= 10 is 1
10 >= 20 is 0
10 <= 10 is 1
10 <= 20 is 1
C Assignment Operators
Assignment operator is used to assigning a value to any variable. This operator assigns the value of the right-hand side of an operator to the left-hand side. These are the short version formed by combining the two operators.
For example Instead of writing, int a = a+3, we can write a += 3.
Assignment operator: ‘=’ This operator assigns the value on the right to the variable on the left. a = 20; B = 30; Ch = 'cha';
Add AND assignment operator: ‘+=’ This operator first adds the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left. c+=7; a+=b;
Subtract AND assignment operator: ‘-=’ This operator first subtracts the current value of the variable on the left from the value on the right and then assigns the result to the variable on the left. c-=7; a-=b;
Multiply AND assignment operator: ‘*=’ This operator first multiplies the current value of the variable on the left to the value on the right and then assigns the result to the variable on the left. c*=7; a*=b;
Divide AND assignment operator: ‘/=’ This operator first divides the current value of the variable on the left by the value on the right and then assigns the result to the variable on the left. c/=7; a/=b;
Modulus AND assignment operator: ‘%=’ It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A ;
Example ofAssignment Operators
#include <stdio.h>
int main()
{
int x = 10, y;
y = x; // y is 10
printf("Value of y: %d\n", y);
y += x; // y is 20
printf("Value of y: %d\n", y);
y -= x; // y is 10
printf("Value of y: %d\n", y);
y *= x; // y is 100
printf("Value of y: %d\n", y);
y /= x; // y is 10
printf("Value of y: %d\n", y);
y %= x; // y = 0
printf("Value of y: %d\n", y);
return 0;
}
The output of Assignment Operators:
Value of y: 10
Value of y: 20
Value of y: 10
Value of y: 100
Value of y: 10
Value of y: 0
CLogical Operators
Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. All of the binary logical operators return two boolean values that are true and false depending upon 0 and 1.
Operator
Description
Example
&& (logical and)
If both the operands are non-zero, then the condition becomes true.
(X && Y) is false
|| (logical or)
If any of the two operands are non-zero, then the condition becomes true.
(X || Y) is true
! (logical not)
Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(X && Y) is true
Example ofLogical Operators
#include <stdio.h>
int main()
{
int x = 5;
int y = 20;
int z;
if (x && y)
{
printf("Line 1 - Condition is true\n");
}
if (x || y)
{
printf("Line 2 - Condition is true\n");
}
/*let's change the value of a and b */
x = 0;
y = 10;
if (x && y)
{
printf("Line 3 - Condition is true\n");
}
else
{
printf("Line 3 - Condition is not true\n");
}
if (!(x && y))
{
printf("Line 4 - Condition is true\n");
}
return 0;
}
In C programming, Bitwise operators are used to perform a bit-level operation. All the mathematical operations are converted to bit-level which makes processing faster and also saves power.
Operators
Name of operators
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
~
Bitwise complement
<<
Shift left
>>
Shift right
Example of Bitwise Operators.
#include <stdio.h>
int main()
{
int a = 15, b = 28;
printf("Output = %d\n", a &b);
printf("Output = %d\n", a | b);
printf("Output = %d\n", a ^ b);
printf("Output = %d\n", ~19);
printf("Output = %d\n", ~-22);
printf("Left shift by %d: %d\n", b>> 1);
printf("Left shift by %d: %d\n", b << 1);
return 0;
}
The output of Bitwise operator.
Output = 12
Output = 31
Output = 19
Output = -20
Output = 21
Left shift by 14: 0
Left shift by 56: 0
sizeof Operator
sizeof operator is a unary operator that returns the size of constants, variables, array, etc. Example: sizeof(x), return size of the variable x.
Example of sizeof Operator
#include <stdio.h>
int main()
{
int x;
float y;
double z;
char ch;
printf("Size of int = %lu bytes\n", sizeof(z));
printf("Size of float = %lu bytes\n", sizeof(y));
printf("Size of double = %lu bytes\n", sizeof(z));
printf("Size of char = %lu byte\n", sizeof(ch));
return 0;
}
The output of sizeof Operator.
Size of int = 8 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Other Operators:
Comma Operator (,)
This operator is used to link related operators together. We use a comma operator when we declare many variables in a single line as shown below. Example: a, c, d = 0, z;
& operator
This is used to get the address of the variable. Example: pt = &x
* operator
This is used as a pointer to a variable. Example: int *pt;
C Program to demonstrate & and * operator
In this C program, & is used to get the address of a variable and * is used to get the value of variable.
#include <stdio.h>
int main()
{
int *ptr, x;
x = 10;
ptr = &x;
printf("%d", *ptr);
return 0;
}
Scope refers to the visibility of variables. In other words, a scope is a section of a program, and the scope of variables refers to the section of the program where the variables are visible. Variable is declared and used within that region. Also, variables declared within the block cannot be accessed outside that block.
Depending on the region, there are three types of scope that are declared and used:
Local variables: inside a function or a block.
Global variables: outside of all functions.
Formal parameters: function parameters.
1. Local Variable:
A variable that is declared within the body of the function or blockis called a local variable. This variable is used only within that block or function where it was created, other classes cannot access it. And is destroyed after exiting the block.
#include <stdio.h>
void differentFunc()
{
/*local variable of this function */
int a = 10;
printf("%d : Variable from differentFunc function\n", a);
}
int main()
{
/*local variable of function main*/
int a = 50;
{
/*local variable for this block*/
int a = 30;
printf("%d : Variable inside the block\n", a);
}
printf("%d : Variable of main\n", a);
//calling function
differentFunc();
}
The output of Local variable in C:
30 : Variable inside the block
50 : Variable of main
10 : Variable of main
2. GlobalVariable:
Global variables are declared outside any functions and usually at the top of the program as shown below. They can be used in the program inside any block of code.
#include <stdio.h>
//Global Variable
int a = 20;
void funGlobal()
{
/*local variable with
same name on different block*/
int a = 50;
printf("%d : Inside funGlobal Function\n", a);
}
int main()
{
printf("%d : Inside main\n", a);
//caling the function
funGlobal();
}
The Output of Global Variable in C.
20 : Inside main
50 : Inside funGlobal Function
3. Formal Parameters
Formal Parameters are the parameters that are used inside the body of a function. Formal parameters are treated as local variables in that function and get a priority over the global variables.
#include <stdio.h>
/*Global variable*/
int a = 20;
void funFormal(int a)
{
/*here a is a formal parameter*/
printf("%d\n", a);
}
int main()
{
funFormal(50);
}
In C programming, data types specify the varying sizes and values in the variables that can be stored. It allocates the memory to store on OS depending on its type.
A data type or simply type is an attribute of data that tells the compiler or interpreter how the programmer intends to use the data. Most programming languages support common data types of real, integer, and boolean.
There are two types of data type in C. They are:
Primary data-type (Primitive data-type)
Derived data-type (Non-primitive data-type)
1.Primitive data type also known as Primary data types or pre-defined data types.
These are int, char, float, void as shown in the table below.
Data type
Size
Range
Description
char
1 byte
-128 to +127
A character
int
2 or 4 byte
-32,768 to 32,767 or -2,147,483,648 to +2,147,483,647
An integer
float
4 byte
1.2E-38 to 3.4E+38
Single precision floating point number
void
1 byte
-128 to +127
void type stores nothing
Character type (char):
It stores a single character and requires a single byte. It can store 128 characters. charkeyword used to define the character type.
Such as: char ch = 'corn';
Integer data type (int):
It is a data type that can only store integers value.intkeyword is used to define integer type in C Language. Integer can have zero, positive or negative value but it cannot be float or decimal value.
The size of the integer type is 2 or 4 bytes and it can store value upto 32,768 to 32,767 or -2,147,483,648 to +2,147,483,647.
Such as int value_name;
Float type(float & double):
It is used to store decimal numbers (numbers with floating-point value) with single precision. float or double the keyword is used to define real numbers type.
The size of a float is 4 bytes and the size of double is 8 bytes. a float can store value up to 1.2E-38 to 3.4E+38 whereas double store value up to 2.3E-308 to 1.7E+308.
Such as: float salary; double price;
Note that:C considers floating-point literal as double type. Add suffix f or F after floating-point literal to specify a type as a float.
void type(void):
As the name suggests, void internally does not store anything. They are used to define a function return type or a generic pointer void * ptr;
It is used in three kinds of situations:
Function returns as void
Function arguments as void
Pointers to void
2. Non Primitive data typealso known as Derived data types:
These are : arrays, pointers, union, structures, etc.
Array:
An array is a collection of data or finite ordered collection of homogeneous data, stored in contiguous memory locations. Arrays are also referred to as structured data types.
Pointers:
The pointer is a variable the stores/points the address of another variable. The pointer is used to allocate memory dynamically. The other variable can be of type int, char, array function, or any other pointer.
Union:
Union in C is also like structure, i.e. collection of different data types that are grouped together and the element is called a member.
Structure:
The structure is a variable that gives the facility to store data of different data types in one variable which is not possible in an array. Structures are variables that have several parts. Each of those parts is called a member of the structure.
Precedence and Associativity are the rules that are used to determine the operators with the highest priority in evaluating an equation that contains different operations.
For example: x = 10 + 5 * 2;
In this example, x is assigned as 20, not 30 that’s because operator * has higher precedence than +, and hence it first gets multiplied (5*2), and then the result is added to 10.
Lists operator precedence and associativity in C
Operator
Meaning of operator
Associativity
() [] -> .
Functional call Array element reference Indirect member selection Direct member selection
Left to right
! ~ + – ++ — & * sizeof (type)
Logical negation Bitwise(1 ‘s) complement Unary plus Unary minus Increment Decrement Dereference Operator(Address) Pointer reference Returns the size of an object Type cast(conversion)
Right to left
* / %
Multiply Divide Remainder
Left to right
+ –
Binary plus(Addition) Binary minus(subtraction)
Left to right
<< >>
Left shift Right shift
Left to right
< <= > >=
Less than Less than or equal Greater than Greater than or equal
Left to right
== !=
Equal to Not equal to
Left to right
&
Bitwise AND
Left to right
^
Bitwise exclusive OR
Left to right
|
Bitwise OR
Left to right
&&
Logical AND
Left to right
||
Logical OR
Left to right
?:
Conditional Operator
Right to left
= *= /= %= -= &= ^= |= <<= >>=
Simple assignment Assign product Assign quotient Assign remainder Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift
From the name constant, we can say that these are fix values that are used in a program and its values remain the same during the entire execution of the program. These fixed values in C are also called Literals.
These constants may be any of the data-types present in C such asinteger constant, a floating constant, a character constant, or a string literal, etc.
Keyword const is used to define the constants in C.
Syntax:
const data-type variable = value;
Example to show the use of constant in C Programming.
#include <stdio.h>
int main()
{
const int LENGTH = 5;
const int BREADTH= 6;
int rectangleArea;
rectangleArea = LENGTH * BREADTH;
printf("Area of a Rectangle: %d", rectangleArea);
return 0;
}
After executing the following code, the output is:
Area of a Rectangle: 30
Following table represent the constant types with example:
constant type
data type(Example)
integer constant
int (45, 657, -845 etc ) unsigned int (4000u, 2000U etc) long int, long long int (483, 6472,147,483,680)
Type Conversion or Type Casting is one the important concept in C programming, it converts one data type to another. It can also be called data conversion. The compiler automatically changes the data type.
In C programming, typecasting operation is of two types:
Implicit type casting
Explicit type casting
Implicit type casting:
Implicit type casting means the conversion of data types without losing its original meaning. The data type is automatically changed. Implicit type casting is essential when users want to change the data types without losing its value stored in a variable.
Example of implicit type casting in C programming:
#include <stdio.h>
int main()
{
char x = 'k'; //ASCII value of k is 107
int y;
y = x; //implicit type casting
printf("Printing character K: %c\n", x);
printf("Printing K ASCII value as integer: %d\n", y);
}
The output if implicit type casting.
Printing character K: k
Printing K ASCII value as integer: 107
Explicit type casting:
As we understood that implicit type conversion is automatic but in some cases, the programmer might need to force the compiler to change the data type. Posing the data type of the expression of a specific type is called Explicit type casting.
The general syntax for type casting operations is:
(type-name) expression;
Here, The type-name is the standard ‘C’ language data type. And an expression can be a constant, a variable, or an actual expression.
Example of Explicit type casting in C programming:
#include <stdio.h>
int main()
{
float f = 94.7;
int a = (int) f + 10;
printf("The Value of f is %f\n", f);
printf("The Value of a is %d\n", a);
return 0;
}
The output if Explicit type casting.
The Value of f is 94.699997
The Value of a is 104
Keep in mind the following rules for programming practice when dealing with different data type to prevent from data loss :
Integer types should be converted to float.
Float types should be converted to double.
Character types should be converted to an integer.