Class 11 | Data types and Variables | Java Programming Notes

UNIT 2 CLASS 11 • JAVA PROGRAMMING

Data Type and Variable

Original Scanned PDF – View Notes

Data Type

  • A data type is a classification of data.
  • It represents the type and size of data values that can be stored in a variable.
  • In other words, a Java data type is a set of values and operations defined on those values.

Data types are divided into two groups:

  1. Primitive data type
  2. Non-primitive data type

Primitive Data Type

Primitive data types are basic data types that specify the size and type of data and cannot be further divided into simpler data types.

1. Integer Types

It stores whole numbers, positive and negative, without decimals. Valid types are byte, short, int and long.

Data Type Size Description
byte 1 byte Stores whole numbers from −128 to 127.
short 2 bytes Stores whole numbers from −32,768 to 32,767.
int 4 bytes Stores whole numbers from −2,147,483,648 to 2,147,483,647.
long 8 bytes Stores whole numbers from −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

2. Floating Point Types

It stores numbers with a fractional part containing one or more decimals. Two types are float and double.

Data Type Size Description
float 4 bytes Stores fractional numbers sufficient for storing 6 to 7 decimal digits.
double 8 bytes Stores fractional numbers sufficient for storing 15 decimal digits.

3. Character Type

  • The char data type is used to store a single character.
  • It occupies 2 bytes of memory.
  • The character value must be surrounded by single quotes, like 'A' or 'a'.

4. Boolean Type

  • The boolean data type is used to store a logical value, either true or false.
  • It occupies 1 bit memory space.

String Type

The String type is used to store a sequence of characters (text). String value must be surrounded by double quotes, like "Ram".

Example

String name = "RAM";
System.out.println(name);

Variables

  • Variables are containers for storing data values.
  • They are names of memory locations that store different types of data specified by data types.

Declaration of Variable

Syntax:

datatype variableName = value;
datatype

Specifies data type such as int, float, double, char, etc.

variableName

Specifies the name of a variable that must be a valid identifier.

=

Assignment operator that assigns a data value to a variable.

value

Data value to be assigned to the variable.

Examples

int num = 5;
float marks = 45.5f;
char grade = 'A';
boolean mybool = true;
String name = "Bipana";

Program to Add Numbers

class sum
{
    public static void main(String []args)
    {
        int a = 5;
        int b = 6;
        int sum = a + b;

        System.out.println("The sum =" + sum);
    }
}

Constant

Constant is a value that cannot be changed after assigning it.

Java does not support the constant directly.

There is an alternative way to define constant in Java using non-access modifiers static and final.

Static and Final Modifiers

static modifier: It is used to manage memory. It allows the variable without loading any instance of the class in which it is defined.

final modifier: It represents that the value of the variable cannot be changed. It also makes primitive data types immutable.

Syntax for Creating Constants

static final type identifier_name = value;

// Example
static final double pi = 3.1416;

Identifier

  • Identifiers are symbolic names used for identification.
  • They can be class name, variable name, method name, package name, constant name and more. These unique names are called identifiers.

Rules for Naming Identifiers

  1. Valid identifiers must have characters A–Z or a–z, numbers 0–9 and underscore (_).
  2. Should not start with a number.
  3. Should not have a space in an identifier.
  4. The source says: “Should be length 4–15 letter only. However there is not limit on its length.”
  5. Keywords cannot be used as identifiers.
  6. The source states that Oracle-language keywords such as SELECT, FROM, WHERE, DELETE, etc. cannot be identifiers.
  7. Identifiers are case sensitive.
Possible source issue: Rule 4 in the handwritten scan contains both “4–15 letters only” and “there is no limit on its length,” so both statements are preserved instead of silently choosing one. Rule 6 also lists SQL/Oracle words exactly as the scan does.

Some Valid Identifiers

a
Sum
num1
num_1
pi
CalculateArea1
RectArea

Keywords

Java keywords are predefined or reserved words used for functionality or meaning.

Keywords cannot be used for identifiers.

List of Java Keywords Shown in the Scan

abstract char for boolean class if break continue else byte default case do catch while

Access Modifiers

The access modifier specifies the accessibility or scope of a field, method, class or constructor.

Access level can be changed by applying the access modifier on a field, method, class or constructor.

