OOC Module 2
OOC Module 2
Java Environment:
Java environment includes a large number of development tools and hundreds of classes and
methods. The Java development tools are part of the systems known as Java development kit (JDK) and the
classes and methods are part of the Java standard library known as Java standard Library (JSL) also known
as application program interface (API).
Java Features:
Compiled and Interpreted
(1) Architecture Neutral/Platform independent and portable
(2) Object oriented
(3) Robust and secure.
(4) Distributed.
(5) Familiar, simple and small.
(6) Multithreaded and interactive.
(7) High performance
(8) Dynamic and extendible.
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 pure object oriented language.
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
Java Development kits(java software:jdk1.6): Java development kit comes with a number of Java
development tools. They are:
(1) Appletviewer: Enables to run Java applet.
(2) javac: Java compiler.
(3) java : Java interpreter.
(4) javah : Produces header files for use with native methods.
(5) javap : Java disassembler.
(6) javadoc : Creates HTML documents for Java source code file.
(7) jdb : Java debugger which helps us to find the error.
Description:
(1) Class declaration: “class sampleone” declares a class, which is an object-
oriented construct. Sampleone is a Java identifier that specifies the name of
the class to be defined.
(2) Opening braces: Every class definition of Java starts with opening braces and
ends with matching one.
(3) The main line: the line “ public static void main(String args[]) “ defines a
method name main. Java application program must include this main. This is
the starting point of the interpreter from where it starts executing. A Java
program can have any number of classes but only one class will have the main
method.
(4) Public: This key word is an access specifier that declares the main method as
unprotected and therefore making it accessible to the all other classes.
(5) Static: Static keyword defines the method as one that belongs to the entire
class and not for a particular object of the class. The main must always be
declared as static.
(6) Void: the type modifier void specifies that the method main does not return
any value.
(7) The println: It is a method of the object out of system class. It is similar to
the printf or cout of c or c++.
2. Save the above program with .java extension, here file name and class name should be
same, ex: Sampleone.java,
3. Open the command prompt and Compile the above program
javac Sampleone.java
From the above compilation the java compiler produces a bytecode(.class file)
4. Finally run the program through the interpreter
java Sapleone.java
Implementing a Java program: Java program implementation contains three stages. They are:
1. Create the source code.
2. Compile the source code.
3. Execute the program.
(1) Create the source code:
1. Any editor can be used to create the Java source code.
2. After coding the Java program must be saved in a file having the same name of the
class containing main() method.
3. Java code file must have .Java extension.
More Examples:
Java program with multiple lines:
Example:
import java.lang.math;
class squreroot
{
public static void main(String args[])
{
double x = 5;
double y;
y = Math.sqrt(x);
System.out.println(“Y = “ + y);
}
}
Java Program structure: Java program structure contains six stages. They are:
(1) DocUMentation section: The documentation section contains a set of comment lines
describing about the program.
(2) Package statement: The first statement allowed in a Java file is a package statement.
This statement declares a package name and informs the compiler that the class defined here
belong to the package.
Package student;
(3) Import statements: Import statements instruct the compiler to load the specific class
belongs to the mentioned package.
Import student.test;
(4) Interface statements: An interface is like a class but includes a group of method
deceleration. This is an optional statement.
(5) Class definition: A Java program may contain multiple class definition The class are
used to map the real world object.
(6) Main method class: The main method creates objects of various classes and establish
communication between them. On reaching to the end of main the program terminates and the
control goes back to operating system.
Java command line arguments: Command line arguments are the parameters that are supplied to
the application program at the time when they are invoked. The main() method of Java program
will take the command line arguments as the parameter of the args[ ] variable which is a string
array.
Java Tokens
Constants: Constants in Java refers to fixed value that do not change during the execution of
program. Java supported constants are given below:
(1) Integer constants: An integer constant refers to a sequence of digits. There are three
types of integer namely decimal integer, octal integer and hexadecimal integer. For
example: 123 -321
(2) Real constants: Any real world number with a decimal point is known as real
constants. For example : 0.0064 12e-2 etc.
(3) Single character constants: A single character constant contains a single character
enclosed with in a pair of single quotes. For ex: „m‟ „5‟
(4) String constants : A string constant is a sequence of character enclosed with double
quotes. For ex: “hello” “java” etc.
(5) Backslash character constants: Java supports some backslash constants those are
used in output methods. They are :
1. \b Backspace
2. \f Form feed
3. \n New Line
4. \r Carriage return.
5. \t Horizontal tab.
6. \‟ Single quotes.
7. \” Double quotes
8. \\ Back slash
Integers Type: Java provides four types of Integers. They are byte, sort, Int, long. All these are
sign, positive or negative.
Byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to 127. Bytes are useful for working with stream or data from a network or file. They are also
useful for working with raw binary data. A byte variable is declared with the keyword “byte”.
byte b, c;
Short: Short is a signed 16-bit type. It has a range from –32767 to 32767. This data type is
most rarely used specially used in 16 bit computers. Short variables are declared using the
keyword short.
short a, b;
int:The most commonly used Integer type is int. It is signed 32 bit type has a range from
–2147483648 to 2147483648.
int a, b, c;
long:Long is a 64 bit type and useful in all those occasions where Int is not enough.
The range of long is very large.
long a, b;
Floating point types:Floating point numbers are also known as real numbers are useful when
evaluating a expression that requires fractional precision. The two floating-point data types
are float and double.
float:The float type specifies a single precision value that uses 32-bit storage.
Float keyword is used to declare a floating point variable.
float a, b;
double: Double DataTips is declared with double keyword and uses 64-bit value.
Characters: The Java data type to store characters is char. char data type of Java uses Unicode
to represent characters. Unicode defines a fully international character set that can have all the
characters of human language. Java char is 16-bit type. The range is 0 to 65536.
Boolean: Java has a simple type called boolean for logical values. It can have only one of two
possible values. They are true or false.
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.
(1) Reserved keyword: Java language has 60 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.
(2) 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.
(3) 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.
(4) Operators: An operator is a symbol that takes one or more arguments and operates on
them to produce an result.
(5) Separators: Separators are the symbols that indicates where group of code are divided
and arranged. Some of the operators are:
1. Parenthases()
2. Braces{ }
3. Brackets [ ]
4. Semicolon ;
5. Comma ,
6. Period .
Java character set: 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.
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
Initializing by read statements: Using read statements we can get the values in the
variable.
Scope of Variable: Java variable is classified into three types. They are
Arrays in Java
Array which 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.
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:
Example:
Creating Arrays:
You can create an array by using the new operator with the following syntax:
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 statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
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: public
class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
JDK 1.5 introduced a new for loop known as for-each loop or enhanced for loop, which
enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
Type Casting:It is often necessary to store a value of one type into the variable of another type. In
these situations the value that to be stored should be casted to destination type. Type casting can be
done in two ways.
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
Widening Casting(Implicit)
Example :
Output :
When you are assigning a larger type value to a variable of smaller type, then you need to perform
explicit type casting.
Example :
}
}
Output :
Java operators:
Relational Operator:
< : Is less then
<= : Is less then or equals to
: Is greater then
>= : Is grater then or equals to
== : Is equals to
!= : Is not equal to
Logical Operators:
&& : Logical AND
|| : Logical OR
! : Logical NOT
Assignment Operator:
+= : Plus and assign to
-= : Minus and assign to
*= : Multiply and assign to.
/= : Divide and assign to.
%= : Mod and assign to.
= : Simple assign to.
Increment and decrement operator:
++ : Increment by One {Pre/Post)
-- : Decrement by one (pre/post)
Conditional Operator: Conditional operator is also known as ternary operator.
The conditional operator is :
Exp1 ? exp2 : exp3
Bitwise Operator: Bit wise operator manipulates the data at Bit level. These operators are
used for tasting the bits. The bit wise operators are:
Binary Left Shift Operator. The left operands value is moved left by A << 2 will give 240
<<
the number of bits specified by the right operand. which is 1111 0000
Binary Right Shift Operator. The left operands value is moved right A >> 2 will give 15 which
>>
by the number of bits specified by the right operand. is 1111
Shift right zero fill Operator. The left operands value is moved right
A >>>2 will give 15
>>> by the number of bits specified by the right operand and shifted values
which is 0000 1111
are filled up with zeros.
Special Operator:
instanceof operator: The instanceof operator is a object refrence operator that
returns true if the object on the right hand side is an instance of the class given in the left hand
side. This operator allows us to determine whether the object belongs to the particular class or not.
Person instanceof student
The expression is true if the person is a instance of class student.
Dot operator: The dot(.) operator is used to access the instance variable or method
of class object.
Example Programs
class arithmeticop
{
public static void main(String args[])
{
float a=20.5f;
float b=6.4f;
System.out.println("a = " + a);
System.out.println("b = " + b );
System.out.println("a + b = " + (a+b));
}
}
class Bitlogic
{
public static void main(String args[])
{
String binary[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"};
int a = 3; int
b = 6; int c =
a | b;
int d = a & b;
int e = a ^ b;
int f = (~a&b)|(a & ~b);
System.out.println("a or b :"+binary[c]);
System.out.println("a and b : "+binary[d]);
System.out.println("a xor b : "+binary[e]);
System.out.println("(~a&b)|(a & ~b) : "+binary[f]);
Dept. of CSE, BGMIT OOC (Module 2) Page 18
Object Oriented Concepts-Module 2 18CS45
}
}
Control Statements
Decision making statements:
1. Simple If statement:
The general form of single if statement is :
If ( test expression)
{
statement-Block;
}
statement-Blocks;
2. If- Else statement:
The general form of if-else statement is
If ( test expression)
{
statement-block1;
}
else
{ statement-block2
3. Else-if statement:
}
The general form of else-if statement is:
If ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{ statement block3;
}
4. Nested if – else statement:
The general form of nested if-else statement is: If (
test condition)
{
if ( test condition)
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block 3
}
5. switch statements:
The general form of switch statement is:
Switch ( expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
......
default:
default block;
break;
}
Loops In Java: In looping a sequence of statements are executed until a number of time or until
some condition for the loop is being satisfied. Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
(1) While loop:
The general structure of a while loop is:
Initialization
While (test condition)
{
body of the loop
}
(2) do loop:
The general structure of a do loop is :
do
{
Body of the loop;
}
while ( test condition);
Continue statement: The “continue” statement will cause skipping some part of the loop.
Labeled loops: We can put a label for the loop. The label can be any Java recognized
keyword. The process of giving label is
Label-name : while (condition)
{
Body ;
}
class BreakTest
{
public static void main(String args[])
{
boolean t= true;
first:
{
second:
{
third:
{
System.out.println("Third stage");
if(t)
break second;
System.out.println("Third stage complete");
}
System.out.println("Second stage");
}
System.out.println("First stage");
}
}
class ContinueTest
{
public static void main(String args[])
{
outer: for(int i=0;i<10;i++)
{
for(int j = 0; j<10;j++)
{
if(j>i)
{
System.out.println("\n");
continue outer;
}
System.out.print(" "+(i*j));
}
}
//System.out.println(" ");
}
}
class ReturnTest
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return");
if(t) return;
System.out.println("After return");
}
}
Methods, Variables and Constructors that are declared private can only be accessed within
the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Using the private modifier is the main way that an object encapsulates itself and hides data from
the outside world.
A class, method, constructor, interface etc declared public can be accessed from any other
class. Therefore fields, methods, blocks declared inside a public class can be accessed from any
class belonging to the Java Universe.
However if the public class we are trying to access is in a different package, then the public class
still need to be imported.
Because of class inheritance, all public methods and variables of a class are inherited by its
subclasses.
Variables, methods and constructors which are declared protected in a superclass can be
accessed only by the subclasses in other package or any class within the package of the protected
members' class.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be
declared protected, however methods and fields in a interface cannot be declared protected.
Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc.A variable or method declared without any access control
modifier is available to any other class in the same package. The fields in an interface are
implicitly public static final and the methods in an interface are by default public.
Advantages of JAVA:
• It is an open source, so users do not have to struggle with heavy license fees each year.
• Platform independent.