0% found this document useful (0 votes)
819 views13 pages

Variables in Java: - : Unit 2

The document discusses variables in Java. There are three types of variables: local variables defined within a method or block, instance variables declared in a class outside methods, and static variables declared using the static keyword. Local variables are created when a method is called and destroyed when it returns, while instance and static variables persist for the lifetime of the class. The document also covers primitive data types like int, float, boolean and non-primitive types like String and Array in Java.

Uploaded by

Aniruddh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
819 views13 pages

Variables in Java: - : Unit 2

The document discusses variables in Java. There are three types of variables: local variables defined within a method or block, instance variables declared in a class outside methods, and static variables declared using the static keyword. Local variables are created when a method is called and destroyed when it returns, while instance and static variables persist for the lifetime of the class. The document also covers primitive data types like int, float, boolean and non-primitive types like String and Array in Java.

Uploaded by

Aniruddh Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Unit 2

Variables in Java: -

A variable is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before use.

How to declare variables?


We can declare variables in java as follows:

type: Type of data that can be stored in this variable.


name: Name given to the variable.
In this way, a name can only be given to a memory location. It can be assigned values in two
ways:

 Variable Initialization
 Assigning value by taking input

How to initialize variables?

1
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Examples:

float simpleInterest; //Declaring float variable


int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of variables: -
There are three types of variables in Java:

 Local Variables
 Instance Variables
 Static Variables

Let us now learn about each one of these variables in detail.


1. Local Variables: A variable defined within a block or method or constructor is called local
variable.
 These variable are created when the block is entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
 Initilisation of Local Variable is Mandatory.

2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
 As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
2
 Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier then the default access specifier will be used.
 Initilisation of Instance Variable is not Mandatory. Its default value is 0
 Instance Variable can be accessed only by creating objects.

3. Static Variables: Static variables are also known as Class variables.


 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initilisation of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like Instance variable (through an object), the compiler
will show the warning message and it won’t halt the program. The compiler will
replace the object name to class name automatically.
 If we access the static variable without the class name, Compiler will automatically
append the class name.

Instance variable Vs Static variable


 Each object will have its own copy of instance variable whereas We can only have one
copy of a static variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of instance variable. In case of static, changes will
be reflected in other objects as static variables are common to all object of a class.
 We can access instance variables through object references and Static Variables can be
accessed directly using class name.
 Syntax for static and instance variables:

Class Example
{
static int a; //static variable
int b; //instance variable
}

Data types in Java:-

3
There are majorly two types of languages.
First, one is statically typed language where each variable and expression type is already known
at compile time. Once a variable is declared to be of a certain data type, it cannot hold values of
other data types.
Example: C, C++, Java.
 The other is Dynamically typed languages. These languages can receive different data types
over time.
Example: Ruby, Python
Java is statically typed and also a strongly typed language because, in Java, each type of data
(such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the
programming language and all constants or variables defined for a given program must be described
with one of the data types.

Data Types in Java

Java has two categories of data:

 Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
 Non-Primitive Data Type or Object Data type: such as String, Array, etc.

4
Primitive Data Type:

Primitive data are only single values and have no special capabilities.
There are 8 primitive data types:

1. Boolean: Boolean data type represents only one bit of information either true or false, but the
size of the boolean data type is virtual machine-dependent. Values of type boolean are not
converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write
conversion code.

 Syntax:

boolean booleanVar;
 Size:

virtual machine dependent


 Values:

true, false
 Default Value:

false

// Java program to demonstrate boolean data type

class hello
{
public static void main(String args[])
{
boolean b = true;
if (b == true)
System.out.println("Hello Students");
}
}

Output:

5
Hello Students

2. byte: The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful
for saving memory in large arrays.

Syntax:
byte byteVar;
Size:
1 byte ( 8 bits )
Values:
-128 to 127
Default Value:
0

// Java program to demonstrate byte data type in Java

class Students {
public static void main(String args[])
{
byte a = 126;

// byte is 8 bit value


System.out.println(a);

a++;
System.out.println(a);

// It overflows here because


// byte can hold values from -128 to 127
a++;
System.out.println(a);

// Looping back within the range


a++;
System.out.println(a);
}
}
Output:
126
127
-128

6
-127

3. short: The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a
short to save memory in large arrays, in situations where the memory savings actually matters.

Syntax:
short shortVar;

Size:
2 byte ( 16 bits )
Values:
-32, 768 to 32, 767 (inclusive)
Default Value:
0

4. int: It is a 32-bit signed two’s complement integer.

 Syntax:

int intVar;
 Size:

4 byte ( 32 bits )
 Values:

-2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)


 Default Value:

