Java Constants, Variables, and Data Types
Java Constants
In Java, constants are typically variables that are marked as final
and cannot be changed once assigned. Constants are used to define values that should remain the same throughout the execution of the program. Here’s how you can create constants in Java:
Integer Constants
In Java, integer constants are values that represent fixed integer numbers and are defined using the int
or long
data types. Integer constants can be declared using the final
keyword and are often made static
if they are part of a class.
Types of Integer Constants:
- Decimal: Standard integer literals (e.g.,
10
,42
,100
). - Hexadecimal: Prefixed with
0x
or0X
(e.g.,0x1A
,0xFF
). - Binary: Prefixed with
0b
or0B
(e.g.,0b1010
,0b1101
). - Octal: Prefixed with
0
(e.g.,012
,077
).
Real Constants
In Java, real constants refer to floating-point numbers, which represent real numbers (numbers with decimal points). These constants are typically declared using the float
or double
data types. Like integer constants, real constants are often declared as final
and sometimes static
if they belong to a class.
Types of Real Constants in Java:
- Float: Represented by the
float
type, typically for single-precision values. Float constants must be suffixed with anf
orF
. - Double: Represented by the
double
type, typically for double-precision values (this is the default type for floating-point literals).
example:
class Real_Constants {
public static final float PI = 3.14159f;
public static final float GRAVITY = 9.8f;
public static void main(String[] args) {
System.out.println("PI: " + PI);
System.out.println("Gravity: " + GRAVITY);
}
}
Character Constants
In Java, character constants refer to single characters enclosed in single quotes (' '
). These constants represent values of the char
data type, which holds a single 16-bit Unicode character. Character constants are used to store individual letters, digits, or special symbols and are represented using the char
keyword.
Declaring Character Constants
A character constant is always enclosed in single quotes. The char
type can store any valid Unicode character, including special characters.
Example:
char letter = 'A';
char digit = '1';
char symbol = '$';
Escape Sequences
Certain characters, like newlines, tabs, or single and double quotes, are represented using escape sequences, which start with a backslash (\
).
\n
: Newline\t
: Tab\'
: Single quote\"
: Double quote\\
: Backslash
String constants
In Java, String constants refer to immutable sequences of characters that are enclosed in double quotes (" "
). Strings are widely used in Java programs to store and manipulate text. String constants are represented by the String
class, and once defined, they cannot be changed (i.e., they are immutable).
Declaring String Constants
String constants can be declared using the final
keyword to make them constant and unchangeable.
Example:
The final
keyword is used to declare a constant. Once a final
variable is assigned a value, it cannot be modified.
example:
final int DAYS_IN_WEEK = 7;
Java Variable
In Java, variables are containers that hold data values. Each variable has a data type, which defines what kind of values the variable can store, and a name that allows you to reference it in your code.
Types of Variables in Java
Java supports different types of variables based on their scope and usage:
1.Local Variables: Declared inside methods, constructors, or blocks and are only accessible within that block.
2. Instance Variables: Also known as fields, they are declared in a class but outside any method, and they represent the state of an object.
3. Class Variables (Static Variables): Declared using the `static` keyword inside a class, these variables belong to the class rather than to any object instance.
4.Parameters: Variables passed to methods or constructors as input.
Declaring Variables
A variable declaration consists of the **type** of the variable and its name. Optionally, it can be initialized at the time of declaration.
Syntax:
Data_type variable_Name = value;
1. Local Variables
Local variables are defined inside a method or block and have scope only within that block. They must be initialized before use.
class Example
{
public static void main(String[] args)
{
int age = 25; // Local variable
System.out.println("Age: " + age);
}
}
2. Instance Variables (Fields)
Instance variables are declared within a class but outside methods. They are initialized to default values if not explicitly initialized.
class Person {
String name; // Instance variable
int age; // Instance variable
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
3. Class Variables (Static Variables)
Static variables are shared across all instances of a class and belong to the class itself rather than to any individual instance. These variables are defined with the `static` keyword.
class Company {
public static String companyName = "OpenAI";
public static void main(String[] args) {
System.out.println("Company: " + companyName);
}
}
4. Method Parameters
Method parameters are variables that are passed into methods and constructors.
class Calculator {
public int add(int a, int b) {
// 'a' and 'b' are parameters
return a + b;
}
public static void main(String[] args)
{
Calculator calc = new Calculator();
int sum = calc.add(5, 10); // Arguments passed to parameters
System.out.println("Sum: " + sum);
}
}
Java Data Types
In Java, **data types** define the type and size of data that a variable can hold. Java is a strongly typed language, meaning that every variable must have a data type, which is determined at compile time. Data types are divided into two main categories: **primitive types** and **reference types**.
1. Primitive Data Types
These are the basic types built into the language. They hold simple values like numbers, characters, and booleans.
#### Primitive data types in Java:
| Data Type | Size | Default Value | Description |
|------------|------------|---------------|---------------------------------------|
| `byte` | 1 byte | 0 | Stores integers from -128 to 127 |
| `short` | 2 bytes | 0 | Stores integers from -32,768 to 32,767|
| `int` | 4 bytes | 0 | Stores integers from -2^31 to 2^31-1 |
| `long` | 8 bytes | 0L | Stores integers from -2^63 to 2^63-1 |
| `float` | 4 bytes | 0.0f | Stores floating-point numbers (single precision)|
| `double` | 8 bytes | 0.0 | Stores floating-point numbers (double precision)|
| `char` | 2 bytes | '\u0000' | Stores a single 16-bit Unicode character|
| `boolean` | 1 bit | `false` | Stores `true` or `false` values |
#### Examples:
```java
public class PrimitiveTypesExample {
public static void main(String[] args) {
byte b = 10; // 1 byte
short s = 300; // 2 bytes
int i = 10000; // 4 bytes
long l = 100000L; // 8 bytes
float f = 5.75f; // 4 bytes
double d = 19.99; // 8 bytes
char c = 'A'; // 2 bytes
boolean isJavaFun = true; // 1 bit
System.out.println("Byte: " + b);
System.out.println("Short: " + s);
System.out.println("Int: " + i);
System.out.println("Long: " + l);
System.out.println("Float: " + f);
System.out.println("Double: " + d);
System.out.println("Char: " + c);
System.out.println("Boolean: " + isJavaFun);
}
}
```
### 2. **Reference Data Types**
Reference types store references (or addresses) to objects in memory, rather than the actual data itself. All non-primitive types are reference types. Examples include classes, arrays, and interfaces.
Key reference data types:
String
: Represents a sequence of characters.String name = "John Doe";
- Arrays: Hold multiple values of the same type.
int[] numbers = {1, 2, 3, 4, 5};
- Classes: Can be user-defined or from the Java API, representing objects.
Person person = new Person();
- Interfaces: Used to define contracts that classes can implement.
Comments
Post a Comment