4 Types of Java Access Modifiers

  1. Private
  2. Default
  3. Protected
  4. Public

1. Private

The access level of private modifier is only within the class. It cannot be accessed from outside of the class.

2. Default

The access level of default modifier is only within the package. It cannot be accessed from outside the package.

3. Protected

The access level is within package and outside the package through child class. If we do not make a child class, it cannot be accessed from outside the package.

4. Public

The access level of it is anywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

Example of Private Access Modifier

class A
{
    private int data = 40;

    private void msg()
    {
        System.out.println("Hello Java");
    }
}

public class Test
{
    public static void main(String []args)
    {
        A obj = new A();

        System.out.println(obj.data);
        obj.msg();
    }
}
Possible source issue preserved: The handwritten example tries to access the private field data and private method msg() from another class. The code is kept because it is what appears in the supplied source.

Escape Sequence in Java

A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler.

Types of Escape Sequences in Java

Escape Sequence Description in the Source
\t Inserts a tab space in the text at this point.
\b Inserts backspace in the text at this point.
\n Inserts a new line in the text at this point.
\r Inserts carriage return in the text at this point. It is used to bring cursor to the starting of the line without changing the line.
\f Inserts form feed in the text. It is an old strategy to show page break.
\' Inserts a single quote character in the text at this point.
\" Inserts a double quote character in the text at this point.
\\ Inserts a backslash character in the text at this point.

Operators in Java

  • Operators are special symbols that perform certain operations on operands.
  • They are used to perform operations on variables and values.

In Java, operators are divided into the following categories in the scan:

  1. Arithmetic operator
  2. Assignment operator
  3. Logical operator
  4. Relational operator
  5. Bitwise operator
  6. Unary operator
  7. Ternary operator
Scan detail: A separate “Shift operator” entry is crossed out on the operators list. Left and right shift are later included under Bitwise Operators, so no separate shift-operator chapter has been invented.

1. Arithmetic Operator

Used to perform basic arithmetic operations such as addition, subtraction, etc.

Operator Description Example (A = 20, B = 5)
+ Addition Adds values of operands. A + B = 20 + 5 = 25
- Subtraction Subtracts the operand. A - B = 20 - 5 = 15
* Multiplication Multiplies the operands. A * B = 20 * 5 = 100
/ Division Divides the operand. A / B = 20 / 5 = 4
% Modulus division Divides the left-hand operand with the right-hand operand and gives remainder. A % B = 20 % 5 = 0

Example

public class OperatorTest
{
    public static void main(String []args)
    {
        int a = 20;
        int b = 5;

        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println(a / b);
        System.out.println(a % b);
    }
}

2. Assignment Operator

Assignment operators are used to assign/store the value of the right-hand operand to the left-hand operand or variable.

Operator Description in the Source Example
= Used to assign the value on the right to the operand on the left. a = b
+= Used to add the right operand to the left operand and assign the result to the left operand. a += b ⇒ a = a + b
-= Used to subtract the right operand from the left operand and assign the result to the left operand. a -= b ⇒ a = a - b
*= Used to multiply the right operand with the left operand and assign the result to the left operand. a *= b ⇒ a = a * b
/= Used to divide the right operand from the left operand and assign the result to the left operand. a /= b ⇒ a = a / b
^= Used to perform exponential calculation on operands and assign the result to the left operand. a ^= b ⇒ a = a ^ b
%= Used to divide the left operand with the right operand and assign remainder to the left operand. a %= b ⇒ a = a % b
Possible source issue preserved: The scan describes ^= as an “exponential calculation” and also writes the example with ^. This wording is kept as supplied rather than silently replaced.

3. Logical Operator

Logical operators are used to combine two or more conditions.

They return a logical value either true or false.

Operator Description Example from the Scan
&&
Logical AND
Performs logical AND operation. It returns true if all inputs are true; otherwise returns false. a < 5 && a > 20
||
Logical OR
Performs logical OR operation. It returns true if at least one input is true; otherwise returns false. a < 5 || a > 20
!
Logical NOT
Performs complement operation. It returns true if input is false and vice versa. !(a < 5 && a > 20)

4. Relational Operators

Relational operators are used to check the relationship between two operands.

