/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2015 * Time: 7:16 PM */ Core Java

Continue/ Next Page

Data Types and Variables in java

Core Java

Relation between Data type and variable

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.


Variables Types :-

Computer programs manipulate (or process) data. A variable is used to store a piece of data for processing. It is called variable because you can change the value stored.
More precisely, a variable is a named storage location, that stores a value of a particular data type.
In other words, a variable has a name, a type and stores a value.

The following diagram illustrates three types of variables: int, double and String. An int variable stores an integer (whole number). A double variable stores a real number. A String variable stores texts.



The word "variable" means changing, because we can change the value stored in it, We can't change its name.
however. Variable names fall in the category of something known as identifiers. Identifiers are names given to things in Java. This includes variables, methods, classes, etc. So far, you don't know anything about methods or classes.don't worry We'll get to them in future tutorials .
An identifier refers to names of "things" in Java.
Java has strict rules about valid identifiers. Make sure you understand them so you don't make errors when you use them.
Here are few tips and example's

don't use blank character in names. It is either not supported (e.g., in Java and C/C++), or will pose you more challenges.

Here are some valid identifiers :-

Although you have great flexibility for identifiers, we're going to make more restrictions for which identifiers we should use. But first, to look at some invalid identifiers.
Examples of Invalid Identifiers

Variable Declaration :-

To use a variable in your program, you need to first "introduce" it by declaring its name and type, in one of the following syntaxes. The act of declaring a variable allocates a storage (of size capable of holding a value of the type).

		// Declare a variable of a specified type
		// i.e. -- type identifier;
				int number;

		// Declare multiple variables of the same type, separated by commas
		// -- i.e. -- type identifier1, identifier2, ..., identifierN;
				double sum, difference, product, quotient;

		// Declare a variable and assign an initial value
		// i.e. -- type identifier = initialValue;
				int myNumber = 88;

		// Declare multiple variables with initial values
		type identifier1 = initValue1, ..., identifierN = initValueN;
				String greetingMsg = "Hi!", quitMsg = "Bye!";

Points to be remeber :-

Constants :-

Constants are non-modifiable variables, declared with keyword final. Their values cannot be changed during program execution.
Also, constants must be initialized during declaration. For examples: final double PI = 3.1415926; // Need to initialize
Constant Naming Convention: Use uppercase words, joined with underscore.
For example, MIN_VALUE, MAX_SIZE

Assignment :-

An assignment statement:

In programming, the equal symbol '=' is known as the assignment operator. The meaning of '=' in programming is different from Mathematics. It denotes assignment of the LHS value to the RHS variable, instead of equality of the RHS and LHS.
The RHS shall be a literal value or an expression that evaluates to a value, while the LHS must be a variable.
The syntax for assignment statement is :-

The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called rvalue or right-value). The rvalue is then assigned to the variable on the left-hand-side (LHS) or lvalue. Take note that you have to first evaluate the RHS, before assigning the resultant value to the LHS.
For examples :-

// Assign the literal value (of the RHS) to the variable (of the LHS)
variable = literalValue;

		number = 8;           		// Assign literal value of 8 to the variable number
		number = number + 1;  // Evaluate the expression of number + 1,
			              //  and assign the resultant value back to the variable number

// Evaluate the expression (RHS) and assign the result to the variable (LHS)
variable = expression;

		8 = number;           		// INVALID
		number + 1 = sum;     // INVALID

Note that x = x + 1 is valid (and often used) in programming. It evaluates x + 1 and assign the resultant value to the variable
While x + y = 1 is allowed in Mathematics, it is invalid in programming (because the LHS of an assignment statement must be a variable).
Some programming languages use symbol ":=", "-<" or "&rt-" as the assignment operator to avoid confusion with equality.

Primitive Types :-

In Java, there are two broad categories of types: primitive types (e.g., int, double) and reference types (e.g., objects and arrays).
We shall describe the primitive types here and the reference types (classes and objects) in the later on OOP( "Object-Oriented Programming")


Example :- minimum, maximum and bit-length of the primitive types

The maximum, minimum and bit-size of int are kept in constans INTERER.MIN_VALUE, INTEGER.MAX_VALUE, INTEGER.SIZE.

		// Print the minimum, maximum and bit-length for primitive types
