[go: up one dir, main page]

0% found this document useful (0 votes)
1 views19 pages

Chapter 2

The document provides a comprehensive overview of Java variable types, including primitive and reference data types, and the rules for naming identifiers. It also covers operators, operator precedence, type conversion, and decision-making statements such as if and switch. Additionally, it highlights best practices for writing efficient and readable Java code.

Uploaded by

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

Chapter 2

The document provides a comprehensive overview of Java variable types, including primitive and reference data types, and the rules for naming identifiers. It also covers operators, operator precedence, type conversion, and decision-making statements such as if and switch. Additionally, it highlights best practices for writing efficient and readable Java code.

Uploaded by

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

In Java, understanding variable types and identifiers is crucial for writing efficient and readable

code. Here's a breakdown:

1. Variable Types

Variables in Java hold data, and each variable has a specific data type that determines the kind
of data it can store. Java has two main categories of data types:

a. Primitive Data Types

These are the basic types of data and are predefined by the language. There are 8 primitive types
in Java:

 byte: 8-bit signed integer. Range: -128 to 127


 short: 16-bit signed integer. Range: -32,768 to 32,767
 int: 32-bit signed integer. Range: -2^31 to 2^31-1
 long: 64-bit signed integer. Range: -2^63 to 2^63-1
 float: 32-bit floating point. Suitable for decimal values.
 double: 64-bit floating point. More precise than float for decimal values.
 char: 16-bit Unicode character. Stores single characters such as 'a', 'b', or '1'.
 boolean: Represents two values: true or false.

b. Reference/Object Data Types

These refer to objects and are created using classes. They store references (memory addresses) to
where data is stored.

 String: A sequence of characters.


 Arrays: Collections of data of the same type.
 Classes and Objects: Custom types defined by the user.
 Interfaces: Contract-based structures.

2. Identifiers

Identifiers are the names used to identify variables, methods, classes, and other user-defined
entities in Java. An identifier must follow these rules:

 Start with a letter (A-Z or a-z), a dollar sign ($), or an underscore (_). It cannot start
with a digit.
 Subsequent characters can be letters, digits (0-9), underscores, or dollar signs.
 Identifiers are case-sensitive. For example, myVar and myvar are different.
 Identifiers cannot be a Java keyword or reserved word (like int, class, if).

Examples
java
Copy code
int number; // "number" is an identifier of type int
double price; // "price" is an identifier of type double
String name = "Java"; // "name" is an identifier of type String
boolean isActive; // "isActive" is an identifier of type boolean

Best Practices for Identifiers:

 Use meaningful names: For example, use totalAmount instead of tA.


 Follow naming conventions:
o Variables and methods: Use camelCase (e.g., myVariable).
o Classes and Interfaces: Use PascalCase (e.g., MyClass).
o Constants: Use UPPERCASE_WITH_UNDERSCORES (e.g., MAX_SIZE).

1. Number Types in Java

Java provides several numeric data types that can be classified into two main categories: integral
types and floating-point types.

a. Integral Types

These types represent whole numbers.

 byte:
o Size: 8 bits
o Range: -128 to 127
o Example: byte b = 100;
 short:
o Size: 16 bits
o Range: -32,768 to 32,767
o Example: short s = 30000;
 int:
o Size: 32 bits
o Range: -2,147,483,648 to 2,147,483,647
o Example: int i = 2000000000;
 long:
o Size: 64 bits
o Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
o To specify a long value, append L or l to the number (e.g., long l =
12345678901L;).

b. Floating-Point Types

These types represent numbers with fractional parts.

 float:
o Size: 32 bits
o Precision: Approximately 7 decimal digits
o To specify a float value, append F or f (e.g., float f = 10.5F;).
 double:
o Size: 64 bits
o Precision: Approximately 15 decimal digits
o Example: double d = 20.99;

2. Strings in Java

Strings in Java are used to represent a sequence of characters. They are implemented using the
String class.

 Creating Strings:
o Using string literals:

java
Copy code
String str1 = "Hello, World!";

o Using the new keyword:

java
Copy code
String str2 = new String("Hello, World!");

 Common String Methods:


