Sunday, November 26, 2023

variable in Java जावा में वेरिएबल

In Java, a variable is a named storage location that can hold a value. Variables are fundamental to programming, allowing developers to store and manipulate data in their programs. 
Here are some key points about variables in Java:

1. Declaration:-
Before you can use a variable, you must declare it. This involves specifying the variable's type and name. For example:
int age; // Declaration of an integer variable named "age"

2. Initialization:-
After declaring a variable, you can assign an initial value to it. This is known as initialization.
age = 50; // Initialization of the "age" variable with the value 50

Alternatively, you can combine declaration and initialization in a single line:
int age = 50; // Declaration and initialization in one line

3. Types:- Java is a statically-typed language, meaning that you must declare the type of a variable before using it. Common variable types include `int` (integer), `double` (floating-point number), `char` (character), `boolean` (boolean value), and more.
int count = 10;
double pi = 3.14;
char grade = 'A';
boolean isStudent = true;

4. Naming Rules:-
- Variable names must begin with a letter, dollar sign ($), or underscore (_).
- Subsequent characters can be letters, digits, dollar signs, or underscores.
- Variable names are case-sensitive.
- Java has reserved words that cannot be used as variable names (e.g., `int`, `float`, `class`).

5. Scope:- The scope of a variable refers to the region of the program where the variable can be used. In Java, variables can have different scopes, such as local scope (within a method or block), class scope (as a class field), or global scope (rarely used, but for constants).

public class Example {
// Class-level variable (field)
int globalVar = 5;

public void exampleMethod() {
// Local variable within a method
int localVar = 10;
System.out.println(localVar);
}
}

6. Final Keyword:- You can use the `final` keyword to make a variable a constant (its value cannot be changed once initialized).

final double PI = 3.14159;

Program:- 

public class SimpleInterest{
public static void main(String args[]){
// Declare variables for principal, rate, time, and simple interest
float p, r, t, si;
// Assign values to the variables
p = 1000; // Principal amount
r = 2; // Rate of interest
t = 5; // Time in years
// Calculate simple interest using the formula: SI = (P * R * T) / 100
si = (p * r * t) / 100;
// Print the calculated simple interest
System.out.println("Simple Interest is= " + si);
}
}

No comments:

Post a Comment

Java program to implement file input stream class to read binary data from image file.

import java.io.FileInputStream; import java.io.IOException; public class ReadImageFile {     public static void main(String[] args) {       ...