2 Programming Concepts in Java — Java Programming
2.1 Introduction
Most of the concepts of Java programming language are similar to C/C++. The main advantage of Java is that it is fully object-oriented. The main objective of this chapter is to give you experience in compiling and running Java programs, introduce variables in Java, and introduce some of the primitive types in Java.
2.2 Variable declarations
The general format of variable declaration is
type varname;
Java is a strongly typed language. There are eight simple types of data: bytes, short, int, long char, float, double, and Boolean. These can be put into four groups.
2.2.1 Integers: Integer variables store whole numbers without decimals. They can be positive or negative numbers. There are four types of integers: long, int, short and byte.
Type | Size in bits | Size in bytes |
long | 64 bits | 8 bytes |
int | 32 bits | 4 bytes |
short | 16 bits | 2 bytes |
byte | 8 bits | 1 byte |
2.2.2 Floating point numbers: These variables represent numbers with fractional precision.
Type | Size in bits | Size in bytes |
float | 32 bits | 4 bytes |
double | 64 bits | 8 bytes |
2.2.3 Characters: A character variable size is 2 bytes. Java char type denotes characters in the Unicode encoding scheme. Unicode is a system of encoding. It is designed to handle almost all characters in all written languages of the world. The first 255 characters of this Unicode correspond to ASCII code.
Examples for variable declaration
byte a; // a is defined as a byte int b,c,d; //b,c,d are integers char e,f; // e,f are characters
2.2.4 Booleans: Boolean variable is used for logical values. It can have only two values, true or false.
Program 2.1 Printing boolean values
//booleanDemo.java
public class booleanDemo {
public static void main(String[] args) {
System.out.println("Hello World");
boolean var1 = true;
boolean var2 = false;
System.out.println(var1); // Outputs true
System.out.println(var2); // Outputs
false } }
//Output: //true //false
2.2.5 Escape Sequences: Finally the following are the escape sequences used to create a new line or tab and so on.
Escape sequence |
Description |
\ddd |
Octal character(ddd) |
\uxxxx |
Hexadecimal UNICODE char |
\’ |
Single quote |
\” |
Double quote |
\\ |
Backslash |
\r |
Carriage return |
\n |
New line |
\f |
Form feed |
\t |
Tab |
\b |
Blank |
** Java is case sensitive.
2.3 Scope and lifetime of variables
2.3.1 Scope of a variable
A variable’s scope is the block within which the variable is accessible, Also a variable scope decides when a variable is created and destroyed.
As a general rule, variable declared inside a scope is not visible to code that is defined outside that scope. Scopes can be nested. Outer scope encloses the inner scope. However, the reverse is not true. Objects declared within the inner scope will not be visible outside it.
The scope is demonstrated in the program 2.2.
Program 2.2 Program demonstrating scope.
//scopeDemo.java //Click here for code
public class scopeDemo
{
public static void main(String[] args) {
System.out.println("Hello World");
int a;
a=5;
if(a==5)
{ //start new scope
int b=20; //known only to this block
System.out.println("a="+a+" b="+b);
a=b*2;
}
/* b=100; error, b is unknown here and
a is known */
System.out.println("a is "+a);
}
}
//Output: a=5 b=20 a is 40
2.3.2 Lifetime of a variable
Lifetime of a variable occupies a significant portion of the programming effort. How long does the variable last? If you are supposed to destroy it, when should you? Java greatly simplifies the work by doing the entire clean up for us.
Program 2.3. Program to demonstrate lifetime of variable.
//lifedemo.java //Click here for code class lifedemo { public static void main(String args[]) { int i,j; for(j=0; j<3;j++) { i=1; System.out.println(i= +i); i=100; System.out.println(i= +i); } } } //Output: 1 100 1 100 1 100
i is initialized with 1 and then with 100 and i is again initialized with 1 and this repeats all three times. This is because, the lifetime of variable is within that block only.
2.4 Operator overloading
Although operator overloading would have been much simpler to implement in Java than it was in C++, this feature was considered still too complex. Java does not support Operator Overloading except for one case i.e “+” operator it can be used to add number as well as strings.
2.4.1 String operators+
If an expression begins with a String, then all operands that follow must be strings. Program 2.4 demonstrates that + operator can be overloaded to concatenate strings. Overloading means the operator can perform multiple operations. Here +operator is able to concatenate strings and numbers. Note that addition is not being done on numbers a, b and c but their values are concatenated.
Program 2.4. Program to demonstrate +operator
//stringOp.java //click here for code public class stringOp { public static void main(String[] args) { System.out.println("Hello World"); int a=0,b=1,c=2; String s="a,b,c"; System.out.println(s+a+b+c); } } //Output: a,b,c012
2.5 Size of data types in Java
In C and C++, the sizeof() operator satisfies a specific need. It tells the number of bytes allocated for data items. All the data types in Java are of the same size on all machines. We need not think about portability.
2.6 Type conversions and casting
2.6.1 Automatic conversion and casting
When one type of data is assigned to another type of a variable, automatic type conversion will take place. This is also called as implicit type conversion. For widening conversions, the numeric types including integer and floating point types are compatible with each other. However, numeric types are not compatible with char or boolean, char and boolean are not compatible with each other. There are two types of casting, namely widening and Narrowing.
a) Widening Casting : convert a smaller type to a larger type size
byte
-> short
-> char
-> int
-> long
-> float
-> double
b) Narrowing Casting : convert a larger type to a smaller size type
double
-> float
-> long
-> int
-> char
-> short
-> byte
2.6.2 Casting incompatible types
General form of casting incompatible types is
(Target-type) value;
Target-type specifies the desired type to convert the specified value to. The following are few examples for typecasting.
int a; byte b; double pi=3.1412; int x=(int)pi; //outputs 3 a=1 b=(byte) a; // outputs 1
Program 2.5 shows how to typecast from double to int.
Program 2.5 Program to demonstrate type casting
//typeCasting.java //click here for code public class typeCasting { public static void main(String[] args) { System.out.println("Hello World"); int wide_mark = 85; double wide_money = wide_mark; // casting int to double System.out.println(wide_mark); System.out.println(wide_money); double narrow_money=85.0; int narrow_mark; narrow_mark=(int)narrow_money; //type cast System.out.println(narrow_mark); System.out.println(narrow_money); } } //Output: 85 85.0 85 85.0
2.7 Constants
These values can not be changed during the program’s execution.
Example:
//num is a variable of type double
static final double num 1.40;
Setting a variable to final will prevent it from being overridden and cannot be modified.
The variable num is declared as static. That means num variable belongs to the class where it is defined. Even if an instance(object) is created for this class, it will not belong to that instance. In other words, there can be only one copy of the variable num in main memory. Functions can also be declared static. An example is given in Chapter 1.
2.8 Operators
Operators are two types.
Unary operators: Operators requiring one operand. Example: ++.
Binary operators: Operators that require two operands. Examples: +, –
2.8.1 Arithmetic operators
Operators like +,-,*,/,% are arithmetic operators.
Operator | Description |
+ | Addition: c=a+b |
– | Subtraction: c=a-b |
* | Multiplication: c=a*b |
/ | Division: c=a/b |
% | Reminder after division: c=a%b |
2.8.2 Exponentiation
There is no ‘^’ sign. The function pow() must be used. It is built in java.lang package.
2.8.3 Increment and Decrement operators(++,–)
Increment and decrement operators are the additional arithmetic operators. Consider the following statements.
i++; //i is incremented after operation, m–; //m is decremented after operation, ++j; //j is incremented before operation, –n; //n is decremented before operation.
2.8.4 Bitwise operators
Bitwise operator |
Description |
Usage |
& |
AND |
c=a&b |
| |
OR |
c=a|b |
^ |
XOR |
c=a^b |
! |
NOT |
c=!b |
>> |
SHIFT RIGHT |
c=>>a |
<< |
SHIFT LEFT |
c=<<a |
2.9 Parenthesis and operator hierarchy
Operator |
Description of hierarchy |
[ ] ( ) |
Left to right |
! ++ = +(unary) () (cast) |
Right to left |
*/ % |
Left to right |
+ – |
Left to right |
<< <= > >= instanceof |
Left to right |
== != |
Left to right |
& |
Left to right |
^ |
Left to right |
| |
Left to right |
&& |
Left to right |
|| |
Left to right |
?: |
Left to right |
= += -=/= %= &= \= ^= <<= >>= |
Right to Left |
2.10 Relational Operators ( Comparison)
Operator |
description |
== |
Equals |
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
!= |
Not equal to |
&& |
AND Operator |
|| |
OR Operator |
2.11 Expressions
An expression is a collection of variables and operators that specify a computation. Expressions are used to perform operations on the data in program.
For example,
c=a+b;
In the above example a+b is an expression, the result is computed and is assigned to c.
2.12 Summary
You have been introduced to the variables, expression, operators, scope, lifetime of variables. In the next chapters we will be using these concepts.