Static and Non-Static
In Java, static is used when something belongs to the class itself. It is common for all objects. Non-static is used when something belongs to a particular object. It is different for each object created from the class.
Example:
public class Home
{
// non-static: object specific information
String name1 = "dhanush";
int age1 = 25;
// static: class specific information
static String name2 = "tamil";
static int age2 = 15;
public static void main(String[] ramesh)
{
System.out.println(Home.name2);
System.out.println(Home.age2);
Home person = new Home(); // new object
System.out.println(person.name1);
System.out.println(person.age1);
}
}
Objects
An object is created from a class using the new keyword. It creates space in memory to store data and methods defined in the class.
Example:
Home person = new Home();
Methods
Methods are sets of instructions grouped together with a name. They are used to perform specific tasks. Methods can be reused and called again whenever needed.
Example:
public class Shop
{
static String shopName = "seenu";
String product_name = "pen";
int product_price = 10;
public static void main(String[] args)
{
Shop product = new Shop();
// method calling statement
String greeting = product.buy();
System.out.println(greeting);
}
String buy()
{
System.out.println("buy method");
return "thank you";
}
}
Return Types
Methods have return types. If a method does not return anything, we use void in its declaration. If a method returns something, we mention its datatype. The return keyword is used to send back a value from the method, which can be stored in a variable for later use.
In the above example:
- The buy() method returns a String value "thank you".
- The returned value is stored in the variable greeting.
Top comments (0)