Unit I Basic Syntactical Constructs in Java
Unit I Basic Syntactical Constructs in Java
Java derives its syntax from C. Object oriented features of Java are
influenced by C++.
1.1.1 Simple
Java is a simple programming language. It is easy for programmer to
learn and use. For a programmer who knows C, learning java is easy. For a
programmer having experience of C++, very less energy will be required for
learning and using java.
Also some of the confusing concepts in C/C++ are either removed in java
or are made simpler. (e.g. pointers, preprocessor header files, goto, operator
overloading, multiple inheritance)
1.1.2 Object-Oriented
Java is a true object-oriented language. Everything in java is in the form
of classes and objects. Even main( ) method is also a method of a class. Object
model in java is simple and easy to extend.
5-1
byte-code can run on any system that provides Java Virtual Machine. Thus java
enables creation of cross-platform programs.
1.1.5 Robust
As java is application language for World Wide Web, the program needs
to be run reliably on any platform at any web location. To bring this robustness,
java forces programmer to find the mistakes in the program at early stage of
program development. As java is strictly typed language, it strictly checks the
code at compile-time. The code is again checked at run-time.
The main reasons for failure of any program are memory management
mistakes and mishandled exceptions. In java dynamic memory allocation and
de-allocation is not needed to be handled by programmer, it is handled by java
itself. Also java provides object oriented exception handling for dealing with the
exceptions. Due to this risk of crashing of the program is eliminated.
1.1.6 Secure
Security is an important concern for the languages that are used for
programming on Internet. Java system verifies all memory accesses. It also
ensures that no virus is communicated through applet.
1.1.7 Dynamic
Java is a dynamic language. Java program carries significant amount of
run-time information, which is used to verify and resolve accesses to objects at
run-time. Due to this, code can be linked dynamically in a safe manner.
1.1.8 Distributed
Java is designed for distributed environment of Internet. Using Remote
Method Invocation (RMI) package of java, procedures can be called from remote
locations. Thus multiple programmers at multiple locations can may collaborate
on the same project.
1.1.9 Multi-threaded
Java supports multi-threaded programming. It allows writing a program
that does many things simultaneously.
5-2
1.1.10 High performance
Java performs well even on low-power CPUs. Java byte-code is designed
so that it can be easily translated to machine-code for high performance using
Just-In-Time compiler.
Also, java architecture is designed to reduce overheads during run-time.
class classname
{
data-type instance-variable1;
data-type instance-variable2;
---
data-type instance-variableN;
return-type methodname1(parameter-list)
{
// Body of method
}
return-type methodname2(parameter-list)
{
// Body of method
}
---
return-type methodnameN(parameter-list)
{
// Body of method
}
}
In java methods can be defined within class only (not like C++ where we
can de
fine the member functions outside the class). In C++ class definition ends
with a semicolon. But in java class definition ends with mere closing brace.
Example:
class point
{
int x;
5-3
int y;
void getd( )
{
//body of getd( )
}
void putd( )
{
//body of putd( )
}
}
class-name variable-name;
e.g. point p;
The new operator allocates memory required for an object of the specified
class and returns reference to it.
The above two steps may be combined together for object creation as,
Examples:
p.x=10;
p.display( );
1.3.1.1 Keywords
The reserved words whose meaning is predefined with Java are called
keywords. There are 50 keywords in Java. All keywords are in lower-case only.
As the keywords are having specific meaning, we cannot use them as identifiers.
The keywords in Java are listed below.
1.3.1.2 Identifiers
They are used for naming classes, methods, variables, objects, labels,
packages and interfaces. Rules for defining identifiers are as follows,
- Allowed characters in identifiers are: alphabets (A-Z, a-z), digits (0-9),
underscore (_) and dollar ($). No any other character can be used in
identifier.
- Identifiers should not begin with a digit.
- They can be of any length.
- Keyword cannot be used as identifier.
1.3.1.3 Literals
Sequence of characters (may contain digits, alphabets or other characters)
that represent constant values to be stored in variables are called literals. There
can be different types of literals as integer literals, floating-point literals,
character literals, string literals and Boolean literals.
1.3.1.4 Operators
Operator is a symbol(s) that takes one or more arguments (operands) and
performs an operation on the operands. Operators will be discussed in detail in
1.4.
1.3.1.5 Separators
The symbols that are used identifying the separation of group of code are
called separators. Various separators in Java are shown in table 1.1,
5-5
1.3.2 Constants
The thing of which value cannot be changed throughout the execution of a
program is called a constant. In Java constants are classified as numeric
constants and string constants. Numeric Constants can be either integer
constants or real constants. String constants can be either single character
constants or string constants.
Integer constants are the constants of integer type. They can contain
only digits and/or sign (in case of hexadecimal constants ‘x’ or ‘X’ is allowed
along with ‘a’ to ‘f’ or ‘A’ to ‘F’). Some of the examples of integer constants are,
172 -53 0x3A 0x4bc
Real constants are the constants of values that represent real-world
entities like price, temperature etc. They can contain digits, decimal point
and/or sign. We can also have constants in exponential representation.
72.54 -53.0 0.67 1.23e-4 0.51E8
Single character constants contain single character enclosed within
single quotation marks.
‘M’ ‘y’ ‘&’ ‘3’
String constants contain sequence of characters enclosed within double
quotation marks.
“Sanjivani” “Java 2 Programming” “b4u”
Java also supports escape sequences. Some of escape sequences are
listed below.
‘\b’ Backspace
‘\n Newline
‘\t’ Horizontal tab
‘\’ ‘ Single quote
‘\” ‘ Double quote
‘\\’ Backslash
1.3.3 Variables
The thing of which value can be changed throughout the execution of a
program is called a variable. We have already discussed about rules for naming
variables in Java in 1.3.1.2. Syntax for declaring variable is as follows,
data-type identifier-name[,identifier-name[,…]];
5-6
int x=-145;
byte
- It is smallest integer data type which can hold signed whole numbers.
- Memory required is 1 byte or 8 bits
- Range: -128 to 127
- Keyword: byte
- Example: byte a,b;
- Default value is 0.
short
- It is integer data type which can hold signed whole numbers.
- Memory required is 2 bytes or 16 bits
- Range: -32768 to 32767
- Keyword: short
- Example: short x,y;
- Default value is 0.
int
- It is integer data type which can hold signed whole numbers.
- Memory required is 4 bytes or 32 bits
- Range: -2147483648 to 2147483647
- Keyword: int
- Example: int m,n;
- Default value is 0.
long
- It is integer data type which can hold signed whole numbers.
- Memory required is 8 bytes or 64 bits
- Range: -9223372036854775808 to 9223372036854775807
- Keyword: long
- Example: long e,f;
5-7
- Default value is 0.
float
- It is floating point data type which can hold single-precision floating
point numbers.
- Memory required is 4 bytes or 32 bits
- Range: 1.4e-45 to 3.4e+38
- Keyword: float
- Example: float result;
- Default value is 0.0.
double
- It is floating point data type which can hold double-precision floating
point numbers.
- Memory required is 8 bytes or 64 bits
- Range: 4.9e-324 to 1.8e+308
- Keyword: double
- Example: double r,a;
- Default value is 0.0.
char
- It is non-numeric data type which can hold single character. Java used
Unicode to represent characters. Unicode defines a fully international
character set that can represent all the characters found in all human
languages.
- Memory required is 2 bytes or 16 bits
- Range: 0 to 65535 (Standard ASCII characters range within 0 to 127 of
this range)
- Keyword: char
- Example: char ch1,ch2;
- Default value is null.
boolean
- It is Boolean data type which can hold logical values as true or false.
- Memory required is 8 bytes or 64 bits
- Range: true or false
- Keyword: boolen
- Example: boolean temp;
- Default value is false.
5-8
1.3.7 Arrays
Array is a collection of elements of same data type. All the elements of
array are referred by same name. Arrays can have one or more dimensions.
Arrays in java work somewhat different as compared to C/C++.
One-dimensional array can be declared as,
data-type arr-name[ ];
Here arr-name is a reference only. No any memory is allocated to this
array. Memory allocation may be done with the help of new as follows,
arr-name = new data-type[size];
Example:
int a[ ]; //reference creation
a = new int[15]; //Reference is referring to array of 15 integers
1.3.8 Strings
In Java, string is neither a primary data type nor an array of characters.
Rather, String defines an object. String type is used to declare string variables.
It may be done as follows,
String str;
str = new String( );
We may also initialize the string at the time of creation only as follows,
String str;
str = new String(“Sanjivani”); //str contains “Sanjivani”
Java strings may be concatenated using ‘+’ operator as follows,
String s3 = s1 + s2;
String str = “Kopargaon” + “Bet”
5-9
Table 1.2: Some Methods of String class
Method Call Use
s2 = s1.toLowerCase( ); Converts string s1 to lowercase and stores result in s2
s2 = s1.toUpperCase( ); Converts string s1 to uppercase and stores result in s2
s1.equals(s2) Returns true if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns true if s1 is equal to s2 (ignoring case)
s2=s1.trim( ); Removes white spaces at the beginning and end of
string s1 and copies it to s2
s1.length( ) Returns length of s1
s1.charAt(n) Returns character at ‘n’ location
s1.compareTo(s2) Returns negative value (<0), if s1<s2
Returns positive value (>0), if s1>s2
Return zero, if s1 = s2
s1.concat(s2) Concatenates s1 and s2
s1.substring(n) Returns substring starting from nth character
s1.substring(n,m) Returns substring starting from nth character up to mth
character (not including mth character)
1.4.1 Operators
Operators of Java can be classified as,
- Arithmetic operators
- Relational operators
- Logical operators
- Assignment operators
- Increment/decrement operators
- Conditional operator
- Bit-wise operators
- Special operators
5-10
Table 1.4: Relational Operators
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
5-11
These operators are used for increasing or decreasing value of a
variable by 1. These operators are unary operators and require a variable
as their operand.
When postfix ++ (or – –) is used with a variable in an expression,
the expression is evaluated with original value of variable and then the
variable is incremented (or decremented).
When prefix ++ (or – –) is used with a variable in an expression,
the variable is incremented (or decremented) and then the expression is
evaluated with new value of variable.
Automatic type conversion is very much helpful. But it does not always
fulfill the requirements. In many situations there is a need to change data type
of a value temporarily. This may be required while assigning value to other
variable or in evaluation of an expression. It is achieved through typecasting. (In
case of compatible types, it may happen automatically.) Typecasting is
explicit type conversion between two incompatible types. Syntax of
typecasting is as follows,
(target-type) value
Example:
int i=10;
short s=(short)i;
5-14
Table 1.11: Important Methods of Math class
Method Use
min(a,b) Returns minimum of a and b
max(a,b) Returns maximum of a and b
sqrt(x) Returns square root of a
pow(x,y) Returns x raised to the power y (xy)
exp(x) Returns e raised to the power x (ex)
round(x) Returns closest integer to x
floor(x) Returns largest whole number less than or equal to x (Rounding
down)
ceil(x) Returns smallest whole number greater than or equal to x
(Rounding up)
abs(a) Returns absolute value of x
log(x) Returns natural logarithm of x
sin(x) Returns sine value of angle x in radians
cos(x) Returns cosine value of angle x in radians
tan(x) Returns tangent value of angle x in radians
asin(y) Returns sine inverse of y
acos(y) Returns cosine inverse of y
atan(y) Returns tangent inverse of y
1.5.1.1 if statement
We can use selection statement if in different ways as,
- if
- if-else
- nested if
- if-else-if ladder
If the selection is to be done between two opposite criteria, we may use ‘if-
else’. Its syntax is as follows,
if(test-condition)
{
Statement-block A
}
else
{
Statement-block B
}
The Statement-block A gets executed if the test-condition gives true
result. Otherwise Statement-block B gets executed.
5-16
{
Statement-block B
}
else if(test-condition3)
{
Statement-block C
}
else
{
Statement-block D
}
One may also use nested switch-case. i.e. one switch-case in another.
1.5.2.1 while
Syntax of while loop is as follows.
1.5.2.3 for
Syntax of for loop is as follows.
Example:
int a[ ] = {21,42,63,84,105};
for(int x : a)
{
System.out.println(x);
}
Output:
21
42
63
84
105
Example:
//Code for deciding whether given number is prime or not
int n=23;
int i;
5-18
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
break;
}
}
if(i>n/2)
{
System.out.println(“Numer is prime”);
}
else
{
System.out.println(“Numer is not prime”);
}
Example
//import java.io.*;
//Code for summing five integers (should be non-negative)
int sum=0;
int i,x;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for(i=0;i<5;i++)
{
x=0;
try
{
System.out.println(“Enter a value: ”);
x = Integer.parseInt(br.readLine( ));
if(x<=0)
{
continue;
}
}
catch(IOException e)
{
System.out.println(e);
}
sum=sum+x;
}
System.out.println(“Summation of non-negative numbers is: ”+sum);
5-19
1.5.2.7 return statement
The return statement immediately terminates the method in which it is
executed and returns to the caller of that method. The return statement may or
may not return a value to the caller of the method.
Example:
L1: for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
}
}
The labeled loops help in jumping the control of execution to any loop. In
the following example, control of execution is continuing to outer loop instead of
inner loop.
Outer: for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i>j)
{
continue Outer;
}
}
}
5-20