Fundamentals of Java

Java Data Types

In Java, data types are crucial for defining the nature of variables. There are two main categories:

Primitive Data Types:

  • int: Represents integer values.

  • double: Stores decimal numbers.

  • char: Holds a single character.

  • boolean: Represents true or false values.

  • byte, short, long, float: Additional numeric types with varying ranges.

Reference Data Types:

  • String: Represents sequences of characters.

  • Arrays: Collections of elements.

Understanding and choosing the right data type is essential for efficient and error-free coding.

Operators in Java

Java supports a wide range of operators, categorized as:

  • Arithmetic Operators: +, -, *, /, %.

  • Relational Operators: ==, !=, >, <, >=, <=.

  • Logical Operators: &&, ||, !.

  • Assignment Operators: =, +=, -=, *=, /=.

  • Bitwise Operators: &, |, ^, ~, <<, >>, >>>.

  • Unary Operators: +, -, ++, --.

Mastery of these operators is fundamental for performing various operations in Java.

Flow Control: If/Else Blocks

Conditional statements, such as if and else, allow you to control the flow of your program based on certain conditions. For example:

javaCopy codeint x = 10;

if (x > 0) {
    System.out.println("x is positive");
} else {
    System.out.println("x is non-positive");
}

Understanding these blocks is vital for building decision-making logic in your programs.

Loops

For loops are useful when we know ahead of time how many times we want to repeat something. We declare a loop variable (or loop counter) and in each iteration we increment it until we reach the number of times we want to execute some code.

// for loop 
for (int i = 0; i < 5; i++) {
    // ....
}

// while loop
while (someCondition) {
…
if (someCondition)
break;
}

// do while loop 
// executed at least once. In contrast, 
// a while loop may never get executed if the condition is initially false
do {
…
} while (someCondition);

// for each loop 
// For-each loops are useful for iterating over an array or a collection.
int[] numbers = {1, 2, 3, 4};
for (int number : numbers) {
    // ...
}

Switch Statement

switch (x) {
case 1:
…
break;
case 2:
…
break;
default:
…
}

Strings in Java

Strings are a fundamental part of Java programming. Some tricks to remember:

  • Concatenation using the + operator.

  • Methods like length(), charAt(), substring(), and indexOf() for manipulation.

  • The equals() method for string comparison.

String name = "Shohanur Rahman";
name.startsWith("a");
name.endsWith("a");
name.length()
indexOf("a")
name.replace("a", "b")
name.toUpperCase()
name.toLowerCase()

Proper handling of strings is crucial for text processing and manipulation.

Arrays in Java

Arrays are containers that store multiple values of the same type. We use arrays to store a list of objects. We can store any type of object in an array (primitive or reference type). All items (also called elements) in an array have the same type.

  • 1D Arrays: Single-dimensional arrays.

  • 2D Arrays: Two-dimensional arrays for representing tables.

  • Array manipulation using methods like length, clone, and copyOf.

// Creating and and initializing an array of 3 elements
int[] numbers = new int[2];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

// Shortcut
int[] numbers = { 10, 20, 30 };

Java arrays have a fixed length (size). You cannot add or remove new items once you instantiate an array. If you need to add new items or remove existing items, you need to use one of the collection classes.

The Arrays Class

The Arrays class provides a few useful methods for working with arrays.

// sort 
int[] numbers = { 4, 2, 7 };
Arrays.sort(numbers);

// toString
String result = Arrays.toString(numbers);
System.out.println(result);

// binary Serarch 
int[] numbers = {1, 2, 5, 6, 8};
int index = Arrays.binarySearch(numbers, 5);

// fill array
int[] arr = new int[5];
Arrays.fill(arr, 42);

// copy array
int[] source = {1, 2, 3};
int[] destination = Arrays.copyOf(source, 5);

// checking equality 
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean isEqual = Arrays.equals(arr1, arr2);

Multi-dimensional Arrays

// Creating a 2x3 array (two rows, three columns)
int[2][3] matrix = new int[2][3];
matrix[0][0] = 10;
// Shortcut
int[2][3] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};

Constant

Constants (also called final variables) have a fixed value. Once we set them, we cannot change them.

final float INTEREST_RATE = 0.04;

By convention, we use CAPITAL LETTERS to name constants. Multiple words can be separated using an underscore.

Casting

Implicit Casting (Widening):

Implicit casting occurs when you convert a smaller data type to a larger data type, and Java can perform the conversion automatically without any loss of information. For example, converting an int to a double:

int intValue = 42;
double doubleValue = intValue; // Implicit casting

In this case, the int value is automatically converted to a double value. Implicit casting is generally considered safe because you are moving from a data type with a smaller range to one with a larger range.

Explicit Casting (Narrowing):

Explicit casting is required when you convert a larger data type to a smaller data type, and there is a potential loss of information. For example, converting a double to an int:

double doubleValue = 42.75;
int intValue = (int) doubleValue; // Explicit casting

Here, the double value is explicitly cast to an int. Keep in mind that explicit casting may result in loss of precision or data truncation, as the decimal part of the double is discarded in this case.

It's crucial to be cautious with explicit casting and ensure that you are not losing essential information in the process. When converting between data types, consider whether the range and precision of the destination type are sufficient for the values you are working with.

Example:

double doubleValue = 42.75;
int intValue = (int) doubleValue; 
// intValue will be 42, as the decimal part is truncated

In this example, the intValue will be 42 after explicit casting, and the fractional part (0.75) is discarded.

Class Declaration:

In Java, a class is declared using the class keyword. The general structure of a class looks like this:

javaCopy codepublic class MyClass {
    // Class members (fields, constructors, methods)
}
  • public: This keyword is an access modifier, indicating that the class is accessible from any other class.

  • MyClass: This is the name of the class. It follows the Java naming conventions (starting with an uppercase letter).

Class:

Inside a class, you can have various members, including fields, constructors, and methods.

Fields (Instance Variables):

Fields are variables declared within a class. They represent the attributes or properties of an object.

public class MyClass {
    int myField; // Instance variable
}

Constructors:

Constructors are special methods used for initializing objects. They have the same name as the class and no return type.

javaCopy codepublic class MyClass {
    int myField;

    // Constructor
    public MyClass(int initialValue) {
        this.myField = initialValue;
    }
}

Methods:

Methods are functions defined within a class. They encapsulate behavior associated with the class.

public class MyClass {
    int myField;

    // Constructor
    public MyClass(int initialValue) {
        this.myField = initialValue;
    }

    // Method
    public void displayValue() {
        System.out.println("MyField value: " + myField);
    }
}

Instantiating Objects:

Once you've defined a class, you can create objects (instances) of that class using the new keyword.

public class Main {
    public static void main(String[] args) {
        // Creating an object of MyClass
        MyClass myObject = new MyClass(42);

        // Calling a method on the object
        myObject.displayValue();
    }
}