0% found this document useful (0 votes)
48 views

Java 1

The document discusses object-oriented programming in Java. It introduces some key concepts in OOP like classes, objects, and methods. It then discusses basics of classes like constructors. It provides a high-level overview of object-oriented programming in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Java 1

The document discusses object-oriented programming in Java. It introduces some key concepts in OOP like classes, objects, and methods. It then discusses basics of classes like constructors. It provides a high-level overview of object-oriented programming in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

OOP-JAVA

Introduction
Basics of class, objects, methods,
constructors

Md. Rayhan Ahmed


Assistant Professor
Dept. of CSE
United International University
WHAT IS PROGRAMMING?
• Instruction to computer/device to perform task.
• Computer understands only 0 and 1. Nothing else.
• So, we need to send the instruction in the form of 0, 1
• Do you write program with just 0 and 1?
CLASSIFICATION/EVOLUTION OF PROGRAMMING
 Machine level programming
Send instruction in binary format

 Assembly Programming
Send code instead of binary code.
Need assembler to convert to binary

 High level programming


Code is close to English Language
Need Compiler to convert to binary
3 types –
Non structured
Structured/Procedural
Object Oriented Programming
CLASSIFICATION/EVOLUTION OF PROGRAMMING
Non structured
Generate spaghetti code
Sequential and has GoTo
COBOL, BASIC, FORTRAN

 Structured/Procedural
Use Subroutine/Function
Improving the clarity, quality, and development time
C, PASCAL

 Object Oriented Programming

Object-oriented programming (OOP) is a programming language model


organized around objects rather than "actions" and data rather than logic.

Historically, a program has been viewed as a logical procedure that takes input
data, processes it, and produces output data.
Java, C++, C#
Introduction to Java

JAVA was developed by Sun Microsystems Inc in 1991, later acquired by


Oracle Corporation.
• It was developed by James Gosling and Patrick Naughton.
• A key goal of Java is to be able to write programs that will run on a
great variety of computer systems and computer-control devices. This
is sometimes called “write once, run anywhere.”
• Java is related to C++, which is a direct descendent of C.
• Much of the character of Java is inherited from these two languages.
Java vs C++

L 1.5
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
Enterprise Applications such as banking
applications.
Mobile
Embedded System
Smart Card
Robotics
Games etc.
There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)


2) Java EE (Java Enterprise Edition)
3) Java ME (Java Micro Edition)
4) JavaFx ( It is used to develop rich internet
applications. It uses light-weight user interface API)
The Java Buzzwords

The key considerations were summed up by the Java


team in the following list of buzzwords:
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic

L 1.9
Java Platform Independent
Java is platform independent because it is different
from other languages like C, C++ etc. which are
compiled into platform specific machines while Java is
a write once, run anywhere language.

A platform is the hardware or software environment in


which a program runs.

There are two types of platforms software-based


and hardware-based. Java provides software-
based platform.
 Java code can be run on multiple platforms e.g. Windows, Linux,
Sun Solaris, Mac/OS etc. Java code is compiled by the compiler and
converted into Bytecode. This Bytecode is a platform-independent
code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).

 Bytecode is a highly optimized set of instructions designed to be


executed by the Java run-time system, which is called the Java
Virtual Machine (JVM).

 This code can be executed on any system that implements the Java
Virtual Machine

 The execution of Bytecode by the JVM is the easiest way to create


truly portable programs.
JAVA – THE PLATFORM

 Java has a large API (application programming interface) covering a wide


range of areas. The following list of Java APIs and applications from Sun
show the range of applications of Java .
 For reference http://java.sun.com/products/index.html
 Java Foundation Classes (JFC) – GUI
 JDBC Database Access
 Java Web Server
 Embedded Java - Java on embedded devices
JAVA IDE
 Creating, Compiling, Debugging and Execution for these four steps JDK is
not user friendly. IDE is provided for that.
 A list of IDEs are:
Eclipse.
Netbeans
IntelliJ IDEA

Using JDK you can compile and run java program from command line.

# c:> javac HelloWorld. Java


Compiling here and it will produce HelloWorld.class i.e. bytecode.

# c:>java HelloWorld
It runs java byte code on native machine
AN EXAMPLE HELLOWORLD

public class HelloWorldExample


{
public static void main( String args[] )
{
System.out.println("Hello World");
}
}
Java source code naming conventions

 All java source file should end with .java


 Each .java file can contain only one public class
 The name of the file should be the name of the public class plus ".java"
 Do not use abbreviations in the name of the class
 If the class name contains multiple words

-- capitalize the first letter of each word ex. HelloWorld.java


Naming Convention
 Class Naming
 Uses Capitalized word(s) i.e. Title case
 Examples:- HelloWorld, MyList, StudentMark

 Variable and method names


 starts with a lowercase letter and after that use Title case
 Examples:- variableAndMethodNames, aFloat, studentName

 Names of constants
 All are capital letters and separated by underscore.
 Example: NAMES_OF_CONSTANTS
JAVA IDENTIFIERS RULES
Identifier is a name given to a variable, class, or method.

 Java identifier
 Can contain letter, number, underscore (_), or dollar sign ($).
 Cannot start with number.
 Identifiers are case sensitive
 Have no maximum length.
 Can not be a keyword, but it can contain a keyword as part of its name.
