Java Data and Variables
Java Data and Variables
There are 8 primitive data types. he 8 primitive data types are numeric types. The names of the eight primitive data types are:
byte
|
short
|
int
|
long
|
float
|
double
|
char
|
boolean
|
There are both integer and floating point primitive types. Integer types have no fractional part; floating point types have a fractional part. On paper, integers have no decimal point, and floating point types do. But in main memory, there are no decimal points: even floating point values are represented with bit patterns. There is a fundamental difference between the method used to represent integers and the method used to represent floating point numbers.
Integer Primitive Data Types
| ||
Type
|
Size
|
Range
|
byte
|
8 bits
|
-128 to +127
|
short
|
16 bits
|
-32,768 to +32,767
|
int
|
32 bits
|
(about)-2 billion to +2 billion
|
long
|
64 bits
|
(about)-10E18 to +10E18
|
Floating Point Primitive Data Types
| ||
Type
|
Size
|
Range
|
float
|
32 bits
|
-3.4E+38 to +3.4E+38
|
double
|
64 bits
|
-1.7E+308 to 1.7E+308
|
Examples
int yr = 2006;
double rats = 8912 ;
For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes:
double rats = 8912 ;
For each primitive type, there is a corresponding wrapper class. A wrapper class can be used to convert a primitive data value into an object, and some type of objects into primitive data. The table shows primitive types and their wrapper classes:
primitive type
|
Wrapper type
|
byte
|
Byte
|
short
|
Short
|
int
|
Int
|
long
|
Long
|
float
|
Float
|
double
|
Double
|
char
|
Character
|
boolean
|
Boolean
|
Variables only exist within the structure in which they are defined. For example, if a variable is created within a method, it cannot be accessed outside the method. In addition, a different method can create a variable of the same name which will not conflict with the other variable. A java variable can be thought of as a little box made up of one or more bytes that can hold a value of a particular data type:
Syntax: variabletype variablename = data;
Source Code ( demonstrating declaration of a variable )
class example
{
public static void main ( String[] args )
{
long x = 123; //a declaration of a variable named x with a datatype of long
System.out.println("The variable x has: " + x );
}
}
Source Code
public class MaxDemo {
public static void main(String args[]) {
//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
//other primitive types
char aChar = 'S';
boolean aBoolean = true;
//Display them all.
System.out.println("largest byte value is " + largestByte + ".");
System.out.println("largest short value is " + largestShort + ".");
System.out.println("largest integer value is " + largestInteger + ".");
System.out.println("largest long value is " + largestLong + ".");
System.out.println("largest float value is " + largestFloat + ".");
System.out.println("largest double value is " + largestDouble + ".");
}
}
Sample Run
The largest byte value is 127.
The largest short value is 32767.
The largest integer value is 2147483647.
The largest long value is 9223372036854775807.
The largest float value is 3.4028235E38.
The largest double value is 1.7976931348623157E308.
Syntax: variabletype variablename = data;
Source Code ( demonstrating declaration of a variable )
class example
{
public static void main ( String[] args )
{
long x = 123; //a declaration of a variable named x with a datatype of long
System.out.println("The variable x has: " + x );
}
}
Source Code
public class MaxDemo {
public static void main(String args[]) {
//integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
//real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
//other primitive types
char aChar = 'S';
boolean aBoolean = true;
//Display them all.
System.out.println("largest byte value is " + largestByte + ".");
System.out.println("largest short value is " + largestShort + ".");
System.out.println("largest integer value is " + largestInteger + ".");
System.out.println("largest long value is " + largestLong + ".");
System.out.println("largest float value is " + largestFloat + ".");
System.out.println("largest double value is " + largestDouble + ".");
}
}
Sample Run
The largest byte value is 127.
The largest short value is 32767.
The largest integer value is 2147483647.
The largest long value is 9223372036854775807.
The largest float value is 3.4028235E38.
The largest double value is 1.7976931348623157E308.
Class Definition Files
Files containing Java class definitions follow these guidelines;
- A Java class definition must be fully enclosed within a single file.
- The file name must match exactly, in upper and lower case, the name of a class definition in the file.
- It's recommended to put each class definition into its own file except for small utility classes needed only by the primary class.
- Only one public class is allowed per file (see Access/Visibility rules).
- The compilation of a Java file will result in separate *.class bytecode files for each class definition in the file.
A package is the Java version of a library. A package refers simply to a group of related class files in the same directory and having in each class file a package directive (Java statements only occur within a class definition) with that directory name at the top of the file.
For example, say that we put the files TestA.java and TestB.java into the directory mypack, which is a subdirectory of myApps. So on a MS Windows platform the file path looks like
c:\myApps\mypack\TestA.java
and
c:\myApps\mypack\TestB.java.
At the top of each file we put the statement
package mypack;
as shown in the following code:
package mypack;
public class TestA
{ public int i; public TestA (int arg1) { i = arg1; } } |
package mypack;
public class TestB
{ public double x; public TestB (double y) { x = y; } } |
We can illustrate how to use a package with TestAB.java which we put in the next directory above that of the package mypack.
public class TestABApplet extends java.applet.Applet
{
public void init () {
mypack.TestA testa = new mypack.TestA (4);
mypack.TestB testb = new mypack.TestB (31.3);
System.out.println("Prod = " + (testa.i * testb.x));
}
// Paint message in Applet window.
public void paint(java.awt.Graphics g) {
g.drawString ("TestABApplet",20,20);
}
}
{
public void init () {
mypack.TestA testa = new mypack.TestA (4);
mypack.TestB testb = new mypack.TestB (31.3);
System.out.println("Prod = " + (testa.i * testb.x));
}
// Paint message in Applet window.
public void paint(java.awt.Graphics g) {
g.drawString ("TestABApplet",20,20);
}
}
From the command line in the directory myApps, the compilation of TestAB.java:
myApps> javac TestAB.java
will also lead to the compilation of the files in mypack. The compiler looks for the TestA and TestB class definitions using the combination of the package and class names mypack.TestA testa and mypack.TestB. The "." acts in this case like the slash line directory name separator in DOS or Unix.
In this case the compiler will look for a sub-directory named mypack in the current directory holding TestAB.java. When the compiler finds the files and they have not yet been compiled, it will do the compilation.
You can also compile the package files directly but the compilation must occur from the higher directory, as in.
myApps> javac mypack\TestAB.java
(If you try to compile from in the mypack directory, the compiler will say it cannot find the files.)
So a directory browser shows a file and directory organization as follows:
Just as a directory can contain sub-directories, a package can contain sub-packages. For example, here we create add extrapack as a sub-package of mypack.
The class definition for TestC belongs to the package mypack.extrapack, as indicated here by the package statement at the top of the file:
package mypack.extrapack;
public class TestC { public boolean flag; public TestC(boolean b) { flag = b; } } |
Note: By convention, package names begin with a lowercase letter, while classes begin with an uppercase letter.
In addition to organizing classes in a clearly defined manner, packages also prevent name collisions. That is, if you use classes from other sources, it is inevitable that eventually duplicate class names will occur. If they are in different packages, however, this is not a problems since their full package names would differ.
Of course, it's also possible that two packages from different sources could also have the same names. An ingenious naming convention promulgated by Sun from the earliest days of Java is to name packages based on a company's internet domain name with the order of the names reversed. Since domain names are unique, package names based on domain names are completely under the control of the company that owns that domain name. Thus our companies ABC and XYZ would probably name their packages com.abc and com.xyz, respectively.
If a program needed to create an instance of TestC, it can explicitly give the full package path name, also referred to as the the "fully qualified" name:
mypack.extrapack.TestC testc = new mypack.extrapack.TestC();
An exception to this rule holds for all the classes in the standard java.lang package. Thus, whenever we use the Float class, for instance, we merely use something like
Float someFloat = new Float (3.14);
For all other classes, however, the fully qualified names must be specified in some way. There are nearly 3000 classes in the 135 packages in the J2SE 1.4.2 standard class library (over 3000 classes in 165 packages in J2SE 5.0). Commercial class libraries that you might use add many more packages.
Such long names obvious become unwieldy when a program involves many different classes from many different packages. The Java compiler allows instead for a short cut.
The import directive tells the compiler where to look for the class definitions when it comes upon a class that it cannot find in the default java.lang package. So, for example, in the class definition below for TestABC, the import statements
import mypack.*;
import mypack.extrapack.*;
import java.applet.*;
import mypack.extrapack.*;
import java.applet.*;
indicate that classes can be found in the mypack and mypack.extrapack packages and also that the Applet class can be found in the java.applet package.
import java.applet.Applet;
import mypack.*; import mypack.extrapack.*; public class TestABCApplet extends Applet { public static void init (String [] arg) { TestA testa = new TestA (4); TestB testb = new TestB (31.3); if( testc.flag) System.out.println ("testa.i = "+testa.i); else System.out.println ("testa.x = "+testb.x); } // Paint message in Applet window. public void paint(java.awt.Graphics g) { g.drawString ("TestABACpplet",20,20); } } |
TestABC.java (application)
|
The first import statement gives the full package path name for the Applet class in the packages included with the standard JVM. Then when the compiler sees just Applet in the class definition title, it will know where to find it.
In the next two import statements, we see the "*" wildcard character used for the classes in the mypack and mypack.extrapack packages. This indicates that these packages hold multiple classes and the compiler should look here if it cannot find a class in the core packages.
The wildcard only applies to classes, not to sub-packages. That is, mypack.* only refers to the classes in the package, not to the sub-directory extrapack. You must import each package name separately.
If the packages that you import happened to have two classes with the same name, to use one of them you will need to give the fully qualified name so that the compiler will know which of these classes you want to use.
NotesNote 1: C/C++ programmers usually assume that an import statement brings code into the .class bytecode files in a similar manner as the include statements in C/C++. However, that is not the case. An import statement simply provides an address where the compiler can look for class definitions.
We will also point out that Java is a so-called late binding object language, which means that it does not load class definitions until they are needed during processing. In fact, while a program is running it can dynamically load a class that was never mentioned in the source code. (For example, the class name could be read in from a file.)
Note 2 : To insure the uniqueness of package names, Sun proposes that the package name include your domain name (if you own one). For example,
com.mycompany.mypack.Test;
indicates that the Test class file belongs to the the mypack package owned by mycompany.com.
Access (Visibility) Rules
Access or visibility rules determine whether a method or a data variable can be accessed by another method in another class or subclass.
We have used the public modifier frequently in class definitions. It makes classes, methods, or data available to any other method in any other class or subclass.
Java provides for 4 access modifiers :
- public - access by any other class anywhere.
- protected - accessible by the package classes and any subclasses that are in other packages .
- Default - (also known as "package private") accessible to classes in the same package but not by classes in other packages, even if these are subclasses.
- private - accessible only within the class. Even methods in subclasses in the same package do not have access.
These access rules allow one to control the degree of encapsulation of your classes. For example, you may distribute your class files to other users who can make subclasses of them. By making some of your data and methods private, you can prevent the subclass code from interfering with the internal workings of your classes.
Also, if you distribute new versions of your classes at a later point, you can change or eliminate these private attributes and methods without worrying that these changes will affect the subclasses.
As we mentioned earlier, if you do not put your class into a package, it is placed into the "default unnamed package". For simple demonstration programs this usually suffices. However, with more serious programs you should use packages since otherwise any other class in the unnamed package has access to your class's fields and methods that are not set to private.
final Modifier & Constants
The final modifier indicates that a data field cannot be modified, as in
final double PI = 3.14;
Any attempt to assigne PI to a new value will result in a runtime error. Thus final makes data useful as constants.
Often such constants are needed by other classes, so they are declared static as well, as in
public class MyMath
{
public final static double TWO_PI = 6.28;
...
}
Then other classes can then reference it, as in
...
double y = theta / MyMath.TWO_PI; ...
final Methods
The final modifier is also used with methods to indicate that they cannot be overriden by subclasses. public class MyMath
{
...
public final double MyFormula() {
...
}
}
This helps to improve their performance since the JVM will not need to check for overriding versions with the method is invoked.
Kindly change background, as it appears difficult to read. Very useful material.
ReplyDeletewow very nice site..........dear.............
ReplyDelete