Module_1_java.pdf
Module_1_java.pdf
MODULE 1
Dept of CS&E,KVGCE
1
Object Oriented Programming with JAVA BCS306A Module 1
System and do not have to compile the program again and again on different
Operating Systems. The meaning of this point can be understood as you read
further.
C and C++ are platform dependent languages as the file which compiler
of C,C++ forms is a .exe(executable) file which is operating system
dependent. The C/C++ program is controlled by the operating system whereas,
the execution of a Java program is controlled by JVM (Java Virtual Machine).
The JVM is the Java run-time system and is the main component of making the
java a platform independent language. For building and running a java
application we need JDK(Java Development Kit) which comes bundled with Java
runtime environment(JRE) and JVM. With the help of JDK the user compiles
and runs his java program. As the compilation of java program starts the Java
Bytecode is created i.e. a .class file is created by JRE. Bytecode is a highly
optimized set of instructions designed to be executed by JVM. Now the JVM
comes into play, which is made to read and execute this bytecode. The JVM is
linked with operating system and runs the bytecode to execute the code
depending upon operating system. Therefore, a user can take this class
file(Bytecode file) formed to any operating system which is having a JVM
installed and can run his program easily without even touching the syntax of
a program and without actually having the source code. The .class file which
consists of bytecode is not user- understandable and can be interpreted by JVM
only to build it into the machine code.
Remember, although the details of the JVM will differ from platform to platform,
all understand the same Java bytecode. If a Java program were compiled to
native code, then different versions of the same program would have to exist for
each type of CPU connected to the Internet. This is, of course, not a feasible
solution. Thus, the execution of bytecode by the JVM is the easiest way to create
truly portable programs. Java also has the standard data size irrespective of
operating system or the processor. These features make the java as a portable
(platform-independent) language.
Dept of CS&E,KVGCE
2
Object Oriented Programming with JAVA BCS306A Module 1
directly compiling Java bytecode into native platform code, thereby relieving the
JVM of its need to manually call underlying native system services. When JIT
compiler is installed, instead of the JVM calling the underlying native operating
system, it calls the JIT compiler. The JIT compiler in turn generates native code
that can be passed on to the native operating system for execution. This makes
the java program torun faster than expected.
Moreover, when a JIT compiler is part of the JVM, selected portions of bytecode
are compiled into executable code in real time, on a piece-by-piece, demand
basis. It is important to understand that it is not practical to compile an entire
Java program into executable code all at once, because Java performs various
run-time checks. Instead, a JIT compiler compiles code as it is needed, during
execution. Furthermore, not all sequences of bytecode are compiled—only those
that will benefit from compilation. The remaining code is simply interpreted.
1.2 Object-Oriented Programming
Two Paradigms
Every program consists of two elements viz. code and data. A program is
constructed based on two paradigms: a program written around what is
happening (known as process-oriented model) and a program written
around who is being affected (known as object-oriented model). In
process-oriented model, the program is written as a series of linear (sequential)
steps and it is thought of as code acting on data. Since this model fails to
focus on real-world entities, it will create certain problems as the program grows
larger.
The object-oriented model focuses on real-world data. Here, the program is
organized as data and a set of well-defined interfaces to that data. Hence, it can
be thought of as data controlling access to code. This approach helps to
achieve several organizational benefits.
Abstraction
Abstraction can be thought of as hiding the implementation details from
the end-user. A powerful way to manage abstraction is through the use of
Dept of CS&E,KVGCE
3
Object Oriented Programming with JAVA BCS306A Module 1
Dept of CS&E,KVGCE
4
Object Oriented Programming with JAVA BCS306A Module 1
Dept of CS&E,KVGCE
5
Object Oriented Programming with JAVA BCS306A Module 1
javac Prg1.java
(Note: You have to store the file Prg1.java in the same location as that of javac
compiler or you should set the Environment PATH variable suitably.)
Now, the javac compiler creates a file Prg1.class containing bytecode version
of the program, which can be understandable by JVM. To run the program, we
have to use Java application launcher called java. That is, use the command –
java Prg1
The output of the program will now be displayed as –
Hello World!!!
Note: When java source code is compiled, each class in that file will be put into
separate output file having the same name as of the respective class and with
the extension of .class. To run a java code,we need a class file containing
main() function (Though, we can write java program without main(), for thetime-
being you assume that we need a main() function!!!). Hence, it is a tradition to
Dept of CS&E,KVGCE
6
Object Oriented Programming with JAVA BCS306A Module 1
give the name of the java source code file as the name of the class containing
main() function.
Let us have closer look at the terminologies used in the above program now –
class is the keyword to declare a class.
Prg1 is the name of the class. You can use any valid identifier for a class
name.
main() is name of the method from which the program execution starts.
public is a keyword indicating the access specifier of the method. The public
members can be accessed from outside the class in which they have
been declared. The main() function must be declared as public as it
needs to be called from outside the class.
static The keyword static allows main() to be called without having to
instantiate a particular instance of the class. This is necessary since
main() is called by the Java Virtual Machine before any objects are
made.
Void indicates that main() method is not returning anything.
String args[ ] The main() method takes an array of String objects as a
command-line argument.
Dept of CS&E,KVGCE
7
Object Oriented Programming with JAVA BCS306A Module 1
In the above program, we have declared an integer variable n and then assigned
a value to it. Now, observe the statement, System.out.println(“The value of n is:
” + n);
Here, we are trying to print a string value “The value of n is:” and also value of
an integer n together. For this, we use + symbol. Truly speaking, the value of n
is internally converted into string type and then concatenated with the string
“The value of n is:”. We can use + symbol as many times as we want to print
several values.
The above program uses one more method System.out.print() which will keep
the cursor on the same line after displaying the output. That is, no new line is
not included in it.
Though control structures are discussed in Module 2, here we will glance two
important structures which are needed for some of the examples in the current
Module.
if Statement: When a block of code has to be executed based on the value of a
Dept of CS&E,KVGCE
8
Object Oriented Programming with JAVA BCS306A Module 1
if(x < y)
System.out.println("x is less than y");
x = x * 2;
if(x == y)
System.out.println("x now equal to y");
x = x * 2;
if(x > y)
System.out.println("x now greater than y");
if(x == y)
System.out.println("you won't see this");
}
}
The output would be –
x is less than y
x now equal to y
x now greater than y
Dept of CS&E,KVGCE
9
Object Oriented Programming with JAVA BCS306A Module 1
Dept of CS&E,KVGCE
10
Object Oriented Programming with JAVA BCS306A Module 1
{ //
block
begins
x = y;
y = 0;
} // block ends here
Comments : There are three types of comments defined by Java. Two of these
are well-know viz.
1 . single- line comment ( starting with //),
2. multiline comment (enclosed within /* and */).
3. documentation comment is used to produce an HTML file that
documents your program. The documentation comment begins
with a /** and ends with a */.
Dept of CS&E,KVGCE
11
Object Oriented Programming with JAVA BCS306A Module 1
shown in the Table 1.1. These keywords, combined with the syntax
of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as names for a variable,
class, or method.
Table 1.1 Keywords
Abstrac Assert Boolea Break byt case catch char Whil
t n e e
Contin Default Goto Do doubl else enum extend
ue e s
Float For If impleme impor instance int interfa
nts t of ce
New Package Privat protected publi return short static
e c
Switch synchroniz This Throw thro transien try void
ed ws t
Class const Final finally Long native Strictf Super
p
The keywords const and goto are reserved but are rarely used. In addition to
the keywords, Java reserves the following: true, false, and null. These are
values defined by Java. You may not use these words for the names of variables,
classes and so on.
Separators : In Java, there are a few characters that are used as separators.
The most commonly used separator in Java is the semicolon
which is used to terminate statements. The separators are shown
in the Table 1.2:
Table 1.2 Separators
Symbol Name Purpose
Dept of CS&E,KVGCE
12
Object Oriented Programming with JAVA BCS306A Module 1
Dept of CS&E,KVGCE
13
Object Oriented Programming with JAVA BCS306A Module 1
every type is strictly defined. And, all assignments, whether explicit or via
parameter passing in method calls, are checked for type compatibility. There
are no automatic coercions or conversions of conflicting types as in some
languages. The Java compiler checks all expressions and parameters to ensure
that the types are compatible. Any type mismatches are errors that must be
corrected before the compiler will finish compiling the class. These features of
Java make it a strongly typed language.
Integers
Java defines four integer types viz. byte, short, int and long. All these are
signed numbers and Java does not support unsigned numbers. The width of an
integer type should not be thought of as the amount of storage it consumes, but
rather as the behaviour it defines for variables and expressions of that type. The
Java run-time environment is free to use whatever size it wants, as long as the
types behave as you declared them. The width and ranges of these integer
types vary widely, as shown in this table 1.3:
Dept of CS&E,KVGCE
14
Object Oriented Programming with JAVA BCS306A Module 1
byte: This is the smallest integer type. Variables of type byte are especially
useful when you are working with a stream of data from a network or file.
They are also useful when you are working with raw binary data that may
not be directly compatible with Java’s other built-in types. Byte variables are
declared by use of the byte keyword.
For example,
byte b, c;
short : It is probably the least-used Java type. Here are some examples of
short variable declarations: short s;
short t;
int : The most commonly used integer type is int. In addition to other uses,
variables of type int are commonly employed to control loops and to index
arrays. Although you might think that using a byte or short would be more
efficient than using an int in situations in which the larger range of an int is
not needed, this may not be the case. The reason is that when byte and
short values are used in an expression they are promoted to int when the
expression is evaluated. (Type promotion is described later in this chapter.)
Therefore, int is often the best choice when an integer is needed.
long : It is useful for those occasions where an int type is not large enough
to hold the desired value. The range of a long is quite large. This makes it
useful when big, whole numbers are needed.
Program 1.5: Program to illustrate need for long data type
class Light
{
public static void main(String args[ ])
{
int lightspeed;
long days, seconds, distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute
distance
System.out.print("In " + days);
Dept of CS&E,KVGCE
15
Object Oriented Programming with JAVA BCS306A Module 1
float : The type float specifies a single-precision value that uses 32 bits of
storage. Single precision is faster on some processors and takes half as much
space as double precision, but will become imprecise when the values are
either very large or very small. Variables of type float are useful when you
need a fractional component, but don’t require a large degree of precision.
For example, float can be useful when representing currencies, temperature
etc. Here are some example float variable declarations:
float hightemp, lowtemp;
double : Double precision is actually faster than single precision on some
modern processors that have been optimized for high-speed mathematical
calculations. All transcendental math functions, such as sin( ), cos( ), and
sqrt( ), return double values. When you need to maintain accuracy over
many iterative calculations, or are manipulating large-valued numbers,
double is the best choice.
Program 1.6 Finding the area of a cirlce
class Area
{
public static void main(String args[])
{
double pi, r, a; r =
Dept of CS&E,KVGCE
16
Object Oriented Programming with JAVA BCS306A Module 1
10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
The output would be –
Area of circle is 366.436224
Characters
In Java, char is the data type used to store characters. In C or C++, char is of 8
bits, whereas in Java it requires 16 bits. Java uses Unicode to represent
characters.
Dept of CS&E,KVGCE
17
Object Oriented Programming with JAVA BCS306A Module 1
/*ch1=35;
ch2=30;
char ch3;
ch3=ch1+ch2;//Error*/
ch2='6'+'A'; //valid
System.out.println("ch2 now contains "+ch2);
}
}
Booleans
For storing logical values (true and false), Java provides this primitive data
type. Boolean is the output of any expression involving relational operators. For
control structures (like if, for, while etc.) we need to give boolean type. In C or
C++, false and true values are indicated by zero and a non-zero numbers
respectively. And the output of relational operators will be 0 or 1. But, in Java,
this is not the case. Consider the following program as an illustration.
Dept of CS&E,KVGCE
18
Object Oriented Programming with JAVA BCS306A Module 1
b is false
b is
true
True
block
3<5 is true
NOTE: Size of a Boolean data type is JVM dependent. But, when Boolean
variable appears in an expression, Java uses 32-bit space (as int) for Boolean to
evaluate expression.
2.3 A Closer Look at Literals
Integer Literals
Integers are the most commonly used type in the typical program. Any whole
number value is an integer literal. For example, 1, 25, 33 etc. These are all
decimal values, having a base 10. With integer literals we can use octal (base 8)
and hexadecimal (base 16) also. Octal values are denoted in Java by a leading
zero. Normal decimal numbers cannot have a leading zero. Thus, a value 09 will
produce an error from the compiler, since 9 is outside of octal’s 0 to 7 range.
Hexadecimal constants denoted with a leading zero-x, (0x or 0X). The range of
a hexadecimal digit is 0 to 15, so A through F (or a through f ) are substituted for
10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. It is
possible to assign an integer literal to other integer types like byte or long.
Dept of CS&E,KVGCE
19
Object Oriented Programming with JAVA BCS306A Module 1
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean
value can have, true and false. The values of true and false do not convert
into any numerical representation. The true literal in Java does not equal 1, nor
does the false literal equal 0. In Java, they can only be assigned to variables
declared as boolean, or used in expressions with Boolean operators.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit
values that can be converted into integers and manipulated with the integer
operators, such as the addition and subtraction operators. A literal character is
represented inside a pair of single quotes. All of the visible ASCII characters can
be directly entered inside the quotes, such as ‘a’, ‘z’, and ‘@’. For characters
that are impossible to enter directly, there are several escape sequences that
allow you to enter the character youneed, such as ‘\’’ for the single-quote
character itself and ‘\n’ for the new-line character.
There is also a mechanism for directly entering the value of a character in octal
or hexadecimal. For octal notation, use the backslash followed by the three-digit
number. For example, ‘\141’ is the letter ‘a’. For hexadecimal, you enter a
backslash-u (\u), then exactly four hexadecimal digits. Following table 1.4 shows
Dept of CS&E,KVGCE
20
Object Oriented Programming with JAVA BCS306A Module 1
2.4 Variables
The variable is the basic unit of storage. A variable is defined by the combination
of an identifier, a type, and an optional initializer. In addition, all variables have a
scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form
of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is any of primitive data type or class or interface. The identifier is the
name of the variable. We can initialize the variable at the time of variable
Dept of CS&E,KVGCE
21
Object Oriented Programming with JAVA BCS306A Module 1
declaration. To declare more than one variable of the specified type, use a
comma-separated list. Here are several examples of variable declarations of
various types. Note that some include an initialization.
int a, b=5, c;
byte z = 22;
double pi = 3.1416;
char x = '$';
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java
allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared. For example,
int a=5, b=4;
int c=a*2+b; //variable declaration and dynamic initialization
The key point here is that the initialization expression may use any element
valid at the time of the initialization, including calls to methods, other variables,
or literals.
The scope defined by a method begins with its opening curly brace. However, if
that method has parameters, they too are included within the method’s scope.
As a general rule, variables declared inside a scope are not visible (that is,
accessible) to code that is defined outside that scope. Thus, when you declare a
variable within a scope, you are localizing that variable and protecting it from
unauthorized access and/or modification. Indeed, the scope rules provide the
foundation for encapsulation. Scopes can be nested. For example, each time you
Dept of CS&E,KVGCE
22
Object Oriented Programming with JAVA BCS306A Module 1
create a block of code, you are creating a new, nested scope. When this occurs,
the outer scope encloses the inner scope. This means that objects declared in
the outer scope will be visible to code within the inner scope. However, the
reverse is not true. Objects declared within the inner scope will not be visible
outside it.
Variables are created when their scope is entered, and destroyed when their
scope is left. This means that a variable will not hold its value once it has gone
out of scope. Therefore, variables declared within a method will not hold their
values between calls to that method. Also, a variable declared within a block
will lose its value when the block is left. Thus, the lifetime of a variable is
confined to its scope.
Program 1.9 Demonstration of scope of variables
class Scope
{
public static void main(String args[])
{
int x=10, i; // x and i are local to main()
if(x == 10)
{
int y = 20; // y is local to this block
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
Dept of CS&E,KVGCE
23
Object Oriented Programming with JAVA BCS306A Module 1
the loop gets executed, variable a is created newly and there is no effect of a++
for next iteration.
NOTE:
In Java, same variable name cannot be used in nested scopes. That is, the
following code snippet generates error.
class Test
{
public static void main(String args[])
{
int x=3;
{
int x=5; //error!!
}
}
}
Dept of CS&E,KVGCE
24
Object Oriented Programming with JAVA BCS306A Module 1
char.
Dept of CS&E,KVGCE
25
Object Oriented Programming with JAVA BCS306A Module 1
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Dept of CS&E,KVGCE
26
Object Oriented Programming with JAVA BCS306A Module 1
result = 626.7784146484375
Let’s look closely at the type promotions that occur in this line from the program:
2.7 Arrays
Array is a collection of related items of same data type. Many items of an array
share common name and are accessed using index. Array can be one
dimensional or multi-dimensional.
Dept of CS&E,KVGCE
27
Object Oriented Programming with JAVA BCS306A Module 1
type arr_name[];
Here, type determines the data type of elements of arr_name. In Java, the
above declaration will not allocate any memory. That is, there is no physical
existence for the array now. To allocate memory, we should use new operator
as follows:
arr_name=new type[size];
Here, size indicates number of elements in an array. The new keyword is used
because, in Java array requires dynamic memory allocation. The above two
statements can be merged as –
type arr_name[]=new type[size];
For example, following statement create an array of 10 integers –
Array index starts with 0 and we can assign values to array elements as –
Java strictly checks to make sure you do not accidentally try to store or
reference values outside of the range of the array. The Java run-time system will
check to be sure that all array indexes are in the correct range. If you try to
access elements outside the range of the array (negative numbers or numbers
greater than the length of the array), you will get a run-time error.
Multidimensional Arrays
Multidimensional arrays are arrays of arrays. Here, we will discuss two
Dept of CS&E,KVGCE
28
Object Oriented Programming with JAVA BCS306A Module 1
Instead of allocating memory for 2-day as shown in the above program, we can
even do it in a different way. We can first mention row_size and then using
different statements, mention col_size as shown below
int twoD[][]= new
int[3][];
twoD[0]=new int[4]
; twoD[1]=new
int[4] ;
twoD[2]=new int[4]
;
But, above type of allocation is not having any advantage unless we need
Dept of CS&E,KVGCE
29
Object Oriented Programming with JAVA BCS306A Module 1
int a[ ][ ]={{1,2},{3,4} };
We can have more than 2 dimensions as –
Dept of CS&E,KVGCE
30
Object Oriented Programming with JAVA BCS306A Module 1
Here, the array elements can be accessed using 3 indices like a[i][ j][k].
Alternative Array Declaration Syntax
There is another way of array declaration as given below –
type[] arr_name;
That is, following two declarations are same –
int a[ ]=new int[3];
int[ ] a= new int[3];
Both the declarations will create an integer array of 3 elements. Such
declarations are useful when we have multiple array declarations of same type.
For example,
int [ ] a, b, c;
will declare three arrays viz. a, b and c of type integer. This declaration is same
as –
int a[ ], b[ ], c[ ];
The alternative declaration form is also useful when specifying an array as a
return type for a method.
2.8 A few words about Strings
In Java, String is a class but not array of characters. So, the features of String
class can be better understood after learning about the concepts of classes in
further chapters. For the time-being, we will glance at String type.
We can have array of strings.
A set of characters enclosed within double quotes can be assigned to a
String variable.
One variable of type String can be assigned another String variable.
Object of type String can be used as an argument to println as –
String str=”Hello”;
System.out.println(str);
VTU QUESTIONS
Dept of CS&E,KVGCE
31
Object Oriented Programming with JAVA BCS306A Module 1
JUNE/JULY 2024(Makeup)
Dept of CS&E,KVGCE
32