It is said that the best way to learn swimming is to jump into the water right away. Similarly, the best way to learn a programming language is to start coding straight away. Let us start our study of Java programming in an informal way. Let us write a simple Java program and run it.
In our first Java program, we will find the area of a circle with radius 5.
Problem: Write a program to find area of a circle with radius 5.
Solution: See Program 3.1.
PROGRAM 3.1 Area of a Circle
// first.java
class first
{
public static void main( String args[] )
{
int r ;
r = 5 ;
System.out.println(3.14 * r * r);
}
}
If you run the program, you will get the following output.
Output
78.5
The output was as expected. Though the program was very simple still it had many components (parts). Let us describe its every part (Table 3.1).
Table 3.1 Program Parts Illustrated
Program code | Explanation |
---|---|
// first.java |
This is a comment |
class first |
The name of the class is first . This program must be in a file first.java |
{ |
Left brace: start of class |
public static void main |
The execution of program starts with method main () |
( String args[] ) { |
Left brace: start of main method |
int r ; |
Declaration of variable r |
r = 5 ; |
Initialization of r |
System.out.println (3.14 * r * r); |
Program statement. Prints the value |
} |
Right brace: end of method main |
} |
Right brace: end of class first |
A useful Java program will consist of many parts. It will have many features. It will not be easy to absorb every thing at one go. Therefore, we should first think of very simple programs, then simple programs, and so on. We should study Java step by step. Now in light of this program, let us study structure of a very simple Java program.
Structure of a very simple Java program can be summarized as follows:
first
is written in a file named first.java.
first
, as a rule.main
. It has to be declared with parameters: String args[],
as shown in Table 3.1.main()
.As a matter of the rule, name of the class which contains method main()
and the name of the file (without extension) must be identical.
Please note that this is description of a very simple program. As we start studying more and more features, we will refine this definition.
Any Java program (or a program in any other language for that matter) consists of few building blocks like comments, declarations, statements, and methods. These blocks are formed by some small atomic quantities known as tokens. Here we will not go into the grammar in depth. Still we will discuss step by step how programs, that is declarations and statements, are written. We will talk about grammar in a later chapter.
Comments are that part of the program, which are supposed to give more information (or explanation) to the reader. They increase the readability of the program. The compiler does not convert it into code. (We may say compiler ignores it.) Therefore, presence of comments has no relevance to program (execution) speed. In Java, comments are enclosed in pair of /*
and */
. Such comments can be of one or more lines. It may be noted that, such comment can appear anywhere, where a white space can appear in a program.
In addition Java uses double slash (//
) for single-line comments. Any text from //
to the end of that line is treated as comment.
In this text, you will see every program starts with the program name as a comment. It is not merely a style. It is a discipline which helps in long run.
When we write a program, we actually write characters. The console input and output also uses characters. Character set stands for the collection of characters used by any programming language. Java supports Unicode character set. Unicode characters need 16 bits (instead of 8 for ASCII) to store a character. It will be heartening to know that in Unicode there is representation for scripts (languages), like Japanese, Chinese, and many Indian ones, like Devnagri and Tamil.
Earlier languages used ASCII character set. Java also supports it as Unicode encompasses the ASCII character set.
A Java program can generate all of these characters. If we talk of writing Java program, that is source code, then there are some restrictions. We cannot use each and every character in writing a program. Table 3.2 illustrates the characters used in writing a program.
All Unicode characters can be written to file. However, if we are writing them to screen, some of them may not be shown properly.
Let us write a small program to verify this fact.
Table 3.2 Characters for Writing Java Programs
Group | Details |
---|---|
Letters—English alphabets | a to z and A to Z |
Letters—non-English alphabets | All characters that are considered to be a letter by the Unicode 2.0 standard. |
Digits | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 |
Special characters I | dollar mark ($ ) and underscore (_ ) character |
Special characters II | ! @ # % ^ & * - = + < > / ? |
Special characters III | { } [ ] ( ) ; , |
Separator | blank, tab, new line |
Problem: Write a program to print all ASCII characters on the screen.
Solution: We know that first 31 characters are used for special purpose. Hence, we will show characters with value 32 to 255. To restrict limited say 16 characters in one line, we will use 2 for loops (see Program 3.2).
PROGRAM 3.2 ASCII Characters
// char1.java
class char1
{ public static void main(String args[])
{ char x= 65 ;
int i,j,key ;
for(j=2;j<16;j++)
{ System.out.print(j*16 + “ : ”);
for(i=0;i<16;i++)
{ key = j*16 + i;
System.out.print( (char) key + “ ”);
}
System.out.println();
}
}
}
If you run the program, you will get the following output.
Output
Please note that some characters are not shown properly on the screen. Hence, the computer (Windows OS) is showing question mark (?) in their place.
The most basic things in a program are the variables and the values they take. We have seen a statement:
r = 5 ;
Here, r is a variable and it takes value “5”.
We will call this value appearing in a program as constant. (In strict computer jargon, it is called literal).
Constants can be divided into following three categories:
Integers can be expressed in three possible notations, that is octal, decimal, and hexadecimal.
In daily use, we use integer constants in decimal form. These constants are either positive or negative. Plus sign is optional.
Following are examples of valid integer constants in decimal notation:
23
–55
+2367
If we have to state an integer constant in octal notation (format), we must precede it with zero. This is the way we tell the computer that we mean octal representation. Please note that digits 8 and 9 are not valid in octal notation.
Following are examples of valid integer constants in octal notation:
023
055
02367
Hexadecimal number system consist of digits 0 to 9 and alphabets “a” to “f”. These constants are preceded by 0x
Following are examples of valid integer constants in hexadecimal notation:
0x23
0x5B
0Xff23
Please note that alphabets “a” to “f” and “x” can be in either small or capital.
Let us study these constants in a simple program.
Problem: Write a program to study octal, decimal, and hexadecimal notation for integers.
Solution: See Program 3.3.
PROGRAM 3.3 The Octal Notation
// const1.java
class const1
{ public static void main(String args[])
{ int i,j,k ;
i = 23 ; // decimal notation
j = 023 ; // octal notation
k = 0X23 ; // hexadecimal notation
System.out.println(“--->const1.java starts<---”);
System.out.println(“Decimal notation 23 -> ” + i );
System.out.println(“Octal notation 023 -> ” + j );
System.out.println(“Hexadecimal notation 0x23 -> ” + k );
}
}
If you run this program, you will get the following output.
Output
--->const1.java starts<---
Decimal notation 23 -> 23
Octal notation 023 -> 19
Hexadecimal notation 0x23 -> 35
Real or floating-point constants are written in either fixed point or scientific notation. Following are examples of valid real constants in fixed point notation.
2.3
–5.54
236.7
Notice the presence of decimal point. Also note, optional sign. Following are examples of valid real constants in scientific notation:
0.2e3
–5E5
2E67
Following conventions are used with scientific notation:
When we write numerical constants, they may belong to different types like float
, double
, integer
, or long
. There may be some confusion in the mind of compiler. If we write 2 it can very well represent an integer
or long
or float
value. Hence, Java allows us to specify the data type of a constant using a suffix. If we use suffixes f, F, l, L, d, D they tell the compiler the necessary data type of the constant. Type float
is specified by f or F. Type long
is specified by l or L. Similarly, type double
is specified by d or D.
Can you figure out why type integer
is not given a suffix? The answer is simple; the type integer
is the default numeric type. Any constant if not specified is treated as integer
.
Enclosing a single character in single quotes forms simple character constants:
Example: ‘A’, ‘B’, ‘)’
There are many characters in ASCII character set which are used for special purpose (for example, carriage return, form feed). Some of them cannot be typed with a keyboard. Naturally, they cannot be placed within single quotes. Therefore, alternate notation (format) has been developed. It uses a backslash character. It is also referred as escape codes.
Table 3.3 illustrates commonly used special characters.
It is interesting to note that to denote a single backslash character we use two such characters. Please note that unlike C++, Java does not define escape codes for vertical tab and the bell characters. See escape codes in action at the end of chapter example.
If we have to specify Unicode character, we have to write its hexadecimal value preceded by character u.
For example,
‘u0100’
Please note that you cannot use uppercase U. Also, there must be four (no more no less) hexadecimal digits. Hence, constants like
‘U0100’ or u100
are invalid.
A collection of characters is known as string
. Putting characters in the pair of double quotes forms a string
constant.
Table 3.3 Escape Characters
Character | Represented by |
---|---|
Backspace | ‘’ |
Form feed | ‘f’ |
New line | ‘
’ |
Carriage return | ‘
’ |
Horizontal tab | ‘ ’ |
Single quote | ‘’’ |
Double quote | ‘”’ |
Backslash | ‘\’ |
Following are examples of valid string
constants:
“Hello”
“World”
“good morning” *
Java has an in-built class String
to deal with character strings
. We will deal with it later in a separate chapter.
We have seen constants. To store their values we need what is called variables. As name suggests, computer allows us to vary (change, manipulate) the values stored in a variable. In earlier programs, we have used variable names like area1. Grammatically variable name is an identifier. Hence, rule for forming variables are same as those for forming identifiers.
Rules for forming variable names can be stated as follows:
_
) and Dollar symbol ($
) are treated as letter as far as variables are concerned.Following are valid variable names:
marks
Marks
K3G
Kabhi_Kushi_Kabhi_Gum
$JamesBond
Following are invalid variable names:
mark’s
4you
m.x
These rules are general. Java treats few non-letter characters for use in variable names. We will discuss this again in Chapter 9 on “Wrapper Classes”.
Every language reserve few words for its own use. They are termed as keywords or reserved words. We can group keywords of Java in three separate groups. Some keywords are in use as of today. Some are reserved for future use. Some of them actually represent values. It goes without saying that we cannot use keywords as variables (or user-defined name for any other entity like method).
Table 3.4 illustrates the keywords from Java which are currently in use.
Table 3.5 illustrates the keywords from Java which are reserved for future use.
Table 3.5 Keywords Reserved for Future Use
const |
goto |
Table 3.6 Keywords which are Value Defined
false |
null |
true |
Table 3.6 illustrates the keywords from Java which are value defined.
We have said that variables store values. They basically represent data. In computer, data may be numeric or non-numeric. Therefore, various data types have been defined. The basic classification of data types can be numeric and non-numeric. These can be sub-classified further. Let us study these data types one by one.
Numeric data types are for storing numbers. Not all of our school and college days number types are supported by Java. It basically supports only integers and real numbers. (As a programmer, we have to write code ourselves for numbers like rational numbers.)
Integer data type has a peculiarity that it has an exact representation in a computer. In different programs, we may be using large or small values. To store small numbers, we need fewer bytes and to store big number we need many bytes. Earlier computers had very little memory. Hence, different sub-data types for storing integers were defined. They are byte
, short
, int
, and long
. Java supports all these types. The memory required to store them varies from 1–4 bytes.
In C++ there is a qualifier named unsigned. There is no such qualifier in Java. Hence, all integer
types can handle positive as well as negative numbers in Java.
To store real numbers, Java uses floating-point method. That is the reason for type name float
. The beauty of float
type is that in a given space (number of bits) it can store a very large as well as small numbers. (This is not possible in fixed point notation.)
To store real numbers, Java defines two sub-types, namely float
and double.
They require 4 and 8 bytes, respectively. They are capable of handling fairly large as well as fairly small values. Table 3.7 illustrates the length in bytes and range of numeric data types.
Type float
and double
are capable of storing very small values. The smallest values they can store are 1.4E–45
and 4.9E–324
, respectively.
We will now discuss non-numeric data types one by one.
Character
Variables of type
char
store characters. Java supports 16 bits Unicode characters. If you have studied ASCII character set, for simplicity you can assume that Java supports ASCII character set.
Boolean
Variable of type
boolean
storetrue
orfalse
values.
Void
Void means nothing. We cannot have a variable of type
void
. When a function (called method in Java) does not return anything, we say it returns a value of typevoid
. Data typevoid
is used only with reference to functions.
Reference
Programming languages like C and C++ have a type called
pointer
. It stores the address of the variable it references. A similar data type in Java is termed asreference
. However, Java does not allow any numeric processing on this type.Arrays
,strings
, andclasses
are handled by typereference
.
Table 3.7 Length and Range of Numeric Data Types
Type | Length in bytes | Range |
---|---|---|
byte |
1 | –128 to +127 |
short |
2 | –32,768 to 32,767 |
intent | 4 | –2,147,473,648 to 2,147,483,647 |
long |
8 | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float |
4 | –3.4E38 to +3.4 E38 |
double |
8 | –1.7E308 to +1.7E308 |
At this stage just assume that it is some mechanism to represent complex (or in general multi valued) data type. We will discuss this in more details when we discuss objects and methods.
Variables are declared with the help of its data type.
A declaration
int j ;
tells the compiler that j is a variable of type int (integer)
. If you have more than one variable of type int
, they are separated by comma, for example
int j, k, m ;
Please note that we must assign initial values (using assignment operator) to these variables before using them in a program. Otherwise, compiler will fail to compile the program. This helps in avoiding many unintended errors. Note that C++ does not behave like this. It assigns arbitrary values to the variable. In this respect, Java scores over C++.
Java allows us to initialize a variable at the time of declaration as shown hereafter.
int marks = 100;
This statement declares a variable marks
of type integer
and assigns value 100 to it.
Operator performs operations on operands. Operands may be one, two, or three. Operands are either variables or constants. The operators, which take single operand, are called unary operators. Those taking two are known as binary operators and one having three operands is called ternary operator.
Most of the operators are binary operators, few are unary while there is only one ternary operator (for example “?:” operator).
For further study, we can group operators depending on functionality.
Let us discuss all of them one by one.
From our school days, we are familiar with following arithmetic operators:
addition ( )
subtraction (-)
multiplication (*)
division ( / ) and
modulo (%)
.
All these operators are binary operators and work on all integer and floating-point types. Please note that in Java, you can use modulo operator (%)
with floating-point operands. (This is not a case with C++.) Following unary operators also work on integers and floating-point numbers:
Unary plus+
Unary minus–
Pre-increment or post-increment++
Pre-decrement or post-decrement––
Please note that last two operators work only with variables (not constants). Consider a case where we use say for example mark++
(post-increment) in an expression. First current value of mark is used in evaluating that expression and then variable mark is incremented by one.
Consider a case where we use say for example ++mark
(pre-increment) in an expression. First variable mark is incremented by one and then the new value of mark is used in evaluating that expression.
Operation with decrement is similar in nature. Here value of the variable is decremented by one.
Mixing too many pre- and post-increment/decrement operators in a single expression is quite confusing. It must be avoided. Language has given this facility as convenience. We should not make our life miserable with it.
Problem: Write a program to demonstrate use of modulo operator.
Solution: See Program 3.4.
PROGRAM 3.4 Modulo Operator
// modulo1.java
class modulo1
{ public static void main(String args[])
{ int amount = 320;
int rupees,paise;
System.out.println(“--->modulo1.java starts<---”);
rupees = amount / 100 ;
paise = amount % 100 ;
System.out.println(“rupees = ” + rupees);
System.out.println(“paise = ” + paise);
}
}
If you run the program, you will get the following output.
Output
--->modulo1.java starts<---
rupees = 3
paise = 20
Table 3.8 Relational Operators
Operator | Description |
---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal to |
!= | Not equal to |
Table 3.8 illustrates the various relational operators available in Java.
Here we have seen a simple application of modulo operator. It involved integers as operands. The “modulo division” may be applied to floating-point values in Java. This is not permitted in C/C++. However, we have not come across any decent use of this facility.
When we use relational operator in an expression it returns Boolean value, that is true or false. Please note that in C++, such expressions actually return number 1 for true and number 0 for false. Hence, a code
int k ;
k = 5>4 ;
is valid in C++, but not in Java. Java will flag compilation error saying “Can’t convert boolean
to int”
. See Program 3.8 relop1.java
in the end of chapter programs.
To work with variables and constants of type Boolean
, we have logical operators. They are also termed as Boolean operators. Some texts call them conditional operators. Table 3.9 illustrates these operators.
Table 3.9 Logical Operators
Operator | Description |
---|---|
&& |
Logical AND short-circuit evaluation |
& |
Logical AND operator |
| | |
Logical OR short-circuit evaluation |
| |
Logical OR operator |
! |
Logical negation (NOT) |
^ |
Exclusive OR |
Let us study a simple program.
Problem: Write a program to demonstrate evaluation of Boolean expression.
Solution: Let us take the question closest to the heart of first-year students. Whether they will enter second year or not? Consider that there are two semesters whose results are stored as Boolean. Rules of University A are lenient. If a student passes any one semester, he is allowed to go to next year. Rules of University B are stringent. Student must pass both the semesters (see Program 3.5).
PROGRAM 3.5 Evaluating Boolean Expression
// logical1.java
class logical1
{ public static void main(String args[])
{ boolean semI = true ;
boolean semII = false ;
boolean resultA, resultB ;
System.out.println(“<---logical1--->”);
resultA = semI || semII ;
resultB = semI && semII ;
System.out.println(“resultA ->” +resultA);
System.out.println(“resultB ->” +resultB);
}
}
If you run the program, you will get the following output.
Output
<---logical1--->
resultA ->true
resultB ->false
It goes without saying that these logical/Boolean operators need Boolean operands. Any attempt to use it with operands of type integer
(as allowed in C/C++) will result in error.
For example, in Program 3.5, resultA
and semI
are Boolean variables. A statement like
resultA = semI || 3 ;
results in compilation error.
Consider an expression
op1 || op2 ;
Here first op1
is evaluated. If it is true, the value of expression is true. Naturally, there is no need to evaluate op2
. Hence, op2
is not evaluated.
If op2
was a method, it will not be invoked.
If we are executing
op1 | op2
op2
will always be evaluated.
Operator | Description |
---|---|
~ |
Bit-wise (1’s) complement |
& |
Bit-wise AND |
^ |
Bit-wise XOR |
| |
Bit-wise OR |
In case of doubt do not use short-circuit operation.
(Please note that | stands for vertical bar character. It is seen on keyboard as “¦”.)
Twenty-five years ago when programming language C was introduced, there was lot of noise regarding bit manipulation. Bit-wise operators were in limelight. However, over the years the enthusiasm has subsided. In the past 5 years, we hardly remember any program written by us using bit manipulation. However, it is still required in specific fields like communication engineering.
Table 3.10 illustrates the bit-wise operators.
The following points may be noted regarding use of bit-wise operators:
(char
, byte
, short
, int
, or long)
type. It means float
and double
are not allowed as operands.long
, result is of type long
.long
, result is of type int
.Let us see a simple program using bit-wise operators.
Problem: Write a program to demonstrate bit-wise operators.
Solution: In this program we have one example of AND
and OR
operator each (see Program 3.6).
PROGRAM 3.6 Bit Manipulation
// bit1.java
class bit1
{ public static void main(String args[])
{ int i=5;
long a=2,b ;
short c=4,d=3 ;
System.out.println(“<---bit1--->”);
b = i | a ; // 101 | 010
d = (short)( d & c ); // 011 & 100
System.out.println(“ ->” + b );
System.out.println(“ ->” + d );
}
}
If you run the program, you will get the following output.
Output
<---bit1--->
->7
->0
Are the results as expected? You may note that d & c
produce a result of type integer
. Hence, typecasting to short
is required. Effective use of bit-wise operators can be seen in Chapter 24 on “Multimedia Experience”.
A shift operator also performs bit manipulation by shifting the bits left or right. The bits of the first operand are shifted number of places as specified by the second operand. Java has three operators for this purpose. Table 3.11 summarizes these operators.
Table 3.11 Shift Operators
Operator | Use | Operation |
---|---|---|
>> | op1 >> op2 |
Shift bits of op1 right by distance op2 |
<< | op1 << op2 |
Shift bits of op1 left by distance op2 |
>>> | op1 >>> op2 |
Shift bits of op1 right by distance op2 (unsigned) |
It goes without saying that these operators work with only operands, which are integral in nature (sorry no floating-point operands).
When we shift right with >> the sign bit (left most) is copied in the left most position. With >>> sign is ignored. Zero is entered in MSB position.
Let us study a problem with shift operators.
Problem: Write a program to study shift operators.
Solution: See Program 3.7.
PROGRAM 3.7 Shift Operator
// shift1.java
class shift1
{ public static void main(String args[])
{ int i,j;
byte k = 4 ;
i = 6 << 2 ;
j = 23 >> 2;
k = (byte) (k >> 1) ;
System.out.println(“--->shift1.java starts<---”);
System.out.println(“1) “ + i );
System.out.println(“2) “ + j );
System.out.println(“3) ” + k );
}
}
If you run this program, you will get the following output.
Output
--->shift1.java starts<---
1) 24
2) 5
3) 2
Note the following:
“<<”
is left shift operator. Shifting a binary number by 2 bits left is equal to multiplying by4(=2*2)
. Hence,6 * 4 = 24
is the output.
“>>”
is right shift operator. Shifting a binary number by 2 bits right is equal to dividing (integer mode) by4 (= 2 raised to 2)
. Hence,23/4 = 5
is the output.
Here 4 is divided by 2. Hence, the answer. The point to note is k>>1
is evaluated as an integer. Hence, before substituting in k
we have to typecast it to byte.
We have seen equal sign as basic assignment operator. It assigns value on right-hand side to variable on left-hand side. For example, marks = 95.
Many times we need expressions as marks = marks + 3;
(grace marks). To handle such situations, Java provides shortcut operators. For example, +=
is a shortcut operator. If you write marks=+3
it means a shortcut for longer expression marks = marks+3
. There are many such shortcut operators. They are listed in Table 3.12
Table 3.12 Shortcut Assignment Operators
Operator | Description |
---|---|
= |
Simple assignment |
*= |
Assign product |
/= |
Assign quotient |
%= |
Assign remainder (modulus) |
+= |
Assign sum |
-= |
Assign difference |
&= |
Assign bit-wise AND |
^= |
Assign bit-wise XOR |
|= |
Assign bit-wise OR |
<<= |
Assign left shift |
>>= |
Assign right shift |
Operator | Description |
---|---|
?: |
For conditional evaluation |
() |
Used in Function call |
[] |
Used for Array subscript |
. |
Used as reference to member |
new |
Used for creating an object or an array |
(type) |
Used in typecasting the operand |
instanceof |
Used for checking an object for belonging to a class |
Table 3.13 lists other special operators.
Please note that these are not operators in strict mathematical sense. It is the requirement of grammar that forces Java to call them as operators. Let us not worry about it. We will study these operators later at appropriate time.
Those who know C++ will notice the absence of comma operator. In our opinion, this is a good thing because there are not many uses of this operator. Inadvertent use of this operator produces many bugs in C++ programs. Many times we may use a two-dimensional matrix element as A[j,k]. (This is an error as we must be using A[j][k].) C++ accepts this assuming that we are consciously using comma operator. It produces unexpected results. This does not happen in Java as error is caught at compile time only.
We are faced with all sorts of calculations from our school days. Calculations primarily involve numeric expressions. In Java, we will see numeric as well as non-numeric expressions. Expressions are combinations of operators and operands; operands are literals (constants), variables or keywords, or symbols that evaluate a value of some type (for example true). Let us start with arithmetic expressions.
Simple arithmetic expressions can be classified as unary expressions or binary expressions.
When we apply unary + or – operator to a constant or variable we get unary expression. If we have expression -Marks
, it is evaluated as -1 *
Marks. Similarly, expression +Y
is evaluated as +1 * Y
.
These expressions involve two operands and a binary operand. If one fruit costs 3 rupees, five fruits costs
3 * 5 equal to 15 rupees.
Here 3 and 5 are operands and * (for multiplication) is the operator.
General expressions involve many operands and operators. Their evaluation follows standard rules known to us from our school days.
All the operators and their precedence are shown in Appendix C.
Strictly speaking, when more than one operator with same precedence appears in an expression, we have to look for the associativity of the operators. Most of the operators have left to right associativity. The important exceptions are assignment operator and all of shorthand assignment operators. They operate from right to left.
Expressions involving logical operators are called logical expressions. Alternate name is Boolean expressions. These evaluations follow the Boolean algebra. They result in only true or false answer.
Rules for evaluating such expressions (precedence and left to right) are similar to that of arithmetic expressions.
Assignment expressions are evaluated as follows. First right-hand side sub-expression is evaluated. Then this result is assigned to variable of left-hand side. It must be noted that at left-hand side we must have something, which can store the value.
j = 5+5;
is fine, but 3 = 5
is not acceptable. If you write such an expression compiler will generate error message as L-value required.
Java is a strongly typed language. Hence, it does not allow you to assign value of one type to variable of other type in arbitrary manner. Consider following declarations:
long n = 2 ;
int j = 5 ;
j = n ;
Here n
is a long
integer. Its value is assigned to a variable of type int
. We know that long
can store values larger than capacity of type int
. Hence, there is a possibility of error. Hence, Java does not compile this code. It gives error. On the contrary if we write
n = j;
Java allows this. Reason is very simple. Capacity of long
is much more than int
, therefore, long
can accept any int
value without error. This is called “widening” principle.
Table 3.14 illustrates the assignment compatibility of numeric types
Table 3.14 Assignment Compatibility
Type on left-hand side | Type on right-hand side |
---|---|
short |
byte |
int |
short, byte |
long |
int, short, byte |
float |
int, short, byte |
double |
float, int, short, byte |
Right from Fortran days, programmers are interested in knowing whether integer values can be put to real variables and vice versa. Let us first talk of substituting integer values in real variables. Type float
handles values much greater than the largest value of type integer
. Hence, it can accept integer values. Similarly, double
can take long
.
On the other side, conversion from float
to int
is not permitted directly. A float
may contain a fraction, which is not acceptable in integers
. Hence, specific conversion is required. From our knowledge of school mathematics, we know that there are two well-known ways for conversion. They are truncation and rounding. Java supports method round()
for rounding. There is no first-hand support for truncation. Java supports methods ceil()
and floor()
for this purpose.
Table 3.15 describes the methods ceil
, floor
, and round
.
Figure 3.1 will illustrate their action graphically.
Please note that in this diagram a
represents a whole number, which can be either positive or negative. If we want to truncate a real value we can use methods ceil
and floor (details are left to you as an exercise). Alternately, we can use brute force and use typecasting to truncate a floating-point value. See Program 3.10 trunc1.java
in the end of chapter programs.
char
in assignmentIn C language, type integer
and type char
are treated as equal and exchangeable. A highly typed Java does not make such assumption. Also, size in bytes of these types also differs. Still Java considers type char
as something like an (16 bits) integer
. We are allowed to use operators like (++) with variables of type char
. As far as assignment is concerned, type char
can appear on right side of int
or float
or double
assignment expression. However, we cannot assign any non-character variable even of type byte
to character variable.
Table 3.15 Methods for Converting Real to Integer
Return type | Method | Description |
---|---|---|
Static double |
ceil (double x) |
Returns the smallest (closest to negative infinity) double value that is, not less than the argument and is equal to a mathematical integer |
Static double |
floor (double x) |
Returns the largest (closest to positive infinity) double value that is, not greater than the argument and is equal to a mathematical integer |
Static long |
round (double x) |
Returns the closest long to the argument |
Static int |
round (float x) |
Returns the closest int to the argument |
Figure 3.1 ceil
and floor
All these were natural and logical conversions. What about brute force? What if we want to convert anyway? What if we do not want to care about ensuing error? Well solution in that case is straightforward. We must use a technique called “typecasting”.
If we specify a type inside brackets ahead of any expression, then value of that expression is converted to value of type specified in a bracket. For example,
(int) 3.5 ;
This type of conversion will not alert us even if there is loss of information. Hence, such typecasting must be used with caution.
Final
The variables are for holding different values at different times. If we want to keep a value constant, we may declare a variable as final. Such a variable has to be initialized only once. For example,
final int j;
.
.
j = 30 ; // first initialization
If we try to modify its values at later stage, we will get compilation error.
It is possible to initialize such a variable at the time of declaration only.
For example,
final int j= 30 ;
See Program 3.12 on final1
at the end of chapter programs.
Please note that use of keyword final is equivalent to const declaration of C++. However, const
is a reserved word for future use in Java.
Program code consists of statements. Statements are separated by semicolon (;
) from each other. In general, computer executes statements one after the other. However, there are some statements, which changes or controls the flow of execution of statements. Let us discuss various types of statements briefly.
Any valid expression can be considered as expression statement. In general, expressions return a value. Hence, if it is not stored anywhere, action of such statement will not have any effect on the program. For example,
i+j;
The computer will add two values. But the result is not stored anywhere. Hence, such statements will be redundant. Hence, Java does not allow such expressions as statement. Note that in C++, such statements are valid.
Java allows only two types of expressions as statements. They are
Assignment expression and
Auto-increment/decrement expression.
This is fine as both these expression leave some effect after their evaluation.
See the following statement. It consists of assignment expression.
i = j+5;
This is a valid statement in Java.
Here right-hand side is evaluated and then the value is stored in variable appearing on the left-hand side. It means there is action associated with it.
This is the most fundamental statement in any programming language.
Another effective expression statement consists of auto-increment/decrement expressions. For example,
i++;
— —j;
Such expressions are evaluated and its effect is stored in the computer.
A call to a method is technically an expression. It returns a value after executing the body (which may imply action). Grammatically a method call is a valid statement.
When we write an expression with new operator, it creates an object.
That is,
Point origin = new Point (0,0);
This is a valid statement in Java. We will discuss this type of expression in detail in chapter on objects.
We need variables to be declared explicitly. Such statements can be considered as declaration statements. For example,
int myMarks =99; // out of 100!
We can group these statements in following manner:
The first group consists of decision-making statements.
Examples are if-else
and switch-case
statements.
Second group consist of looping statements.
Examples are while
, do-while
, and for
statements.
The third group consists of branching statements.
Examples are break
, continue
, label
, and return
statements.
The last group consists of exception handling statements.
Examples are try-catch-finally
and throw
statements.
These statements are discussed separately at a later stage.
When we do not write any statement, it effectively becomes null or empty statement. Consider two consecutive semicolons with some blanks in between.
; ;
These semicolons are containing a blank statement. Such blank statements are allowed in Java. (They are allowed in C/C too.) Here no action is involved. We do not know the logic in allowing such statements in a program.
These are source of errors when coupled with loops. The investor lost most of the interest on a fixed deposit when the programmer (of the bank) wrote the following code:
int_rate = 0.08;
balance = 1000;
for ( j=0;j<10;j++ );
balance = balance + balance * int_rate;
Strictly speaking, this is not a separate type of statement. Java allows us to attach a label to a statement. Most of the times, it will have no significance. Only when we use labelled break
or continue
statements, the label will have some importance. We are discussing such statements in a later chapter.
Officially, there is no distinction as simple or difficult Java program. Java is a very vast language. We cannot study it in one go. We have to study it step by step. Naturally, the programs in initial chapter must be very simple. They must be using only few of the large number of language facilities (or concepts). We are, therefore, describing (not defining) very simple Java program.
Very simple Java programs are as follows:
Special suggestion: Though it is not necessary, we should follow the practice of keeping every program in separate directory.
Problem: Write a program to demonstrate relational expression.
Solution: See Program 3.8.
PROGRAM 3.8 Relational Expression Returns Boolean
// relop1.java
class relop1
{ public static void main(String args[])
{ int k ;
boolean flag ;
System.out.println(“--->relop1.java<---”);
// k = 5>4 ;
flag = 5>4 ;
System.out.println(“ value of flag is : ” + flag);
}
}
If you run the program, you will get the following output.
Output
--->relop1.java<---
value of flag is : true
Notice the commented statement. If present, it would have resulted in following compilation error:
relop1.java:6: Incompatible type for =. Can’t convert
boolean to int.
k = 5>4 ;
^
1 error
press any key to continue
Problem: Write a program to study special characters.
Solution: See Program 3.9.
PROGRAM 3.9 Special Characters
// char3n.java
class char3n
{public static void main(String args[])
{ char x[]={'','f','
', '
', ' '} ;
int i ;
System.out.println("program char3n.java starts");
System.out.println("1. Writing back space --->" + x[0] + "<---") ;
System.out.println("2. Writing form feed --->" + x[1] + "<---" );
System.out.println("3. Writing new line --->" + x[2] + "<---" );
System.out.println("4. Writing return --->" + x[3] + "<---" );
System.out.println("5. Writing tab --->" + x[4] + "<---" );
System.out.println("--->the end<---");
}
}
If you run the program, you will get the following output.
Output
program char3n.java starts
1. Writing back space ---<---
2. Writing form feed --->†<---
3. Writing new line --->
<---
<---riting return --->
5. Writing tab ---> <---
--->the end<---
It is very surprising that characters 4. W
are missing from the output. Can you interpret the result?
Problem: Write a program to study truncation of a real number.
Solution: See Program 3.10.
PROGRAM 3.10 Truncating a Real Number
// trunc1.java
class trunc1
{ public static void main(String args[])
{ double a = 5.1;
double b = -3.99 ;
long i=0,j=0;
System.out.println(“--->trunc1<---”);
i = (long) a;
j = (long) b;
System.out.println(“truncating a -> ” +i);
System.out.println(“truncating b -> ” +j);
}
}
If you run this program, you will get the following output.
Output
--->trunc1<---
truncating a -> 5
truncating b -> -3
In this example we have used a brute force, that is typecast.
In school geometry, we learn equation of a straight line as
y = m*x + c
where m is the slope and c is the intercept on y-axis (Figure 3.2).
Let us write a program to compute them.
Problem: Write a program to find the slope and intercept on y-axis of a straight line. Assume that two points on the given straight line are specified.
Solution: Assume that two points are specified with coordinates as x1
, y1
and x2
, y2
(see Figure 3.2). By substituting these coordinates in the standard equation and rearranging the terms, we get following formulae:
m = (y2 - y1) / (x2 - x1)
c = y1 - m * x1
See Program 3.11.
Figure 3.2 Straight Line Slope and Intercept
PROGRAM 3.11 Straight Line Slope and Intercept
// PROGRAM 3.12 Straight Line slope and intercept
// line1.java
class line1
{ public static void main(String args[])
{ double x1, y1, x2, y2 ;
double m , c ;
System.out.println("<---line1.java--->");
x1= -1; y1 = 1;
x2=11; y2 =13;
m= (y2 - y1) / (x2 - x1);
c = y1- m*x1;
System.out.println(" slope= " + m);
System.out.println(" intercept = " + c);
}
}
If you run the program, you will get the following output.
Output
<---line1.java--->
slope= 1.0
intercept = 2.0
final
Problem: Write a program to study keyword final.
Solution: See Program 3.12.
// final1a.java
class final1a
{ public static void main(String args[])
{ int i = 20;
final int j =30;
System.out.println(“--->final1a.java starts<---”);
i = i + 30 ;
j = j + 20 ; // note 1
System.out.println(“i = ” + i);
System.out.println(“j = ” + j);
}
}
If you run the program, you will get the following compilation error.
Output
Compiling JDK6injavac final1a.java
final1a.java:10: cannot assign a value to final variable j
j = j + 20 ; // note 1
^
1 error
press any key to continue
Let us remove that line by commenting it out and run the program. In that case, you will get the following output.
Output
--->final1.java starts<---
i = 50
j = 30
AND
operator, Arithmetic Operators, Assignment operators, Bit-wise operators, Boolean operators, character set, comment, conditional operators, constant-character, constant-integer, constant-real, Constants, constant-string, Data types, Empty statement, Expression, final, keywords, literal, method main()
, modulo operator, Operators, OR
operator, post-decrement, post-increment, Pre-decrement, Pre-increment, reference, relational operators, shift operators, Statements, string-constant, Typecasting, Unicode character, variable
Relational expressions return Boolean value. Note C++ returns int.
You can assign a character variable to integer but not vice versa. In C++, you are allowed to do so.
“j+k
”; which is valid statement in C++, is invalid in Java
$
is not allowed as part or start of a variable name in C++. It is allowed in Java.
C++ does not flag compilation error, when un-initialized variables are used. This is sure to create unexpected errors. In this case, Java is a better language than C++.
There is no direct equivalent of “enum
” in Java. However, its effect can be obtained by defining an interface. Interface is discussed later in chapter on inheritance.
At present Java does not support keyword const
. If we want C++ like action of const on a variable, we have to make use of keyword final.
Java does not support the comma operator of C++. Inadvertent use of this operator produces many bugs in C++ programs.
round, ceil
, and floor
?char
as operands? **************************************
// default1.java
class default1
{ public static void main(String args[])
{ int i ;
float f ;
boolean b ;
System.out.println("<---default1.java starts--->");
System.out.println(" int i = " + i );
System.out.println(" float f = " + f );
System.out.println(" boolean b = " + b );
}
}
**************************************
**************************************
// logical2.java
class logical2
{ public static void main(String args[])
{ boolean semI = true ;
boolean semII = false ;
boolean resultA, resultB ;
System.out.println("<---logical2--->");
resultA = semI || 3 ;
resultB = 5 & 6;
System.out.println("resultA ->" +resultA);
System.out.println("resultB ->" +resultB);
}
}
**************************************
**************************************
// bit2.java
class bit2
{ public static void main(String args[])
{ float j ;
System.out.println("<---bit2--->");
j = 3.2f & 4.2;
System.out.println("j ->" + j );
}
}
**************************************
**************************************
// tcheck1.java
class tcheck1
{ public static void main(String args[])
{ char ch = ‘A’ ;
int i = ch ;
System.out.println("<---tcheck1.java--->");
System.out.println(ch + " " + i );
i = 66 ;
ch = i ;
System.out.println(ch + " " + i );
}
}
**************************************
**************************************
// tcheck2.java
class tcheck2
{ public static void main(String args[])
{ char ch = ‘A’ ;
int i ;
short j = 32000;
byte k = 5;
float a = ch;
System.out.println("<---tcheck2.java--->");
i = 66 + ch*4 ;
System.out.println("66 +ch " + i );
System.out.println("float a = " + a );
}
}
**************************************
3.144.119.170