If the relationship (condition) is true, it returns true value; otherwise it returns false value.

Operator Operator Name Example (A = 10, B = 5)
== Equal to A == B ⇒ 10 == 5 ⇒ Returns false
> Greater than A > B ⇒ 10 > 5 ⇒ Returns true
>= Greater than or equal to A >= B ⇒ 10 >= 5 ⇒ Returns true
< Less than A < B ⇒ 10 < 5 ⇒ Returns false
<= Less than or equal to A <= B ⇒ 10 <= 5 ⇒ Returns false
!= Not equal to A != B ⇒ 10 != 5 ⇒ Returns true

Example

public class RelationalOP
{
    public static void main(String []args)
    {
        int a = 10, b = 5;

        System.out.println(a == b);
        System.out.println(a > b);
        System.out.println(a >= b);
        System.out.println(a < b);
        System.out.println(a <= b);
        System.out.println(a != b);
    }
}

5. Bitwise Operators

These operators are used to perform bit-level operations on integer and boolean data.

Values used in the source example: a = 10 and b = 3
Operator Description in the Source Example
&
Bitwise AND
Returns 1 if all bits are 1. a & b = 2
0010
|
Bitwise OR
Returns 1 if any or all bits are 1. a | b = 11
1011
^
Bitwise XOR
Returns 1 if only one bit is 1. a ^ b = 9
1001
~
Bitwise NOT
Returns 1's complement of the operand. It is a unary operator. ~a = -11
<<
Bitwise Left Shift
Moves the number of bits to the left. a << 2 = 40
>>
Bitwise Right Shift
Moves the number of bits to the right. a >> 2 = 2

Program Example

public class BitwiseOP
{
    public static void main(String []args)
    {
        int A = 10, B = 3;

        System.out.println(A & B);
        System.out.println(A | B);
        System.out.println(A ^ B);
        System.out.println(~A);
        System.out.println(A << 2);
        System.out.println(A >> 2);
    }
}

Bitwise Left Shift (a << 2)

A = 10 = 1010

101000

= 40

Bitwise Right Shift (a >> 2)

A = 10 = 1010

0010

= 2

6. Unary Operators

  • It takes only a single operand.
  • Used to increment or decrement the value, negate an expression or invert a boolean value.

I. Increment Operator (++)

Used to increment the value of operand by 1.

Two types: post-increment (a++) and pre-increment (++a).

In post-increment, the value is first used for computing the result and then incremented.

In pre-increment, the value is incremented first and then the result is computed.

II. Decrement Operator (--)

Used for decrementing the value of operand by 1.

Also two types: post-decrement (a--) and pre-decrement (--a).

III. Logical NOT Operator (!)

Used for inverting a boolean value (!b).

Sample Example

public class OpTest
{
    public static void main(String []args)
    {
        int a = 10;
        boolean b = true;

        System.out.println(a++);
        System.out.println(++a);
        System.out.println(a--);
        System.out.println(--a);
        System.out.println(!b);
    }
}

Result Notes Written in the Scan

a++ = 10, 11

++a = 11

a-- = 10, 9

--a = 9

!b = False

Source fidelity note: The result list above is reproduced from the handwritten page as written. It is not recalculated or silently changed.

7. Ternary Operator

  • It is a shorthand version of the if-else statement.
  • It has 3 operands and hence the name ternary.

General Format

(condition ? true-value : false-value)

If condition is true, then execute the statement after ?; else execute the statement after :.

Sample Example

public class OPTest
{
    public static void main(String []args)
    {
        int a = 20, b = 10;
        int result;

        result = ((a > b) ? a : b);

        System.out.println("greater no is = " + result);
    }
}
Scan note: The final println line contains a visibly marked/corrected area in the handwritten source. The readable intended structure is retained without adding any new example.

8. If / Else Structure

The last scanned page shows the following if/else structure:

if (condition)
{
    statement 1;
}
else
{
    statement 2;
}
If else flowchart shown on the final scanned page Start condition True Statement 1 False Statement 2 End
If/else flowchart recreated from the final scanned page.
Incomplete source section: The final PDF page contains the syntax and flowchart only. No further definition or explanation is visibly supplied, so no additional textbook explanation has been invented.

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play