o length(): Returns the length of the string.
o charAt(index): Returns the character at the specified index.
o substring(start, end): Returns a substring from the string.
o toUpperCase() / toLowerCase(): Converts the string to uppercase or lowercase.
o concat(String str): Concatenates the specified string to the end of the current
string.

3. Constants in Java

Constants are variables whose values cannot be changed once assigned. In Java, constants are
typically defined using the final keyword.

 Defining Constants:
o Constants are often declared in uppercase with underscores separating words.
o Example:

java
Copy code
final int MAX_VALUE = 100;
final String COMPANY_NAME = "OpenAI";
 Using Constants:
o Once a constant is defined, its value cannot be altered. Attempting to do so will
result in a compilation error.

In Java, operators are special symbols that perform operations on variables and values.
Understanding operators and their precedence is crucial for writing effective object-oriented
code. Here’s a breakdown of operators and operator precedence in Java:

1. Types of Operators

Java operators can be classified into several categories:

a. Arithmetic Operators

These operators perform basic mathematical operations:

 Addition (+): Adds two operands.


 Subtraction (-): Subtracts the second operand from the first.
 Multiplication (*): Multiplies two operands.
 Division (/): Divides the first operand by the second (integer division if both operands
are integers).
 Modulus (%): Returns the remainder of division.

Example:

java
Copy code
int a = 10;
int b = 3;
int sum = a + b; // sum = 13
int difference = a - b; // difference = 7
int product = a * b; // product = 30
int quotient = a / b; // quotient = 3
int remainder = a % b; // remainder = 1

b. Relational Operators

These operators are used to compare two values:

 Equal to (==): Checks if two operands are equal.


 Not equal to (!=): Checks if two operands are not equal.
 Greater than (>): Checks if the left operand is greater than the right.
 Less than (<): Checks if the left operand is less than the right.
 Greater than or equal to (>=): Checks if the left operand is greater than or equal to the
right.
 Less than or equal to (<=): Checks if the left operand is less than or equal to the right.
Example:

java
Copy code
int x = 5;
int y = 10;
boolean isEqual = (x == y); // false
boolean isGreater = (x > y); // false

c. Logical Operators

These operators are used to combine multiple boolean expressions:

 Logical AND (&&): Returns true if both operands are true.


 Logical OR (||): Returns true if at least one operand is true.
 Logical NOT (!): Reverses the logical state of its operand.

Example:

java
Copy code
boolean a1 = true;
boolean a2 = false;
boolean result1 = a1 && a2; // false
boolean result2 = a1 || a2; // true

d. Assignment Operators

These operators assign values to variables:

 Assignment (=): Assigns the right operand's value to the left operand.
 Add and assign (+=): Adds the right operand to the left operand and assigns the result.
 Subtract and assign (-=): Subtracts the right operand from the left and assigns the result.
 Multiply and assign (*=): Multiplies the left operand by the right and assigns the result.
 Divide and assign (/=): Divides the left operand by the right and assigns the result.
 Modulus and assign (%=): Computes the modulus and assigns the result.

Example:

java
Copy code
int a = 5;
a += 3; // a = a + 3; a = 8

e. Unary Operators

These operators operate on a single operand:

 Unary plus (+): Indicates a positive value.


 Unary minus (-): Negates the value.
 Increment (++): Increases the value by 1.
 Decrement (--): Decreases the value by 1.

Example:

java
Copy code
int num = 5;
num++; // num = 6
num--; // num = 5

2. Operator Precedence

Operator precedence determines the order in which operators are evaluated in expressions.
Operators with higher precedence are evaluated before those with lower precedence.

Operator Precedence Hierarchy (from highest to lowest):

1. Postfix: expr++, expr--


2. Unary: ++expr, --expr, +, -, !, ~
3. Multiplicative: *, /, %
4. Additive: +, -
5. Shift: <<, >>, >>>
6. Relational: <, >, <=, >=, instanceof
7. Equality: ==, !=
8. Bitwise AND: &
9. Bitwise XOR: ^
10. Bitwise OR: |
11. Logical AND: &&
12. Logical OR: ||
13. Ternary (conditional): ? :
14. Assignment: =, +=, -=, *=, /=, %=, etc.

