Java Basic
1. Type Conversion
Type conversion in Java refers to converting values from one data type to another. This can be automatic or explicit.
Automatic Type Conversion:
- Principle: Java automatically converts smaller data types to larger data types to prevent data loss. For instance, a
bytecan be seamlessly converted to anint. - Example:
byte a = 10;int b = a;// Here,byteis automatically converted toint.
- In Expressions: Within expressions, smaller data types (like
byte,short,char) are promoted tointbefore computation.- Example:
- Incorrect:
byte b3 = b1 + b2;(where both b1 and b2 are bytes) - Correct:
int b3 = b1 + b2;orbyte b3 = (byte) (b1 + b2);
- Incorrect:
- Example:
- Principle: Java automatically converts smaller data types to larger data types to prevent data loss. For instance, a
Explicit Type Conversion (Type Casting):
- Principle: When converting from larger to smaller data types, explicit casting is required to avoid compile-time errors.
- Examples:
int a = 1500;byte b = (byte)a;// Potential data loss, asbytecan hold values from -128 to 127.double a = 99.5;int i = (int)a;// Here, i becomes 99, losing the decimal part.
2. Operators
Java supports various operators for arithmetic, relational, and logical operations.
Arithmetic Operators: Common operators include
+,-,*,/, and%./in integer division truncates any fractional part.*with a floating point results in a floating-point number.
String Concatenation: Using
+with strings concatenates them, e.g.,"Hello " + "World"results in"Hello World".Increment/Decrement Operators (
++,--):- Pre-increment/decrement (
++var,--var) modifies the variable before use. - Post-increment/decrement (
var++,var--) modifies the variable after use.
- Pre-increment/decrement (
Assignment Operators: Include
=,+=,-=,*=,/=,%=which perform an operation and assignment in one step.Relational Operators:
==,!=,>,<,>=,<=evaluate to boolean values.Logical Operators: Include
&,|,&&,||,!,^. Short-circuit versions (&&,||) do not evaluate the second expression if the first is sufficient to determine the result.Ternary Operator: Used for conditional assignments, e.g.,
int result = (condition) ? value1 : value2;.Operator Precedence: Determines the order of operations, with parentheses having the highest priority.
3. Keyboard Input Technology
Java provides mechanisms to handle user input through the keyboard using the Scanner class.
- Procedure:
- Import the Scanner class:
import java.util.Scanner; - Create a Scanner object:
Scanner sc = new Scanner(System.in); - Use the Scanner to read different types of input (e.g.,
nextInt()for integers,next()for strings).
- Import the Scanner class: