#Java Lecture 1
#Java Lecture 1
Key Points:
• Java programs must be compiled before they can be run.
• Programs can either be applets (which run in a web browser) or applications (which run on a
standalone machine).
code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
code
javac HelloWorld.java
Lexical Structure
In Java, there are several key components to understand:
• Literals: These are constant values written directly into the code, such as numbers (5, 3.14),
characters ('a'), and strings ("hello").
• Identifiers: These are names given to variables, methods, and classes (e.g., int age;).
• Reserved Words: Special keywords used by Java for control flow (if, while), operators
(instanceof, throw), and definitions (public, class, void).
code
public class Test {
public static void main(String[] args) {
int age = 30; // 'int' is a reserved word, 'age' is an identifier, and '30' is a literal
System.out.println("Age: " + age); // 'Age: ' is a string literal
}
}
Example:
code
public class DataTypesExample {
public static void main(String[] args) {
int num = 10;
boolean isTrue = false;
char letter = 'C';
Output:
Number: 10
Boolean: false
Letter: C
If Statements:
An if statement executes a block of code if a condition is true.
code
if (condition) {
// code to execute if the condition is true
}
Example:
code
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
Output:
You are an adult.
While Loops:
The while loop executes a block of code as long as the condition is true.
Example:
code
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
Output:
1
2
3
4
5
For Loops:
The for loop is used to execute a block of code a specific number of times.
Example:
code
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Output:
1
2
3
4
5
Example:
code
System.out.printf("Number with 2 decimal places: %.2f\n", 3.14159);
Output:
Number with 2 decimal places: 3.14
Scope in Java
The scope of a variable refers to the part of the program where the variable can be accessed. In Java,
scope is defined by curly braces ({}).
Example of Scope:
code
public class ScopeExample {
public static void main(String[] args) {
int x = 10; // x is in scope here
if (x > 5) {
int y = 20; // y is in scope inside this block
System.out.println("x: " + x + ", y: " + y);
}
// y is out of scope here, so the following line would cause an error
// System.out.println(y);
}
}
Example:
code
boolean isRaining = false;
boolean isCold = true;
if (isRaining || isCold) {
System.out.println("Stay indoors.");
} else {
System.out.println("Go outside!");
}
Output:
Stay indoors.