Adblock breaks this site

Java Basics [3] - Primitive Variables

Discussion in 'Guides' started by SuF, Sep 20, 2013.

  1. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    Java Basics [3] - Primitive Variables
    By SuF​


    If you have questions or comments feel free to post! If you have a specific issue or want some help with anything Java related, PM me. If you are browsing as a guest, feel free to register so you can post or PM me.

    Before reading this guide, make sure you can do the following things:

    • Java Development Kit (JDK) installed and configured (guide upcoming)
    • Compile and run a Java program (guide upcoming)
    • Create a basic Java Program (Java Basics [2] - Your First Program)

    A primitive variable is basic building block provided by Java that holds specific data. Java is a statically typed (also know as strongly typed) language which simply means that before you use a variable, you must tell Java what type of data that the variable will hold. You are not allowed to put a character in an int because int only holds integers. There are eight different primitive variable types in Java:

    • int - integers between -2,147,483,648 and 2,147,483,647
    • long - integers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
    • float - floating point numbers (like 2.3) with minimal precision
    • double - floating point numbers (like 2.3) with much more precision (use this instead of float)
    • char - a single character, like 't'
    • boolean - true or false
    • byte - integers between -128 and 127
    • short - integers between -32,768 and 32,767

    In general, you will be using int for most integer values. Long is used only if the values will be quite large and exceed the maximum int can hold. Byte and short are rarely used because they can only hold small values. They use less memory than int but today that really is not a concern. Always use double and not float or your decimals may be very incorrect due to float's low precision. char holds a single character that you must surround with single quotes like 'f'. boolean can only hold two values "true" or "false" (without the quotes).

    There is one more data type that Java "pretends" is a primitive because it is very convenient to do so, which is String (note the capitalization). A String is simply a sequence of characters like "This is a string". Be careful when working with Strings because they seem like primitives but actually are not.

    In order to use a variable, you must first declare it by specifying a type and an identifier like:

    Code:
    ...
    int myFirstVariable;
    ...
    In this example I am declaring an integer variable (with int) called "myFirstVariable". Note the capitalization that I used: This is called camel casing and is the standard convention for naming variables in Java. Remember that Java is case sensitive so "myfirstvariable" is not the same as "myFirstVariable".

    There are some rules for what an identifier can be. It must be at least one character long and can contain uppercase letters, lowercase letters, underscores, dollar signs, and digits. However, it may not begin with a digit. The following are valid identifiers:

    Code:
    a
    man56
    $56
    _myVariableThatIsReallyQuiteLongAndYouShouldNotReallyDoThisBecauseTypingTakesForever
    The following are invalid identifiers:

    Code:
    45L
    my!
    (.)(.)
    &myVar
    3var
    
    Back to the previous example, "myFirstVariable" does not hold any data. It has been declared, meaning that it exists but it has not be initialized, meaning it does not yet hold any data. Initializing a variable simply means giving it an initial value like so:

    Code:
    ...
    myFirstVariable = 5;
    ...
    This code snippet assumes that you have already declared "myFirstVariable" as we did above. This is an example of what we call assignment. The value on the right is assigned, to the variable on the left. Another way of saying this is that the variable on the left is given the value on the right. It is also possible to declare and initialize a variable in one statement like:

    Code:
    ...
    int myNewVar = 10;
    ...
    It is also possible to declare multiple variables of the same type in one statement like:

    Code:
    ...
    double var1, var2, var3;
    ...
    Additionally, you can declare multiple variables in one statement and initialize the last one:

    Code:
    ...
    boolean first, second, third = true;
    ...
    Counterintuitively, in this example, "first" and "second" are not initialized and do not yet have a value. Only "third" has been initialized and has a value of true.

    After we have declared and initialized a variable, we can use it in other statements wherever we would have used a hard coded value of that type like:

    Code:
    ...
    long a = 5;
    long b = a;
    ...
    In this case, we declare and initialize a long called "a" to 5. We then assign "b" the value that is in "a", which is 5. So in this case, "a" and "b" are set to the same value. To show that this is true, we can print the values in each of these variables to the console like:

    Code:
    ...
    System.out.println(a);
    System.out.println(b);
    ...
    If you put these two code snippets into a Java program, 5 would be printed to the console twice like:

    Code:
    5
    5
    
    System.out.println() is the same method that was used to print a String out in the previous guide. This method is extremely versatile and can be used to print out the value of any type like:

    Code:
    long c = 10;
    double d = 6.4;
    boolean e = true;
    String f = "Hello";
    System.out.println(c);
    System.out.println(d);
    System.out.println(e);
    System.out.println(f);
    which will output:

    Code:
    5
    5
    10
    6.4
    true
    Hello
    
    Note how String behaves just like the primitives. At this point it will but later there will be differences that can easily catch you out. For now pretend it is a primitive but know that it is actually not.
     
  2. THE ILL 90s

    THE ILL 90s Active Member
    Banned

    Joined:
    Sep 13, 2013
    Posts:
    144
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    Good guide, managed to read a good chunk of it.
     
  3. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    Bump.
     
  4. Shin

    Shin Join the Sythe.org Discord
    Retired Administrator Legendary Mudkips $100 USD Donor

    Joined:
    Mar 10, 2007
    Posts:
    14,171
    Referrals:
    23
    Sythe Gold:
    196
    Discord Unique ID:
    777373911821713408
    Pool Shark (4) Village Drunk <3 n4n0 (29) Battleship Champion
    Java Basics [3] - Primitive Variables

    Don't forget when you declare primitive variables (data types), they will be assigned a default value unless otherwise declared through initialization.
    * This is generally considered bad for programming (goes along with camel casing), but it is very important to remember sometimes.

    • String
      • has a default value of 'null'.
    • char
      • has a default value of '\u0000'.
    • boolean
      • has a default value of 'false'.
    • double
      • has a default value of 0.0d (not a format identifier).
    • float
      • has a default value of 0.0f (not a format identifier).
    • long
      • has a default value of 0L (not a format identifier).
    • byte, short, and int
      • has a default value of 0 (as stated above).
     
  5. CompileTime

    CompileTime Professional desktop/web application developer.
    Banned

    Joined:
    Apr 16, 2014
    Posts:
    451
    Referrals:
    0
    Sythe Gold:
    3
    Java Basics [3] - Primitive Variables

    String isn't a primitive type in Java.
     
  6. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    At this point I am talking about local variables and talking about member variables as well would confuse things.

    This is technically true but there is syntactic sugar that makes it seem like it is one, so it fits kind of between the two.
     
  7. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    I had to create an account on this site just to tell you how wrong you are man. String are NOT primitives. That "syntactic sugar" is called a String literal, and does not make a String a primitive. String are not primitives, do not act like primitives, and will never be a primitive. String literals are to support an intern system on Strings, allowing you to access the String pool to check if the String already exists (so it can use the pre-existing String instead of a new one) to save memory. It was not put there to act like a primitive.. If Strings were meant to act like/be primitives, you wouldnt be allowed to call methods from em, which would suck.

    Oh, and when you mention "bytes and shorts are rarely used", that goes to show how much experience you really have. Bytes and shorts are quite common in networking. If you want, I could help teach you, get you on the proper path. The knowledge you are giving here is somewhat false
     
  8. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    I did not say that they are primitives. The syntactic sugar is being able to do String a = "Hey man", without doing new String("Hey man") as would be required without the syntactic sugar. They act like primitives in the sense that you do not need to use new in order to get one, as you do with objects. Thus all primitives do not need the new keyword while all objects do, except for String.

    But really, this is a beginners guide. In the topics I covered in this guide, Strings act EXACTLY like primitives. I have not given any wrong information and I have told them that there is additional complexity that I am purposely pushing to the side to facilitate their understanding. So when I say bytes and shorts are rarely used I am talking in the context of a beginners guide. There is no reason for a beginner to use a byte and run into overflow issues when they are just learning. In addition, networking code is a small part of code that is actually written and ints are the generally understood as the default integer type for Java unless you have some specific need for a different type (longs for larger numbers, bytes or shorts for smaller numbers where more information is known and or memory use is a concern).
     
  9. Shin

    Shin Join the Sythe.org Discord
    Retired Administrator Legendary Mudkips $100 USD Donor

    Joined:
    Mar 10, 2007
    Posts:
    14,171
    Referrals:
    23
    Sythe Gold:
    196
    Discord Unique ID:
    777373911821713408
    Pool Shark (4) Village Drunk <3 n4n0 (29) Battleship Champion
    Java Basics [3] - Primitive Variables

    I never stated that a String is a primitive type.

    I was listing all of the default values for variables not initialized.
     
  10. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    You're telling them "pretend Strings are like primitives even though they're not". I'm saying this as a teacher rather than a programmer: you're getting them off to a bad stary by saying that. This is a beginner's guide to primitive variables, so String should not be mentioned here at all. If anything, dedicate your next topic to it. Unbanned even took the extra step in including it into his "default values" chart, which is a bad idea. Beginners will expect String to be usable due to default, and end up with a NullPointerException. Now they're wondering "wtf is a nullpointerexception", and most likely "what is an exception and why did I get it?", overwhelming them.

    My point is, just don't include String with primitives. Even if you feel string literals give it a primitive field, you can call methods from it, and you can't call methods from primitives. You mention String once from what I see, so why even mention it at all right now? Mention it in the next guide, so they don't get mixed up. Strings do not behave just like primitives, as you stated. Yes, I understand this guide is for beginners. Please don't get them start them on a crooked path; it makes other programmers asume you too are a beginner. Seeing this makes me want to release a more sturdy guide, and it's not to compete with you, rather than ensure beginner programmers get the proper knowledge. Don't tell them to pretend something is what it's not. If you can't explain it clearly and correctly, then you don't understand it enough yourself, and telling beginners to pretend a String is a primitive is definitely not correct. This is just based off what I'm seeing. I'm sure you're a better programmer than I'm invisioning right now, it's just the way you're teaching will hurt the programming community. You don't know how many times I've had to correct these kinds of wrongs.. What if for some reason, you never get to your next lesson? Now they're going around pretending Strings are primitives, and it's up to other programmers to fix that up. If you're gonna give info, give solid info. Don't leave cliffhangers like "if we are pretending it's a primitive, what is it really?"
     
  11. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    I did not include the default values because they are only applicable to member variables, which are not discussed here. I included Strings here because they are an essential part of writing programs. People will want to know how to print out their name or something in order to make a console application that actually does something. I have not given any incorrect information in this post and I'm not sure why you insist I have. I have not at this point introduced any method calls other than System.out.println, so I fail to see the merit in your objections in that regard.

    I feel that my way of explaining it is easier to understand and will stop misconceptions going forward than how I was taught. In order to give Strings justice you have had to have covered methods, classes, member variables, scope, OOP principals, references, call by reference vs call by value, etc. That is impossible and at this point in their understand beginners (who at this point would have less than an hours experience) should understand variables as a concept. In order to build up the knowledge needed some concepts are going to have to be simplified. Perhaps I should have called this "Variable Basics" but that has nothing to do with programming and is a purely semantical debate.

    To me, your insistence to bring up Java internals such as the intern string system simply shows that you do not understand the principle of encapsulation. If you are changing the way you code because of that internal structure or if that knowledge is needed to properly code, either the language is shit or you are doing something very wrong. This knowledge of the intern system has essentially no practical value and will only cause much confusion to beginners.

    I am not pretending that Strings are primitives. I am telling the people following the guide (whom likely have less than an hour of programming experience) to pretend that Strings are primitives for this guide. That is so that they know that they are not actually primitives but can be used in System.out.println anyways. This allows me to introduce them to the idea that there is something other than a primitive but the syntax for using them is the same even though the technical details of what is happening (stack vs heap, pass by reference vs pass by value, why Java is only pass by value, etc) are different.

    I do not believe that teaching abstract concepts without concrete examples works and thus I am not. This guide series (which I never did finish) was to have the person following it code extensively in order to comprehend concepts instead of simply reading about them.

    As to your PM, I do not have a SO account because of people like you who create toxic environments and actively ridicule anyone that they can. I can not stand people like you because you put off people from programming and scare people away from seeking or giving help. You promote the stereotype that programmers are socially inept nerds who will not let anyone live down even the smallest seeming mistake. People learn in different ways and at different rates and many people are unable to understand all of the theoretical concepts of computer science without concrete experience with them. When people like you come along and insist on forcing computer science theory on complete beginners you make them feel inferior and unintelligent and force them out of the field. That is absolutely disgusting and you should be ashamed of the practice.
     
  12. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    You said "pretend Strings are primitives". You're acting as if I've never came across students who were confused by this subject. It's people like you who are creating the toxic environments. You obviously know the basics of programming, but the way you teach is harmful. SO is to get answers on questions thay have yet to be answered. How is that "toxic" at all? The only time people might be rude is if you post before checking out the guidelines on how to post. Just because someone might have downed you for one of your posts on there doesn't mean the environment is bad; it just means you were too lazy and too inconsiderate to learn how the site actually works.

    I meet fresh programmers all the time, im sure more often than you do, and not one of them has had problems with how I taught them. But when some kid that reads guides with misleading information, such as "pretend Strings are variables, cause you might use them, but I don't wanna explain it right now". Thats not how you teach man. Thats how you get students coming up to me saying "but this guide said I should". YOU'RE the suspect for creating a toxic environment. When I mentioned interning, I was only expressing how theres a pretty big difference between initializing a primitive variable, and using "syntactic sugar" to initialize a String. Not to mention, comparing values.. you just shouldn't have mentioned String, end of story.

    I thought you'd like a helping hand, but you're just as ignorant as you think I am. And you think I don't understand encapsulation because I mentioned interning? How is that even relevant? interning is a public feature, performed by the intern() method. I really felt you might have been a decent programmer til you said that. Do YOU know what encapsulation is? I didnt force anything on anyone. I came here to tell you that the way you're teaching will bring real teachers harm. Thats why I came here man. You are doing stupid things that you feel helped you when you were a beginner. That goes to show just how far from beginner you actually are. And you don't gotta describe every concept of OOP to let a person know a String is not (and should not be seen as, even if pretend) a primitive. I'm not trying to force anything on anyone. I have never attempted to teach someone something above their skill level. I have, though, had to reteach people how Strings work, cause teachers like you are impatient and tend to introduce it in a nasty way. Yeah, now they understand primitive variables, so what are they gonna do now? They aren't just gonna create variables, "oh that was fun", then wait for your next guide. They're gon a try to compare, and find out that it doesn't quite work the same for Strings. YOU'RE the one forcing the unneeded introduction to Strings, not I. All I said was to wait until the next guide. I make many mistakes myself, and for you to say I'm any stereotype shows you're prejiduce. You think a socially inept nerd would name himself slimeychicken? Just because you feel you're more "laid back" when teaching does not make you a better teacher, and does not make it easier for beginners to learn. The whole act of teaching is ensuring the students get the correct knowledge, no matter what the pace. Your hypocricsy is truely amazing, telling me that introducing Strings would force people to need to learn all these other aspects. Yet, you introducded Strings. So I think it'll be best if I released my own guides
     
  13. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    You are one of the most arrogant people I have ever met. I did not lie when I said that I do not have SO account. Thank you for creating a toxic environment by assuming I was lying. Your students must love you when you accuse them of lying. You have had students that have had problems with the way you have taught them. That is a statistical reality. I brought up string interning because you did. There is almost never a reason to call that method or use it as Java already interns string literals behind the scenes. The only reason you would need to use it would be for performance reasons so that you could use == instead of .equals. This would violate encapsulation since you need to know how Java internals work in order to make sure that the code works as intended. It also would be very bad practice without profiling and comments explaining exactly why you need to have the performance increase that increases the risk that you will introduce bugs.

    Your point is not to tell me to not mention Strings right now. Even if it was my next guide was going to explore basic math and I was going to have them write some basic programs, which to not just print out numbers would require Strings. I already introduced Strings in a hello world program and not mentioning them here would lead to confusion and questions about whether strings could be a variable.

    Your point is to stroke your ego and make yourself feel better about your undersized dick by telling me I am wrong. Go read your own post:

    You said it yourself. Your purpose here is to be an asshole. Had you come here and given me constructive criticism I may have agreed with you but when you are a dick you will never convince anyone of anything.

    You want to feel superior to someone. Perhaps that is because of your small dick. I'll never know. I do know that I do not need your help nor do I want it. I know that I can spell correctly and understand proper grammar, which is something that you seem to fail to grasp. I know that I am going to graduate next week with a BS in Computer Science and make six figures next year as a software engineer. I wrote these guides for fun and to try to help people. I am very open to constructive criticism but I'm not going to put up with some rude, assnine person telling me I'm wrong over the internet. Go stroke your cock somewhere else.
     
  14. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    Wtf man, you said you do not have an account on SO. You could have deleted it, or maybe you don't use it enough to say you have an account. I never said you were lying. I just assumed since you're making accusasions, but now I see you're just a judgemental little turd. How are you gonna say its toxic if you haven't used it? Millions use that site, from beginners to microsoft employees. If it were toxic as you say, it wouldn't be as big as it is now (and it's still growing buddy). I never accused you of lying, but seeing how you jumped on that before asking questions, you really need to mature and think before you speak. I dont want to feel superior. I just don't wanna waste time having to drain a student if the wrong theyve been taught before I can continue with real teachings. You saying "you have a small dick", nice to know you're still a child. And here you are, going on about grammar like all people do when they have no where else to turn. Do you really think some immature kid whos a beginner himself should be the gateway into programming? I came here to let you know that the way you are teaching has been done before, many times, and its harmful. You anger easily, and you should work on that.
     
  15. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    And so what if it's for fun? What if I went out killing just for fun? Its still harmful, and others have to pay for it. You are the one creating the toxic environment, sir, talking about wangs when it's totally irrelevant. And to add onto that, you can't even suck up your pride and realize (or even ask) how it's harmful. If you ask me, thats pretty toxic
     
  16. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    I do not care what your opinion is because you are one of the most obnoxious, stupid, dickheads I have ever met. I know I am smarter than you. I know I am more liked than you. I know I am a better person than you. I know I am more successful than you. Why would I ever care what you thought when you treat others so horribly?
     
  17. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    Sounds a little arrogant, don't you think? I'm here to ensure people get the right knowledge, not fight with some babbling kid who likes to talk about penises. Get a grip, man, you're seriously losing it. Yeah my greeting was a little harsh at the start, but the world is harsh m8. If you would have at least questioned why I thought what I did, this could have turned out a lot differently. Instead, you assume you already know everything, and try to defend yourself before knowing what you're going up against. How about reading up on the Dunning-Kruger effect, so you'll start asking questions before making statements. Good luck on your guides. I suggest cleaning them up so it's easier on the eyes, and gl once again (you're gonna need it)
     
  18. SuF

    SuF Legend
    Pirate Retired Global Moderator

    Joined:
    Jan 21, 2007
    Posts:
    14,212
    Referrals:
    28
    Sythe Gold:
    1,234
    Discord Unique ID:
    203283096668340224
    <3 n4n0 Two Factor Authentication User Community Participant Spam Forum Participant Sythe's 10th Anniversary
    Java Basics [3] - Primitive Variables

    Good luck to you too. I know morons and dicks have a hard time in the world. Great job with the Dunning Kruger effect. It's not like everyone who has every visited Reddit already has seen that, or anything. Hope you learn the error of your ways and stop acting like a 13 year old. It will help you out a lot in life.
     
  19. slimeychicken

    slimeychicken Newcomer

    Joined:
    Dec 11, 2014
    Posts:
    15
    Referrals:
    0
    Sythe Gold:
    0
    Java Basics [3] - Primitive Variables

    Guess that makes you a nobody, eh? ^_^
     
  20. CompileTime

    CompileTime Professional desktop/web application developer.
    Banned

    Joined:
    Apr 16, 2014
    Posts:
    451
    Referrals:
    0
    Sythe Gold:
    3
    Java Basics [3] - Primitive Variables

    I understand, however your post could be misinterpreted to reinforce the misconception that String is among the primitive types.
    I just hoped to clear that up :)

    For any beginners, all you really need to know about Strings is this:

    Code:
    - Strings are objects. 
    - Strings are immutable which means they cannot change.
    - A String to put it simply, is just an array of chars(The primitive type) wrapped in an object.
    - The == operator should not be used to compare Strings.
    - To compare strings use the built in .equals() method.
    To give a better understanding of why, a String(internally) works a bit like this:

    Code:
    char[] chris = {'c', 'h', 'r', 'i', 's'};
    
    Now, this is wrapped in an class called String.
    *Note that '' denotes a char(primitive) and "" denotes a String(Object).

    Code:
    public class String {
          char[] chris = {'c', 'h', 'r', 'i', 's'};
    }
    
    When you do "chris" == "chris", what java does is it compares the value of both OBJECTS.
    Since a string is an Object, it checks if "chris" is the same object as "chris".
    For example:

    Code:
    Object obj = new Object();
    if(obj == obj) {
      System.out.println("This is the same as 'chris' == 'chris'");
    }
    
    if(object == new Object()) {
      System.out.println("This is not, and will return false");
    }
    

    In this case "chris" == "chris" will return true because Java under normal circumstances creates strings and caches them in the String pool.
    So the first time you do "chris", Java creates a new String object and adds it to the String pool.
    The second time it grabs the Object "chris" from the string pool.

    Thus they are the SAME object and that statement will return true.

    "chris" == "bob" WILL return false because they are two DIFFERENT Objects.
    Even though this does work, it's not garunteed to work because it does not compare their values.

    The .equals() method should be used instead because it compares each character in the strings and checks if they match.
    (It does: 'c' == 'c' and 'h' == 'h' and 'r' == 'r', and so on to check if the strings match)

    I'm not the best teacher, so I hope this was easily understood :)
     
< Teamviewin' Trent!'s Ultimate Teamviewer Guide! | >


 
 
Adblock breaks this site