Data type variable in java

Java Variables and Data Types with EXAMPLE

Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold. Variable is a memory location name of the data. The Java variables have mainly three types : Local, Instance and Static.

In order to use a variable in a program you to need to perform 2 steps

In this tutorial, you will learn-

Variable Declaration:

To declare a variable, you must specify the data type & give the variable a unique name.

Variable Declaration

Examples of other Valid Declarations are

int a,b,c; float pi; double d; char a;

Variable Initialization:

To initialize a variable, you must assign it a valid value.

Variable Initialization

Example of other Valid Initializations are

You can combine variable declaration and initialization.

combine variable declaration and initialization

int a=2,b=4,c=6; float pi=3.14f; double do=20.22d; char a=’v’;

Types of variables

In Java, there are three types of variables:

1) Local Variables

Local Variables are a variable that are declared inside the body of a method.

2) Instance Variables

Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables.

3) Static Variables

Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables.

Example: Types of Variables in Java

What is Data Types in Java?

Data Types in Java are defined as specifiers that allocate different sizes and types of values that can be stored in the variable or an identifier. Java has a rich set of data types. Data types in Java can be divided into two parts :

  1. Primitive Data Types :- which include integer, character, boolean, and float
  2. Non-primitive Data Types :- which include classes, arrays and interfaces.

Java Data Types

Primitive Data Types

Primitive Data Types are predefined and available within the Java language. Primitive values do not share state with other primitive values.

There are 8 primitive types: byte, short, int, long, char, float, double, and boolean

Integer data types

byte (1 byte) short (2 bytes) int (4 bytes) long (8 bytes)

Integer data types

Floating Data Type

float (4 bytes) double (8 bytes)

Textual Data Type

Data Type Default Value Default size
byte 0 1 byte
short 0 2 bytes
int 0 4 bytes
long 0L 8 bytes
float 0.0f 4 bytes
double 0.0d 8 bytes
boolean false 1 bit
char ‘\u0000’ 2 bytes

Points to Remember:

  • All numeric data types are signed(+/-).
  • The size of data types remain the same on all platforms (standardized)
  • char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports internationalization. UNICODE is a character set which covers all known scripts and language in the world

Java Variable Type Conversion & Type Casting

A variable of one type can receive the value of another type. Here there are 2 cases –

Читайте также:  Find java installation path

Case 1) Variable of smaller capacity is be assigned to another variable of bigger capacity.

Java Variables and Data Types

This process is Automatic, and non-explicit is known as Conversion

Case 2) Variable of larger capacity is be assigned to another variable of smaller capacity

Java Variables and Data Types

In such cases, you have to explicitly specify the type cast operator. This process is known as Type Casting.

In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is enforced by the compiler, it makes the programmer aware that the conversion he is about to do may cause some loss in data and prevents accidental losses.

Example: To Understand Type Casting

Step 1) Copy the following code into an editor.

Step 2) Save, Compile & Run the code.

Expected Output:

int converted to byte a and x 270 14 double converted to int b and a 128.128 128 double converted to byte b and x 128.128 -128

Источник

Data Types and Variables

Lakshay Sharma

Enroll in Selenium Training

Having a good understanding of Data types and variables is the basic step towards understanding programming. This chapter is critical and please go through the details and practice the exercises given below related to Data types and Variables in Java.

What is Variable?

As its names suggest, variable is a value that can change. A simple computer program uses a set of instructions and data. Data can be constants or fixed values that never change and it can be variable that can change during the execution. Rather than entering data directly into a program, a programmer can use variables to represent the data. When compiler runs the program, variables used in the instructions are replaced with the real data entered by the programmer.

In technical terms, a variable is a reserved space or a memory location to store some sort of information. Information can be of any data type such as int, string, bool or float. Each variable in the program has its space allocated in the memory and based on the data type, the system allocates only required memory to the variables.

Every variable in the program has its name and data type.

How Variables work?

Declaring Variables: Ask the compiler to allocate some amount of memory to the variable for storing some value. As compiler would like to know the data type of the variable so that it can allocate only required memory to the variable. That can be done by ‘declaring the data type‘ of the variable.

Naming Variables: After variable declaration, when the program needs the stored value, the compiler will go to the memory location to fetch the value and pass it back to the program. To effectively handle this transaction, the compiler would need two pieces of information from the program: name and data type of the variable. Give the name of your choice to the variable and let the compiler know about it. So that next time when you refer to that name, the compiler would know what piece of memory you are referring to. The name of the variable is called the Identifier.

This process is called as Variable Declaration.

Initialization of Variables: Once the variable declaration is done, then a value can be stored in the reserved memory location. Before that, you would not be able to use the variable. The initialization of a variable is very important before using the variable for any sort of operation. Putting an initial value is referred to as Initializing the Variable.

What is Data Type?

A data type indicates what sort of value or the type of data the variable can represent, such as integer, floating-point numbers, character, boolean or an alphanumeric string.

There are other data types as well like short, long and float but in Selenium programming you may not face any situation where you have to use these data types. These data types are used when each byte of memory is important for better performance of the system.

Читайте также:  Как поставить на фон картинку в HTML

Examples of different data types

Data Type — boolean

Boolean data type is used to store only ‘boolean‘ values such as ‘true‘ and ‘false‘. To declare a Boolean variable, you can use the ‘boolean‘ keyword.

