Results 1 to 2 of 2
  1. #1
    TheRockIng is offline Member
    Join Date
    Feb 2015
    Rep Power

    Default Quick question about initializing variables


    so today I was doing a programming exercise that taught me about methods and constructor. I was finishing up the program and it said "variable may be uninitianlized" ( something along those lines). I was wondering, what makes it so that I don't need to initialize a variable sometimes but at other point, the compiler requires it. I mean it doesn't make great sense to me, what if the variable is an input from the user? ( so let's say we say:

    int x;
    Scanner kb= new Scanner(
    x =scanner.nextInt() )

    I'm pretty sure once eclipse told me it was uninitialized ( or other reasons, I'd have to looks but don't have the files with me ). It just bothers me to not understand when I have to initialize a variable and when not to. Any help understanding? :D

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Madgaon, Goa, India
    Rep Power

    Default Re: Quick question about initializing variables

    It's all in the Java Language Specification: Chapter*4.*Types, Values, and Variables

    The parts that are presently of most interest to you are:
    Each class variable, instance variable, or array component is initialized with a default value when it is created.
    A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified using the rules for definite assignment.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Quick 'this' question
    By stuckonjava in forum New To Java
    Replies: 3
    Last Post: 05-08-2012, 08:21 AM
  2. Initializing an array of class type variables.
    By xpl0rerchr in forum New To Java
    Replies: 5
    Last Post: 04-10-2012, 11:03 AM
  3. Quick question
    By sAntA199 in forum New To Java
    Replies: 2
    Last Post: 12-09-2009, 04:01 AM
  4. Quick Question
    By Graeme in forum New To Java
    Replies: 4
    Last Post: 01-08-2009, 09:01 PM
  5. Initializing variables using constructors
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-13-2008, 09:28 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts