Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: modifiers for variable

  1. #1
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default modifiers for variable

    Hi,I needed to know why we should use modifiers for variables?
    I have this piece of code:

    import java.util.*;
     
    public class Test{
     
    	public String student;
    	private int sGrade;
     
     
    	public void shame(String stdn){
    		student=stdn;
     
    	}
     
    	public void setGrade(int grade){
    		sGrade=grade;
    	}
     
    	public void printInfo(){
     
    		System.out.println("Student's name is " + student);
    		System.out.println("Grade = " + sGrade);
     
    	}
     
     
    	public static void main(String args[]){
     
     
     
    		Test dars = new Test();
    		dars.shame("james");
    		dars.setGrade(17);
    		dars.printInfo();
     
    		Test dars2 = new Test();
    		dars2.shame("jim");
    		dars2.setGrade(17);
    		dars2.printInfo();
    	}
     
     
    }

    now, if I use < String student > and <int sGrade> instead of public String student and private int grade as instance variables in the code above, I'll get the same result!
    what good are they for?!
    thanks

    --- Update ---

    Another one

    in this code:

    public class Reverse{
     
    	public String name;
    	private int grade;
    	public void student(String s,int g){
    		s=name;
    		g= grade;
     
    			}
     
    	public void print(){
    		System.out.println("name is "+name);
     
    		System.out.println("grade is "+grade);
    	}
     
     
    }

    when I invoke the method student("Jim", 15), it would give me null and 0 for name and grade, BUT, if I change the code to name = s and grade = g, it will give me Jim and 15....why is that?


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: modifiers for variable

    Accessibility modifiers don't change accessibility inside a class, they're used to limit accessibility outside of the class.

    For example, a private field can only be accessed within that class, protected means the field can only be accessed in the same package or a descendant class, and public means it's accessible everywhere.

    Why would you want to have different modifiers? To keep nosy developers out. Take the ArrayList class as an example.

    Internally, there is a size field. The ArrayList class needs to be able to update this field as the size changes so it can't be declared final. However, at the same time it would be very bad if external code changed the size field, either intentionally or unintentionally. The best solution is to declare the size field private so the ArrayList internals can do whatever it needs with the size field and access can be controlled through accessor methods (a.k.a. getters/setters).

    Is it the end of the world if external code does get access to "private" fields? Not really, and some languages completely lack a "hard" accessibility limit (i.e. Python, Javascript). These languages often have "gentleman's agreements" on what you shouldn't and should access on the off chance you really know what you're doing and want to work outside the typical bounds. More often than not, though, you don't want to do this as it usually makes code more obscure and harder to understand. Java takes this approach and enforces the hard limits.

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    ashl7 (March 27th, 2013)

  4. #3
    Member Chris.Brown.SPE's Avatar
    Join Date
    May 2008
    Location
    Fort Wayne, Indiana
    Posts
    190
    Thanks
    1
    Thanked 31 Times in 31 Posts

    Default Re: modifiers for variable

    I'm not entirely sure what the question is for the first half, could you explain again or show code in a different way that isnt working as expected? Your issue in the second half is that your assignment puts the value of the right side into the value of the left side. So, name and grade start as null and 0 and you are assigning them to s and g which doesnt change name and grade at all. The other way around sets s and g to name and grade which is what you are looking for i think.
    Writing code is your job, helping you fix and understand it is mine.

    <-- Be sure to thank and REP (Star icon) those who have helped you. They appreciate it!

  5. #4
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: modifiers for variable

    Quote Originally Posted by helloworld922 View Post
    Accessibility modifiers don't change accessibility inside a class, they're used to limit accessibility outside of the class.

    For example, a private field can only be accessed within that class, protected means the field can only be accessed in the same package or a descendant class, and public means it's accessible everywhere.

    Why would you want to have different modifiers? To keep nosy developers out. Take the ArrayList class as an example.

    Internally, there is a size field. The ArrayList class needs to be able to update this field as the size changes so it can't be declared final. However, at the same time it would be very bad if external code changed the size field, either intentionally or unintentionally. The best solution is to declare the size field private so the ArrayList internals can do whatever it needs with the size field and access can be controlled through accessor methods (a.k.a. getters/setters).

    Is it the end of the world if external code does get access to "private" fields? Not really, and some languages completely lack a "hard" accessibility limit (i.e. Python, Javascript). These languages often have "gentleman's agreements" on what you shouldn't and should access on the off chance you really know what you're doing and want to work outside the typical bounds. More often than not, though, you don't want to do this as it usually makes code more obscure and harder to understand. Java takes this approach and enforces the hard limits.
    Ok thanks a lot
    So you mean in general, we only use public, private, protected,etc... only when we want to make a class that is going to be used in some other program, or external codes?! in this case, is there any difference between "public String student" and "String student" at all?! since both can be accessed by other external codes...

    --- Update ---

    Quote Originally Posted by Chris.Brown.SPE View Post
    I'm not entirely sure what the question is for the first half, could you explain again or show code in a different way that isnt working as expected? Your issue in the second half is that your assignment puts the value of the right side into the value of the left side. So, name and grade start as null and 0 and you are assigning them to s and g which doesnt change name and grade at all. The other way around sets s and g to name and grade which is what you are looking for i think.
    I meant if I change my code to this:

    import java.util.*;
     
    public class Test{
     
    	String student;
    	int sGrade;
     
     
    	public void shame(String stdn){
    		student=stdn;
     
    	}
     
    	public void setGrade(int grade){
    		sGrade=grade;
    	}
     
    	public void printInfo(){
     
    		System.out.println("Student's name is " + student);
    		System.out.println("Grade = " + sGrade);
     
    	}
     
     
    	public static void main(String args[]){
     
     
     
    		Test dars = new Test();
    		dars.shame("james");
    		dars.setGrade(17);
    		dars.printInfo();
     
    		Test dars2 = new Test();
    		dars2.shame("jim");
    		dars2.setGrade(17);
    		dars2.printInfo();
    	}
     
     
    }

    there won't be any difference in final result...so why should we use public,private...for variables at all?!

    got my answer for the second part, thanks. I didn't know that till now lol!!!!!!!

  6. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: modifiers for variable

    Having no modifier is not the same as a public modifier, you can only access the field from within the same class or package. Public allows access from anywhere.

    See: Controlling Access to Members

    I explained above why we would use it, it's not meant for external programs, but other parts of your program. Most useful Java programs have more than one class, and ideally more than one package.

  7. The Following User Says Thank You to helloworld922 For This Useful Post:

    ashl7 (March 27th, 2013)

  8. #6
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: modifiers for variable

    Oooooh "the same class or package"...now I get it...and thanks for the link

  9. #7
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: modifiers for variable

    Hi again
    I know it's been a while, but wrote a piece of code, and can't find what my mistake is!
    it's about variables again

     public int result;
        private void playerBetActionPerformed(java.awt.event.ActionEvent evt) {                                          
           String stringBet = playerBet.getText();
           int intBet = Integer.parseInt(stringBet);
           result = intBet;       
     
        }                                         
     
        private void rollButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            Random x = new Random();//calling random generator method
    		int dice1,dice2,roll;
    		dice1 = x.nextInt(6)+1;//gives dice one a number from 1-6
    		dice2 = x.nextInt(6)+1;
                    String stDice1 = Integer.toString(dice1);
                    String stDice2 = Integer.toString(dice2);
                    dice1Lable.setText(stDice1);
                    dice2Lable.setText(stDice2);
                    roll = dice1 + dice2;
     
     
            if(roll==7 || roll==11){ 
            int prize =  result*3;
            resultMessage.setText("Congradulation, you have won $"+prize);               
     
                            }
            else{
                resultMessage.setText("Sorry,you've lost the bet!");
            }
     
        }


    it's a part of my code, but when I run it, it will give 0 for "result" all the time...seems like the variable "result" is always set as 0 or null!
    why is it like that?! I assigned the value of variable "intBet" to it earlier!!!

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,165
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: modifiers for variable

    the variable "result" is always set as 0 or null!
    The int variable: result can never have a null value.

    I assigned the value of variable "intBet" to it
    What was the value of intBet? Could it be 0? To see its value, add a println to print intBet's value after it is set.
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following User Says Thank You to Norm For This Useful Post:

    ashl7 (April 11th, 2013)

  12. #9
    Member Chris.Brown.SPE's Avatar
    Join Date
    May 2008
    Location
    Fort Wayne, Indiana
    Posts
    190
    Thanks
    1
    Thanked 31 Times in 31 Posts

    Default Re: modifiers for variable

    I would start by debugging the line wher eyou get playerBet.getText() and see what is coming out of that. Either put a System.out.println() there or a break point (debugging through your IDE, highly recommended you learn how to do this with your IDE). I'm betting (pun intended) that your playerBet is not getting set the way you expect. If not that then maybe you're action playerBetActionPerformed is never getting triggered. Try setting result to some arbitrary number and see if it is ever getting changed to 0 or if it has just been staying at 0.

    --- Update ---

    Program Tracking Tip: Additionally, when making a program with lots of actions, it can be beneficial to put a System.out.println("<Function name> called") in all of your functions. This will allow you to follow what the program is doing when it runs and quickly find something like "Hey, that function wasnt ever called."

    Advanced Logging Tip: I know proper logging tecniques can go over most people's heads. Something i like to do when in a pinch is put the following lines all over the place:

    //Put this at the top of your class
    static private boolean logging = true;
     
    //Put this all over the place. You can now turn them on and off whenever you want to.
    if(logging){
        System.out.println("Message here");
    }
    Writing code is your job, helping you fix and understand it is mine.

    <-- Be sure to thank and REP (Star icon) those who have helped you. They appreciate it!

  13. The Following User Says Thank You to Chris.Brown.SPE For This Useful Post:

    ashl7 (April 11th, 2013)

  14. #10
    Member ashl7's Avatar
    Join Date
    Mar 2013
    Posts
    32
    My Mood
    Mellow
    Thanks
    24
    Thanked 0 Times in 0 Posts

    Default Re: modifiers for variable

    Quote Originally Posted by Norm View Post
    The int variable: result can never have a null value.


    What was the value of intBet? Could it be 0? To see its value, add a println to print intBet's value after it is set.
    intBet is the user's input...the program is part of a GUI made by netBeans GUI maker!!! so I wasn't sure I should put it all here!

    --- Update ---

    @Chris Brown
    I see what you mean
    I got my mistake by putting System.out.println
    Thanks a lot guy
    about using debugging of the IDE, I've tried using it, but it doesn't really do anything...my IDE is netBeans, when I press debug project button, there be something like 121/321 mb...and just the numbers change...I'm not sure what debugging does in this IDE!!!

    another thing...I've used GUI of netBeans with design area to make this code...is there anyway I could run this code on Eclipse?! or command line?!
    it has already some built in codes that I'm not supposed to change!

  15. #11
    Member Chris.Brown.SPE's Avatar
    Join Date
    May 2008
    Location
    Fort Wayne, Indiana
    Posts
    190
    Thanks
    1
    Thanked 31 Times in 31 Posts

    Default Re: modifiers for variable

    The way java is designed, you should be able to run it anywhere. There shouldnt be anything tying it to your IDE. I understand the thing with netbeans developed GUIs (oh how i hate them). But they dont need netbeans to run.

    As for debugging, pressing the debug button simply runs your program in debug mode. You need to set a breakpoint on a line to get the program to stop so you can look at variable and step through code line by line. Check out this tutorial Netbeans Debugger Short Tutorial
    Writing code is your job, helping you fix and understand it is mine.

    <-- Be sure to thank and REP (Star icon) those who have helped you. They appreciate it!

  16. The Following User Says Thank You to Chris.Brown.SPE For This Useful Post:

    ashl7 (April 11th, 2013)

Similar Threads

  1. declared with the wrong access modifiers ?????????????????????????????
    By cosmickinect in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 12th, 2013, 06:57 AM
  2. Replies: 0
    Last Post: October 30th, 2012, 10:06 AM
  3. For-loop: initialisation of variable, can't set variable to value zero?
    By Bitbot in forum Loops & Control Statements
    Replies: 4
    Last Post: July 15th, 2012, 02:32 PM
  4. about access modifiers (abstract and protected)
    By Satyanvesh in forum Java Theory & Questions
    Replies: 12
    Last Post: February 2nd, 2012, 12:43 AM
  5. Replies: 5
    Last Post: November 16th, 2011, 11:22 AM