Data and Variables

From Wikibooks, open books for an open world
Jump to: navigation, search

Access Modifiers Java Programming
Data and Variables
Generics
Navigate Language Fundamentals topic: v  d  e )


A variable in Java can store two kinds of variables:

Java's primitive types are

  • integers (whole numbers, declared as byte, short, int, or long; only int need be of interest to a beginner)
  • floating-point numbers (decimal numbers, declared as float or double; only float need be of interest at first)
  • characters (declared as char, representing one character like 'A' or ',')
  • boolean (holding only true or false as values)

In addition, the Java language has special features for its String class, and strings can be treated very much like primitives for many purposes.

As in most languages, a variable is declared to be a particular type of data; the syntax for a declaration is:

variabletype variablename;

To store a value in a variable, a program statement like

variablename = data;

And can reference the variable (and use the data stored in it) by its name.

For example, to create an int primitive type value, named year that stores 2007;

Computer code
year = 2007;


To access the data in year, use the variable in place of the number.

Computer code
System.out.println(year);

Produces

2007

[edit] Strong Typing

Variables in Java are strongly typed, which means that the compiler checks the type of a variable matches the type of data stored in that variable. If you declare a variable to hold a String, for instance, you cannot assign an integer value to that variable. Some languages (such as C) define an interpretation of such a statement and use that interpretation without any warning; others (such as PL/I) define a conversion for almost all such statements and perform the conversion to complete the assignment. Strong typing is intended to prevent mistakes made by unwittingly assigning the wrong kind of value to a variable, and catching those mistakes when the program is compiled rather than waiting to find it when the program is running.

[edit] Case Conventions

Java is case-sensitive. A method called mymethod is completely separate from a method called myMethod. Be careful!

By convention, most identifiers that includes more than one word uses camel case. Classes begin with a capital letter; methods and variables do not. (Constructors have to start with a capital, because they must have the same name as the class.) Package names use lowercase, and do not use camel case. Thus:


Computer code
package org.wikibooks.samplecode;

class CaseConventions {
   int variable;
   int multipleWordVariable;

   CaseConventions(String id) {
   }

   void method() {
   }

   void longMethodName() {
   }
}


[edit] Scope

Java uses block scope, which means that a variable is "un-defined" (and becomes useless) at the end of the block in which it is defined. A block is any section of code within curly braces. Common blocks include class definitions, methods and constructors, if/else blocks, and for, while, and do-while loops.


Computer code
class BlockScope {
    int classScope; // valid in all of class BlockScope

    BlockScope(int param) { // param is valid only in this constructor
        int localVariable = 0; // valid only in this constructor
    }

    void someMethod() {
        int local = 42; // valid only in this method

        if (local > 0) {
            boolean positive = true; // valid only within the if block
        } else {
            // positive is not defined here!
        }
    }
}


There are three basic kinds of scope for variables in Java:

  • local variable, declared within a method in a class, valid for (and occupying storage only for) the time that method is executing. Every time the method is called, a new copy of the variable is used.
  • instance variable, declared within a class but outside any method. It is valid for and occupies storage for as long as the corresponding object is in memory; a program can instantiate multiple objects of the class, and each one gets its own copy of all instance variables. This is the basic data structure rule of Object-Oriented programming; classes are defined to hold data specific to a "class of objects" in a given system, and each instance holds its own data.
  • static variable, declared within a class as static, outside any method. There is only one copy of such a variable no matter how many objects are instantiated from that class.


Access Modifiers Java Programming
Data and Variables
Generics
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export