O O P Java: Bject Riented Rogramming in

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

Object Oriented

Programming in JAVA
Introduction
• Welcome to the course Advance Object
Oriented Programming in JAVA. This course
will cover a core set of computer science
concepts needed to create a modern software
application using Java.

5/4/2018 Object Oriented Programming using JAVA 2


Course Objectives
On completion of this course we will be able to:

1. Identify the importance of Java .


2. Identify the additional features of Java compared to C++ .
3. Identify the difference between Compiler and Interpreter .
4. Identify the difference between applet and application .
5. Apply Advance Object Oriented Principles of Encapsulations,
Data abstraction, Inheritance, Polymorphism.
6. Program using java API (Application Programming Interface).
7. Program using Exception Handling, Files and Threads .
8. Program Using applets and swings .

5/4/2018 Object Oriented Programming using JAVA 3


JAVA Basics
Why Java is Important
• Two reasons :
– Trouble with C/C++ language is that they are not
portable and are not platform independent
languages.
– Emergence of World Wide Web, which demanded
portable programs
• Portability and security necessitated the
invention of Java
History
• James Gosling - Sun Microsystems
• Co founder – Vinod Khosla
• Oak - Java, May 20, 1995, Sun World
• JDK Evolutions
– JDK 1.0 (January 23, 1996)
– JDK 1.1 (February 19, 1997)
– J2SE 1.2 (December 8, 1998)
– J2SE 1.3 (May 8, 2000)
– J2SE 1.4 (February 6, 2002)
– J2SE 5.0 (September 30, 2004)
– Java SE 6 (December 11, 2006)
– Java SE 7 (July 28, 2011)
Cont..
• Java Editions.
J2SE(Java 2 Standard Edition) - to develop
client-side standalone applications or applets.
J2ME(Java 2 Micro Edition ) - to develop
applications for mobile devices such as cell
phones.
J2EE(Java 2 Enterprise Edition ) - to develop
server-side applications such as Java servlets
and Java ServerPages.
What is java?

• A general-purpose object-oriented language.

• Write Once Run Anywhere (WORA).

• Designed for easy Web/Internet applications.

• Widespread acceptance.
How is Java different from C…
• C Language:
– Major difference is that C is a structure oriented language and
Java is an object oriented language and has mechanism to
define classes and objects.
– Java does not support pointer type
– Java does not have preprocessor, so we cant use #define,
#include and #ifdef statements.
– Java does not include structures, unions and enum data types.
– Java does not include keywords like goto, sizeof and typedef.
– Java adds labeled break and continue statements.
– Java adds many features required for object oriented
programming.
How is Java different from C++…
• C++ language
Features removed in java:
 Java doesn’t support pointers to avoid unauthorized access
of memory locations.
 Java does not include structures, unions and enum data
types.
 Java does not support operator over loading.
 Preprocessor plays less important role in C++ and so
eliminated entirely in java.
 Java does not perform automatic type conversions that
result in loss of precision.
Cont…
 Java does not support global variables. Every method and
variable is declared within a class and forms part of that
class.
 Java does not support inheritance of multiple super classes
by a sub class (i.e., multiple inheritance). This is
accomplished by using ‘interface’ concept.
 It is not possible to declare unsigned integers(Unsigned can
hold a larger positive value, and no negative value.
Unsigned uses the leading bit as a part of the value, while
the signed version uses the left-most-bit to identify if the
number is positive or negative) in java.
 In java objects are passed by reference only. In C++ objects
may be passed by value or reference.
Cont …
New features added in Java:

 Multithreading, that allows two or more pieces of the


same program to execute concurrently.
 C++ has a set of library functions that use a common
header file. But java replaces it with its own set of
API(Application Programming Interface) classes.
 It adds packages and interfaces.
 Java supports automatic garbage collection.
 break and continue statements have been enhanced in
java to accept labels as targets.
Cont …
Features that differ:

 Though C++ and java supports Boolean data type, C++ takes
any nonzero value as true and zero as false. True and false in
java are predefined literals that are values for a boolean
expression.
 Java has replaced the destructor function with a finalize()
function.
 C++ supports exception handling that is similar to java's.
However, in C++ there is no requirement that a thrown
exception be caught.
Characteristics of Java
• Java is simple • Java is architecture-neutral
• Java is object-oriented • Java is portable
• Java is distributed • Java’s performance
• Java is interpreted • Java is multithreaded
• Java is robust • Java is dynamic
• Java is secure
• Simple
According to Sun, Java language is simple because syntax is based on C++ (so easier for programmers to
learn it after C++). It removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc. No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.

• Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior. Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.

• Platform Independent
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.
The Java platform differs from most other platforms in the sense that it is a software-based platform that runs
on the top of other hardware-based platforms. It has two components:

5/4/2018 Object Oriented Programming using JAVA 15


• Runtime Environment
• API(Application Programming
Interface)
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).

• Secured
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
5/4/2018 Object Oriented Programming using JAVA 16
• Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers
that avoids security problem. There is automatic garbage collection in java. There is exception
handling and type checking mechanism in java. All these points makes java robust.

• Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is fixed.
In C programming, in data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for
64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and 64 bit architectures.

5/4/2018 Object Oriented Programming using JAVA 17


