ā What is Java?
š 1. About Java
Java is a powerful, object-oriented programming language that is:
- Platform Independent: "Write Once, Run Anywhere" (WORA)
- Object-Oriented: Everything is an object
- Secure: Built-in security features
- Robust: Strong memory management
- Multi-threaded: Supports concurrent programming
š 2. Java is Used For
- š Web Development: Spring, JSP, Servlets
- š± Mobile Apps: Android development
- š¢ Enterprise Applications: Large-scale systems
- š„ļø Desktop Apps: Swing, JavaFX
- āļø Cloud Applications: Microservices
- š® Games: Minecraft was built in Java!
š 3. Why Learn Java?
- š¼ High Demand: One of the most popular languages
- š° Great Salary: Well-paying career opportunities
- š Large Community: Huge support and resources
- š Rich Libraries: Extensive built-in functionality
- š Regular Updates: Constantly evolving
š 4. Java vs Other Languages
Feature | Java | Python | C++ |
---|---|---|---|
Learning Curve | Moderate | Easy | Hard |
Performance | Fast | Slower | Very Fast |
Platform | Cross-platform | Cross-platform | Platform-specific |
š 5. Java Versions
- Java 8 (LTS): Lambda expressions, Stream API
- Java 11 (LTS): Local variable type inference
- Java 17 (LTS): Records, sealed classes
- Java 21 (LTS): Latest long-term support version
š” LTS = Long Term Support (recommended for production)
š 6. Java Architecture
Java follows the "Write Once, Run Anywhere" principle:
- š Source Code (.java) ā Written by developers
- āļø Bytecode (.class) ā Compiled by javac
- š JVM (Java Virtual Machine) ā Executes bytecode
- š» Any Platform ā Windows, Linux, macOS
š 7. Popular Java Frameworks
- š± Spring Boot: Enterprise applications
- š °ļø Android SDK: Mobile app development
- šļø Hibernate: Database operations
- š§ Apache Maven: Project management
- š Apache Kafka: Streaming platform
š 8. First Java Program Example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
This simple program prints "Hello, World!" to the console!
Practice Editor
ā Getting Started with Java
š 1. What You Need to Begin
- A computer (Windows, macOS, or Linux)
- Internet connection (for downloading JDK)
- A text editor or IDE (like IntelliJ IDEA, Eclipse, or VS Code)
- Java Development Kit (JDK)
š 2. Installing Java Development Kit (JDK)
ā Official Website:
Download JDK from: š Oracle JDK or Eclipse Temurin
š¦ Steps:
- Choose the latest LTS version (Java 21 recommended)
- Select your operating system
- Download and run the installer
- Follow the installation wizard
ā Verify Installation:
Open your terminal (CMD, PowerShell, or Bash):
java --version
and
javac --version
š 3. Setting up JAVA_HOME (Important!)
šŖ Windows:
- Right-click "This PC" ā Properties
- Advanced System Settings ā Environment Variables
- New System Variable: JAVA_HOME
- Value: Path to JDK (e.g., C:\Program Files\Java\jdk-21)
š§ Linux/macOS:
export JAVA_HOME=/usr/lib/jvm/java-21-openjdk
export PATH=$JAVA_HOME/bin:$PATH
š 4. Your First Java Program
ā Create a file named HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java World!");
}
}
ā Compile and Run:
# Compile
javac HelloWorld.java
# Run
java HelloWorld
š” Important: File name must match the class name!
š 5. Java Development Tools
š§ IDEs (Integrated Development Environments):
- IntelliJ IDEA: Most popular, excellent features
- Eclipse: Free, widely used in enterprise
- VS Code: Lightweight with Java extensions
- NetBeans: Official Oracle IDE
š Text Editors:
- Sublime Text, Atom, Vim, Emacs
š Online Compilers:
- repl.it, codepen.io, jdoodle.com
š 6. Java File Structure
- Java files end with
.java
- Compiled files end with
.class
- Each public class must be in its own file
- File name must match the public class name
- Java is case-sensitive
š 7. Understanding the Hello World Program
public class HelloWorld { // Class declaration
public static void main(String[] args) { // Main method
System.out.println("Hello, World!"); // Print statement
} // End of main method
} // End of class
š Breakdown:
public class HelloWorld
- Defines a public classmain
- Entry point of the programString[] args
- Command-line argumentsSystem.out.println()
- Prints text to console
ā Java Syntax: The Basics
š 1. Java is Case Sensitive
Java is case-sensitive, meaning myVariable
and MyVariable
are different!
public class CaseSensitive {
public static void main(String[] args) {
int myVariable = 10;
int MyVariable = 20; // Different variable!
System.out.println(myVariable); // Prints: 10
System.out.println(MyVariable); // Prints: 20
}
}
š 2. Comments
Used to explain code. They are ignored by the compiler.
// This is a single-line comment
/*
* This is a
* multi-line comment
*/
/**
* This is a JavaDoc comment
* Used for documentation
*/
š 3. Print Statements
System.out.println("Hello World!"); // With new line
System.out.print("Hello "); // Without new line
System.out.print("World!"); // Continues on same line
š 4. Variables Declaration
Java is statically typed - you must declare variable types.
int age = 25; // Integer
double price = 19.99; // Double (decimal)
String name = "John"; // String
boolean isValid = true; // Boolean
char grade = 'A'; // Character
š 5. String Formatting
String name = "Alice";
int age = 30;
// Concatenation
System.out.println("Hello " + name + ", you are " + age);
// printf style
System.out.printf("Hello %s, you are %d%n", name, age);
// String.format
String message = String.format("Hello %s, you are %d", name, age);
š 6. Basic Input (Scanner)
import java.util.Scanner;
public class InputExample {
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 + ", age " + age);
scanner.close();
}
}
š 7. Conditional Statements
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
š 8. Loops
š¹ for Loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
š¹ while Loop
int i = 0;
while (i < 5) {
System.out.println("Count: " + i);
i++;
}
š¹ Enhanced for Loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
š 9. Switch Statement
int day = 3;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
}
System.out.println("Day: " + dayName);
š 10. Basic Math Operations
int a = 10;
int b = 3;
System.out.println("Addition: " + (a + b)); // 13
System.out.println("Subtraction: " + (a - b)); // 7
System.out.println("Multiplication: " + (a * b)); // 30
System.out.println("Division: " + (a / b)); // 3 (integer)
System.out.println("Modulus: " + (a % b)); // 1
š Java Variables
ā What is a Variable?
A variable is a container that holds data. In Java, you must specify the type of data it will hold.
int age = 25; // Integer variable
String name = "John"; // String variable
double height = 5.9; // Double variable
boolean isStudent = true; // Boolean variable
š¹ 1. Variable Naming Rules
ā Valid names:
- Must start with a letter, underscore (_), or dollar sign ($)
- Can contain letters, digits, underscores, and dollar signs
- Cannot be a Java keyword
- Case-sensitive
ā Invalid names:
int 2name = 10; // ā Cannot start with digit
int user-name = 10; // ā Hyphens not allowed
int class = 10; // ā 'class' is a keyword
ā Valid examples:
int userName = 10;
int _age = 25;
int $price = 100;
int name2 = 5;
š¹ 2. Variable Types
šø Primitive Types:
byte smallNumber = 127; // 8-bit integer
short mediumNumber = 32000; // 16-bit integer
int number = 2000000000; // 32-bit integer
long bigNumber = 9000000000L; // 64-bit integer
float decimal = 3.14f; // 32-bit decimal
double preciseDecimal = 3.14159; // 64-bit decimal
char letter = 'A'; // Single character
boolean flag = true; // true or false
šø Reference Types:
String text = "Hello World";
int[] numbers = {1, 2, 3, 4, 5};
Scanner input = new Scanner(System.in);
š¹ 3. Variable Declaration and Initialization
// Declaration only
int age;
String name;
// Declaration with initialization
int score = 95;
String city = "New York";
// Multiple declarations
int x, y, z;
int a = 1, b = 2, c = 3;
š¹ 4. Constants (final keyword)
final int MAX_SCORE = 100;
final double PI = 3.14159;
final String COMPANY_NAME = "TechCorp";
// MAX_SCORE = 200; // ā Error: cannot reassign
š Constants cannot be changed once assigned. Use UPPER_CASE naming convention.
š¹ 5. Type Casting
// Implicit casting (automatic)
int intValue = 100;
double doubleValue = intValue; // int to double
// Explicit casting (manual)
double bigDecimal = 9.87;
int wholeNumber = (int) bigDecimal; // 9 (loses decimal part)
// String to primitive
String numberText = "123";
int parsedNumber = Integer.parseInt(numberText);
double parsedDecimal = Double.parseDouble("45.67");
š¹ 6. Variable Scope
public class VariableScope {
static int globalVar = 100; // Class variable
public static void main(String[] args) {
int localVar = 50; // Local variable
if (true) {
int blockVar = 25; // Block variable
System.out.println(globalVar); // ā
Accessible
System.out.println(localVar); // ā
Accessible
System.out.println(blockVar); // ā
Accessible
}
// System.out.println(blockVar); // ā Error: out of scope
}
}
š¹ 7. Default Values
public class DefaultValues {
// Instance variables have default values
int number; // 0
double decimal; // 0.0
boolean flag; // false
String text; // null
public static void main(String[] args) {
DefaultValues obj = new DefaultValues();
System.out.println(obj.number); // Prints: 0
System.out.println(obj.flag); // Prints: false
// Local variables must be initialized before use
int localVar;
// System.out.println(localVar); // ā Error: not initialized
}
}
š Java Data Types
ā Java Data Types Overview
Java has two categories of data types:
- Primitive Types: Store simple values directly
- Reference Types: Store references to objects
š¹ 1. Primitive Data Types
šø Integer Types
byte smallInt = 127; // 8-bit: -128 to 127
short mediumInt = 32000; // 16-bit: -32,768 to 32,767
int regularInt = 2000000000; // 32-bit: -2^31 to 2^31-1
long bigInt = 9000000000L; // 64-bit: -2^63 to 2^63-1
System.out.println("byte: " + smallInt);
System.out.println("short: " + mediumInt);
System.out.println("int: " + regularInt);
System.out.println("long: " + bigInt);
šø Floating-Point Types
float singlePrecision = 3.14f; // 32-bit decimal
double doublePrecision = 3.14159; // 64-bit decimal (more precise)
System.out.println("float: " + singlePrecision);
System.out.println("double: " + doublePrecision);
šø Character Type
char letter = 'A'; // Single character
char unicode = '\u0041'; // Unicode for 'A'
char number = '7'; // Character '7', not number 7
System.out.println("char: " + letter);
System.out.println("unicode: " + unicode);
šø Boolean Type
boolean isTrue = true;
boolean isFalse = false;
boolean result = (5 > 3); // true
System.out.println("boolean: " + isTrue);
System.out.println("comparison: " + result);
š¹ 2. Reference Data Types
šø String
String greeting = "Hello World";
String name = "Java";
String empty = "";
String nullString = null;
System.out.println("greeting: " + greeting);
System.out.println("length: " + greeting.length());
System.out.println("uppercase: " + greeting.toUpperCase());
šø Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
double[] prices = new double[3]; // Creates array of size 3
System.out.println("first number: " + numbers[0]);
System.out.println("array length: " + numbers.length);
š¹ 3. Data Type Sizes and Ranges
Type | Size | Range |
---|---|---|
byte | 8 bits | -128 to 127 |
short | 16 bits | -32,768 to 32,767 |
int | 32 bits | -2,147,483,648 to 2,147,483,647 |
long |