0
 Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit
integer, which has value in the range [0, 232-1]. Use the Integer class to use int data type as an
unsigned integer.

5. long: The long data type is a 64-bit two’s complement integer.

7
 Syntax:

long longVar;
 Size:

8 byte ( 64 bits )
 Values:
-9, 223, 372, 036, 854, 775, 808
to
9, 223, 372, 036, 854, 775, 807
(inclusive)
 Default Value:

0
 Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit
long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also
contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic
operations for unsigned long.

6. float: The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point numbers.

 Syntax:

float floatVar;
 Size:

4 byte ( 32 bits )
 Values:

upto 7 decimal digits


 Default Value:

0.0
7. double: The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice.

 Syntax:

8
double doubleVar;
 Size:

8 byte ( 64 bits )
 Values:

upto 16 decimal digits


 Default Value:

0.0
 Note: Both float and double data types were designed especially for scientific calculations,
where approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead.

8. char: The char data type is a single 16-bit Unicode character.

 Syntax:

char charVar;
 Size:

2 byte ( 16 bits )
 Values:

'\u0000' (0) to '\uffff' (65535)


 Default Value:

'\u0000'

Why is the size of char is 2 byte in java..?

In other languages like C/C++ uses only ASCII characters and to represent all ASCII characters
8-bits is enough, But java uses the Unicode system not the ASCII code system and to represent
Unicode system 8 bit is not enough to represent all characters so java uses 2 bytes for characters.
Unicode defines a fully international character set that can represent most of the world’s written
languages. It is a unification of dozens of character sets, such as Latin, Greeks, Cyrillic,
Katakana, Arabic, and many more.

9
// Java program to demonstrate

// primitive data types in Java

class GeeksforGeeks {

public static void main(String args[])

// declaring character

char a = 'G';

// Integer data type is generally

// used for numeric values

int i = 89;

// use byte and short

// if memory is a constraint

byte b = 4;

// this will give error as number is

// larger than byte range

// byte b1 = 7888888955;

short s = 56;

// this will give error as number is

10
// larger than short range

// short s1 = 87878787878;

// by default fraction value

// is double in java

double d = 4.355453532;

// for float use 'f' as suffix

float f = 4.7333434f;

System.out.println("char: " + a);

System.out.println("integer: " + i);

System.out.println("byte: " + b);

System.out.println("short: " + s);

System.out.println("float: " + f);

System.out.println("double: " + d);

Output:
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532

11
Non-Primitive Data Type or Reference Data Types:
The Reference Data Types will contain a memory address of variable value because the
reference types won’t store the variable value directly in memory.

They are strings, objects, arrays, etc.

 String: Strings are defined as an array of characters. The difference between a character
array and a string in Java is, the string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate char type entities.
 Unlike C/C++, Java strings are not terminated with a null character.
Below is the basic syntax for declaring a string in Java programming language.
Syntax:

<String_Type> <string_variable> = “<sequence_of_string>”;

