Skip to main content

Unit 2 Java


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.

 

Access Modifiers in Java


Access modifiers in Java are keywords that set the visibility (scope) of classes, methods, variables, and constructors. They control which parts of a program can access them.

Public: public means the class, method, or variable can be used from anywhere in the program.

Protected: protected means it can be used by classes in the same package and also by child classes in other packages.

Default: If no access specifier is written, it is called default access, and it can be used only by classes in the same package.

Private:  private means the method or variable can be used only inside the class where it is declared.


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 */

2.6 Java Operators

Operators are symbols that perform operations on variables and
 values. For example, + is an operator used for addition, 
and * is used for multiplication. Java offers a rich set of 
operators to manipulate variables. These operators can be 
categorized as follows:
•	Unary Operators
•	Arithmetic Operators
•	Shift Operators
•	Relational Operators
•	Bitwise Operators
•	Logical Operators
•	Ternary Operator
•	Assignment Operators

Arithmetic Operators

Arithmetic operators perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus.

Operator

Description

Example (A=10, B=20)

+

Adds values on either side of the operator

A + B results in 30

-

Subtracts right operand from left operand

A - B results in -10

*

Multiplies values on either side

A * B results in 200

/

Divides left operand by right operand

B / A results in 2

%

Returns remainder of division

B % A results in 0

Example: Arithmetic Operators in Java

import java.util.Scanner;

public class Arithmetic {

    public static void main(String[] args) {

        int first, second, add, subtract, multiply, mod;

       float divide;

       Scanner sc = new Scanner(System.in);

        System.out.print("Enter Two Numbers: ");

       first = sc.nextInt();

       second = sc.nextInt();

       add = first + second;

        subtract = first - second;

        multiply = first * second;

        divide = (float) first/ second;

        mod = first % second;

        System.out.println("Sum= " + add);

      System.out.println("Difference= " + subtract);

        System.out.println("Multiplication= " + multiply);

       System.out.println("Division= " + divide);

        System.out.println("Modulus= " + mod);

    }

}

Relational Operators

Relational operators compare two operands and return a

boolean result (true or false).

Operator

Description

Example (A=5, B=10)

==

Checks if operands are equal

(A == B) is false

!=

Checks if operands are not equal

(A != B) is true

> 

Checks if left operand is greater than right operand

(A > B) is false

< 

Checks if left operand is less than right operand

(A < B) is true

>=

Checks if left operand is greater or equal

(A >= B) is false

<=

Checks if left operand is less or equal

(A <= B) is true

Bitwise Operators

Bitwise operators work at the bit level on integer values.For example:

  • a = 60 → Binary: 0011 1100
  • b = 13 → Binary: 0000 1101

Operator

Description

Example

Result (Binary)

&

Bitwise AND – copies bit if set in both operands

a & b

12 (0000 1100)

|

Bitwise OR – copies bit if set in either operand

a | b

61 (0011 1101)

^

Bitwise XOR – copies bit if set in one operand only

a ^ b

49 (0011 0001)

~

Bitwise Complement – flips all the bits

~a

-61 (Two’s complement)

Logical Operators

Logical operators are used to combine or reverse boolean expressions. They return true or false as the result.

Operator

Description

Example (A = trueB = false)

Result

&&

Logical AND – true only if both conditions are true

A && B

false

||

Logical OR – true if at least one condition is true

A || B

true

!

Logical NOT – reverses the boolean value

!(A && B)

true

Example in Java:

boolean A = true, B = false;

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

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

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

Assignment Operators

Assignment operators are used to assign values to variables. They can also combine an operation with assignment.

Operator

Description

Example

=

Assigns the value of the right-hand operand to the left-hand operand

C = A + B

+=

Adds and assigns

C += A (same as C = C + A)

-=

Subtracts and assigns

C -= A

*=

Multiplies and assigns

C *= A

/=

Divides and assigns

C /= A

%=

Finds remainder and assigns

C %= A

<<=

Left shifts and assigns

C <<= 2

>>=

Right shifts and assigns

C >>= 2

&=

Bitwise AND and assigns

C &= 2

^=

Bitwise XOR and assigns

C ^= 2

|=

Bitwise OR and assigns

C |= 2


Unary Operators

Unary operators work with only one operand and usually increment or decrement values by 1.

  • Postfix increment (val++) → Returns the current value, then increments.
  • Postfix decrement (val--) → Returns the current value, then decrements.
  • Prefix increment (++val) → Increments first, then returns the new value.
  • Prefix decrement (--val) → Decrements first, then returns the new value.

Example meanings:

  • val = a++; → Assigns a to val, then increases a by 1.
  • val = ++a; → Increases a by 1, then assigns it to val.
  • val = a--; → Assigns a to val, then decreases a by 1.
  • val = --a; → Decreases a by 1, then assigns it to val.

Ternary Operator (Conditional Operator)

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

Syntax:

variable = (condition) ? expression1 : expression2;

  • If the condition is true, expression1 is assigned.
  • If the condition is false, expression2 is assigned

Example:

int februaryDays = 29;

String result = (februaryDays == 28) ? "Not a leap year" : "Leap year";

System.out.println(result);

Output:

Leap year

Shift Operators

Shift operators are used to move bits of a number to the

left or right by a specified number of positions.

1. Left Shift (<<)

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

Each shift to the left multiplies the

number by 2 for each position shifted.

Example:

public class ShiftExample {
    public static void main(String[] args) {
        System.out.println(10 << 2); // 40 (10 × 2²)
        System.out.println(5 << 3);  // 40 (5 × 2³)
    }
}

Output:

40
40

2. Right Shift (>>)

 Moves all bits to the right and fills the left side with

the sign bit (0 for positive, 1 for negative numbers).

 Each shift to the right divides the number by 2 for each position shifted.

Example:

public class ShiftExample {

    public static void main(String[] args) {
        System.out.println(20 >> 2); // 5 (20 ÷ 2²)
        System.out.println(16 >> 3); // 2 (16 ÷ 2³)
    }
}
Output:
5

2

Java Escape sequence

In Java, escape sequences are special character combinations that start with a backslash (\). They are used inside string and character literals to represent characters that cannot be typed directly or would otherwise cause confusion in the code.

Here’s a list of the commonly used escape sequences in Java:




Escape Sequence

Meaning

\n

New line (line break)

\t

Tab (adds horizontal space)

\b

Backspace (deletes one character to the left)

\r

Carriage return (moves cursor to the beginning of the line)

\'

Single quote (used inside character literals `''')

\"

Double quote (used inside string literals "\"")

\\

Backslash itself

\f

Form feed (advances to the next page in printing, rarely used)

\0

Null character (value 0)

\uXXXX

Unicode character (e.g., \u2764 = )


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 (removes previous character)    

System.out.println("ABC\bD"); // prints "ABD"

        // 4. Carriage return (overwrites line start)

System.out.println("Hello World\rHii"); // "Hii" overwrites "Hello"

        // 5. Single quote inside character   

System.out.println('\''); // prints '

        // 6. Double quotes inside string     

System.out.println("She said, \"Java is fun!\"");

// 7.Backslash itself      

System.out.println("Path: C:\\Users\\Dinesh");

        // 8. Form feed (rarely visible in console, useful in printing) 

System.out.println("First Page\fSecond Page");

        // 9. Null character 

System.out.println("Java\0Programming"); // \0 is just ignored in console

        // 10. Unicode character

        System.out.println("Heart: \u2764  Smiley: \u263A");

    }

Comments

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...