BCS306A Module 1
BCS306A Module 1
Java
MODULE 1
An Overview of Java:
● Lexical Issues
Arrays:
● Integers
● Floating-Point types
● Characters
● Booleans
● Variables
● Arrays
Microsystems. It was invented by James Gosling and his team and was initially called
as Oak.
● The most important feature that made Java very popular was the
―Platform- Independent‖ approach.
● It was the first programming language that did not tie-up with any particular operating
system ( or hardware) rather Java programs can be executed anywhere and on any
system.
● Java was designed for the development of the software for consumer electronic
devices like TVs, VCRs, etc.
Two Paradigms:
● Two approaches are there to solve the problem and in program writing:
Procedure oriented and object oriented.
Procedure Oriented:
● Problems increase in procedure oriented as the program grows larger and more
complex.
Object Oriented:
● It organises program around data and well defined interfaces of that data.
● Characterized as data controlling access to code. Ex: C++, JAVA, Small Talk etc
● Encapsulation
● Inheritence
● Polymorphism
Object Oriented Programming with BCS306
Java
Encapsulation:
● Encapsulation is the mechanism that binds together code and data it manipulates, and
keeps both safe from outside interference and misuse.
● In Java the basis of encapsulation is the class. A class defines the state and behavior(
data & code) that will be shared by set of objects.
● Each object contains the structure and behavior defined by the class. The data
defined by the class are called instance variables(member variables), the code that
operates on that data are called methods(member functions).
Inheritence:
● By the use of inheritence, a class has to define only those qualities that make it
unique. The general qualities can ber derived from the parent class or base
class.
Polymorphism
used for a general class of actions. The specific action determined by the exact
nature of the situation. This concept is often expressed as ― one interface, multiple
methods‖.
● Ex: ―+‖ can be used for addition of 2 numbers and also concatenation of 2
strings. System.out.println(2+4); // outputs 6 as answer
System.out.println(―Hello‖ + ―Gautham‖); // outputs Hello Gautham as answer
Object:
Object Oriented Programming with BCS306
Java
Abstraction:
● Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed informatin in
program without presenting the details.
● Ex: a database system hides certain details of how data is stored and created and
maintained.
class Example
{
public static void main(String args[])
{
System.out.println(―Welcome to Programming in Java‖);
}
Object Oriented Programming with BCS306
Java
}
Note:
● In Java all code must reside inside a class and name of that class should match
the name of the file that holds the program.
● Java is case-sensitive
● The ―javac: compiler creates a file called ―Example.class‖ that contains the
bytecode version of the program.
● To run the program, we must use the java interpreter called ―java‖. To do so we
pass the class name ―Example‖ as a command-line argument as shown below
C:\> java Example
Description:
Object Oriented Programming with BCS306
Java
The System.out.print( ) method is just like println( ) except that it does not output a newline
character after each call.
if statement
● The if- statement is the most basic of all the control flow statements. It tells your
if (condition) statement;
● If the condition is true then the statement is executed, if false then statement will
be skipped.
Example:
class Example
{
public static void main(String args[])
{
int a=10;
if(a>0)
System.out.println(―a is positive number‖);
System.out.println(― End of program‖);
Object Oriented Programming with BCS306
Java
}
Object Oriented Programming with BCS306
Java
}
In the above program since a is greater than o it prints the output as
a is positive number
End of program
{
//body
● Iteration expression tells hoe the control variable has to change at each
iteration. Generally the increment or decrement operator is used to perform
iteration.
Example:
class Example
{
public static void main(String args[])
{
Output: 0
1
i
n
t
Object Oriented Programming with BCS306
Java
a
;
f
o
r
(
a
=
0
;
a
<
5
;
a
+
+
)
Syste
m.out.p
rintln(a)
;
System.
out.prin
tln(―
End of
progra
m‖);
}
}
Object Oriented Programming with BCS306
Java
2
3
4
End of Program
● Java supports code blocks - which means that two or more statements are
grouped into blocks of code.
Lexical issues:
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace:
Object Oriented Programming with BCS306
Java
● Java is a free from language- means no need to follow any indentation rules.
● The smallest unit of Java language are its character set used to write Java tokens.
This character are defined by unicode character set that tries to create character for a
large number of character worldwide.
● The Unicode is a 16-bit character coding system and currently supports 34,000
defined characters derived from 24 languages of worldwide.
Key Words:
Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statement contains an
expression that contains the action carried out on data. The compiler recognizes the tokens
for building up the expression and statements. Smallest individual units of programs are
known as tokens. Java language includes five types of tokens. They are
(a) Reserved Keyword
(b) Identifiers
(c) Literals.
(d) Operators
(e) Separators.
Reserved keyword:
Java language has 50 words as reserved keywords. They implement specific feature of the
language. The keywords combined with operators and separators according to syntax build
the Java language.
Object Oriented Programming with BCS306
Java
Identifiers:
Identifiers are programmer-designed token used for naming classes methods variable,
objects, labels etc. The rules for identifiers are
1. They can have alphabets, digits, dollar sign and underscores.
2. They must not begin with digit.
3. Uppercase and lower case letters are distinct.
4. They can be any lengths.
5. Name of all public method starts with lowercase.
6. In case of more than one word starts with uppercase in next word.
7. All private and local variables use only lowercase and underscore.
8. All classes and interfaces start with leading uppercases.
9. Constant identifier uses uppercase letters only.
Literals:
Literals in Java are sequence of characters that represents constant values to be stored in
variables. Java language specifies five major types of Literals. They are:
1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce
an result.
Object Oriented Programming with BCS306
Java
Separators:
Separators are the symbols that indicates where group of code are divided and arranged.
Some of the operators are:
Comments:
● Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
● Single line comments: this type of comment begins with // and ends at the end
of current line
Ex: // Welcome to java Programming
that documents your program. The documentation comment begins with /** and
ends with */
Data types,
variables and arrays
● The strongly typed nature of Java gives it the robustness and safety for it.
Data types
The various data types supported in java is as follows
Data types
Numeric
arra
ys
Non clas
Numeric
s
boolean interfaces
Integer Floating type
int
t Primi types:
Object Oriented Programming with BCS306
Java
f d
l o
o u
a b
t l
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
● The primitive types represent single values—not complex objects. Although Java
is otherwise completely object-oriented, the primitive types are not.
Object Oriented Programming with BCS306
Java
● They are analogous to the simple types found in most other non–object-
oriented languages.
● The reason for this is efficiency. Making the primitive types into objects would have
degraded performance too much. The primitive types are defined to have an
explicit range and mathematical behavior.
● Because of Java‗s portability requirement, all data types have a strictly defined
range. For example, an int is always 32 bits, regardless of the particular platform.
Integers
● Java defines four integer types: byte, short, int, and long.
● All of these are signed, positive and negative values. Java does not support
unsigned, positive-only integers.
● Many other computer languages support both signed and unsigned integers.
Specifically, they felt that the concept of unsigned was used mostly to specify the
behavior of the high-order bit, which defines the sign of an integer value.
byte
● Byte variables are declared by use of the ● For example, the following declares two
byte keyword. byte variables called b and c: byte b, c;
short
short s;
short t;
Floating-Point Types
● There are two kinds of floating-point types, float and double, which
represent single- and double-precision numbers, respectively.
float
● The type float specifies a single-precision value that uses 32 bits of storage.
double
● Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Characters
● However, C/C++ programmers beware: char in Java is not the same as char in C
or C++.
● In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses
Unicode to represent characters.
● Unicode defines a fully international character set that can represent all of
Object Oriented Programming with BCS306
Java
the characters found in all human languages.
Arabic, Cyrillic,Hebrew, Katakana, Hangul, and many more. For this purpose, it
requires 16 bits.
Object Oriented Programming with BCS306
Java
● Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are
no negative
Booleans:
Java has a simple type called boolean for logical values. It can have only one of two possible
values. They are true or false.
Literals:
A constant value in Java is created by using a literal representation of it. There are 5 types of
literals.
● Integer Literals.
● Floating-point Literals.
● Character Literals.
● String Literals.
● Boolean Literals.
Integer literals:
● There are two other bases which can be used in integer literal, octal( base 8) where 0
is prefixed with the value, hexadecimal (base 16) where 0X or 0x is prefixed with the
integer value.
Object Oriented Programming with BCS306
Java
Example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
Object Oriented Programming with BCS306
Java
● The default type when you write a floating-point literal is double, but you
can designate it explicitly by appending the D (or d) suffix
● However, the suffix F (or f) is appended to designate the data type of a floating-
point literal as float.
Example:
0.0314 *10² (i.e 3.14).
6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal
Character literals:
● You must know about the ASCII character set. The ASCII character set includes
128 characters including letters, numerals, punctuation etc.
● The values true and false are treated as literals in Java programming.
● When we assign a value to a boolean variable, we can only use these two values.
● We have to use the values true and false to represent a Boolean value.
Example
boolean chosen = true;
String Literal
● There are few methods provided in Java to combine strings, modify strings and
to know whether to strings have the same values.
Example:
―hello world‖
―Java‖
Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may have different value in the different phase of the program. To declare one
identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
The syntax is
Object Oriented Programming with BCS306
Java
type identifier [ = value][, identifier [= value] ...] ;
Example:
int a,b,c;
float quot, div;
Object Oriented Programming with BCS306
Java
Initializing a variable:A variable can be initialize in two ways. They are
Variable-name = Value;
Example: int a=10,b,c=16;
Double pi=3.147;
Dynamic initialization:
● Java allows variables to be declared within any block. A block is begun with an
opening curly brace and ended by a closing curly brace. A block defines a
scope.
● A scope determines what objects are visible to other parts of your program. It
also determines the lifetime of those objects.
● Many other computer languages define two general categories of scopes: global
and local. However, these traditional scopes do not fit well with Java‗s strict,
Object Oriented Programming with BCS306
Java
object-oriented model.
● 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
Object Oriented Programming with BCS306
Java
scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main x =
10; if(x == 10) // start new scope
{
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here. System.out.println("x is " + x);
}
}
Note:
● There should not be two variables with the same name in different scope.
● The variable at outer scope can be accessed in inner scope but vice versa is
not possible.
Example :
}
Output :
Object Oriented Programming with BCS306
Java
Int value 100
Long value 100
Float value 100.0
}
Output :
Double value 100.04
Long value 100
Int value 100
● Java automatically promotes each byte, short, or char operand to int when
evaluating an expression.
byte b = 50;
Object Oriented Programming with BCS306
Java
b = b * 2; // Error! Cannot assign an int to a byte!
Object Oriented Programming with BCS306
Java
the operands were automatically promoted to int when the expression was evaluated, the
result has also been promoted to int. Thus, the result of the expression is now of type
int, which cannot be assigned to a byte without the use of a cast.
byte b = 50;
b = (byte)(b * 2); which yields the correct value of 100.
Java defines several type promotion rules that apply to expressions. They are as follows:
● First, all byte, short, and char values are promoted to int, as just described.
Arrays in Java
Arraywhich stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Example:
You can create an array by using the new operator with the following syntax:
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to
the variable can be combined in one statement, as shown below:
Example:
Following picture represents array myList. Here, myList holds ten double values and
the indices are from 0 to 9.
Object Oriented Programming with BCS306
Java
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all
of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
Multidimensional Arrays
Java does not support multidimensional arrays. However, you can declare and create an array
of arrays (and those arrays can contain arrays, and so on, for however many dimensions you
need), and access them as you would C-style multidimensional arrays:
int coords[] [] = new int[12] [12];
Object Oriented Programming with BCS306
Java
coords[0] [0] = 1; coords[0] [1] = 2;
● Java supports string type which is an object. It is used to declare string variables
Programs:
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long 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);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
Object Oriented Programming with BCS306
Java
}
}
This program generates the following output:
Object Oriented Programming with BCS306
Java
In 1000 days light will travel about 16070400000000 miles.
class Area
{
public static void main(String args[])
{
double pi, r, a; r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2; ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y
class CharDemo2
{
public static void main(String args[])
{
Object Oriented Programming with BCS306
Java
char ch1; ch1 = 'X';
Object Oriented Programming with BCS306
Java
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
The output generated by this program is shown here:
ch1 contains X ch1 is now Y
// Demonstrate boolean
values. class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b); // a boolean value can control the if statement
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is
false b is
true
This is executed.
10 > 9 is true
Object Oriented Programming with BCS306
Java
Scope of variable
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown
here: y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Type conversion
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142; System.out.println("\
nConversion of int to byte."); b = (byte) i;
System.out.println("i and b " + i + " " + b);
Object Oriented Programming with BCS306
Java
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i); System.out.println("\
nConversion of double to byte.");
b = (byte) d; System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int. d
and i 323.142 323 Conversion
of double to byte. d and b
323.142 67
Additional:
Applications of Java
● Some of the applications of Java is that internet users can use Java to create applet
programs and run them using a web-browser.
● The first application program written in Java was HotJava, a web browser to run
● Further internet users can also set up their websites containing java applets,that could
be used by other remote users of the internet. Hence Java is popularly called as ―
Language of Internet‖.
● Before the invention of Java, world wide web was limited to displaying text and still
images. However, the incorporation of Java into web pages has made web capable of
supporting animations, graphics, games and wide range of special effects.
Java Environment:
● The development tools are part of the system known as Java Development Kit(JDK)
● The classes and methods area apart of the Java Standard Library (JSL) also
known as Application Program Interface (API)
🡺 applet viewer: Enables us to run java applet (without actually using a Java
compatible browser)
🡺 java: Java interpreter, which runs applets and applications by reading and interpreting
bytecode files.
🡺 javac: the Java compiler, which translates java source code to bytecode files that the
🡺 javap: Java disassembler, which enables us to convert bytecode files into a program
description.
Object Oriented Programming with BCS306
Java
Java is iterpreted:
Java as a language initially gained popularity mainly due to its platform independent
architecture or portaibility feature. The reason for Java to be portable is that it is interpreted.
Firstly Java compiler translates source code into bytecode(an intermediate representation).
This byte code is given as an input to the Java interpreter that generates the machine code
that can be executed by the native system. So we call java as an interpreter language.
The Bytecode:
This concept allows java to solve both security and portability problems. When the source
program is given as an input to the Java compiler, it will never generate the machine level
language executable code, rather it generates ―bytecode‖.
Bytecodes are highly optimized set if instructions designed to be executed by the java
runtime system called JVM. Translating a java program into bytecode makes it much easier
to run a program in a wide variety of environment because only the JVM needs to be
implemented for each platform.
Java Features:
3. Object oriented
In java everything is an Object. Java can be easily extended since it is based
on the Object model. Java is a true object oriented language. All data
resides in objects and classes
5. Distributed.
Java is designed for the distributed environment of the internet.java
applications can open and access remote objects on internet as easily as
they can do in the local system.
6. Familiar, simple and small.
Java is designed to be easy to learn. If you understand the basic
concept of OOP java would be easy to master.
8. High performance
Because of the intermediate bytecode java language provides high performance