Java Programming Concepts
### 1. Access Modifiers
Access modifiers in Java define the scope and visibility of a class, method, or variable. Java
provides four types of access modifiers:
- **Public**: Accessible from any other class.
- **Private**: Accessible only within the class in which it is declared.
- **Protected**: Accessible within the same package and by subclasses.
- **Default (Package-private)**: Accessible only within the same package.
**Example:**
```java
package example;
public class AccessModifierExample {
public int publicVariable = 10;
private int privateVariable = 20;
protected int protectedVariable = 30;
int defaultVariable = 40;
public void display() {
System.out.println("Public: " + publicVariable);
System.out.println("Private: " + privateVariable);
System.out.println("Protected: " + protectedVariable);
System.out.println("Default: " + defaultVariable);
}
```
---
### 2. Main Method [public static void main(String[] args)]
The `main` method is the entry point of any Java application. Its signature is:
```java
public static void main(String[] args)
```
- **Public**: The method is accessible from outside the class.
- **Static**: The method can be called without creating an object.
- **Void**: The method does not return a value.
- **String[] args**: Command-line arguments passed to the program.
**Example:**
```java
public class MainExample {
public static void main(String[] args) {
System.out.println("Hello, World!");
```
---
### 3. Java Keywords
Java keywords are reserved words with predefined meanings and purposes. Examples include:
- **Control statements**: `if`, `else`, `switch`, `for`, `while`
- **Access modifiers**: `public`, `private`, `protected`
- **Class and object management**: `class`, `interface`, `extends`, `implements`
- **Data types**: `int`, `double`, `boolean`
**Example:**
```java
public class KeywordExample {
public static void main(String[] args) {
int number = 10;
if (number > 5) {
System.out.println("Number is greater than 5");
```
---
### 4. Java Data Types
Data types specify the type of data that variables can hold.
#### Primitive Data Types:
1. **Numeric**:
- `byte`, `short`, `int`, `long`: Whole numbers.
- `float`, `double`: Decimal numbers.
2. **Non-numeric**:
- `char`: Single character.
- `boolean`: True or false.
#### Non-Primitive Data Types:
1. **String**: Sequence of characters.
2. **Arrays**: Collection of elements.
3. **Objects**: Instances of classes.
**Example:**
```java
public class DataTypeExample {
public static void main(String[] args) {
int age = 25;
double price = 19.99;
char grade = 'A';
boolean isStudent = true;
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Is Student: " + isStudent);
```
---