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.
In this tutorial, we will write a program for method overriding and method overloading. Before that, you should have knowledge on the following topic in Java.
class Dog
{
public void display()
{
System.out.println("I am A Dog");
}
}
class breed extends Dog
{
public void display()
{
System.out.println("Breed: German Shepard");
}
}
public class Main
{
public static void main(String args[])
{
Dog d = new Dog(); // Animal reference and object
Dog b = new breed(); // Animal reference but Dog object
d.display(); // runs the method in Animal class
b.display(); // runs the method in Dog class
}
}
Outputmethod overriding:
I am A Dog Breed: German Shepard
Explanation: In the above example, we can see that ‘b‘ is a type of dog but still executes the display method in the breed class. In the runtime, JVM first looks at the object type and runs the method that belongs to that particular object.
Since the class Dog has the method display, the compiler will have no problem in compiling, and during runtime, the method specific for that particular object will run.
1. Method overloading by changing the data type of Arguments
class MethOverloadingTest
{
void add (int x, int y)
{
System.out.println("sum is "+(x+y)) ;
}
void add (double x, double y)
{
System.out.println("sum is "+(x+y));
}
}
public class Main
{
public static void main (String[] args)
{
MethOverloadingTest sum = new MethOverloadingTest();
sum.add (5,5); // method with int parameter is called.
sum.add (5.5, 5.5); //method with float parameter is called.
}
}
Output:
sum is 10 sum is 11.0
2. Method overloading by changing the number of the argument
class MethOverloadingTest2
{
void Info()
{
System.out.println("Argument List is empty") ;
}
void Info (String c, int id)
{
System.out.println("\nName:"+c+" Id:"+id);
}
void Info (String c, int id, int age)
{
System.out.println("\nName:"+c+" Id:"+id+" Age:"+age);
}
}
public class Main
{
public static void main (String[] args)
{
MethOverloadingTest2 sum = new MethOverloadingTest2();
sum.Info(); //method with empty parameter is called.
sum.Info ("Karan",1101); // method with two parameter is called.
sum.Info ("Prashant",1102,23); //method with three parameter is called.
}
}
C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by the European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO).
C# was developed by Anders Hejlsberg and his team during the development of the .Net Framework. It is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows the use of various high-level languages on different computer platforms and architectures.
This language is also used to develop Web Applications, apps, and also in game development.
The below points are the reason why C# is widely used in various platform:
It is a modern, general-purpose programming language.
It is easy to learn and easily understandable.
It is an object-oriented language.
It is a component-oriented and structured language.
It can be compiled on a variety of computer platforms.
It is a part of .Net Framework through which memory management becomes easy.
C# is used in almost all the developer fields such as developing applications, games and more.
Following is the list of few important features of C#:
Variables are like a storage unit that stores the values of various data-types present in a C# programming language. The types are different in C# and accordingly, the memory sizes are allocated to those types to store data values.
Consider an example where you have declared a variable of type int that means that the int variable will be allocated to a memory where it will integer values and some specific operation can be performed.
And for operation, consider the variable int that you described and since it is an integer the operation like addition and subtraction, multiplication, or modulus is performed on those integer operands.
C# consists of various types variables provided by its data-types:
int: It stores integers values such as 65 or -65.
double: It stores floating-point numbers such as 15.34 or -15.34.
char: It stores the character in a single-quotes such as ‘s‘.
string: It is for storing the string in double quotes such as “simple code“
bool: It states two values: true and false.
Like variables in C, C++, java or any other programming language, the variable is declared before use and can be modified at runtime within any section of the code depending upon its types.
Syntax:
data-type variable_name = value;
or
data-type variable_name;
How to declare variable in C#?
It is simple to declare a variable and it must be declared before the use of that variable. You need to specify the data-type for the variable and also give it a unique name.
//syntax
<data-types> <variable_name>;
As mentioned above data-types can be of any type: int, float, double, char, string or bool, according to the need.
Let us see an example how you can declare it in a program.
int number;
char ch;
double d;
float flt;
How to initialize a variable in C#?
Initialization means giving the variable an initial value to start with. We can initialize the variable at the declaration part such as: int number = 45;.
The syntax is simple, first, start with the data-types and unique name the same as a declaration and then assign it a value with equal sign ‘=’.
The data value is always assigned at the right-hand sign of the assignment operator ‘=‘. Let us see some valid examples of how you can initialize a variable.
int num1 = 45, num2 = 67;
double pi = 3.14159;
char ch = 's';
In the above example as you can see the first line contains two initialization which is possible considering you ant the two variable n you program to be an integer type.
User Inputs
Sometimes in a program you need to the value from the user and store it in a variable and use those variable at run time in a programs.
To accept the inputs from the user, C# provides a particular function named as ReadLine() that take the inputs and store it in a variable. It is present in the console class in the System.
How to use it in a program:
int number;
number = Convert.ToInt32(Console.ReadLine());
The above example specifies that the variable is declared and it takes the user input and places it in a number variable. Conversion of inputs to integer data-type is done by Convert.ToInt32 and acceptance of input is completed by Console.ReadLine() in the program.
C# defines two kinds of expressions:
lvalue: The expression may appear on either on the right-hand side or the left-hand side of the assignment operator.
rvalue: The expression can only appear on the right-hand side but not on the left-hand side of the assignment operator.
Variables are lvalue expression as it can appear on the right-hand side as well as on the left-hand side of an equal sign’=’ in a program. However numeric values are rvalues as it can only be assigned to the right-hand side of the ‘=’ value.
This is because the assignment operator(=) always assigns the right-hand side value to the left-hand side and we cannot assign something to a numeric value that is why they are the rvalue.
Look at the below example that shows which are valid and which are not.
There are few rules you need to follow which naming the variables such as it must be unique, it has to be letters, digits, or the underscore _. Variables are case sensitive that is Number and number are considered different variables.
As we know the variables holds the data and the type of data that it holds refers to the data-types. Theses types are: integer, float, double, boolean, etc. and each of this data-types has a specific size such as integer has the memory size of 4 byte and so on.
Now, C# has categorized its data-types in three different parts:
Value types: int, float, short, char, etc.
Reference types: String, Class, Object and Interface
Pointer types: simply Pointers
C# contains two general categories of built-in data types: value types and reference types.
The difference between the two types is what a variable contains.
For a value type, a variable holds an actual value, such 3.1416 or 212.
For a reference type, a variable holds a reference to the value.
Let us discuss each of them:
1. Value types
Value types are derived from the class System.ValueType. They refer to the direct value used in the program such as integers, float, double and more. These data-types are both integer-based and floating-point types. Memory allocates for the memory space whenever some value type is assigned.
Value types are of two types, Predefined Data Types (Integer, Boolean, etc) and User-defined Data Types (Structure, Enumerations, etc).
Follow the table below for the value type list in C#:
Data Types
Memory Size
Range
int
4 byte
-2,147,483,648 to -2,147,483,647
float
4 byte
1.5 * 10-45 – 3.4 * 1038, 7-digit precision
short
2 byte
-32,768 to 32,767
char
1 byte
-128 to 127
long
8 byte
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
double
8 byte
5.0 * 10-324 – 1.7 * 10308, 15-digit precision
signed short
2 byte
-32,768 to 32,767
unsigned short
2 byte
0 to 65,535
signed int
4 byte
-2,147,483,648 to -2,147,483,647
unsigned int
4 byte
0 to 4,294,967,295
signed long
8 byte
?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
unsigned long
8 byte
0 – 18,446,744,073,709,551,615
decimal
16 byte
at least -7.9 * 10?28 – 7.9 * 1028, with at least 28-digit precision
Memory size changes according to the Operating System.
2. Reference Types
Reference types are a bit different than Value Types, this kind of data-types do not contain the actual data stored in a variable, but they contain a reference to the variables.
Reference types specify to the memory location and if the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value.
They are also of two types, Predefined Data Types (Objects, String and Dynamic) and User-defined Data Types (Classes, Interface).
3. Pointer Type
It is also known as the indicator as it points to the address of a value. Pointer type variables store the memory address of another type. The abilities to do the task is same as the pointers that we use in C or C++.
Literals refer to fixed values that are represented in their human-readable form. For the most part, literals and their usage are so intuitive that they have been used in one form or another by all the preceding sample programs.
For example, the number 100 is a literal.
C# literals can be of any simple type. The way each literal is represented depends upon its type.
To specify a float literal, append an F or f to the constant. For example, 10.19F is of type float.
To specify a decimal literal, follow its value with an m or M. For example, 9.95M is a decimal literal.
Literals can be any of the following types that can be used in a program:
Integer Literals
Floating-point Literals
Character Literals
String Literals
Null Literals
Boolean Literals
Integer Literals
An integer literal can be decimal(base 10) or hexadecimal(base 16) constant or Octal(base 8). A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
For unsigned and signed, the suffix U and L are used. And the only rule is you can represent these suffix either in uppercase or the lower case and in any order you may prefer.
Example of integer literals:
20 // simply int
30u // u for unsigned int
30L // l for long
Floating-Point Literals
Literals is called the floating-point literals if it has the following part:
an integer part
a decimal point
a fractional part
an exponent part
We can constitute them in decimal or exponential form. Representation of decimal form required the decimal point or the exponent or the both while the exponential form required the integer part or the fractional part or both.
By default, the floating-point literals are of double type and assigning it directly to a float variable is not possible. Instead, we can use the suffix for a float that is I or F.
Some example to show how can it be used and how it can’t be used in a program:
Character literals are those literals that are enclosed within the single quote(‘ ‘) such as ‘S’ is stored as a character. we can represent the character literals in several ways:
Single quote: These are the plain character enclosed within a single quote. Eg: char c = 'S';
Unicode Representation: These are the universal character denoted in Unicode such as char c = '\u0061'; //this Unicode value represents a character.
Escape Sequence: This is also a character literal that can be used as a character such as char c = '\t';
The following table shows some escape sequence that are used in a program with their meaning. Go through them carefully.
Escape sequence
Meaning
\\
\ character
\’
‘ character
\”
” character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\xhh . . .
Hexadecimal number of one or more digits
String Literals
This type of literals is enclosed within double-quotes (“”) or with @””. A string also enclosed the same character as the character literal does such as plain character, universal characters and more.
The below example show how the string literals are represented in a program.
This literal has only two values that show the result and they are true and false. You can assign the value at the beginning while declaring the boo as shown in an example below.
In this article, we learn all about JVM and its architecture and also we will compare JDK, JRE, and JVM with important points required.
What is JVM?
JVM stands for Java Virtual Machine, which is an abstract machine that provides a run-time environment to run Java programs. It converts Java byte-code into machine language, so not only Java but it also enables the computer to run other programs that are compiled to byte-code.
JVM is a part of the JRE(Java Run Environment). However, the reason for the Java program is executed by the JVM helps to solve the major problems related to web-based programs and also to make it secure.
JVM working process can be explained in the following manner:
It first loads byte-code.
then verifies the byte-code.
Then executes byte-code providing runtime environment.
JVM Architecture:
1. ClassLoader subsystem:
This subsystem is used for loading class files. It performs three major functions :
Loading, Linking, and Initialization.
There are three built-in classloaders in Java.
Bootstrap ClassLoader: It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes.
Extension ClassLoader: It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System ClassLoader: It loads the class files from the classpath. Also known as Application classloader.
2. JVM Memory:
Method Area: In the method area, structures like the run-time constant pool, field and method data, variables information, static variables, etc. are stored.
Heap: It is a shared resource among all the threads and created during run-time. All the Objects, metadata, and arrays are stored in the heap.
JVM language Stacks: Java language Stacks stores parameters, local variables, and return addresses during method calls. It is not a shared resource. One JVM stack is created simultaneously for each thread that is each thread contains its own JVM stack.
PC Registers: PC(Program Counter) Register contains/stores the address of JVM(Java Virtual Machine) instruction that is being currently executed. Each thread in Java has its own PC register.
Native Method Stacks: Every thread has its own separate native stack hold the native method information.
3. Execution Engine:
The execution engine executes the bytecode, reading it line by line.
It contains three parts:
Interpreter: The work of the interpreter is to read the byte-code line by line and then execute it.
Just-In-Time Compiler(JIT): It is used to increase the performance of the compiler by taking the block of similar byte-code that is the repeated method calls. Hence reducing the compilation time and making it more efficient.
Garbage Collector: It is used to destroy the useless objects or objects that are no longer required.
4. Java Native Interface (JNI):
It provides the native libraries required for the execution of a program. It allows the JVM to call other Libraries like C, C++, Assembly, etc., providing the interface to interact with other Native Application.
5. Native Method Libraries:
This is a collection of the Native Libraries(C, C++) which are required by the Execution Engine. These are the “native” codes, that is, the code that is compiled for a specific hardware architecture or operating systems such as X86 or windows.