Example:

java
Copy code
int a = 10, b = 20, c = 30;
int result = a + b * c; // Multiplication has higher precedence than addition
// result = 10 + (20 * 30) = 10 + 600 = 610

Type conversion (or type casting) in Java is the process of converting a variable from one data
type to another. This is important in object-oriented programming as it helps manage the
different types of data effectively. Here’s a detailed look at type conversion in Java:

1. Types of Type Conversion


Java supports two main types of type conversion:

a. Implicit Type Conversion (Widening Conversion)

This type of conversion occurs automatically when a smaller primitive type is converted into a
larger primitive type. No data loss occurs during this conversion.

Examples of Implicit Conversion:

 byte to short
 short to int
 int to long
 float to double

Example:

java
Copy code
byte b = 10;
int i = b; // Implicit conversion from byte to int
long l = i; // Implicit conversion from int to long
double d = l; // Implicit conversion from long to double

b. Explicit Type Conversion (Narrowing Conversion)

This type of conversion requires explicit casting and occurs when a larger primitive type is
converted into a smaller primitive type. This may result in data loss, so it is done with caution.

Examples of Explicit Conversion:

 int to byte
 long to int
 double to float

Example:

java
Copy code
double d = 9.78;
int i = (int) d; // Explicit conversion from double to int (data loss occurs)
System.out.println(i); // Output: 9

2. Type Casting with Reference Types

In addition to primitive types, type casting also applies to reference types (objects) in Java,
particularly when working with inheritance. There are two types of casting:

a. Upcasting
Upcasting refers to casting a subclass reference to a superclass type. This is safe and does not
require explicit casting.

Example:

java
Copy code
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

Animal animal = new Dog(); // Upcasting


animal.sound(); // Output: Bark

b. Downcasting

Downcasting refers to casting a superclass reference back to a subclass type. This requires
explicit casting and can throw a ClassCastException if the object being cast is not an instance
of the target subclass.

Example:

java
Copy code
Animal animal = new Dog(); // Upcasting
Dog dog = (Dog) animal; // Downcasting
dog.sound(); // Output: Bark

// Downcasting example that may cause an exception


Animal anotherAnimal = new Animal();
Dog anotherDog = (Dog) anotherAnimal; // This will throw ClassCastException

3. Type Conversion of Wrapper Classes

Java also supports type conversion for wrapper classes (like Integer, Double, etc.). You can
convert between these classes and their corresponding primitive types.

Example:

java
Copy code
Integer num = 100; // Autoboxing (primitive to wrapper)
int n = num; // Unboxing (wrapper to primitive)
Double d = 5.75;
int intValue = d.intValue(); // Converts double to int (data loss)

Summary

 Implicit Type Conversion: Automatically converts smaller types to larger types without
data loss.
 Explicit Type Conversion: Requires casting when converting larger types to smaller
types and may result in data loss.
 Upcasting and Downcasting: Involves casting between superclass and subclass
references.
 Wrapper Class Conversion: Java allows conversion between primitive types and their
corresponding wrapper classes.

In Java, decision-making and repetition statements allow you to control the flow of execution in
your programs. They enable your code to make choices and repeat actions based on specific
conditions. Here's a detailed overview of decision-making statements, specifically the if
statement and the switch statement, in the context of object-oriented programming (OOP).

1. Decision Statements

a. If Statement

The if statement evaluates a condition (a boolean expression) and executes a block of code if the
condition is true. It can also include an optional else clause for alternative execution when the
condition is false.

Syntax:

java
Copy code
if (condition) {
// Block of code to execute if the condition is true
} else {
// Block of code to execute if the condition is false (optional)
}

Example:

java
Copy code
int number = 10;

if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
Nested If Statements

You can also nest if statements within each other.

Example:

java
Copy code
int score = 85;

if (score >= 60) {


System.out.println("You passed!");
if (score >= 90) {
System.out.println("Excellent!");
}
} else {
System.out.println("You failed.");
}

b. Switch Statement

The switch statement is used to select one of many code blocks to be executed based on the
value of an expression. It is generally more efficient than using multiple if statements when
dealing with multiple conditions based on the same variable.

Syntax:

