Today I learned important Java concepts as a beginner, these topics were a bit confusing at first, but now I understand them better. Here's a summary of what I learned:
Static and Non-Static
Static means something belongs to the class, not the object.
A static method or variable can be used without creating an object.
public class Demo {
static int number = 10;
static void show() {
System.out.println("This is a static method");
}
}
You can call it like:
Demo.show();
Non-static belongs to the object. You need to create an object to use it.
public class Demo {
int age = 25;
void display() {
System.out.println("This is a non-static method");
}
}
You can call it like:
Demo d = new Demo();
d.display();
What is an Object
An object is an instance of a class.
It helps us access non-static methods and variables.
public class Car {
String brand = "Honda";
void start() {
System.out.println("Car is starting...");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object creation
myCar.start(); // Using object
}
}
Method in Java
A method is a block of code that runs only when it is called.
public class Hello {
void greet() {
System.out.println("Hello, Java!");
}
}
To call:
Hello h = new Hello();
h.greet();
Return Type
The return type defines what a method gives back.
void means it returns nothing.
You can also return values like int, String, etc.
Example with return type:
int add() {
return 10 + 20;
}
To call:
int result = add(); // result will be 30