Mahavir Polytechnic Department of Computer Engineering Unit - I
Mahavir Polytechnic Department of Computer Engineering Unit - I
Mahavir Polytechnic Department of Computer Engineering Unit - I
Unit – I
Basic Syntactical Constructs in Java
What is Java
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from
humble beginnings to power a large share of today’s digital world, by providing the reliable platform upon which many services
and applications are built. New, innovative products and digital services designed for the future continue to rely on Java, as
well.
Java ही एक प्रोग्रॅमिंग भाषा आणि संगणकीय प्लॅटफॉर्म आहे जी सन मायक्रोसिस्टम्सने 1995 मध्ये प्रथम प्रसिद्ध के ली आहे. ती विनम्र सुरुवातीपासून विकसित झाली आहे, ज्यामुळे आजच्या डिजिटल जगाचा मोठा वाटा आहे, ज्यावर अनेक सेवा आणि अनुप्रयोग
. ,
तयार के ले जातात भविष्यासाठी डिझाइन के लेली नवीन नाविन्यपूर्ण उत्पादने आणि डिजिटल सेवा देखील Java वर अवलंबून राहतील.
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.
Even for the same machine, there may be some upgrades in operating system,
system resources or even processor. So, the main goal while designing java programming
language was making it platform independent (program may run on any platform),
architecture-neutral (program may run on any processor-operating_system combination)
and portable (program developed on one architecture/machine may run on any other
architecture/machine).
Java provides portability in two ways. Byte-code generated by java compiler is
machine-independent. Also, sizes of primitive data types of java are machine-
independent.
1.1.2 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.3 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.4 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.5 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.6 Multi-threaded
Java supports multi-threaded programming. It allows writing a program that does
many things simultaneously.
1.1.7 . 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
}
}
can de
In java can be defined within class only (not like C++ where we
methods 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;
int y;
void getd( )
{
//body of getd( )
}
void putd( )
{
//body of putd( )
}
}
1.2.2 Creating object
Class is just a declaration. It does not create actual object. Creating an object is a
two-step process. In first step, variable of class type is declared with following syntax.
class-name variable-name;
e.g. point p;
This is not an object. It is just a variable which can refer to an object. In second
step we have to acquire actual object and assign it to the variable with following syntax.
variable-name = new class-name( );
e.g. p = new point( );
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,
class-name variable-name = new class-name( );
e.g. point p = new point( );
Examples:
p.x=10;
p.display( );
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,
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[,…]];
We may also use array-initializer for initializing the arrays as follows. int a[ ] =
{12, 14, 5, 78, 35, 25};
//creates array of six integers with the values mentioned
//as their initial values.
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”
String class supports various methods. Some of them are explained in table 1.2.
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 n th 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
1.4.1.1 Arithmetic Operators
Java provides all the basic arithmetic operators. They are shown in Table
1.3. These operators can operate on built-in data types of Java.
Table 1.3: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo Division (used with only integers)
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;
During the type conversion, some changes may occur as,
- float to int – truncation of fractional part
- long to int – dropping of excess higher order bits
- double to float – rounding of digits
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.
There might be a need where we have to nest different if-else statements within
one another. Such statements are called nested if. Syntax for the same is given below.
if(test-condition1)
{
if(test-condition2)
{
Statement-block A
}
else
{
Statement-block B
}
}
else
{
if(test-condition3)
{
Statement-block C
}
else
{
Statement-block D
}
}
Sometimes we have to take alternate decisions on the previous tes conditions.
This can be achieved with the help of if-else-if ladder. Syntax for the same is given below.
if(test-condition1)
{
Statement-block A
}
else if(test-condition2)
{
Statement-block B
}
else if(test-condition3)
{
Statement-block C
}
else
{
Statement-block D
}
1.5.1.2 switch statement
We can use switch statement for selection among multiple choices. Syntax for
switch-case is given below.
switch(choice)
{
case value1:
Stament-block A
break;
case value2:
Stament-block B
break;
--
default:
Stament-block Z
}
One may also use nested switch-case. i.e. one switch-case in another.
1.5.1.3 Conditional operator (? : operator)
This operator is already discussed in 1.4.1.6.
Example:
//Code for deciding whether given number is prime or not
int n=23;
int i;
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”);
}
1.5.2.6 continue statement
We can use continue statement if we want to skip remaining part of current
iteration and continue to next iteration of the loop.
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);
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;
}
}
}
Important Questions:
1.State any four features of java.
2.Why java is a object oriented language.
3.Differentiate between C,C++ and Java.
4.Explain Decision making and looping statements in java.
5.List java tokens.