java
Copy code
switch (expression) {
case value1:
// Block of code to execute if expression == value1
break;
case value2:
// Block of code to execute if expression == value2
break;
// You can have any number of case statements
default:
// Block of code to execute if expression doesn't match any case
}

Example:

java
Copy code
int day = 3;
String dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}

System.out.println("The day is: " + dayName); // Output: The day is: Wednesday

2. Control Flow in Object-Oriented Programming

In OOP, decision-making statements help determine how objects interact and how methods are
executed based on conditions. For example:

 Method Overriding: You can use if statements within overridden methods to provide different
behavior depending on the object's state.
 Polymorphism: Different classes can implement the same method differently, and you can use
switch or if statements to execute specific code based on the type of object.

Example:

java
Copy code
class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Meow");
}
}

public class TestAnimal {


public static void main(String[] args) {
Animal animal = new Dog(); // Upcasting
makeSound(animal);

animal = new Cat(); // Upcasting


makeSound(animal);
}

static void makeSound(Animal animal) {


if (animal instanceof Dog) {
System.out.println("This is a dog.");
} else if (animal instanceof Cat) {
System.out.println("This is a cat.");
}
animal.sound();
}
}

Summary

 If Statement: Evaluates a condition and executes code based on whether the condition is true or
false. It can include else if and else clauses for additional conditions.
 Switch Statement: A more efficient way to execute different blocks of code based on the value
of an expression, especially when there are multiple possible values.
 Decision-making statements are crucial in controlling the flow of execution in OOP, allowing
methods to behave differently based on object states or types.

In Java, iteration statements (or loops) allow you to execute a block of code repeatedly based on
a specified condition. These loops are fundamental in object-oriented programming as they
enable repetitive actions without the need to write the same code multiple times. Here's a detailed
overview of the different types of loops in Java, including the for loop, while loop, and do-while
loop.

1. Iteration Statements

a. For Loop

The for loop is used when the number of iterations is known beforehand. It consists of three
parts: initialization, condition, and increment/decrement.

Syntax:

java
Copy code
for (initialization; condition; update) {
// Block of code to be executed
}
Example:

java
Copy code
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
// Output:
// Iteration: 1
// Iteration: 2
// Iteration: 3
// Iteration: 4
// Iteration: 5
Enhanced For Loop (For-Each Loop)

Java also provides an enhanced for loop (or for-each loop) that is used to iterate over arrays or
collections.

Syntax:

java
Copy code
for (dataType variable : collection) {
// Block of code to be executed
}

Example:

java
Copy code
String[] fruits = {"Apple", "Banana", "Cherry"};

for (String fruit : fruits) {


System.out.println(fruit);
}
// Output:
// Apple
// Banana
// Cherry

b. While Loop

The while loop repeatedly executes a block of code as long as the specified condition is true. It
is used when the number of iterations is not known in advance.

Syntax:

java
Copy code
while (condition) {
// Block of code to be executed
}
Example:

java
Copy code
int count = 1;