public class PrimitiveTypesMinMax
	public static void main(String[] args)
			  // int (32-bit signed integer)				OutPut :-
		System.out.println("int(min) = " + Integer.MIN_VALUE);		//int(min) = -2147483648
		System.out.println("int(max) = " + Integer.MAX_VALUE);	//int(max) = 2147483647
		System.out.println("int(bit-length) = " + Integer.SIZE);	//int(bit-length) = 32

		// byte (8-bit signed integer)
		System.out.println("byte(min) = " + Byte.MIN_VALUE);	//byte(min) = -128
		System.out.println("byte(max) = " + Byte.MAX_VALUE);		//byte(max) = 127
		System.out.println("byte(bit-length)=" + Byte.SIZE);	//byte(bit-length)=8

       // short (16-bit signed integer)
       System.out.println("short(min) = " + Short.MIN_VALUE);	//short(min) = -32768
       System.out.println("short(max) = " + Short.MAX_VALUE);	//short(max) = 32767
	   System.out.println("short(bit-length) = " + Short.SIZE);	//short(bit-length) = 16

	    // long (64-bit signed integer)
      System.out.println("long(min) = " + Long.MIN_VALUE);	//long(min) = -9223372036854775808
      System.out.println("long(max) = " + Long.MAX_VALUE);	//long(max) = 9223372036854775807
      System.out.println("long(bit-length) = " + Long.SIZE);	//long(bit-length) = 64

      // char (16-bit character or 16-bit unsigned integer)
      System.out.println("char(min) = " + (int)Character.MIN_VALUE);	//char(min) = 0
      System.out.println("char(max) = " + (int)Character.MAX_VALUE);	//char(max) = 65535
      System.out.println("char(bit-length) = " + Character.SIZE);	//char(bit-length) = 16

      // float (32-bit floating-point)
      System.out.println("float(min) = " + Float.MIN_VALUE);	//float(min) = 1.4E-45
      System.out.println("float(max) = " + Float.MAX_VALUE);	//float(max) = 3.4028235E38
      System.out.println("float(bit-length) = " + Float.SIZE);	//float(bit-length) = 32

      // double (64-bit floating-point)
      System.out.println("double(min) = " + Double.MIN_VALUE);	//double(min) = 4.9E-324
      System.out.println("double(max) = " + Double.MAX_VALUE);	//double(max) = 1.7976931348623157E308
      System.out.println("double(bit-length) = " + Double.SIZE);	//double(bit-length) = 64

String :-

Another commonly-used type is String, which represents texts (a sequence of characters) such as "Hello, world". String is not a primitive type, and will be further elaborated later. In Java, a char is enclosed by single quotes (e.g., 'A', '0'), while a String is enclosed by double quotes (e.g., "Hello"). For example,

String message = "Hello, world!"; // strings are enclosed in double-quotes
char gender = 'm';                // char is enclosed in single-quotes

Choice of Data Types for Variables :-

As a programmer, you need to choose variables and decide on the type of the variables to be used in your programs. Most of the times, the decision is intuitive. For example, use an integer type for counting and whole number; a floating-point type for number with fractional part, String for text message, char for a single character, and boolean for binary outcomes. Rules of Thumb Use int for integer and double for floating point numbers. Use byte, short, long and float only if you have a good reason to choose that specific precision. Use int for counting and indexing, NOT floating-point type (float or double). This is because integer type are precise and more efficient in operations. Use an integer type if possible. Use a floating-point type only if the number contains a fractional part.

Data Representation

Read "Data Representation" if you wish to understand how the numbers and characters are represented inside the computer memory. In brief, It is important to take note that char '1' is different from int 1, byte 1, short 1, float 1.0, double 1.0, and String "1". They are represented differently in the computer memory, with different precision and interpretation.
For example,

byte 1 is "00000001", short 1 is "00000000 00000001", int 1 is "00000000 00000000 00000000 00000001", long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001", float 1.0 is "0 01111111 0000000 00000000 00000000", double 1.0 is "0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000", char '1' is "00000000 00110001", and String "1" is a complex object. There is a subtle difference between int 0 and double 0.0.

Furthermore, you MUST know the type of a value before you can interpret a value. For example, this value "00000000 00000000 00000000 00000001" cannot be interpreted unless you know the type.

Input From Keyboard in Java

You can read input from keyboard via System.in (standard input device). Java SE 5 introduced a new class called Scanner in package java.util to simplify formatted input (and a new method printf() for formatted output described earlier). You can construct a Scanner to scan input from System.in (keyboard), and use methods such as nextInt(), nextDouble(), next() to parse the next int, double and String token (delimited by white space of blank, tab and newline).

	import java.util.Scanner;    // Needed to use the Scanner
	public class ScannerTest {
	   public static void main(String[] args) {
	      int num1;
	      double num2;
	      String str;
	      // Construct a Scanner named "in" for scanning System.in (keyboard)
	      Scanner in = new Scanner(System.in);
	      System.out.print("Enter an integer: ");
	      num1 = in.nextInt();         // Use nextInt() to read int
	      System.out.print("Enter a floating point: ");
	      num2 = in.nextDouble();      // Use nextDouble() to read double
	      System.out.print("Enter a string: ");
	      str  = in.next();            // Use next() to read a String token, up to white space
	      // Formatted output via printf()
	      System.out.printf("%s, Sum of %d & %.2f is %.2f%n", str, num1, num2, num1+num2);

You can also use method nextLine() to read in the entire line, including white spaces, but excluding the terminating newline.

	import java.util.Scanner;    // Needed to use the Scanner
	public class ScannerNextLineTest {
	   public static void main(String[] args) {
	      Scanner in = new Scanner(System.in);
	      System.out.print("Enter a string (with space): ");
	      // Use nextLine() to read entire line including white spaces,
	      //   but excluding the terminating newline.
	      String str  = in.nextLine();
	      System.out.printf("%s%n", str);


For method overloading and Overriding please referer OOP concept

Click here to access OOp's Concept

feel free to ask any of your doubts