Java Basics: Java Syntax and Data Type

Java Basics: Syntax and Data Types

{getToc} $title={Table of Contents} $count={true}

Primitive Data Types & Wrapper Classes

In Java, there are eight primitive data types. These are the building blocks of data manipulation. Each primitive type has a corresponding wrapper class for object representation.


// Primitive Data Types
int age = 25; // 4 bytes
double salary = 50000.50; // 8 bytes
char grade = 'A'; // 2 bytes
boolean isJavaFun = true; // 1 bit

// Wrapper Classes
Integer wrappedAge = Integer.valueOf(age);
Double wrappedSalary = Double.valueOf(salary);
Character wrappedGrade = Character.valueOf(grade);
Boolean wrappedIsFun = Boolean.valueOf(isJavaFun);
        
Example: The Integer wrapper class allows methods like parseInt() to convert strings to integers.

Auto Boxing

Auto-boxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes.


// Auto Boxing Example
int number = 100;
Integer boxedNumber = number; // Auto-boxing happens here

// Auto Unboxing Example
int unboxedNumber = boxedNumber; // Auto-unboxing happens here
        
Example: You can directly use primitive types in collections like ArrayList due to auto-boxing.

Casting

Casting is converting one data type into another. It can be implicit (automatic) or explicit (manual).


// Implicit Casting (Widening)
int smallNumber = 100;
double bigNumber = smallNumber; // Automatically widened

// Explicit Casting (Narrowing)
double pi = 3.14159;
int approxPi = (int) pi; // Manually narrowed
        
Example: Be cautious with narrowing as it may lead to data loss.

Enumeration

Enumerations (enums) are a special type of class used to define collections of constants.


// Enum Definition
enum DaysOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

// Enum Usage
DaysOfWeek today = DaysOfWeek.MONDAY;
System.out.println("Today is " + today);
        
Example: Enums are useful for representing fixed sets of constants like days, months, etc.

Regular Expressions

Regular expressions (regex) are patterns used to match character combinations in strings.


// Regex Example
String text = "Hello, my email is example@example.com";
String regex = "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}";
if (text.matches(".*" + regex + ".*")) {
    System.out.println("Email found!");
}
        
Example: Use regex to validate emails, phone numbers, or other formatted data.

Operators

Java provides various operators to perform operations on variables and values.


// Arithmetic Operators
int a = 10, b = 3;
System.out.println(a + b); // Addition
System.out.println(a - b); // Subtraction
System.out.println(a * b); // Multiplication
System.out.println(a / b); // Division
System.out.println(a % b); // Modulus

// Logical Operators
boolean x = true, y = false;
System.out.println(x && y); // AND
System.out.println(x || y); // OR
System.out.println(!x);     // NOT
        
Example: Operators are essential for performing calculations and decision-making in programs.

System Class Input/Output

The System class provides standard input, output, and error streams.


// Output using System.out
System.out.println("Hello, World!");

// Input using System.in
byte[] buffer = new byte[50];
System.out.print("Enter something: ");
System.in.read(buffer);
System.out.println("You entered: " + new String(buffer).trim());
        
Example: Use System.out for printing and System.in for reading user input.

Scanner Class

The Scanner class simplifies reading input from various sources.


import java.util.Scanner;

public class Main {
    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("Hello, " + name + "! You are " + age + " years old.");
        scanner.close();
    }
}
        
Example: The Scanner class is widely used for interactive console applications.

Previous Post Next Post