0% found this document useful (0 votes)
3 views

Variables_DataTypes_Operators

The document provides an overview of variables in Java, detailing local, instance, and static variables, along with their characteristics and examples. It also covers data types, including primitive and reference types, as well as type casting. Additionally, it explains operators in Java, categorizing them into arithmetic, relational, logical, bitwise, assignment, unary, and ternary operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Variables_DataTypes_Operators

The document provides an overview of variables in Java, detailing local, instance, and static variables, along with their characteristics and examples. It also covers data types, including primitive and reference types, as well as type casting. Additionally, it explains operators in Java, categorizing them into arithmetic, relational, logical, bitwise, assignment, unary, and ternary operators.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Variables

1. Local Variables

Explanation:

 Declared inside a method, constructor, or block.

 Can only be accessed within the block where they are declared.

 Must be initialized before use.


Example:

public class LocalVariableExample {

public void calculateSum() {

int num1 = 5; // Local variable

int num2 = 10; // Local variable

int sum = num1 + num2; // Local variable

System.out.println("Sum: " + sum);

public static void main(String[] args) {

LocalVariableExample obj = new LocalVariableExample();

obj.calculateSum();
}

}
Output:

Sum: 15

2. Instance Variables

Explanation:

 Declared inside a class but outside any method.


 Each object of the class gets its own copy.

 Default values are assigned if not initialized (0 for int, null for objects, etc.).
Example:

public class InstanceVariableExample {

int age = 25; // Instance variable

public void displayAge() {

System.out.println("Age: " + age);


}

public static void main(String[] args) {

InstanceVariableExample obj = new InstanceVariableExample();

obj.displayAge();

}
Output:

Age: 25

3. Static Variables

Explanation:

 Declared with the static keyword.

 Shared among all instances of a class.

