Professional Documents
Culture Documents
int i = 1;
import java.awt.Font;
m.engineState = true;
Statements sometimes return values—for example, when you add two numbers
together or test to see whether one value is equal to another. These kind of
statements are called expressions.
The most important thing to remember about Java statements is that each one
ends with a semicolon. Forget the semicolon and your Java program won‘t
compile.
Java also has compound statements, or blocks, which can be placed wherever a
single statement can. Block statements are surrounded by braces ({}).
Java actually has three kinds of variables: instance variables, class variables, and
local variables.
Instance variables, are used to define attributes or the state for a particular
object. Class variables are similar to instance variables, except their values apply
Page 1 of 25
to all that class’s instances (and to the class itself) rather than having different
values for each object.
Local variables are declared and used inside method definitions, for example,
for index counters in loops, as temporary variables, or to hold values that you need
only inside the method definition itself. They can also be used inside blocks ({}).
Once the method (or block) finishes executing, the variable definition and its value
cease to exist. Use local variables to store information needed by a single method
and instance variables to store information needed by multiple methods in the
object.
Although all three kinds of variables are declared in much the same ways, class
and instance variables are accessed and assigned in slightly different ways from
local variables.
Note: Unlike other languages, Java does not have global variables—that is,
variables that are global to all parts of a program. Instance and class variables can
be used to communicate global information between and among objects.
Remember, Java is an object-oriented language, so you should think in terms of
objects and how they interact, rather than in terms of programs.
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable
declarations consist of a type and a variable name:
int myAge;
String myName;
boolean isTired;
int count;
String title;
Page 2 of 25
boolean isAsleep;
...
You can string together variable names with the same type:
int x, y, z;
You can also give each variable an initial value when you declare it:
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only one initializer (as in the
first of the previous examples), the initial value applies to only the last variable in a
declaration. You can also group individual variables and initializers on the same
line using commas, as with the last example, above.
Local variables must be given values before they can be used (your Java
program will not compile if you try to use an unassigned local variable). For this
reason, it‘s a good idea always to give local variables initial values. Instance and
class variable definitions do not have this restriction (their initial value depends on
the type of the variable: null for instances of classes, 0 for numeric variables, ‗\0‘
for characters, and false for booleans).
Local variables:
Local variables are declared in methods, constructors, or blocks.
Page 3 of 25
Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor or block.
Local variables are visible only within the declared method, constructor or block.
Example:
Here, age is a local variable. This is defined inside pupAge() method and its scope
is limited to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]){
Test test = new Test();
test.pupAge();
}
}
Instance variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present
throughout the class.
Instance variables can be declared in class level before or after use.
The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access level).
However visibility for subclasses can be given for these variables with the use of
access modifiers.
Instance variables have default values. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned
during the declaration or within the constructor.
Page 5 of 25
Instance variables can be accessed directly by calling the variable name inside the
class. However within static methods and different class (when instance variables
are given accessibility) should be called using the fully qualified name
. ObjectReference.VariableName.
Example:
import java.io.*;
name : Ransika
Page 6 of 25
salary :1000.0
Class/static variables:
Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final and static. Constant variables
never change from their initial value.
Static variables are stored in static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0;
for Booleans, it is false; and for object references, it is null. Values can be assigned
during the declaration or within the constructor. Additionally values can be
assigned in special static initializer blocks.
Example:
import java.io.*;
// DEPARTMENT is a constant
Page 7 of 25
public static final String DEPARTMENT = "Development ";
Variable names in Java can start with a letter, an underscore (_), or a dollar sign
($). They cannot start with a number. After the first character, your variable names
can include any letter or number. Symbols, such as %, *, @, and so on, are often
reserved for operators in Java, so be careful when using symbols in variable names.
In addition, the Java language uses the Unicode character set. Unicode is a
character set definition that not only offers characters in the standard ASCII
character set, but also several million other characters for representing most
international alphabets. This means that you can use accented characters and other
glyphs as legal characters in variable names, as long as they have a Unicode
character number above 00C0.
Finally, note that the Java language is case-sensitive, which means that uppercase
letters are different from lowercase letters. This means that the variable X is
different from the variable x, and a roseis not a Roseis not a ROSE. Keep this in
mind as you write your own Java programs and as you read Java code other people
have written.
Page 8 of 25
By convention, Java variables have meaningful names, often made up of several
words combined. The first word is lowercase, but all following words have an
initial uppercase letter:
Button theButton;
long reallyBigNumber;
boolean currentWeatherStateOfPlanetXShortVersion;
Variable Types
In addition to the variable name, each variable declaration must have a type, which
defines what values that variable can hold. The variable type can be one of three
things:
There are four Java integer types, each with different ranges of values (as listed in
Table 2.1). All are signed, which means they can hold either positive or negative
numbers. Which type you choose for your variables depends on the range of values
you expect that variable to hold; if a value becomes too big for the variable type, it
is truncated.
Floating-point numbers are used for numbers with a decimal part. Java floating-
point numbers are compliant with IEEE 754 (an international standard for defining
floating-point numbers and arithmetic). There are two floating-point types:
float(32 bits, single-precision) and double(64 bits, double-precision).
The char type is used for individual characters. Because Java uses the Unicode
character set, the char type has 16 bits of precision, unsigned.
Finally, the boolean type can have one of two values, true or false. Note that
unlike in other C-like languages, boolean is not a number, nor can it be treated as
one. All tests of boolean variables should test for true or false.
In addition to the eight basic data types, variables in Java can also be declared to
hold an instance of a particular class:
String LastName;
Font basicFont;
OvalShape myOval;
Each of these variables can then hold only instances of the given class. As you
create new classes, you can declare variables to hold instances of those classes
(and their subclasses) as well.
Technical Note: Java does not have a typedef statement (as in C and C++). To
declare new types in Java, you declare a new class; then variables can be declared
to be of that class‘s type.
size = 14;
tooMuchCaffiene = true;
Page 10 of 25
Java Identifiers
All Java components require names. Names used for classes, variables and
methods are called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
After the first character identifiers can have any combination of characters.
Java Keywords
The following list shows the reserved words in Java. These reserved words may
not be used as constant or variable or any other identifier names.
Constants
A constant is an identifier that is similar to a variable except that it holds the
same value during its entire existence
The compiler will issue an error if you try to change the value of a constant
Third, they formally establish that a value should not change, avoiding
inadvertent errors by other programmers
Strings
Strings, which are widely used in Java programming, are a sequence of characters.
In the Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
Page 12 of 25
In this case, "Hello world!" is a string literal—a series of characters in your code
that is enclosed in double quotes. Whenever it encounters a string literal in your
code, the compiler creates aString object with its value—in this case, Hello world!.
As with any other object, you can create String objects by using the new keyword
and a constructor. The String class has thirteen constructors that allow you to
provide the initial value of the string using different sources, such as an array of
characters:
Note: The String class is immutable, so that once it is created a String object
cannot be changed. The String class has a number of methods, some of which will
be discussed below, that appear to modify strings. Since strings are immutable,
what these methods really do is create and return a new string that contains the
result of the operation.
String Length
String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}
To accomplish the string reversal, the program had to convert the string to an array
of characters (first for loop), reverse the array into a second array
(second for loop), and then convert back to a string. The String class includes a
method, getChars(), to convert a string, or a portion of a string, into an array of
characters so we could replace the first for loop in the program above with
Page 14 of 25
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
which results in
"Hello, world!"
which prints
Such a concatenation can be a mixture of any objects. For each object that is not
a String, its toString() method is called to convert it to a String.
Note: The Java programming language does not permit literal strings to span lines
in source files, so you must use the + concatenation operator at the end of each line
in a multi-line string. For example:
String quote =
"Now is the time for all good " +
"men to come to the aid of their country.";
Breaking strings between lines using the + concatenation operator is, once again,
very common in print statements.
Page 15 of 25
Creating Format Strings
You have seen the use of the printf() and format() methods to print output with
formatted numbers. The String class has an equivalent class method, format(), that
returns a String object rather than a PrintStream object.
Using String's static format() method allows you to create a formatted string that
you can reuse, as opposed to a one-time print statement. For example, instead of
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
System.out.println(fs);
Comments in Java
Java supports single-line and multi-line comments very similar to c and c++. All
characters available inside any comment are ignored by Java compiler.
Java Literals
A literal is a source code representation of a fixed value. They are represented
directly in the code without any computation.
For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base
16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using
these number systems for literals. For example:
String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";
Page 17 of 25
Java language supports few special escape sequences for String and char literals as
well. They are:
Numeric Operations
The operations that can be done on numeric data include the standard algebraic
operations: addition (+), subtraction (-), multiplication (*), division (/), as well as
the modulus (%) operator. Note that in Java, the multiplication symbol is * and not
x. The arithmetic operators are binary operators, meaning that they each take two
operands.
Page 18 of 25
Although these operations should seem familiar, there are some important
differences between their use in algebra and their use in a Java program. Consider
the following list of expressions:
In each of these cases we are dividing the quantity 3 by the quantity 2. However,
different results are obtained depending on the type of the operands involved.
When both operands are integers, as in (3/2), the result must also be an integer.
Hence, (3/2) has the value 1, an integer. Because integers cannot have a fractional
part, the 0.5 is simply discarded. Integer division (/) always gives an integer result.
Thus, the value of (6/2) is 3 and the value of (7/2) is also 3. Because 3.5 is not an
integer, the result of dividing 7 by 2 cannot be 3.5.
Operator Precedence
The built-in precedence order for arithmetic operators is shown in Table 2.3.
Parenthesized expressions have highest precedence and are evaluated first. Next
come the multiplication, division, and modulus operators, followed by addition and
subtraction. When we have an unparenthesized expression that involves both
multiplication and addition, the multiplication would be done first, even if it occurs
to the right of the plus sign. Operators at the same level in the precedence
hierarchy are evaluated from left to right. For example, consider the following
expression:
Page 19 of 25
3 */% Multiplication, division, modulus
4 +- Addition, subtraction
5 <><=>= Relational operators
6 = = != Equality operators
Example:
9+6-3*6/2
In this case, the first operation to be applied will be the multiplication (*), followed
by division (/), followed by addition (+), and then finally the subtraction (-). We
can use parentheses to clarify the order of evaluation. A parenthesized expression
is evaluated outward from the innermost set of parentheses:
Step 1. ( (9 + 6) - ((3 * 6) / 2 ) )
Step 2. ( (9 + 6) - (18 / 2 ) )
Step 3. ( (9 + 6) - 9 )
Step 4. ( 15 - 9 )
Step 5. 6
Parentheses can (and should) always be used to clarify the order of operations in an
expression.
int k;
k = k + 1;// Add 1 to k and assign the result back to k
Contrast that with the expression ++k in which the ++ operator precedes its
operand. In this case, it is used as a preincrement operator, which means that the
increment operation is done before the operand's value is used.
When they are used in isolation, there is no practical difference between k++ and
++k. Both are equivalent to k = k + 1. However, when used in conjunction with
other operators, there is a significant difference between preincrement and
postincrement. For example, in the following code segment,
Precedence order
the variable k is incremented after its value is assigned to i. After execution of the
assignment statement, i will have the value 0 and k will have the value 1. The
preceding sequence is equivalent to
In addition to the increment operator, Java also supplies the decrement operator --,
which can also be used in the predecrement and postdecrement forms. The
expression -- k will first decrement k's value by 1 and then use k in any expression
in which it is embedded. The expression k-- will use the current value of k in the
expression in which k is contained and then it will decrement k's value by 1. Table
2.4 summarizes the increment and decrement operators. The unary increment and
decrement operators have higher precedence than any of the binary arithmetic
operators.
class PrePostFixTest {
public static void main (String args[]) {
int x = 0;
int y = 0;
System.out.println(―x and y are ― + x + ― and ― + y );
x++;
System.out.println(―x++ results in ― + x);
++x;
System.out.println(―++x results in ― + x);
System.out.println(―Resetting x back to 0.‖);
x = 0;
System.out.println(―——————‖);
y = x++;
System.out.println(―y = x++ (postfix) results in:‖);
System.out.println(―x is ― + x);
System.out.println(―y is ― + y);
Page 22 of 25
System.out.println(―——————‖);
y = ++x;
System.out.println(―y = ++x (prefix) results in:‖);
System.out.println(―x is ― + x);
System.out.println(―y is ― + y);
System.out.println(―——————‖);
}
}
Output
x and y are 0 and 0
x++ results in 1
++x results in 2
Resetting x back to 0.
——————
y = x++ (postfix) results in:
x is 1
y is 0
——————
y = ++x (prefix) results in:
x is 2
y is 2
——————
Java supports two types of castings – primitive data type casting and reference
type casting. Reference type casting is nothing but assigning one Java object to
another object. It comes with very strict rules and is explained clearly in Object
Casting. Now let us go for data type casting.
Java data type casting comes with 3 flavors.
1. Implicit casting
2. Explicit casting
Page 23 of 25
3. Boolean casting.
1. Implicit casting (widening conversion)
A data type of lower size (occupying less memory) is assigned to a data type of
higher size. This is done implicitly by the JVM. The lower size is widened to
higher size. This is also named as automatic type conversion.
Examples:
double x = 10.5;
int y = (int) x;
The double x is explicitly converted to int y. The thumb rule is, on both sides, the
same data type should exist.
3. Boolean casting
A boolean value cannot be assigned to any other data type. Except boolean, all the
remaining 7 data types can be assigned to one another either implicitly or
explicitly; but boolean cannot. We say, boolean is incompatible for conversion.
Maximum we can assign a boolean value to another boolean.
Following raises error.
boolean x = true;
Page 24 of 25
int y = x; // error
boolean x = true;
int y = (int) x; // error
byte –> short –> int –> long –> float –> double
In the above statement, left to right can be assigned implicitly and right to left
requires explicit casting. That is, byte can be assigned to short implicitly but short
to byte requires explicit casting.
Following char operations are possible.
Page 25 of 25