Object Oriented Java
Programming (OOJ)
PLATFORM
• Any hardware or software environment in
which a program runs, is known as a platform.
Since Java has its own runtime environment
(JRE) and API, it is called platform.
Where it is used?
According to Sun, 3 billion devices run java. There are
many devices where java is currently used. Some of
them are as follows:
• Desktop Applications such as acrobat reader, media
player, antivirus etc.
• Web Applications such as [Link], [Link]
etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games etc.
Java is Interpreted
• Java is compiled to an intermediate "byte code" at compilation time.
• This is in contrast to a language like C that is compiled to machine language at compilation time.
• The Java byte code cannot be directly executed on hardware the way that compiled C code can.
• Instead the byte code must be interpreted by the JVM (Java Virtual Machine) at runtime in order to be
executed
The Java Buzzwords
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic
Types of Java Applications
There are mainly 4 type of applications that can be
created using java programming:
1) Standalone Application
• It is also known as desktop application or
window-based application. An application that we
need to install on every machine such as media
player, antivirus etc. AWT and Swing are used in java
for creating standalone applications.
2) Web Application
• An application that runs on the server side and
creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are
used for creating web applications in java.
3) Enterprise Application
• An application that is distributed in nature,
such as banking applications etc. It has the
advantage of high level security, load
balancing and clustering. In java, EJB is used
for creating enterprise applications.
4) Mobile Application
• An application that is created for mobile
devices. Currently Android and Java ME are
used for creating mobile applications.
Two Paradigms for Computer Programs
There are two paradigms for a program construction:
▪ Process Oriented Model
❖ This model can be thought of as code acting on data
✔ Procedural languages, such as C, characterize a series of
linear steps (that is, code)
▪ Object- Oriented Programming
❖ Aims to manage increasing complexity.
❖ Organizes a program around its data (that is object) and a set of
well-defined interfaces to that data.
✔ This program can be characterized as data controlling
access to code.
Object-Oriented Programming (OOP)
▪ OOP is the core of Java
▪ All Java programs are object-oriented.
❖ This isn’t the option the way that it is in C++
▪ OOP and Java are integrated, it is important to understand its
basic principles before writing java programs
Abstraction
The essential element of OOP is abstraction
▪ It is the process of focusing on those features of something that are essentials for
the task at hand and ignoring those that are not.
❖ For a personal system, we are interested only in people objects and only the
ones that are employed by the company. The skiers, golfers, and cyclists are
not included.
▪ The powerful way to manage abstraction is through the use of hierarchical
classifications
❖ This allows us to layer semantic of complex systems, breaking them into more
manageable pieces.
✔ From the outside, the car is a single object. Once inside, we see that car
consists of several subsystems: steering, clutch pedal, brakes, sound
system, seat belts, heading,, and so on.
✔ Each subsystem is made of more specialized units.
✔ The sound system consists of a radio, CD player, a tape player
Hierarchical Abstractions
▪ We have to manage the complexity of system through the use of
hierarchical abstractions.
▪ The data from a traditional process-oriented program can be
transformed by abstraction into its component objects.
▪ A sequence of process steps can become a collection of messages
between these objects.
▪ Each of these objects describes its own unique behavior.
▪ We can threat objects as concrete entites that respond to
messages telling them to do something
This is the essence of object-oriented programming.
It is important that we understand how the
object-oriented concepts, forming the heart of
Java, translate into programs
▪ All OOP languages provide mechanism that help us
to implement OO model they are
❖ Encapsulation
❖ Inheritance
❖ Polymorphism
▪ A programming language is said to support OO design
if it supports these three concepts in its syntax
A First Simple Program
/*
This is a simple Java program.
Call this file "[Link]".
*/
class Example {
// Your program begins with a call to main().
public static void main(String args[]) {
[Link]("This is a simple Java program.");
}
}
Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the
name of the source file on the command line, as shown here:
C:\>javac [Link]
• The javac compiler creates a file called [Link] that contains the
bytecode version of the program.
• The Java bytecode is the intermediate representation of your program that
contains instructions the Java Virtual Machine will execute.
• Thus, the output of javac is not code that can be directly executed.
• To actually run the program, you must use the Java application launcher, called
java.
• To do so, pass the class name Example as a command-line argument, as shown
here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
• When Java source code is compiled, each individual class is put into its own output file
named after the class and using the .class extension.
• This is why it is a good idea to give your Java source files the same name as the class
they contain—the name of the source file will match the name of the .class file.
• When you execute java as just shown, you are actually specifying the name of the class
that you want to execute.
• It will automatically search for a file by that name that has the .class extension. If it
finds the file, it will execute the code contained in the specified class
/*
Here is another short example.
Call this file "[Link]".
*/
class Example2 {
public static void main(String args []) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
[Link]("This is num: " + num);
num = num * 2;
[Link]("The value of num * 2 is ");
[Link](num);
}
}
output:
This is num: 100
The value of num * 2 is 200
Two Control Statements
The if Statement
if(condition) statement;
class IfSample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y) [Link]("x is less than y");
x = x * 2;
if(x == y) [Link]("x now equal to y");
x = x * 2;
if(x > y) [Link]("x now greater than y");
// this won't display anything
if(x == y) [Link]("you won't see this");
}
}
Output
x is less than y
x now equal to y
x now greater than y
The for Loop
for(initialization; condition; iteration) statement;
class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
[Link]("This is x: " + x);
}
}
output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
Java Is a Strongly Typed Language
• every variable has a type, every expression has a type, and
every type is strictly defined.
• all assignments, whether explicit or via parameter passing in
method calls, are checked for type compatibility.
Primitive Data Types
Java defines eight primitive types of data:
byte, short, int, long, char, float, double and
boolean.
Primitive Data Types
These can be put in four groups:
• Integers This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
• Floating-point numbers This group includes float and double, which
represent numbers with fractional precision.
• Characters This group includes char, which represents symbols in a
character set, like letters and numbers.
• Boolean This group includes boolean, which is a special type for
representing true/false values.
Appendix A: Introduction to Java 48
// 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
[Link]("In " + days);
[Link](" days light will travel about ");
[Link](distance + " miles.");
}
}
output:
In 1000 days light will travel about 16070400000000 miles.
// Compute the area of a circle.
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
[Link]("Area of circle is " + a);
}
}
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
}
output:
ch1 and ch2: X Y
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
[Link]("ch1 contains " + ch1);
ch1++; // increment ch1
[Link]("ch1 is now " + ch1);
}
}
Output
ch1 contains X
ch1 is now Y
// Demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
// a boolean value can control the if statement
if(b) [Link]("This is executed.");
b = false;
if(b) [Link]("This is not executed.");
// outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}
Output
b is false
b is true
This is executed.
10 > 9 is true
Variables
The variable is the basic unit of storage in a Java program.
Declaring a Variable
type identifier [ = value ][, identifier [= value ] …];
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
variables to be initialized dynamically, using any expression
valid at the time the variable is declared.
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0; // c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}
The Scope and Lifetime of Variables
a block is begun with an opening curly brace and ended by a
closing curly brace. A block defines a scope.
Thus, each time you start a new block, you are creating a new
scope.
A scope determines what objects are visible to other parts of
your program.
It also determines the lifetime of those objects.
// Demonstrate block scope.
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.
[Link]("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}
count = 100; // oops! cannot use count before it is declared!
int count;
// Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1;
[Link]("y is: " + y);
y = 100;
[Link]("y is now: " + y);
}
}
}
// Demonstrate lifetime of a 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
[Link]("y is: " + y); // this always prints -1
y = 100;
[Link]("y is now: " + y);
}
}
}
Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
class ScopeErr {
public static void main(String
args[]) {
int bar = 1;
{
int bar = 2
}
}
}
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{
int bar = 2
}
}
}
Type Conversion and Casting
If the two types are compatible, then Java will perform the conversion
automatically.
For example, it is always possible to assign an int value to a long variable.
not all types are compatible, and thus, not all type conversions are implicitly
allowed.
For instance, there is no automatic conversion defined from double to byte.
cast, which performs an explicit conversion between incompatible types.
an automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For
example, the int type is always large enough to hold all valid byte values, so
no explicit cast statement is required.
Casting Incompatible Types
To create a conversion between two incompatible types, you must
use a cast. A cast is simply an explicit type conversion. It has this
general form:
(target-type) value
int a;
byte b;
b = (byte) a;
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
[Link]("\nConversion of int to byte.");
b = (byte) i;
[Link]("i and b " + i + " " + b);
[Link]("\nConversion of double to int.");
i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}
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
Automatic Type Promotion in Expressions
there is another place where certain type conversions may occur: in
expressions.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of
either of its byte operands. To handle this kind of problem, Java
automatically promotes each byte, short, or char operand to int when
evaluating an expression.
This means that the subexpression a*b is performed using integers—not
bytes. Thus, 2,000, the result of the intermediate expression, 50 * 40, is
legal even though a and b are both specified as type byte.
byte b = 50;
b = b * 2;
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back
into a byte variable. However, because 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.
This is true even if, as in this particular case, the value being assigned would
still fit in the target type.
In cases where you understand the consequences of overflow, you should
use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
which yields the correct value of 100.
The Type Promotion Rules
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 above.
Then, if one operand is a long, the whole expression is
promoted to long.
If one operand is a float, the entire expression is promoted to
float. If any of the operands are double, the result is double.
Arrays
An array is a group of like-typed variables that are referred to by
a common name.
One-Dimensional Arrays
type var-name[ ];
int month_days[];
this declaration establishes the fact that month_days is an array
variable, no array actually exists.
To link month_days with an actual, physical array of integers,
you must allocate one using new and assign it to month_days.
new is a special operator that allocates memory.
array-var = new type [size];
month_days = new int[12];
month_days[1] = 28;
[Link](month_days[3]);
combine the declaration of the array variable with the
allocation of the array itself, as shown here:
int month_days[] = new int[12];
// Demonstrate a one-dimensional array.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + " days.");
}
}
Arrays can be initialized when they are declared. The
process is much the same as that used to initialize the
simple types.
An array initializer is a list of comma-separated
expressions surrounded by curly braces.
The commas separate the values of the array elements.
The array will automatically be created large enough to
hold the number of elements you specify in the array
initializer.
There is no need to use new.
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30,
31,30, 31 };
[Link]("April has " + month_days[3] + "
days.");
}
}
// Average an array of values.
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
[Link]("Average is " + result / 5);
}
}
Multidimensional Arrays
are actually arrays of arrays
int twoD[][] = new int[4][5];
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
output:
01234
56789
10 11 12 13 14
15 16 17 18 19
code allocates memory for the first dimension of twoD
when it is declared. It allocates the second dimension
manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
// Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}
output:
0
12
345
6789
// Initialize a two-dimensional array.
class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
[Link](m[i][j] + " ");
[Link]();
}
}
}
output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0
// Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
[Link](threeD[i][j][k] + " ");
[Link]();
}
[Link]();
}
}
}
output:
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax
There is a second form that may be used to declare
an array:
type[ ] var-name;
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when
declaring several arrays at the same time.
For example,
int[] nums, nums2, nums3; // create three arrays
creates three array variables of type int. It is the same as
writing
int nums[], nums2[], nums3[]; // create three
arrays
How to take input from a user in Java
Java program to get input from a user:
we are using Scanner class to get input from the user.
Scanner a = new Scanner([Link]);
Scanner class is present in [Link] package so we import this package into our
program. We first create an object of Scanner class and then we use the
methods of Scanner class.
Following methods of Scanner class are used in the program:
1) nextInt to input an integer
2) nextFloat to input a float
3) nextLine to input a string
import [Link];
class GetInputFromUser
{
public static void main(String args[])
{
int a;
float b;
String s;
Scanner in = new Scanner([Link]);
[Link]("Enter an integer");
a = [Link]();
[Link]("You entered integer "+a);
[Link]("Enter a float");
b = [Link]();
[Link]("You entered float "+b);
[Link]("Enter a string");
s = [Link]();
[Link]("You entered string "+s);
}}
Java program to find odd or even
import [Link];
class OddOrEven
{
public static void main(String args[])
{
int x;
[Link]("Enter an integer to check if it is odd or even ");
Scanner in = new Scanner([Link]);
x = [Link]();
if ( x % 2 == 0 )
[Link]("You entered an even number.");
else
[Link]("You entered an odd number.");
}
}
Program asks a user to input an integer and prints it until the user enter 0 (zero)
import [Link];
class WhileLoop {
public static void main(String[] args) {
int n;
Scanner input = new Scanner([Link]);
[Link]("Input an integer");
while ((n = [Link]()) != 0) {
[Link]("You entered " + n);
[Link]("Input an integer");
}
[Link]("Out of loop");
}
}
Java Buzzwords
Sriram Study Point
List of Buzzwords
1. Simple 7. Architectural
2. Secure neutral
3. Portable 8. Interpreted
4. Object-Oriented 9. High Performance
5. Robust 10. Distribute
6. Multithreaded 11. Dynamic
Simple
• Java easy to learn
• It is easy to write programs using
Java
• Expressiveness is more in Java.
• Most of the complex
or confusing features in C++ are
removed in Java like pointers etc
Secure
• Interpreted
• Java Virtual Machine (JVM)
• “Sandbox”
• No pointers
• Applets are run within the JVM
Portable
• Programs can be executed on any kind
of computer containing JVM.
• When compiled, it generates an
intermediate code file called as
“bytecode”.
• Bytecode helps Java to achieve
portability.
• This bytecode can be taken to any
computer and executed directly.
Object-Oriented
• Java follows object oriented model.
Encapsulation
Inheritance
Polymorphism
Abstraction
Robust
• Strongly typed language
• No pointers
• Automatic garbage collection
• Exception handling
Architecture – Neutral
• Bytecode helps Java to achieve
portability.
• Bytecode can be executed on computers
having any kind of operating system or
any kind of CPU.
• Since Java applications can run on any
kind of CPU, Java is architecture –
neutral.
Multithreaded
• Interactive, networked programs
• Built-in support for process
synchronization
• A thread is a light weight process
Interpreted
The compiled code of Java is not
machine instructions but rather its a
intermediate code called ByteCode.
This code can be executed on any
machine that implements the Java
virtual Machine. JVM interprets the
ByteCode into Machine instructions
during runtime.
High Performance
When java programs are executed, JVM
does not interpret entire code into
machine instructions. JVM was
intelligently developed to interpret only
the piece of the code that is required to
execute and un touch the rest of the
code. The performance of java is never
questioned compared with another
programming language.
Distributed
• Designed for the internet
• Built-in support for TCP/IP
• Remote Method Invocation (RMI)
• Resources are Shared.
Dynamic
• JVM maintains a lot of runtime
information about the program and the
objects in the program.
• Libraries are dynamically linked during
runtime.
• So, even if you make dynamic changes
to pieces of code, the program is not
effected.
Thank You
Visit Again