 Memory is allocated only once.


Example:

public class StaticVariableExample {

static String companyName = "TechCorp"; // Static variable


public static void displayCompany() {

System.out.println("Company Name: " + companyName);

public static void main(String[] args) {

StaticVariableExample.displayCompany();

}
Output:

Company Name: TechCorp

4. Scope and Lifetime of Variables

Example:

public class VariableScopeExample {

int instanceVar = 10; // Instance variable

static int staticVar = 20; // Static variable

public void methodWithLocalVariable() {

int localVar = 30; // Local variable


System.out.println("Local Variable: " + localVar);

public static void main(String[] args) {


VariableScopeExample obj = new VariableScopeExample();

obj.methodWithLocalVariable();

// Accessing instance variable


System.out.println("Instance Variable: " + obj.instanceVar);

// Accessing static variable

System.out.println("Static Variable: " + staticVar);

}
Output:

Local Variable: 30
Instance Variable: 10

Static Variable: 20

5. Primitive and Reference Variables

Primitive Variables Example:

public class PrimitiveVariablesExample {

public static void main(String[] args) {

int a = 10; // Integer

float b = 5.5f; // Floating-point

char c = 'A'; // Character

boolean d = true; // Boolean

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

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

System.out.println("Character: " + c);


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

}
Output:
Integer: 10

Float: 5.5

Character: A

Boolean: true
Reference Variables Example:

public class ReferenceVariablesExample {

public static void main(String[] args) {

String name = "Java Programming"; // String reference


int[] numbers = {1, 2, 3, 4}; // Array reference

System.out.println("Name: " + name);

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

for (int num : numbers) {

System.out.print(num + " ");

}
Output:

Name: Java Programming


Numbers: 1 2 3 4

6. Constants Using final

Explanation:

 Once assigned, the value of a final variable cannot be changed.

 Used to define constants.


Example:

public class FinalVariableExample {


public static void main(String[] args) {

final int SPEED_LIMIT = 60; // Constant variable

System.out.println("Speed Limit: " + SPEED_LIMIT);

// Uncommenting the below line will cause an error

// SPEED_LIMIT = 70; // Cannot reassign final variable

}
Output:

Speed Limit: 60

7. Variable Initialization and Default Values

Uninitialized Local Variable:

public class UninitializedLocalVariable {

public static void main(String[] args) {

int num;

// Uncommenting the following line will cause an error

// System.out.println("Num: " + num); // Local variables must be initialized

}
}
Default Values of Instance and Static Variables:

public class DefaultValues {

int intVar;
float floatVar;

boolean boolVar;

String stringVar;
public static void main(String[] args) {

DefaultValues obj = new DefaultValues();

System.out.println("Default int: " + obj.intVar);

System.out.println("Default float: " + obj.floatVar);

System.out.println("Default boolean: " + obj.boolVar);

System.out.println("Default String: " + obj.stringVar);

}
Output:

Default int: 0

Default float: 0.0

Default boolean: false

Default String: null

Summary of Key Points:

1. Local variables must be initialized before use, and they have a short lifetime.

2. Instance variables are tied to an object and have default values.

3. Static variables are shared across all instances of a class.

4. Constants are declared with the final keyword and cannot be modified.

5. Default values are assigned only to instance and static variables, not local
variables.

Data Types

What are Data Types in Java?

Data types specify the type of data a variable can hold. In Java, data types are
categorized into two main types:
1. Primitive Data Types
o Basic building blocks of data manipulation.
2. Reference Data Types

o Objects, arrays, and user-defined classes.

1. Primitive Data Types

Overview

Primitive types are predefined by Java and named by reserved keywords. They store
simple values directly in memory.
List of Primitive Data Types

Data Type Size Default Value Example Values

byte 1 byte 0 -128 to 127

short 2 bytes 0 -32,768 to 32,767

int 4 bytes 0 -2^31 to 2^31-1

long 8 bytes 0L -2^63 to 2^63-1

float 4 bytes 0.0f 3.4e-038 to 3.4e+038

double 8 bytes 0.0d 1.7e-308 to 1.7e+308

char 2 bytes \u0000 Single character (e.g., 'A')

boolean 1 bit false true, false

Examples of Primitive Data Types

1. Integer Types

public class IntegerTypes {

public static void main(String[] args) {

byte small = 100; // Small range

short medium = 30000; // Medium range

int normal = 100000; // Default integer type


long large = 1000000000L; // Large range, 'L' suffix for long

System.out.println("Byte: " + small);

System.out.println("Short: " + medium);

System.out.println("Int: " + normal);

System.out.println("Long: " + large);

}
Output:

Byte: 100

Short: 30000

Int: 100000

Long: 1000000000

2. Floating-Point Types

public class FloatingPointTypes {

public static void main(String[] args) {

float pi = 3.14f; // 'f' suffix for float

double e = 2.71828; // Default decimal type

System.out.println("Float: " + pi);

System.out.println("Double: " + e);

}
}
Output:

Float: 3.14

Double: 2.71828
3. Character Type

public class CharTypeExample {

public static void main(String[] args) {

char letter = 'A';

char unicodeChar = '\u0041'; // Unicode for 'A'

System.out.println("Character: " + letter);


System.out.println("Unicode Character: " + unicodeChar);

}
Output:

Character: A

Unicode Character: A

4. Boolean Type

public class BooleanTypeExample {

public static void main(String[] args) {

boolean isJavaFun = true;


boolean isFishTasty = false;

System.out.println("Is Java Fun? " + isJavaFun);

System.out.println("Is Fish Tasty? " + isFishTasty);


}

}
Output:

Is Java Fun? true


Is Fish Tasty? false

2. Reference Data Types

Overview

Reference data types are used to store references (memory addresses) to objects or
arrays.
Common Reference Data Types

1. String: Represents sequences of characters.

2. Array: Stores multiple elements of the same data type.

3. Class/Objects: User-defined or pre-defined Java classes.

Examples of Reference Data Types

1. Strings

public class StringExample {

public static void main(String[] args) {

String greeting = "Hello, World!";

System.out.println(greeting);

}
}
Output:

Hello, World!

2. Arrays

public class ArrayExample {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40}; // Array initialization

System.out.println("Array Elements:");
for (int num : numbers) {

System.out.print(num + " ");

}
Output:

Array Elements:

10 20 30 40

3. Objects

public class ObjectExample {

String color;

public ObjectExample(String color) {

this.color = color;

public void display() {

System.out.println("The color is: " + color);


}

public static void main(String[] args) {

ObjectExample obj = new ObjectExample("Red");


obj.display();

}
Output:
The color is: Red

Default Values of Data Types

Data Type Default Value

byte, short, int, long 0

float, double 0.0

char \u0000

boolean false

String or other objects null

Example:

public class DefaultValuesExample {

int defaultInt;
float defaultFloat;

boolean defaultBoolean;

String defaultString;

public static void main(String[] args) {

DefaultValuesExample obj = new DefaultValuesExample();

System.out.println("Default int: " + obj.defaultInt);

System.out.println("Default float: " + obj.defaultFloat);

System.out.println("Default boolean: " + obj.defaultBoolean);

System.out.println("Default string: " + obj.defaultString);

Type Casting
1. Implicit Casting (Widening Conversion): Automatic conversion from smaller to
larger type.
2. Explicit Casting (Narrowing Conversion): Manual conversion from larger to
smaller type.
Example:

public class TypeCastingExample {

public static void main(String[] args) {

// Implicit Casting

int num = 100;

double largeNum = num; // int to double

System.out.println("Implicit Casting: " + largeNum);

// Explicit Casting
double decimal = 9.78;

int integer = (int) decimal; // double to int

System.out.println("Explicit Casting: " + integer);

}
Output:

Implicit Casting: 100.0

Explicit Casting: 9

Assignments to Practice

1. Declare variables of each primitive type and print their default values.

2. Create a program to demonstrate type casting.

3. Write a program to store and print an array of Strings.

4. Use an object to store data and print it using a method.


Operators in Java
Operators are special symbols or keywords used to perform operations on variables
and values. Java provides a rich set of operators, categorized based on the type of
operations they perform.

Types of Operators in Java

1. Arithmetic Operators

2. Relational (Comparison) Operators

3. Logical Operators

4. Bitwise Operators

5. Assignment Operators

6. Unary Operators

7. Ternary Operator

8. Shift Operators

1. Arithmetic Operators

Used for basic arithmetic operations.

Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (Remainder) a % b

Example:

public class ArithmeticExample {

public static void main(String[] args) {

int a = 10, b = 3;
System.out.println("Addition: " + (a + b));

System.out.println("Subtraction: " + (a - b));

System.out.println("Multiplication: " + (a * b));

System.out.println("Division: " + (a / b));

System.out.println("Modulus: " + (a % b));

2. Relational (Comparison) Operators

Used to compare two values and return a boolean result.

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal a >= b

<= Less than or equal a <= b

Example:

public class RelationalExample {


public static void main(String[] args) {

int a = 10, b = 20;

System.out.println("a == b: " + (a == b));

System.out.println("a != b: " + (a != b));

System.out.println("a > b: " + (a > b));

System.out.println("a < b: " + (a < b));


System.out.println("a >= b: " + (a >= b));

System.out.println("a <= b: " + (a <= b));

3. Logical Operators

Used for logical operations, often with boolean values.

Operator Description Example

&& Logical AND a > 5 && b < 15

` `

! Logical NOT !(a > b)

Example:

public class LogicalExample {

public static void main(String[] args) {

boolean a = true, b = false;

System.out.println("a && b: " + (a && b));

System.out.println("a || b: " + (a || b));

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

4. Bitwise Operators

Used to perform operations on individual bits.

Operator Description Example

& Bitwise AND a&b


Operator Description Example

` ` Bitwise OR

^ Bitwise XOR a^b

~ Bitwise Complement ~a

Example:

public class BitwiseExample {

public static void main(String[] args) {

int a = 5, b = 3; // Binary: a=0101, b=0011

System.out.println("a & b: " + (a & b)); // AND

System.out.println("a | b: " + (a | b)); // OR

System.out.println("a ^ b: " + (a ^ b)); // XOR


System.out.println("~a: " + (~a)); // Complement

5. Assignment Operators

Used to assign values to variables.

Operator Description Example

= Assign a=5

+= Add and assign a += 5

-= Subtract and assign a -= 5

*= Multiply and assign a *= 5

/= Divide and assign a /= 5

%= Modulus and assign a %= 5


Example:

public class AssignmentExample {

public static void main(String[] args) {

int a = 10;

a += 5; // a = a + 5

System.out.println("a after += 5: " + a);

a *= 2; // a = a * 2

System.out.println("a after *= 2: " + a);

6. Unary Operators

Used with a single operand.

Operator Description Example

+ Positive +a

- Negative -a

++ Increment ++a or a++

-- Decrement --a or a--

! Logical NOT !a

Example:

public class UnaryExample {

public static void main(String[] args) {

int a = 10;
System.out.println("a: " + a);

System.out.println("++a: " + (++a)); // Pre-increment

System.out.println("a++: " + (a++)); // Post-increment

System.out.println("--a: " + (--a)); // Pre-decrement

System.out.println("a--: " + (a--)); // Post-decrement

7. Ternary Operator

Short-hand for if-else.


Syntax: condition ? expression1 : expression2;

Example:

public class TernaryExample {

public static void main(String[] args) {

int a = 10, b = 20;

String result = (a > b) ? "a is greater" : "b is greater";

System.out.println(result);
}
}

8. Shift Operators

Used to shift bits left or right.

Operator Description Example

<< Left shift a << 2

>> Right shift a >> 2


Operator Description Example

>>> Unsigned right shift a >>> 2

Example:

public class ShiftExample {

public static void main(String[] args) {

int a = 8; // Binary: 00001000

System.out.println("a << 2: " + (a << 2)); // Left shift

System.out.println("a >> 2: " + (a >> 2)); // Right shift

System.out.println("a >>> 2: " + (a >>> 2)); // Unsigned right shift

Practice Assignments

1. Write a program to demonstrate all arithmetic operators.

2. Create a program using logical operators to evaluate multiple conditions.

3. Use the ternary operator to decide the larger of two numbers.

4. Demonstrate bitwise AND, OR, and XOR with integers.

5. Write a program using shift operators to double and halve a number.

Input/Output (I/O) in Java

Java provides powerful and flexible libraries for input and output operations. These
operations are categorized into different streams to read from and write to various data
sources like files, consoles, and network connections.

Key Concepts of Java I/O


1. Streams
A stream is a sequence of data. Java uses streams to perform input and output
operations. There are two types of streams:
o Input Stream: Used to read data (e.g., FileInputStream).

o Output Stream: Used to write data (e.g., FileOutputStream).

2. Types of I/O Streams

o Byte Streams: Used for handling binary data.

o Character Streams: Used for handling text data.

3. Standard Streams
Java has three standard streams for console I/O:

o System.in (Input from keyboard)

o System.out (Output to console)

o System.err (Error output to console)

1. Console Input/Output

Reading Input from Console

Using the Scanner class:

import java.util.Scanner;

public class ConsoleInputExample {


public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter your name: ");

String name = scanner.nextLine();

System.out.print("Enter your age: ");

int age = scanner.nextInt();


System.out.println("Name: " + name + ", Age: " + age);

}
Explanation:

 nextLine(): Reads an entire line.

 nextInt(), nextDouble(), etc.: Read specific data types.

Writing Output to Console

Using System.out:

public class ConsoleOutputExample {

public static void main(String[] args) {

String message = "Hello, Java!";

System.out.println(message); // Prints with a new line

System.out.print("Welcome to "); // Prints without a new line

System.out.print("Java Programming.");

Arithmetic Operations in Java

Arithmetic operations are fundamental in Java and allow you to perform basic
mathematical operations such as addition, subtraction, multiplication, division, and
finding the remainder (modulus).

Program to Demonstrate Arithmetic Operations

import java.util.Scanner;

public class ArithmeticOperations {


public static void main(String[] args) {

// Create a Scanner object for input

Scanner scanner = new Scanner(System.in);

// Prompt the user to enter two numbers

System.out.print("Enter the first number: ");

double num1 = scanner.nextDouble();

System.out.print("Enter the second number: ");

double num2 = scanner.nextDouble();

// Perform arithmetic operations

double addition = num1 + num2;

double subtraction = num1 - num2;

double multiplication = num1 * num2;

double division = (num2 != 0) ? num1 / num2 : Double.NaN; // Check to avoid


division by zero

double modulus = (num2 != 0) ? num1 % num2 : Double.NaN; // Check to avoid


division by zero

// Display the results

System.out.println("\nResults:");

System.out.println("Addition: " + addition);

System.out.println("Subtraction: " + subtraction);

System.out.println("Multiplication: " + multiplication);

if (num2 != 0) {

System.out.println("Division: " + division);


System.out.println("Modulus: " + modulus);
} else {

System.out.println("Division and Modulus: Cannot divide by zero!");

// Close the scanner

scanner.close();

Explanation of the Code

1. Importing Scanner:

o The Scanner class is imported from java.util to allow user input from the
console.
2. Input from the User:

o scanner.nextDouble() is used to read the numbers entered by the user.


3. Arithmetic Operations:

o Addition (+): Adds the two numbers.

o Subtraction (-): Subtracts the second number from the first.


o Multiplication (*): Multiplies the two numbers.
o Division (/): Divides the first number by the second. A check is included to
avoid dividing by zero.
o Modulus (%): Computes the remainder when the first number is divided
by the second. A check is included for zero division.
4. Conditional Division and Modulus:

o Division and modulus operations are only performed if the second number
is non-zero. If zero is entered, an appropriate message is displayed.
5. Output:

o Results are displayed using System.out.println() for clarity.


6. Closing the Scanner:

o The scanner.close() method is called to free up system resources.

Sample Input and Output

Input:

Enter the first number: 15

Enter the second number: 3


Output:

Results:

Addition: 18.0

Subtraction: 12.0

Multiplication: 45.0

Division: 5.0

Modulus: 0.0
Input:

Enter the first number: 10

Enter the second number: 0


Output:

Results:
Addition: 10.0

Subtraction: 10.0

Multiplication: 0.0

Division and Modulus: Cannot divide by zero!

Practice Assignments

1. Modify the program to include additional operations like exponentiation


(Math.pow).
2. Create a menu-driven program where the user can choose the operation to
perform.

3. Extend the program to handle integer inputs and outputs.


Swapping Variables in Java

Swapping variables means exchanging their values. In Java, there are several ways to
achieve this. Below are two common methods with detailed explanations and code
examples:

Method 1: Using a Temporary Variable

This is the most straightforward method for swapping values.


Code Example

public class SwapUsingTemp {

public static void main(String[] args) {

int a = 5;

int b = 10;

System.out.println("Before Swap:");

System.out.println("a = " + a + ", b = " + b);

// Swapping logic
int temp = a; // Store the value of 'a' in a temporary variable

a = b; // Assign the value of 'b' to 'a'

b = temp; // Assign the value of 'temp' (original 'a') to 'b'

System.out.println("\nAfter Swap:");

System.out.println("a = " + a + ", b = " + b);

}
Explanation

1. Initial Values:

o a = 5 and b = 10.
2. Temporary Variable:

o Store the value of a in a temporary variable (temp = a).


3. Swap Process:

o Assign the value of b to a (a = b).

o Assign the value of temp to b (b = temp).


4. Result:

o The values of a and b are swapped.

Method 2: Without Using a Temporary Variable

This method uses arithmetic operations to swap values.


Code Example

public class SwapWithoutTemp {

public static void main(String[] args) {

int a = 5;

int b = 10;

System.out.println("Before Swap:");

System.out.println("a = " + a + ", b = " + b);

// Swapping logic
a = a + b; // Step 1: Add both numbers

b = a - b; // Step 2: Subtract 'b' from the result to get the original 'a'

a = a - b; // Step 3: Subtract the new 'b' from the result to get the original 'b'
System.out.println("\nAfter Swap:");

System.out.println("a = " + a + ", b = " + b);

}
Explanation

1. Initial Values:

o a = 5 and b = 10.
2. Step-by-Step Swap:

o a = a + b: Now a = 15 and b = 10.

o b = a - b: Now a = 15 and b = 5.

o a = a - b: Now a = 10 and b = 5.
3. No Temporary Variable:

o The swap is achieved using arithmetic, avoiding extra storage.

Method 3: Using Bitwise XOR

This method works for integer data types and uses bitwise XOR.
Code Example

public class SwapUsingXOR {

public static void main(String[] args) {


int a = 5;

int b = 10;

System.out.println("Before Swap:");
System.out.println("a = " + a + ", b = " + b);

// Swapping logic

a = a ^ b; // Step 1: XOR both numbers


b = a ^ b; // Step 2: XOR the result with 'b' to get original 'a'

a = a ^ b; // Step 3: XOR the result with new 'b' to get original 'b'

System.out.println("\nAfter Swap:");

System.out.println("a = " + a + ", b = " + b);

}
Explanation
1. Initial Values:

o a = 5 and b = 10.
2. Step-by-Step XOR Operations:

o a = a ^ b: Now a = 15 and b = 10.

o b = a ^ b: Now a = 15 and b = 5.

o a = a ^ b: Now a = 10 and b = 5.
3. Use Case:

o Efficient for integer swapping, but not suitable for floating-point numbers.
Practice Assignments

1. Write a program to swap two floating-point numbers using a temporary variable.

2. Modify the arithmetic swapping method to handle negative numbers.


3. Implement the XOR method for swapping three numbers without using additional
variables.

You might also like