Hello,
Below is my code for Stack implementation.
Its working fine without errors and exception./* * To change this template, choose Tools | Templates * and open the template in the editor. */ package doubt1; /** * * @author Rohan <Rohan at Home Workstation> */ import java.io.*; class Stack3 { int stack[]; int tos; void push(int ele1) { stack[++tos] = ele1; } int pop() { int ele2 = stack[tos]; tos--; return ele2; } void contents() { if (tos == -1) { System.out.println("Stack empty"); } else { System.out.println("Contents of stack are"); for (int i = tos; i >= 0; i--) { System.out.println(stack[i]); } } } Stack3() { stack = new int[10]; tos = -1; } } public class Doubt1 { public static void main(String args[]) throws java.io.IOException { Stack3 stackcopy = new Stack3(); String choice = null; int getchoice; char menucontinue = 't'; do { System.out.println("---Stack Menu---"); System.out.println(""); System.out.println("1:Push"); System.out.println("2:Pop"); System.out.println("3:Contents of Stack"); System.out.println("4:Exit"); System.out.println(""); BufferedReader is = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter your choice"); choice = is.readLine(); getchoice = Integer.parseInt(choice); switch (getchoice) { case 1: if (stackcopy.tos == 9) { System.out.println("Stack full"); } else { String pushele = null; int ele; BufferedReader is1 = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter element to be inserted"); pushele = is1.readLine(); ele = Integer.parseInt(pushele); stackcopy.push(ele); } break; case 2: if (stackcopy.tos == -1) { System.out.println("Stack Empty"); } else { int popele; popele = stackcopy.pop(); System.out.println("Element poped is " + popele); } break; case 3: stackcopy.contents(); break; case 4: menucontinue = 'f'; break; default: System.out.println("Enter valid choice"); break; } } while (menucontinue == 't'); } }
I have created an instance of class Stack3.But how is my static main() method able to access non static variables,and pass it topush(int ele1) method of Stack3 class. By definition and Java Language specification "a static method cannot access
non-static data
But again if i try to pass non static variable to a class method in main() in another program
Its giving the required error...package doubt2; import java.io.*; /** * * @author Rohan <Rohan at Home Workstation> */ class D{ void call(){} void fill(int g){} } public class Doubt2 { int k=9; /** * @param args the command line arguments */ public static void main(String[] args) throws java.io.IOException { // TODO code application logic here D d = new D(); d.call(); d.fill(k); } }
i.e non static variable cannot be referenced from a static context.
What is the problem or where am i going wrong in understanding the concepts of static? Kindly help me.Getting too confused