 Example:

// Declare String without using new operator


String s = "Collage";

// Declare String using new operator


String s1 = new String("Students");

Class: A class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one type. In general,
class declarations can include these components, in order:

1. Modifiers: A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.

12
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.

Object: It is a basic unit of Object-Oriented Programming and represents the real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an
object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an
object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.

Interface: Like a class, an interface can have methods and variables, but the methods declared in
an interface are by default abstract (only method signature, nobody).
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
 A Java library example is, Comparator Interface. If a class implements this interface, then
it can be used to sort a collection.

Array: An array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some important points
about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each has an index beginning from 0.
 Java array can be also be used as a static field, a local variable or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.

13

Common questions

Powered by AI

Static variables improve memory efficiency by ensuring that only one copy is shared among all instances of a class, as opposed to each instance holding its copy, as is the case with instance variables. This means that memory is saved especially when the variable is used to store data applicable to all objects, as it eliminates redundancy . However, this also changes program behavior in that any modification to a static variable is reflected across all objects, which is vital to understand because it implies all instances of the class see the same value and no object has a unique value for this variable . This global scope and behavior can both be beneficial for maintaining state across instances but also potentially complicate debugging if not carefully managed.

Java is considered a statically typed language because each variable and expression type is known at compile-time, and variables are explicitly declared to be of a specific data type. This means variables cannot change types and must be known before the program runs . It is also strongly typed because the types cannot be implicitly or explicitly converted without code that the programmer defines, ensuring type safety and reducing errors due to type mismatches .

Instance variables are non-static variables declared in a class outside any method, constructor, or block, and each object of the class has its own copy of an instance variable. They are created when an object of the class is instantiated and destroyed when the object is destroyed. Accessibility is through object references, and changes in one object’s instance variable do not affect others . Static variables, on the other hand, are declared with the static keyword, and only one copy exists for the entire class, shared among all instances. They are created when the program execution starts and destroyed at the program's end. Static variables can be accessed directly using the class name, and changes in a static variable are reflected across all objects of the class .

Primitive data types in Java are the most basic data types such as boolean, char, int, byte, short, long, float, and double, and they store simple values with no added object properties . They occupy fixed amounts of memory and are stored directly within their variables. Non-primitive or reference data types, such as Strings, Arrays, and Objects, reference locations in memory where data is stored, instead of storing the direct values . They represent more complex data structures, such as collections or data encapsulated in objects, demonstrating Java’s object-oriented paradigm . Java's reference types are stored as pointers to memory addresses, rather than being stored inline, enabling complex data and behaviors to be associated with variable references .

In Java, arrays are treated as objects, which profoundly impacts their manipulation compared to languages like C or C++, where arrays are treated as contiguous memory blocks. Java arrays being objects allow methods to be called on them, like obtaining the length using the 'length' attribute, providing safety from accessing out-of-bounds data. This object-oriented approach adds safety and functionality, such as dynamic memory allocation . Conversely, in C/C++, arrays are closely tied to pointers, allowing more low-level operations but introducing more risk with manual memory management and risks of pointer arithmetic errors . Java's abstraction with arrays also leads to more readable and maintainable code due to automatic garbage collection . This difference underpins Java's guiding principle of prioritizing safety and simplicity in application development over raw performance or minimal memory use, as seen in lower-level languages .

Local variables in Java differ significantly from instance and static variables regarding scope and lifecycle. They are declared within a method, constructor, or block, and their scope is limited to that context. Local variables are created when the block or method is entered and destroyed upon exiting it, meaning they do not persist beyond the execution of the block or method, unlike instance and static variables . Instance variables, in contrast, have the lifecycle of the hosting object, existing as long as the object does. Static variables exist for the duration of the program's execution, as they are created when the program starts and destroyed when it ends . This short lifecycle and limited scope of local variables means they consume memory only temporarily and cannot retain state between executions .

A programmer may opt to use a byte or short data type instead of an int in Java primarily for memory efficiency, particularly in large arrays or memory-constrained environments. The byte data type is an 8-bit signed integer, which provides a smaller footprint than the 32-bit int, making it suitable for arrays where the potential values fit within the -128 to 127 range . Similarly, the short is a 16-bit signed integer fitting values from -32768 to 32767 . The trade-off, however, is reduced range: using byte and short limits the variable's value range significantly compared to int. This requires careful consideration to avoid overflows or incorrect data representation . Additionally, arithmetic operations may still result in conversion to int, thus mitigating some memory optimization gains .

Java’s char data type is a single 16-bit Unicode character. The use of Unicode allows Java to represent a wide range of international characters beyond the ASCII character set. Unlike languages like C/C++, which typically use an 8-bit system for char, Java uses 16 bits (2 bytes) to accommodate the extensive set of characters defined in Unicode, which includes most of the world’s written languages . This supports Java's capability for internationalization and its platform-independent nature by facilitating the representation of characters globally .

Access specifiers with instance variables determine their accessibility throughout different parts of a program, providing levels of control over who can interact with or modify variable data. Instance variables, because they are part of an object's state, can have access modifiers like private, protected, and public, allowing programmers to implement encapsulation by restricting or allowing access from other classes or packages . In contrast, local variables, confined to a specific method, constructor, or block, do not use access specifiers because their scope naturally limits their accessibility to within the block where they are declared, making external access control redundant . This inherent difference underlines the importance of encapsulation in the context of instance variables as part of object design .

The declaration of strings in Java reflects its object-oriented principles by treating strings as objects rather than primitive types. Declaring a string can be done directly with string literals or via the new keyword, thereby creating instances of the String class, which encapsulates the character sequence data. This aligns with Java's object-oriented nature, emphasizing encapsulation, where the internal state of an object (string's character data here) is hidden, and the implementation is abstracted away . It promotes the use of object references to interact with data, encapsulating the actual handling and manipulation of string data within the String class itself, a hallmark of object-oriented programming .

You might also like