Skip to main content

JAVA unit 2 DATA TYPES AND VARIABLES

 Data Types

A data type defines the kind of data a variable can store, the operations that can be performed on it, and the amount of memory allocated.

Java Primitive Data Types

Data Type

Size

Range (Approx.)

Example

Byte

1 byte

-128 to 127

byte a = 100;

short

2 bytes

-32,768 to 32,767

short s = 1000;

Int

4 bytes

-2,147,483,648 to 2,147,483,647

int num = 50000;

Long

8 bytes

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

long l = 100000L;

float

4 bytes

~6–7 decimal digits

float f = 5.75f;

double

8 bytes

~15 decimal digits

double d = 19.99;

Char

2 bytes

Single Unicode character

char c = 'A';

boolean

1 bit*

true or false

boolean flag = true;

*Boolean size is JVM-dependent (commonly 1 byte in memory, but logically 1 bit).

 

Java Non-Primitive Data Types

Type

Description

Example

String

Sequence of characters

String name = "Dinesh";

Array

Collection of elements

int[] arr = {1, 2, 3};

Class

Blueprint for objects

class Car { }

Object

Instance of a class

Car myCar = new Car();

Interface

Abstract type for methods

interface Shape {}

 Java Variables

A variable in Java is a name given to a memory location where data is stored and manipulated during program execution. Each variable in Java has a data type, which defines:

  • The size of memory to store the value.
  • The range of possible values.
  • The operations that can be performed on it.

Rules for creating a variable name in Java:

  • The name can contain letters (A-Z, a-z), digits (0-9), and the underscore _ or dollar sign $ (although $ is rarely used).
  • The first character must be a letter, underscore, or dollar sign (not a digit).
  • Java is case-sensitive (Name and name are different).
  • Java keywords (like int, class, public) cannot be used as variable names.
  • Variable names should be meaningful and follow camelCase convention for readability.

Syntax:

type variableName = value;

Example:

String name = "Rohit";

int age = 25;

 

 Constants

In Java, a constant is a variable whose value cannot be changed once assigned.
It is declared using the final keyword and is usually written in uppercase letters.
A constant must be given a value when declared, for example:
final double PI = 3.14;.

 

Java Identifiers

In Java, an identifier is the name given to program elements such as classes, methods, variables, and interfaces. They are used to uniquely identify these components.

Rules for defining identifiers in Java:

  • Allowed characters: letters (A-Z, a-z), digits (0-9), underscore _, and dollar sign $.
  • Cannot start with a digit.
  • Cannot contain whitespace.
  • Cannot be a Java keyword (class, public, static, etc.).
  • Java identifiers are case-sensitive.
  • Can be of any length, but extremely long names are discouraged.
  • Should not contain special characters like @, #, -, or spaces.
  • Unicode characters are allowed (e.g., you can technically use non-English characters, but it’s not common).

Valid identifiers:

Name           _name          $price         studentAge

Invalid identifiers:

123name     // starts with a digit

student age // contains a space

class       // keyword

Keywords in Java


Keywords in Java are reserved words that have a predefined meaning in the language. They cannot be used as identifiers (variable names, class names, etc.) because they are part of the Java syntax. There are total 53 keywords in java.

E.g: abstract boolean, break, byte, case, catch, char, class, const,
continue, default, do, double, else, enum, extends, final, finally, float,
for, goto, if, import int, interface, long, new, package, private, protected, public,
return, short, static, switch this try, void while

 

Rules:

  • All keywords are lowercase.
  • Cannot be used for variable, method, or class names.
  • Have a fixed meaning and purpose defined by Java.

 

2.6 Java Operators

Java operators are symbols used to perform operations on variables and values.

Example:

int sum = 10 + 5;

Here, + is an operator used for addition.

Types of Java Operators

  • Unary Operators

  • Arithmetic Operators

  • Relational Operators

  • Bitwise Operators

  • Shift Operators

  • Logical Operators

  • Ternary Operator

  • Assignment Operators


1. Arithmetic Operators

Arithmetic operators perform mathematical calculations.

OperatorDescriptionExample
+Addition10 + 20 = 30
-Subtraction20 - 10 = 10
*Multiplication10 * 20 = 200
/Division20 / 10 = 2
%Remainder20 % 3 = 2

Example

public class ArithmeticDemo {
    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 / b);
        System.out.println(a % b);
    }
}

2. Relational Operators

Relational operators compare two values and return true or false.

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Example

int a = 5, b = 10;

System.out.println(a == b);
System.out.println(a < b);

3. Bitwise Operators

Bitwise operators work directly on the binary representation of integers.

Assume:

int a = 60; // 0011 1100
int b = 13; // 0000 1101
OperatorDescriptionResult
&Bitwise AND12
|Bitwise OR61
^Bitwise XOR49
~Bitwise Complement-61

Example

System.out.println(a & b);
System.out.println(a | b);
System.out.println(a ^ b);
System.out.println(~a);

Note: Left shift (<<) and right shift (>>) are not included in bitwise operators. They are classified separately as Shift Operators in Java.


4. Shift Operators

Shift operators move the bits of a number left or right.

a) Left Shift (<<)

Moves bits to the left and fills the right side with zeros.