while (count <= 5) {


System.out.println("Count: " + count);
count++;
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

c. Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code is
executed at least once before the condition is tested.

Syntax:

java
Copy code
do {
// Block of code to be executed
} while (condition);

Example:

java
Copy code
int number = 1;

do {
System.out.println("Number: " + number);
number++;
} while (number <= 5);
// Output:
// Number: 1
// Number: 2
// Number: 3
// Number: 4
// Number: 5

2. Control Flow in Object-Oriented Programming

Loops are essential in OOP for various tasks, such as:


 Iterating Over Collections: You can use loops to iterate through elements of collections like
ArrayList, HashMap, etc.
 Repeated Method Calls: Loops can be used to call methods repeatedly based on conditions.
 Object Manipulation: You can create and manipulate multiple objects within loops, especially in
scenarios like creating multiple instances of a class or processing a list of objects.

Example of Using Loops with Objects:

java
Copy code
class Student {
String name;

Student(String name) {
this.name = name;
}

void display() {
System.out.println("Student Name: " + name);
}
}

public class TestStudent {


public static void main(String[] args) {
String[] studentNames = {"Alice", "Bob", "Charlie"};
Student[] students = new Student[studentNames.length];

// Creating Student objects in a for loop


for (int i = 0; i < studentNames.length; i++) {
students[i] = new Student(studentNames[i]);
}

// Displaying Student names using an enhanced for loop


for (Student student : students) {
student.display();
}
}
}

Summary

 For Loop: Best used when the number of iterations is known. Includes initialization, condition,
and update sections.
 While Loop: Used when the number of iterations is unknown. Continues executing as long as
the condition is true.
 Do-While Loop: Similar to the while loop but guarantees at least one execution of the block of
code.
 Loops are crucial for managing repetitive tasks and processing collections of objects in object-
oriented programming.

Arrays are a fundamental data structure in Java that allow you to store multiple values of the
same type in a single variable. In object-oriented programming (OOP), arrays are essential for
managing collections of objects, facilitating iteration, and enabling efficient data manipulation.
This section will cover the basics of arrays, how to work with them in Java, and their
applications in OOP.

1. What is an Array?

An array is a fixed-size data structure that holds a collection of elements of the same type. Each
element in the array can be accessed using an index, which starts at 0.

2. Declaring and Initializing Arrays

a. Declaring an Array

You can declare an array by specifying the type of elements it will hold followed by square
brackets.

Syntax:

java
Copy code
dataType[] arrayName; // Declaration

b. Creating an Array

You can create an array using the new keyword along with the desired size.

Syntax:

java
Copy code
arrayName = new dataType[size]; // Allocation

c. Combining Declaration and Creation

You can declare and create an array in a single line.

Example:

java
Copy code
int[] numbers = new int[5]; // An array of integers with 5 elements

d. Initializing an Array

You can initialize an array at the time of declaration using curly braces.

Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5}; // An array initialized with values

3. Accessing Array Elements

Array elements can be accessed using their index.

Example:

java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[2]); // Output: 30

4. Iterating Over Arrays

You can use loops to iterate through the elements of an array.

a. Using a For Loop

java
Copy code
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]); // Print each element
}

b. Using an Enhanced For Loop

java
Copy code
for (int number : numbers) {
System.out.println(number); // Print each element
}

5. Multi-Dimensional Arrays

Java supports multi-dimensional arrays (arrays of arrays), which can be used to represent
matrices or tables.

Declaring a 2D Array:

java
Copy code
int[][] matrix = new int[3][3]; // 3x3 matrix

Initializing a 2D Array:

java
Copy code
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Accessing Elements in a 2D Array:

java
Copy code
System.out.println(matrix[1][2]); // Output: 6

Iterating Over a 2D Array:

java
Copy code
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

6. Working with Arrays in Object-Oriented Programming

Arrays play a significant role in OOP, especially when working with collections of objects. Here
are some common use cases:

a. Storing Objects in Arrays

You can create an array to store objects of a class.

Example:

java
Copy code
class Student {
String name;

Student(String name) {
this.name = name;
}

void display() {
System.out.println("Student Name: " + name);
}
}

public class TestArray {


public static void main(String[] args) {
Student[] students = new Student[3]; // Array to hold Student objects
// Creating Student objects and assigning to array
students[0] = new Student("Alice");
students[1] = new Student("Bob");
students[2] = new Student("Charlie");

// Iterating over the array and displaying student names


for (Student student : students) {
student.display();
}
}
}

b. Using Arrays as Method Parameters

You can pass arrays as parameters to methods, allowing for easy data manipulation.

Example:

java
Copy code
public class ArrayMethods {
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[] args) {


int[] myArray = {5, 10, 15, 20};
printArray(myArray); // Pass the array to the method
}
}

Summary

 Arrays: Fixed-size collections of elements of the same type, accessed by index.


 Declaring, Initializing, and Accessing: You can declare, create, initialize, and access
elements in arrays using various techniques.
 Multi-Dimensional Arrays: Arrays can be multi-dimensional, allowing for more
complex data structures like matrices.
 OOP Applications: Arrays are widely used to store and manage collections of objects
and can be passed to methods for data manipulation.

Understanding arrays and how to work with them is crucial for effective programming in Java,
particularly in the context of object-oriented programming. If you have any questions or need
further clarification, feel free to ask!

You might also like