What is Constants?
Constants in Java refer to fixed values that are not changed during the Execution of the program. Java supports several types of Constants. They are,
Single Character Constants
Backslash Character Constants
Integer Constants refers to a Sequence of digits. There are three types of Integer Constants, namely,
Decimal Integer Constant
Octal Integer Constant
Hexadecimal Integer Constant
Decimal Integer Constants:
Decimal constant consists of a set of digits 0 through 9, preceded by an optional minus (- ) sign.
Eg: 42, 78, - 187
Spaces, Commas and non-digit characters are not permitted between digits.
Eg: 25 763 52,523
Octal Integer Constants:
An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading 0. Eg: O46, O56, O71
Hexadecimal Integer Constants:
A sequence of digits proceeds by ox/OX. They may also include alphabets A through F/through f, this alphabets represents the numbers 10 through 15.
Eg: OX4, OX8C, OX57eb
Integer numbers are inadequate to represent quantities that vary continuously, such as distances, heights, temperatures, prices, and so on. These quantities are represented by numbers containing fractional parts like 54.273. Such numbers are called Real/Floating point constants.
Eg: 0.0087, -0.45, 325.16
These numbers are shown in Decimal Notation, having a whole number followed by a decimal point and the fractional part, which is an Integer. It is possible that the number may not have digits before the decimal point or digits after the decimal point. That is,
Eg: 541. , .87, -.31 are all valid real numbers.
The Mantissa is either a real number expressed in decimal notation/an Integer. The Exponent is an integer with an optional plus/minus sign. The letter e separating the Mantissa and the Exponent can be written in lowercase/ uppercase. Since the Exponent causes the decimal point to “float”, this notation is said to represent a real number in floating point form.
Eg: 0.67e3, 31e-5, 4.5e+6, 7.51E1, -6.2E-6
A real number may also be expressed in Exponential/Scientific Notation.
Eg: 451.25 may be written as 4.5125e2. [e2 means multiply by 10^2 ]
Exponential Notation is useful for representing numbers that are either very larger or very small in magnitude.
Eg:6500000000 may be written as 6.5E9/65E8. Similarly, -0.000000621 is equivalent to -6.21E-7
A Floating-point constant may thus comprise four parts. They are a:
Single Character Constants:
A single character constant/simply character constant contains a single character enclosed within a pair of single quote marks.
Eg: ‘3’, ‘N’, ‘:’, ‘ ’
Here, the character constant ‘3’ is not the same as number 3. The last constant is blank space.
A String Constant is a sequence of characters enclosed between double quotes. The characters may be alphabets, digits, special characters, and blank spaces.
Eg: ”HELLO”, “1967”, “GOOD MORNING”, “/….*”, “6%2”, “J”
Backslash Character Constants:
Java supports some special backslash characters constants that are used in output methods.
Eg: the symbol ‘ n’ stands for the newline character.
The list of backslash character constants,
‘ b ’ backspace
‘ f ’ form feed
‘ n ’ new line
‘ r ’ carriage return
‘ t ’ horizontal tab
‘ ’ ‘ single quote
‘ “ ’ double quote
‘ ‘ backslash
A variable plays a major role in a class as it is used to store a data value. When we define a class, we can declare a member variable. These variables are members of a class.
• string - stores text, such as "Hello". String values are surrounded by double quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
• boolean - stores values with two states: true or false
Declaring (Creating) Variables:
Declare a variable to specify the types (int, float, char, etc..,) and assign it a value
type variable = value;
Here, type refers to the datatype of Java and variable refers to the name of that variable
(1 )Creating a variable and assign the value as a name:
Eg: String name = "Ravi";
(2) Create a variable and assign the value as number:
Eg: int myNum = 15;
(3) Declare a variable without assigning the value and assign the value in a later step:
Eg: int myNum;
myNum = 15;
Declaring the variable using other data types
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
(1) The println() method is often used to display variables. To combine both text and a variable, use the + character:
String name = "David";
System.out.println("Hello " + name);
(2) You can also use the + character to add a variable to another variable:
String firstName = "Raj";
String lastName = "Kumar";
String fullName = firstName + lastName;
(3) For numeric values, the + character works as a mathematical operator (notice that we use int (integer) variables here):
Eg: int x = 5;
int y = 6;
System.out.println(x + y);
Declare Many Variables:
To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
All Java variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, total volume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs
Names should begin with a letter
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive ("myVar" and "myvar" are different variables)
Names should start with a lowercase letter and it cannot contain whitespace
Reserved words (like Java keywords, such as int or String) cannot be used as names
SCOPE OF VARIABLES:
• Local variable
• Instance variable
• Class/Static variable
A variable which is declared inside the method is called local variable
A variable which is declared inside the class but outside the method is called an instance variable. It is not declared as static.
A variable that is declared as static is called static variable. It cannot be local.
Example to understand the types of variables:
int data=50;//instance variable
static int m=100;//static variable
int n=90;//local variable
}//end of class
Data Types specify the size and type of values that can be stored. Every variable in Java has a Data Type. Java language is rich in its Data Types. The variety of Data Types available allows the programmer to select the type appropriate to the needs of the application. Data Types in Java is classified into TWO types. They are,
i. Primitive Data Types [also called Intrinsic/Built-In Types]
ii. Non-Primitive Data Types [also known as Reference Types]
[ Eg: Array, Class, etc..,]
Primitive Data Types are divided into TWO types. They are,
a) Integer Types
b) Floating Point Types
(1) Integer Types can hold whole numbers such as 123, -.96, and 5639. The size of the values that can be stored depends on the Integer Data Type we choose. Java supports FOUR types of Integers. They are a byte, short, int, long. Java does not support the concept of Unsigned types and therefore all Java values are signed meaning they can be positive and negative.
SIZE AND RANGE OF INTEGER TYPES
Type Size Minimum Value Maximum value
byte One byte -128 127
short Two bytes -32,767 32,767
int Four bytes -2, 147, 483, 648 2, 147, 483, 647
long Eight bytes -9,223,372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807
(2)This refers to the memory size and range of all four Integer Data Types. It should be remembered that wider Data Types require more time for manipulation and therefore it is suitable to use smaller Data Types.
Eg: Storing a number like 30 in an int type variable. Instead of int, we use byte variable to handle the number and also improve the speed of execution of the program.
(3) Long Integer Type denotes the letter L (or) l at the end of the number.
Eg: 415L (or) 415l
Floating Point Types:
(1) Floating Point Types can hold numbers. It’s containing fractional parts such as 27.59 and -1.375 (known as Floating Point Constants). Floating Point Types can be divided into TWO types,
o Float Type values represent Single-Precision numbers
o Double Type values represent Double-precision numbers
SIZE AND RANGE OF FLOATING POINT TYPES
Type Size Minimum Value Maximum Value
float 4bytes 3.4e-038 3.4e+038
double 8bytes 1.7e-308 1.7e+308
(2) Floating point numbers are treated as Double-Precision quantities. To force them to be in Single-Precision mode, we must append f (or) F to the numbers.
Eg: 3.1458f, 5.6547e3F
(3) Floating point data types support a special value known as Not-a-Number [NAN]. It is used to represent the result of operations such as dividing Zero by Zero, where an actual number is not produced. Most operations that have NaN as an operand will produce NaN as a result.
Java provides a Character Data Type called char. These type stores a character constant in memory. It assumes a size of 2 bytes but it can hold only a Single Character.
Boolean Type is used for testing a particular condition during the execution of the program. It has two values namely, TRUE/FALSE. These values are taken as keywords. Boolean type is denoted by boolean keyword and uses only one bit of storage. All comparison operators return only boolean type values. It also used in Selection and Iteration Statements.
When you assign the value of one data type to another, the two types might not be compatible with each other. If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion or widening and if not then they need to be cast or converted explicitly known as casting or narrowing.
Casting is an operation that converts a value of one data type into a value of another data type. Casting a type with a small range of a type with a larger range is known as widening a type. Casting a type with a large range of a type with a smaller range is known as narrowing a type. It is always possible to assign an int value to a long variable. There is no automatic conversion defined from double to byte.
Automatic Conversions or widening:
(1) When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are,
The two types are compatible.
The destination type is larger than the source type.
(2)When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required.
Casting Incompatible Types or Narrowing:
(1) When one type of data is assigned to another type of variable, a narrowing type conversion will take place if the following two conditions are met:
The two types are incompatible.
The destination type is smaller than the source type.
(2) When these two conditions are met, a narrowing conversion takes place. For example, the int is not large enough to hold all valid double values, so an explicit cast statement is required.