Data Types

Java defines eight simple types:


1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false

L 1.14
Array Declaration

Array declaration involves:


1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
Two styles of array declaration:
type array-variable[];
or
type [] array-variable;

L 2.8
Array Creation
After declaration, no array actually exists.
In order to create an array, we use the new
operator:
type array-variable[];
array-variable = new type[size];
This creates a new array to hold size elements of
type type, which reference will be kept in the
variable array-variable.

L 2.9
Array Indexing

Later we can refer to the elements of this array through


their indexes:
array-variable[index]
The array index always starts with zero!
The Java run-time system makes sure that all array
indexes are in the correct range, otherwise raises a run-
time error.

L 2.10
Array Initialization

Arrays can be initialized when they are declared:


int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified
elements

L 2.11
Multidimensional Arrays
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation: int array = new int[3][3];
3) initialization
int array[][] = {{1,2,3},{2,4,5},{4,4,5}};

L 2.12
Type Casting

General form: (targetType) value


Examples:
1) integer value will be reduced module bytes
range:
int i;
byte b = (byte) i;
2) floating-point value will be truncated to
integer value:
float f;
int i = (int) f;

L 3.9
CONTROL STATEMENT
 if –else
 switch
 Loop
 for
 while
 do-while
CONTROL STATEMENT
 “Enhance for” or “for-each”
 automatically cycles through an array in sequence from the
lowest index to the highest.
 Syntax : for(type itr-var : collection) statement-block
 Example:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
 Advantage: Avoid boundary error
CONTROL STATEMENT
 break
 Exits out of a loop or switch statement
 Unlabeled break exits out of the innermost loop or switch
 Use labeled break to exit out of nested loops or switch or block.
JUMP STATEMENT
public class BreakExample {
public static void main( String args[] ) {
for ( int row = 0; row < 5; row++ ) {
System.out.println("Outer loop: " + row);
for ( int column = 0; column < 4 ; column++ ) {
System.out.print(column +" " );
if ( ((row + column) % 2 ) == 0 ) {
System.out.println("Break " );
break;
}
}
}
}
}
JUMP STATEMENT
 continue
 A continue statement skips to the end of the current
loop's body.
 The loop's boolean expression is then evaluated.
REFERENCE
 Java- The Complete Reference Chapter 1-5
Simple Java Program
A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}

4.1
CLASSES
• Class is blue print or an idea of an Object
• From One class any number of Instances can be
created
• It is an encapsulation of attributes and methods

class
FIGURE
Ob1 Ob3

CIRCLE Ob2 SQUARE


RECTANGLE

L 3.1
Class
A basis for the Java language.
Each concept we wish to describe in Java must be
included inside a class.
A class defines a new data type, whose values are
objects:
A class is a template for objects
An object is an instance of a class

L 4.6
syntax of CLASS

class <ClassName>
{
Attributes/Variables;
Constructors();
Methods();
}

L 3.2
INSTANCE
• Instance is an Object of a class which is an entity with
its own attribute values and methods.

• Creating an Instance

ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();

L 3.3
Class Definition

 A class contains a name, several variable declarations


(instance variables) and several method declarations. All
are called members of the class.
 General form of a class:
class classname {
type instance-variable-1;

type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }

type method-name-m(parameter-list) { … }
}
L 4.7
Example: Class Usage
class Box {
double width;
double height;
double depth;
}

class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;

mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;

vol = mybox.width * mybox.height * mybox.depth;


System.out.println ("Volume is " + vol);

} L 4.8

}
Constructor
A constructor initializes the instance variables of an object.
It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
constructor is the same class
When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.

L 5.1
Example: Constructor
class Box {
double width;
double height;
double depth;

Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
L 5.2
Parameterized Constructor
class Box {
double width;
double height;
double depth;

Box(double w, double h, double d) {


width = w; height = h; depth = d;
}

double volume() {
return width * height * depth;
}
} L 5.3
Methods

 General form of a method definition:


type name(parameter-list) {
… return value;

}
 Components:
1) type - type of values returned by the method. If a method
does not return any value, its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.
L 5.4
Example: Method

Classes declare methods to hide their internal data


structures, as well as for their own internal use: Within a
class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
L 5.5
Parameterized Method

Parameters increase generality and applicability of


a method:
1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }
Parameter: a variable receiving value at the time
the method is invoked.
Argument: a value passed to the method when it is
invoked.
L 5.6
Keyword this

• Can be used by any object to refer to itself


in any class method
• Typically used to
– Avoid variable name collisions
– Pass the receiver as an argument

L 6.5
Keyword this

Keyword this allows a method to refer to the object


that invoked it.
It can be used inside any method to refer to the
current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
L 6.6
Method Overloading

It is legal for a class to have two or more methods


with the same name.
However, Java has to be able to uniquely associate
the invocation of a method with its definition
relying on the number and types of arguments.
Therefore the same-named methods must be
distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to
implement polymorphism.

L 7.1
Example: Overloading
class OverloadDemo {
void test()
{
System.out.println("No parameters");
}

void test(int a)
{
System.out.println("a: " + a);
}

void test(int a, int b)


{
System.out.println("a and b: " + a + " " + b);
}

double test(double a)
{
System.out.println("double a: " + a); return a*a;
}
L 7.2

}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
L 7.3

You might also like