OOP With Java Module 1 an Overview of Java - Copy[1]
OOP With Java Module 1 an Overview of Java - Copy[1]
An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP
Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments,
Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters,
Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions, Arrays,
Introducing Type Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The Assignment
Operator, The ? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration Statements
(while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop,
Nested Loops), Jump Statements (Using break, Using continue, return).
Chapter 2, 3, 4, 5
Object-Oriented Programming:
Core of Java: OOP is fundamental to Java; all Java programs are object-oriented
to some degree.
Two Paradigms:
Process-Oriented Model: Focuses on "what is happening" (code acting on data).
Object-Oriented Model: Focuses on "who is being affected" (data controls
access to code).
Abstraction:
Simplifies complexity by managing details through hierarchical classifications.
Example: A car is viewed as a single object, despite being composed of many
subsystems.
Polymorphism:
- Allows one interface to be used for a general class of actions.
- Example: Different data types (int, float, char) can use the same stack
operations.
OOP Benefits:
- Encapsulation: Keeps code and data secure and modular.
- Inheritance: Promotes code reusability and manageability.
2|Page OOP with java – Module 1
- Polymorphism: Simplifies code, making it cleaner and more adaptable.
OOP in Java:
- Every Java program utilizes encapsulation, inheritance, and polymorphism.
- Java's built-in class libraries heavily use these principles.
These principles make Java programs more robust, scalable, and maintainable.
- `}`:
- Closes the `main` method and the `Example` class.
- Example:
- In the `if` statement:
if(x < y) {
x = y;
y = 0;
}
- Both statements execute if `x < y`.
Lexical Issues
- Java Program Components:
- Java programs consist of whitespace, identifiers, literals, comments, operators, separators, and keywords.
- Whitespace:
- Java is a free-form language, meaning there are no strict rules on indentation.
- Whitespace includes spaces, tabs, and newlines.
- At least one whitespace character is needed between tokens unless separated by an operator or separator.
- Identifiers:
- Names for classes, variables, and methods.
- Can include letters (both cases), numbers, underscores, and dollar signs.
- Cannot begin with a number and are case-sensitive.
- Example valid identifiers: `AvgTemp`, `count`, `a4`, `$test`, `this_is_ok`.
- Invalid identifiers: `2count`, `high-temp`, `Not/ok`.
- Using an underscore (`_`) alone as an identifier is not recommended from JDK 8 onwards.
- Literals:
- Represent constant values directly in the code.
- Examples:
4|Page OOP with java – Module 1
- `100` (integer) - `98.6` (floating-point) - `'X'` (character) - `"This is a test"` (string).
- Can be used wherever a value of their type is required.
- Comments:
- Three types:
- Single-line (`//`) - Multiline (`/* ... */`) - Documentation (`/ ... */`), used to generate HTML
documentation.
- Separators:
- Parentheses `()`: Used in method definitions, invocations, expression precedence, and control statements.
- Braces `{}`: Contain block of code, arrays, classes, methods, and local scopes.
- Brackets `[]`: Declare and dereference arrays.
- Semicolon `;`: Terminates statements.
- Comma `,`: Separates variables and chains statements in `for` loops.
- Period `.`: Separates package names, subpackages, classes, and reference variables from methods.
- Colons `::`: Used in method or constructor references (introduced in JDK 8).
- Java Keywords:
- Java has 50 keywords that are integral to the language structure.
- Examples: `abstract`, `boolean`, `class`, `static`, `void`, `for`, `if`, `public`, `return`, `while`.
- `const` and `goto` are reserved but not used.
- Additional reserved words: `true`, `false`, `null`.
- These keywords cannot be used as identifiers (variable names, class names, method names).
This ensures that Java programs are safe and less prone to runtime errors due to improper type usage.
Examples:
1. Byte: The smallest integer type (`byte`) is useful when working with raw binary data.
byte b, c;
2. Integer: Most commonly used integer type. Can hold large ranges and is often promoted when evaluating
expressions.
int x = 100;
3. Long: Used when `int` is not large enough to hold the value. Example program:
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed = 186000;
long days = 1000;
long seconds = days * 24 * 60 * 60;
long distance = lightspeed * seconds;
System.out.println("In " + days + " days light will travel about " + distance + " miles.");
}
}
Floating-Point Types:
float: Single-precision 32-bit.
double: Double-precision 64-bit, often faster for complex mathematical calculations.
Example:
// Compute the area of a circle using double
class Area {
public static void main(String args[]) {
double pi = 3.1416;
double r = 10.8;
double a = pi * r * r;
System.out.println("Area of circle is " + a);
6|Page OOP with java – Module 1
}
}
Boolean Type:
`boolean` type can only hold `true` or `false`. Used in control flow and comparisons.
Example:
// Demonstrate boolean values
class BoolTest {
public static void main(String args[]) {
boolan b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// Boolean controlling an if statement
if(b) System.out.println("This is executed.");
// Boolean result of a relational operator
System.out.println("10 > 9 is " + (10 > 9));
}
}
Key Points:
- Primitive types are efficient and represent single values.
- Java’s strict type definitions allow for platform-independent data sizes.
- Arithmetic operations and expressions may involve implicit type promotions.
Literals in Java
1. Integer Literals:
Decimal: Any whole number like `1, 42`, etc.
Octal: Starts with a `0`, valid digits range from `0-7` (e.g., `07`).
Hexadecimal: Starts with `0x` or `0X`, uses `0-9` and `A-F` (e.g., `0x7F`).
Binary** (JDK 7+): Starts with `0b` or `0B` (e.g., `0b1010`).
Underscore usage (JDK 7+): Can be used for readability, e.g., `1_000_000`.
Long literal: Append `L` or `l` (e.g., `9223372036854775807L`).
2. Floating-Point Literals:
Standard notation: Includes fractional components (e.g., `2.0`, `0.6667`).
Scientific notation: Uses `E` or `e` for exponent (e.g., `6.022E23`).
Default type: `double` (64-bit), specify `float` with `F` or `f` (32-bit).
Program Output:
Conversion of int to byte.
i and b: 257 1
Explanation:
int to byte: The value 257 is reduced modulo 256, so the result is 1.
double to int: The fractional part of 323.142 is truncated, leaving 323.
double to byte: The value is reduced modulo 256, resulting in 67.
Explanation of Promotions:
`f * b`: `b` is promoted to `float`; result is `float`.
`i / c`: `c` is promoted to `int`; result is `int`.
`d * s`: `s` is promoted to `double`; result is `double`.
Finally, `float + int` results in `float`, and `float - double` promotes to `double`.
Program Output:
238.14 + 390 - 126.2816
result = 501.8584
Arrays
Definition: An array is a group of variables of the same type, accessed using a common name. Java arrays
can be one-dimensional or multidimensional.
One-Dimensional Arrays
Declaration: Syntax: `type var-name[];`
Example: `int month_days[];` declares an array of integers.
Memory Allocation: Arrays must be allocated memory using `new`.
Syntax: `array-var = new type[size];`
Example: `month_days = new int[12];` allocates space for 12 integers.
Example Program:
class Array {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Multidimensional Arrays
- Example Program:
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
twoD[i][j] = k++;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
#### Syntax
var variableName = value;
#### Example
var num = 10; // inferred as int
var message = "Hello, World!"; // inferred as String
Here, `num` is inferred to be of type `int`, and `message` is inferred to be of type `String`.
Example Program
13 | P a g e OOP with java – Module 1
public class TypeInferenceExample {
public static void main(String[] args) {
var count = 5; // inferred as int
var name = "John"; // inferred as String
System.out.println("Count: " + count);
System.out.println("Name: " + name);
}
}
Limitations
1. Not for Every Use Case: Overuse of `var` can lead to less readable code, especially when the type is
not immediately obvious from the assignment expression.
2. Cannot be used for null**: `var x = null;` is not allowed because the compiler cannot infer the type
from `null`.
By using `var`, Java combines the benefits of strong typing with simpler, more concise code.
Operators
Java provides a rich set of operators that can be divided into four main groups: arithmetic, bitwise,
relational, and logical. Additionally, Java defines certain special operators like the type comparison operator
`instanceof` and the arrow operator `->`.
1. Arithmetic Operators
- Used for mathematical operations.
- Operators:
| Operator | Result |
|----------|---------------------------------|
| `+` | Addition (also unary plus) |
| `-` | Subtraction (also unary minus) |
-Numeric Types Only: Arithmetic operators can only be used with numeric types like `int`, `double`,
`float`, `char`, etc., not with `boolean`.
| **Operator** | **Description** |
|-------------- |------------------------------------------|
| `~` | Bitwise NOT (Unary Operator) |
| `&` | Bitwise AND |
| `|` | Bitwise OR |
| `^` | Bitwise XOR (Exclusive OR) |
| `<<` | Left shift |
| `>>` | Right shift (Sign-extended) |
| `>>>` | Right shift (Zero-fill) |
| `&=` | Bitwise AND assignment |
| `|=` | Bitwise OR assignment |
Shift Operators
1. Left Shift (`<<`): Shifts bits to the left, filling with zeros.
- Example: `64 << 2` results in `256`.
2. Right Shift (`>>`): Shifts bits to the right, preserving the sign (sign extension).
- Example: `35 >> 2` results in `8`.
3. Unsigned Right Shift (`>>>`): Shifts bits to the right, filling with zeros regardless of sign.
- Example: `-1 >>> 24` results in `255`.
Examples
1. Bitwise Operations in a Program:
class BitLogic {
public static void main(String args[]) {
int a = 3; // 0011 in binary
int b = 6; // 0110 in binary
int c = a | b; // 0111 (7 in binary)
int d = a & b; // 0010 (2 in binary)
int e = a ^ b; // 0101 (5 in binary)
int f = (~a & b) | (a & ~b); // 0101 (5 in binary)
int g = ~a & 0x0f; // 1100 (12 in binary)
Relational Operators
- Purpose: Determine the relationship between two operands, such as equality or ordering.
- Operators and Their Functions:
| Operator | Description |
| `==` | Equal to |
| `!=` | Not equal to |
| `>` | Greater than |
| `<` | Less than |
| `>=` | Greater than or equal to |
| `<=` | Less than or equal to |
Applicable Types:
- Equality (`==`) and Inequality (`!=`): Can be used with any type (integers, floating-point numbers,
characters, Booleans).
- Ordering (`>`, `<`, `>=`, `<=`): Only applicable to numeric types (integers, floating-point, characters).
Important Notes:
- Equality Operator: In Java, equality is tested with `==`, not with a single `=` (which is the assignment
operator).
Example Code:
int a = 4;
int b = 1;
boolean c = a < b; // c will be false, as 4 is not less than 1
Example Code:
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
Compatibility:The type of `var` must be compatible with the result of `expression`. For example:
int a = 10; // Valid: int can hold an integer value.
Chain Assignments:
Example:
int x, y, z;
x = y = z = 100; // Sets x, y, and z to 100
- How it works:
- First, `z = 100` is evaluated, which returns the value `100`.
- Next, `y = z`, so `y` also becomes `100`.
- Finally, `x = y`, making `x` also equal to `100`.
- Usage: This is useful for initializing several variables to the same value efficiently.
Key Points:
- The assignment operator returns the value of the right-hand expression, allowing the chaining of
assignments.
- It is widely used for initializing multiple variables at once, keeping the code concise.
The ? Operator
- Purpose: The ternary operator is a shorthand for the `if-then-else` statement.
- Syntax: expression1 ? expression2 : expression3;
- `expression1`: A boolean expression that evaluates to `true` or `false`.
- `expression2`: Executed if `expression1` is `true`.
- `expression3`: Executed if `expression1` is `false`.
- Result: The ternary operator returns the value of either `expression2` or `expression3`, depending on the
condition (`expression1`). Both expressions must return a value of the same or compatible type.
Example:
int ratio = denom == 0 ? 0 : num / denom;
- If `denom == 0`, the value `0` is assigned to `ratio`.
- If `denom != 0`, the value `num / denom` is assigned to `ratio`.
Here is a program that demonstrates the use of the ternary operator to obtain the absolute value of a variable:
// Demonstrate the ternary operator.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
22 | P a g e OOP with java – Module 1
Output:
Absolute value of 10 is 10
Absolute value of -10 is 10
Key Points:
- The ternary operator helps in writing concise conditional statements.
- It's useful when there are simple conditions with two possible outcomes.
Operator Precedence
Using Parentheses
Purpose: Parentheses are used in Java to control or clarify the order of operations in an expression.
Operator Precedence: Java evaluates operators based on a defined order of precedence. If an expression
contains operators of different precedence levels, the higher precedence operator is executed first.
Parentheses are used to change the default precedence.
Examples:
1. Without Parentheses: a >> b + 3
- This expression first adds `3` to `b`, then shifts `a` right by the result of that addition.
- Equivalent to: a >> (b + 3)
2. With Parentheses:
If you want to first shift `a` right by `b` positions and then add `3`: (a >> b) + 3
3. Clarifying Complex Expressions:
Parentheses can help make complex expressions easier to read.
- Without extra parentheses: a | 4 + c >> b & 7
- With parentheses for clarity: (a | (((4 + c) >> b) & 7))
Key Points:
- Priority Management: Parentheses raise the precedence of the enclosed expressions, ensuring the
operations inside are executed first.
- Readability: Adding redundant parentheses can help clarify complex expressions, making the code easier
to understand.
In conclusion, while parentheses change the order of operations, they are also an important tool for
enhancing code readability without any performance cost.
Control Statements
Java’s Selection Statements
`if` Statement
Purpose: Java’s conditional branch statement for selecting between two paths.
Syntax:
if (condition) statement1;
else statement2;
Condition: Any expression that returns a boolean value.
Block of Code: Use curly braces `{}` to include multiple statements.
Example:
int a, b;
if(a < b) a = 0;
else b = 0;
Using Blocks:
int bytesAvailable;
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
{
waitForMoreData();
}
`if-else-if` Ladder
Purpose: Chain of `if-else` statements to test multiple conditions.
Example:
if (month == 12 || month == 1 || month == 2) season = "Winter";
else if (month == 3 || month == 4 || month == 5) season = "Spring";
else season = "Bogus Month";
Output:
April is in the Spring.
`switch` Statement
Purpose: Java’s multiway branch statement for better efficiency than `if-else-if`.
Syntax:
switch(expression) {
case value1: statement sequence; break;
case value2: statement sequence; break;
...
default: default sequence;
}
Expression Type: Can be `byte`, `short`, `int`, `char`, `String` (from JDK 7), or enum.
Example:
class SampleSwitch {
public static void main(String args[]) {
for (int i = 0; i < 6; i++) {
switch(i) {
case 0: System.out.println("i is zero."); break;
case 1: System.out.println("i is one."); break;
case 2: System.out.println("i is two."); break;
default: System.out.println("i is greater than 3.");
}
}
}
}
Output:
```
Output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
Output:
two
Key Points:
`if` vs `switch`: `if` evaluates any boolean expression; `switch` only checks for equality.
Efficiency: `switch` is more efficient for large groups of values due to the use of a "jump table."
Iteration Statements
while` Loop
Purpose: Repeats a statement or block while a condition is true.
Synta*:
while (condition) {
// body of loop
}
Condition: Any boolean expression.
Behavior: Executes the body as long as the condition is true. Exits when the condition becomes false.
Condition False Initially: Loop will not execute if the condition is false at the start.
int a = 10, b = 20;
while (a > b)
System.out.println("This will not be displayed");
Empty Loop Body: The body of the loop can be empty, using a null statement (a single semicolon).
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while (++i < --j); // no body in this loop
System.out.println("Midpoint is " + i);
}
}
Output:
Midpoint is 150
Explanation:
- `i` is incremented and `j` is decremented in the condition.
- Loop continues while `i` is less than `j`.
- Upon loop exit, `i` is midway between the original values of `i` and `j`.
Use Case: Short loops with all logic in the condition itself.
do-while` Loop
Purpose: Ensures that the body of the loop is executed at least once, regardless of the condition.
Syntax:
do {
// body of loop
} while (condition);
Behavior: Executes the loop body first, then evaluates the condition. If the condition is true, the loop
repeats; otherwise, it terminates.
Optimized Example:
do {
System.out.println("tick " + n);
} while (--n > 0);
Explanation: The expression `--n > 0` combines the decrement and condition check. `--n`
decrements `n` and returns the new value, which is then compared with zero.
System.out.println("\n");
switch (choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
29 | P a g e OOP with java – Module 1
System.out.println(" //...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Sample Output:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);
Explanation:
- The `do-while` loop ensures that the menu is displayed at least once.
- User input is read using `System.in.read()`, which requires handling `IOException`.
- `System.in.read()` reads characters as integers, hence casting to `char`.
Explanation:
- Initialization: `int n = 10;` sets the initial value of `n`.
- Condition: `n > 0;` checks if `n` is greater than 0.
- Iteration: `n--` decrements `n` by 1 after each loop iteration.
- Body: `System.out.println("tick " + n);` executes with each loop iteration.
The `for-each` loop simplifies iterating through collections, providing cleaner and less error-prone code for
sequential access. However, it is important to remember that you cannot modify the collection being iterated
directly using this loop.
Java 10 introduced `var` for local variable type inference, simplifying code by letting the compiler determine
the type.
Using `var` in a `for` Loop: Traditional `for` Loop: Before Java 10:**
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
With `var`:
for (var i = 0; i < 10; i++) {
System.out.println(i);
}
Key Points
Type Inference: `var` infers the type based on initialization.
Initialization Required: Must be initialized on the same line.
Improves Readability: Reduces verbosity, but use judiciously for clarity.
Using `var` makes your `for` loops cleaner by removing redundant type declarations.
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop
may be inside another. For example, here is a program that nests for loops:
-Effect: Each iteration of the outer loop prints a new line. The number of `.` characters printed decreases as
`i` increases, leading to a pattern where each line has fewer `.` than the previous one.
Output:
..........
.........
........
.......
......
.....
....
...
..
.
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // Break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Output:
Before the break.
This is after second block.
class BreakLoop4 {
36 | P a g e OOP with java – Module 1
public static void main(String args[]) {
outer: for(int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for(int j = 0; j < 100; j++) {
if(j == 10) break outer; // Exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9
Loops complete.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(j > i) {
System.out.println();
continue outer; // Continue outer loop
37 | P a g e OOP with java – Module 1
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Output:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
Output:
Before the return.