System.out.println(10 << 2); // 40
System.out.println(5 << 3);  // 40

Each left shift multiplies the number by 2.

b) Right Shift (>>)

Moves bits to the right and fills the left side with the sign bit.

System.out.println(20 >> 2); // 5
System.out.println(16 >> 3); // 2

Each right shift divides the number by 2.

c) Unsigned Right Shift (>>>)

Shifts bits right and always fills the left side with zeros.

System.out.println(20 >>> 2); // 5

5. Logical Operators

Logical operators are used with boolean expressions.

OperatorDescription
&&Logical AND
`
!Logical NOT

Example

boolean A = true, B = false;

System.out.println(A && B); // false
System.out.println(A || B); // true
System.out.println(!A); // false

6. Assignment Operators

Assignment operators assign values to variables.

OperatorExampleMeaning
=a = 5Assign
+=a += 2Add and assign
-=a -= 2Subtract and assign
*=a *= 2Multiply and assign
/=a /= 2Divide and assign
%=a %= 2Modulus and assign

Example

int a = 10;

a += 5;
a *= 2;

System.out.println(a); // 30

7. Unary Operators

Unary operators operate on one operand.

OperatorDescription
++aPrefix increment
a++Postfix increment
--aPrefix decrement
a--Postfix decrement

Example

int a = 5;

System.out.println(++a); // 6
System.out.println(a++); // 6
System.out.println(a);   // 7

Prefix: value changes first.
Postfix: value is used first, then changed.


8. Ternary Operator (Conditional Operator)

The ternary operator is a short form of if-else.

Syntax

variable = (condition) ? expression1 : expression2;

Example

int marks = 45;

String result = (marks >= 40) ? "Pass" : "Fail";

System.out.println(result);

Output:

Pass


Comments

Comments are used to explain code and make it more understandable for others or yourself. They are ignored by the compiler.

·         Single-line comments use //

// This is a single-line comment

·         Multi-line comments use /* */

/* This is a 
   multi-line comment */

·         Documentation comments use /** */ and are used for generating documentation.

/** This method adds two numbers */

Java Escape Sequences

In Java, escape sequences are special character combinations that

begin with a backslash (\). They are used inside string and character

literals to print special characters.

Common Escape Sequences

Escape SequenceMeaning
\nNew line
\tTab space
\bBackspace
\"Double quote
\\Backslash
\uXXXXUnicode character

Java Program
public class EscapeSequences { public static void main(String[] args) { // 1. New line
System.out.println("This is line one.\nThis is line
                                two."); // 2. Tab
System.out.println("Name:\tRamesh"); // 3. Backspace
System.out.println("ABC\bD"); // 4. Double quote
System.out.println("She said, \"Java is fun!\""); // 5. Backslash
System.out.println("Path: C:\\Users\\Dinesh"); // 6. Unicode characters
System.out.println("Heart: \u2764 Smiley: \u263A");
}
}

Output
This is line one.
This is line two.
Name: Ramesh
ABD
She said, "Java is fun!"
Path: C:\Users\Dinesh
Heart: ❤ Smiley: ☺

Comments

Popular posts from this blog

Unit-1 Introduction to C#.NET (Class 12)

  What is .NET Framework? The .NET Framework is a software development platform developed by Microsoft. It provides tools and libraries to build and run Windows applications, web services, and web apps. It gives tools and libraries that make it easier to write programs. It also helps the computer run those programs safely and efficiently. Microsoft started working on .NET Framework in the late 1990s . The first version, .NET Framework 1.0 , was released in 2002 .   The .NET Framework is made up of several important components: 1.       Common Language Runtime (CLR) is the core engine that runs your program. It converts your code into machine code that the computer can understand, manages memory, handles errors, and ensures that your program runs safely. 2.       The Class Library is a large collection of ready-made code that helps you perform common tasks like working with files, databases, graphics, the i...

Introduction to Software Engineering (Class 12)

 Introduction to Software Engineering Software engineering is the branch of computer science that deals with the design, development, testing, and maintenance of software applications. Software engineers apply engineering principles and knowledge of programming languages to build software solutions for end users. IEEE, in its standard 610.12-1990, defines software engineering as the application of a systematic, disciplined, which is a computable approach for the development, operation, and maintenance of software. Boehm defines software engineering, which involves, ‘the practical application of scientific knowledge to the creative design and building of computer programs. It also includes associated documentation needed for developing, operating, and maintaining them.’ Importance of Software Engineering Reduces complexity Large software systems are divided into smaller, manageable modules. Each module is developed and solved independently, ...

Unit 2 Operating System

  Unit- 2  Process and Process Scheduling 2.1 Introduce Process, Program and Process Life Cycle  Process Process is something that is currently under execution. So, an active program can be called a Process. Examples: ●        Opening a web browser to search something on the internet — the browser becomes a process. ●        Launching a music player to enjoy your favorite tunes — the music player is also a process. In computing, a process is the instance of a computer program that is being executed by one or many threads. It contains the program code and its activity. Modern operating systems support multithreading , meaning a process can have multiple threads running concurrently .   A Process has various attributes associated with it. Some of the attributes of a Process are: ●          Process Id: Every process will be given a unique id that identifies the process...