package JavaTutorials; public class BooleanTestExercise < public static void main(String[] args) < //Use the boolean keyword to declare boolean variable boolean testResult; //Initialize the boolean variable with value true or false, once boolean declaration is done testResult = true; //Print the value of boolean variable System.out.println("Test Result is: " + testResult); //Change the value of boolean variable testResult = false; //Print the value of boolean variable System.out.println("Test Result is: " + testResult); > > 

Above test will produce this:

Data Type — int

Integer data type is used to store numeric/numbers in the variable. In technical term, an integer store 32- bit of information and it stores the value between -2,147,483,648 and 2,147,484,647. But a decimal number can not be stored in the ‘int‘ data type.

package JavaTutorials; public class IntegerTestExersice < public static void main(String[] args) < //Use the int keyword to declare integer variable int carSpeed; //Initialize the integer variable with value 20 carSpeed = 20; //Print the value of integer variable System.out.println("Car is running at the speed of: " + carSpeed); //Change the value of integer variable carSpeed = carSpeed + 20; //Print the value of integer variable System.out.println("Current speed of the car is: " + carSpeed); > > 

Above test will produce this:

Car is running at the speed of : 20

Current speed of the car is: 40

Data Type — char

Character data type is used to store just one character in the variable. It is very rarely used in Selenium. To initialize such a variable, assign a character within the single-quoted.

package JavaTutorials; public class CharTestExercise < public static void main(String[] args) < //Use the char keyword to declare character variable char a; //Initialize the char variable with value 'P' a = 'P'; //Print the value of char variable System.out.println("Value of char is : " + a); > > 

Above test will produce this:

Data Type — double

To declare a variable used to hold such a decimal number, you can use the double keyword.

package JavaTutorials; public class DoubleTestExercise < public static void main(String[] args) < //Use the double keyword to declare decimal variable double PI; //Initialize the double variable with value 'P' PI = 3.14159; //Print the value of double variable System.out.print("PI: " + PI); > > 

Above test will produce this:

Notes: Rules for naming a variable

  1. A variable name can be of single letter of alphabets (A-Z).
  2. Variable name can start only with a letter, under score ‘_’ and the dollar sign ‘$’.
  3. A variable name can not start with digit.
  4. A variable name can include digits.
  5. The name of a variable cannot be one of the words that the Java languages have reserved for its own use such as static, this, void, final, for, etc.

Everybody follows their own pattern to declare variables and I follow my own. I usually declare all the string variables with small letter ‘s‘ and int variable with small letter ‘i‘. So that in my program when I see any variable starts with the letter ‘s‘, I can understand that it is a String variable. For example:

Читайте также:  Формула трех восьмых питон

Example of declaring multiple variables:

int a, b, c; // Declares multiple int, a, b, and c. int a = 10, b = 20, c= 30; // Example of multiple initialization 

Core Java — Data Types/Variables Practice Exercises, Programs & Questions

1. Write a Java program to print «Hello World» on the screen.
Ans:

public class HelloWorld < public static void main(String[] args) < System.out.println("Hello World"); > > 

2. Write a Java program to print the following output:

public class PrintPattern < public static void main(String[] args) < System.out.println("++++++"); System.out.println("@@@@@@"); System.out.println("******"); System.out.println("######"); > > 

3. Write a Java program to declare three variable a, b, & c and store the values respectively 10, 20.3 & 3.14785 . Then display their values on the screen.
Ans:

public class Exercise_DataType_1 < public static void main(String[] args) < int a = 10; double b = 20.3; double c = 3.14785; System.out.println("The value of a is : "+ a); System.out.println("The value of b is : "+ b); System.out.println("The value of c is : "+ c); > > 

The value of c is : 3.14785

4. Write a Java program to declare a Boolean variable with initial value of «true» and later change it to «false» before printing it.

public class Exercise_DataType_2 < public static void main(String[] args) < boolean value = true; value = false; System.out.println("The value for the Boolean variable is : "+ value); > > 

The value for the Boolean variable is : false

Q1. Which four options are correct in terms of Data Types and their syntax:

 // 1 int value = "ToolsQA"; // 2 int value = 67; // 3 boolean booleanValue = 67; // 4 boolean booleanValue = "ToolsQA"; // 5 boolean booleanValue = "true"; // 6 boolean booleanValue = false; 

Q2. What is the purpose of System.out.println() method?
Ans: Display output on the Console

Q3. Which of the following is not a numerical type?
Options
A – int

Ans: Option B — char

Q4. Which one of the below is not the integer value? Options

E — 103.45
Ans: Option D — ’67’

Q5. What are the data types of the following values?

1. Find the syntax error in the below program:

 public static void main(String[] args) < System.out.println("ToolsQA") > 

Resolution: Missing semi-colon(;), correct statement is:

2. Find the syntax error in the below program:

 public static void main(String[] args) < System.out.println('ToolsQA'); > 

Resolution: Missing single quote( ‘ ) instead of double quotes( » ) around the string, Correct statement is:

3. Find the error in the below program:

 public static void main(String[] args) < integer value = 18; System.out.println("The value of the integer variable is : " + value); > 

Resolution: Integer is not a data type, it should be int;

4. Find the errors in the below program:

 public static void main(String[] args) < valueInt int = 18; valueDob double = 10.10; valueBool boolean = true; > 

Resolution: Data types declarations are not correct, these should be:

 int valueInt = 18; double valueDob = 10.10; boolean valueBool = true; 

Источник

Оцените статью