• Portable
We may carry the java bytecode to any platform.

• High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower than a compiled language (e.g.,
C++)

• Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed applications. We may access files by calling the

• Interpreted
methods from any machine on the internet.

The compiler takes your .java file and compiles it into a .class file (the .class file contains Java byte code).
The interpreter comes in when your program is run. The JVM (or interpreter) takes your .class file and interprets it.

• Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications etc.

5/4/2018 Object Oriented Programming using JAVA 18


Java Environment
• Java includes many development tools, classes and
methods
– Development tools are part of Java Development Kit (JDK) and
– The classes and methods are part of Java Standard Library (JSL),
also known as Application Programming Interface (API).
• JDK constitutes of tools like java compiler, java
interpreter and many.
• API includes hundreds of classes and methods grouped
into several packages according to their functionality.
Example
• File: HelloWorldApp.java

public class HelloWorldApp{

public static void main(String[] args) {

System.out.println("Hello world");

}
}
Compile and Execute
Things to remember
• Name of file must match name of class
– It is case sensitive

• Processing starts in main


– public static void main(String[] args)

• Printing is done with System.out


– System.out.println, System.out.print

• Compile with “javac”


– Open DOS/command prompt window; work from there
– Supply full case-sensitive file name (with file extension)

• Execute with “java”


– Supply base class name (no file extension)
An idiom explained
• You will see the following line of code often:
– public static void main(String args[]) { …}

• About main()
– “main” is the function from which your program starts

– Why public?
• So that run time can call it from outside

– Why static ?
• it is made static so that we can call it without creating an object

– What is String args[] ?


• Way of specifying input at startup of application
Things to Remember
• “+” operator when used with Strings concatenates them
– System.out.pritln(“Hello” + “World”) will produce Hello World on console

– String concatenated with any other data type such as int will also
convert that datatype to String and the result will be a concatenated
String displayed on console
• For Example
– int i = 4
– int j = 5 ;
– System .out.println (“Hello” + i) // will print Hello 4 on screen
• However
– System,.out..println( i+j) ; // will print 9 on the console

– For comparing Strings never use == operator, use equals


methos.
• == compares addresses (shallow comparison) while equals
compares values (deep comparison)
• E.g string1.equals(string2)
String Concatenation
public class StringTest {

public static void main(String[] args) {


int i = 4;
int j = 5;

System.out.println("Hello" + i);
System.out.println(i + j);

String s1 = new String (“pakistan”);


String s2 = “pakistan”;

if (s1 == s2) {
System.out.println(“comparing string using == operator”);
}

if (s1.equals( s2) ) {
System.out.println(“comparing string using equal method”);
}
}
}
Compile and Execute
Taking in Command
Line Arguments
Taking in Command Line Arguments
/* This program will take two arguments Hello World from the command prompt
and prints them to standard console. If you specify less than two arguments
an exception will be thrown */

public class TwoArgsApp {

public static void main(String[] args) {

//Displays the first argument on console


System.out.println(“First argument “ + args[0]);

//Displays the second argument on console


System.out.println(“Second argument “ + args[1]);
}
}
Compile and Execute
Passing any Number of Arguments
/* This program is able to receive any number of arguments and prints them to console using for loop. In
java, arrays knows about their size by using length property
*/

public class AnyArgsApp {

public static void main(String[] args) {

for (int i=0; i<args.length; i++)


{

// The “+” operator here works similar to “<<“ operator in C++. This line is
// equivalent to cout<<“Arguments:”<<i<<“value”<<args[i];
// where cout is replaced by System.out.println, and “<<“ is replaced by + for
// concatenation

System.out.println(“Argument:” + i + “value: ” + args[i] );


}
}
}
Compile and Execute
Primitives Vs. Objects
Primitives Vs. Objects
• Everything in Java is an “Object”, as every class by default inherits from class
“Object” , except a few primitive data types, which are there for efficiency reasons.

• Primitive Data Types


– 8 Primitive Data types of java
• boolean, byte  1 byte
• char, short  2 bytes
• int, float  4 bytes
• long, double  8 bytes

• Primitive data types are generally used for local variables, parameters and instance
variables (properties of an object)

• Primitive datatypes are located on the stack and we can only access their value,
while objects are located on heap and we have a reference to these objects

• Also primitive data types are always passed by value while objects are always
passed by reference in java. There is no C++ like methods
– void someMethod(int &a, int & b ) // not available in java
Primitives (cont)
• For all built-in primitive data types java
uses lowercase. E.g int , float etc

• Primitives can be stored in arrays

• You cannot get a reference to a primitive


– To do that you need an Object or a Wrapper
class
Input / Output
Java Inputting

There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a
delimiter that is whitespace by default. It provides many methods
to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and
primitive types using regular expression.

Java Scanner class extends Object class and implements Iterator


and Closeable interfaces.

5/4/2018 Object Oriented Programming using JAVA 36


Console based Output
System.out
• System class
– Out represents the screen
• System.out.println()
– Prints the string followed by an end of line
– Forces a flush
• System.out.print()
– Does not print the end of line
– Does not force a flush
• System.out.flush()
– Force a flush
flush() is used to empty the buffer data between the server and
the client.
5/4/2018 Object Oriented Programming using JAVA 38

You might also like