Static keyword is used to load the class data into primary memory first to the object. As it is directly loaded into memory, it can be accessible directly.
Write a program to access static & non-static data of class.
class class
{
int x; //non-static
static int y; //static
public static void main (String args[])
{
c c1=new c(); //New object created [1st]
system.out.println(c1.x); //called using c1 object
system.out.println(c1.y); //called using c1 object
system.out.println(c.y); //called using class
system.out.println(x); //directly called
c1.x++; //Operation performed using c1 object [Value becomes x=1]
c1.y++; //Operation performed using c1 object [Value becomes y=1]
c c2=new c(); //New object created [2nd]
system.out.println(c2.x); //called using c2 object
system.out.println(c2.y); //called using c2 object
}
}
Output:0
0
0
0
0
1
Static data can be accessible by three ways.
- Using class object.
- Using class name.
- Directly.
System.out.println() //Statement
System is a built in class and out is static field of it. The combination of this two will send the data from editor to keyboard memory. This memory is the space reserved on primary memory for every java application. The println() method of print stream class sends the data from keyboard memory to console.PrintStream class have two methods
1> println(): This method send the corsor to the next line after printing the data.Example:
class D { public static void main(String args[]) { System.out.println("\t\t Hello\t\t\t"); System.out.println("How Are You?"); System.out.println("Bye..."); } }
Output:Hello
How Are You?
Bye...
2> print(): It remains cursor on the same line after printing.
Example:
class add { public static void main(String args[]) { int a,b,c; a=10; b=20; c=a+b; System.out.println(C); System.out.println("Addition is "+c); System.out.println("Addition of "+a" and "+b" is "+c); System.out.println(a+" + "+b+" = "+c); } }
Output:30
Addition is 30
Addition of 10 and 20 is 30
10 + 20 = 30
Post A Comment: