Java Code Examples
Java Code Examples: Fundamental Concepts for Beginners
Alright, let's talk about Java! This is a seriously powerful programming language that's everywhere – it powers Android apps, huge enterprise systems, and a ton of web applications. While it might seem a bit more structured than Python at first glance, its strength lies in its robustness and "write once, run anywhere" philosophy.
Java is an Object-Oriented Programming (OOP) language, which means it revolves around the concept of "objects." Don't worry if that sounds confusing now; we'll break down the basics with some simple code examples.
1. Your First Java Program (Hello World!)
Every Java program starts with a main method. This is where your program begins executing.
Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java World!");
}
}
What's happening here?
public class HelloWorld: This defines a class named HelloWorld. In Java, almost all code lives inside classes.
public static void main(String[] args): This is the main method. It's the entry point of your program.
public: Means it can be accessed from anywhere.
static: Means you don't need to create an object of the HelloWorld class to run this method.
void: Means the method doesn't return any value.
String[] args: Allows you to pass command-line arguments (we won't worry about this now).
System.out.println("Hello, Java World!");: This line prints the text "Hello, Java World!" to the console.
2. Variables and Data Types: Storing Data
Unlike Python, Java is statically typed, meaning you have to tell Java what kind of data each variable will hold (e.g., a whole number, a decimal, text).
Java
public class VariablesExample {
public static void main(String[] args) {
// Storing whole numbers (integers)
int age = 25;
// Storing decimal numbers (doubles are common for this)
double price = 19.99;
// Storing text (String is a class, not a primitive type)
String customerName = "Sunil";
// Storing a single character
char initial = 'S';
// Storing true/false values (boolean)
boolean isActive = true;
System.out.println("Name: " + customerName);
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Initial: " + initial);
System.out.println("Active: " + isActive);
}
}
What's happening here?
We declare the type of the variable (int, double, String, char, boolean) before its name.
The + sign when used with Strings is for concatenation (joining text together).
3. Conditional Statements (If, Else If, Else): Decision Making
Java uses if, else if, and else just like many other languages to make decisions.
Java
public class ConditionalExample {
public static void main(String[] args) {
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) { // If not A, check if B
System.out.println("Grade: B");
} else if (score >= 70) { // If not B, check if C
System.out.println("Grade: C");
} else { // If none of the above
System.out.println("Grade: F");
}
}
}
What's happening here?
The conditions inside () are evaluated.
The code inside curly braces {} runs if the condition is true.
Java doesn't use indentation for code blocks like Python; it uses {}.
4. Loops: Repeating Actions
Java has for and while loops, similar to Python, but with slightly different syntax.
For Loop: Best when you know how many times to repeat
Java
public class ForLoopExample {
public static void main(String[] args) {
// Loop from 0 to 4
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// Looping through an array (like a list)
String[] colors = {"Red", "Green", "Blue"};
for (String color : colors) { // Enhanced for loop (like Python's for-in)
System.out.println("Color: " + color);
}
}
}
While Loop: Repeats as long as a condition is true
Java
public class WhileLoopExample {
public static void main(String[] args) {
int counter = 0;
while (counter < 3) {
System.out.println("Counter is: " + counter);
counter++; // Shorthand for counter = counter + 1
}
}
}
What's happening here?
for (int i = 0; i < 5; i++):
int i = 0: Initializes a counter i to 0.
i < 5: The loop continues as long as i is less than 5.
i++: Increments i by 1 after each loop iteration.
counter++: This is a shorthand way to add 1 to counter.
5. Methods: Reusable Code Blocks (Functions in Java-speak)
In Java, functions are called methods, and they usually belong to a class.
Java
public class MethodsExample {
// A simple method that greets someone
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// A method that adds two numbers and returns the result
public static int addNumbers(int a, int b) {
int sum = a + b;
return sum; // Returns the integer sum
}
public static void main(String[] args) {
// Calling the greet method
greet("Priya");
greet("Dasun");
// Calling the addNumbers method and storing the result
int total = addNumbers(15, 20);
System.out.println("The total is: " + total);
}
}
What's happening here?
public static void greet(String name):
void: Means this method doesn't return any value.
String name: It accepts one argument, which must be a String.
public static int addNumbers(int a, int b):
int: Means this method will return an integer value.
int a, int b: It accepts two integer arguments.
return sum;: This sends the value of sum back to wherever the method was called.
Getting Started with Java
Java might feel a bit more strict initially, but that structure is what makes it so robust for large-scale applications. You'll often need a Java Development Kit (JDK) to compile and run your Java code. Keep practicing with these basics, and you'll soon grasp the core concepts!
Comments
Post a Comment