Sei sulla pagina 1di 46

Object Oriented Programming

Introduction to OOP: Evolution of Java, OOP principles, Java Buzzwords, Implementing Java
program, JVM, Data Types, Variables, Type conversions and Casting, Operators, Control
statements, Arrays.

Evolution of Java

What is Java?

Java is a programming language and a platform.

 Java is a high level, robust, secured and object-oriented


programming language.

 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.

Types of Java Applications

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 Swings 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 servlets, jsp, struts 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 (J2ME) are used for creating mobile applications.
Where it is used?

1. Desktop Applications such as acrobat reader, media player,


antivirus etc.
2. Web Applications such as irctc.co.in, cleartrip.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.

The Two Paradigms

All computer programs consist of two elements: code and data.


Some programs are written around “what is happening” and others are
written around “who is being affected.”

The two paradigms that govern how a program is constructed.

1. Process-oriented model:

o This approach characterizes a program as a series of linear steps


(i.e. Code).
o The process-oriented model can be thought of as code
acting on data.
o Procedural languages such as C employ this model to
considerable success. Problems with this approach appear as
programs grow larger and more complex.
o To manage increasing complexity, the second approach, called
object-oriented programming, was conceived.
In this approach, the problem is always considered as a sequence of
tasks to be done. A number of functions are written to accomplish these tasks.
Here primary focus on “Functions” and little attention on data.
There are many high level languages like COBOL, FORTRAN, PASCAL,
C used for conventional programming commonly known as POP.
POP basically consists of writing a list of instructions for the computer
to follow, and organizing these instructions into groups known as functions.

A typical POP structure is shown in below:


Normally a flowchart is used to organize these actions and represent the flow
of control logically sequential flow from one to another.
In a multi-function program, many important data items are placed as
global so that they may be accessed by all the functions. Each function may
have its own local data.
Global data are more vulnerable to an in advent change by a function. In
a large program it is very difficult to identify what data is used by which
function. In case we need to revise an external data structure, we should also
revise all the functions that access the data. This provides an opportunity for
bugs to creep in.

Drawback: It does not model real world problems very well,


because functions are action oriented and does not really
corresponding to the elements of the problem.

Characteristics of POP:
 Emphasis is on doing actions.
 Large programs are divided into smaller programs known as functions.
 Most of the functions shared global data.
 Data move openly around the program from function to function.
 Functions transform data from one form to another.
 Employs top-down approach in program design.

2. Object-oriented programming Model


o Organizes a program around its data (i.e objects) and a set of
well-defined interfaces to that data.

o An object-oriented program can be characterized as data

controlling access to code.


OOP allows us to decompose a problem into a number of entities called
objects and then builds data and methods around these entities.
DEF: “OOP is an approach that provides a way of modularizing

programs by creating portioned memory area for both data and


methods that can used as templates for creating copies of such
modules on demand.”
An object is considered to be a partitioned area of computer memory
that stores data and set of operations that can access that data.
Since the memory partitions are independent, the objects can be used in
a variety of different programs without modifications.

Organization of OOP:

method
method

method
Characteristics of OOPs:
 Emphasis on data.
 Programs are divided into what are known as methods.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together.
 Data is hidden.
 Objects can communicate with each other through methods.
 Reusability.
 Follows bottom-up approach in program design.
Difference between Procedure Oriented Programming (POP) & Object Oriented
Programming (OOP)

Procedure Oriented Programming Object Oriented Programming


Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions. called objects.
Importance In POP, Importance is not given In OOP, Importance is given to the data
to data but to functions as well rather than procedures or functions
as sequence of actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
start building the highest level of make the smallest pieces of your
abstraction and then make small bits program first and then use them as
that will fit it blocks to build a bigger program
Access POP does not have any access OOP has access specifiers named
Specifiers specifier. public, private, protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in POP OOP provides an easy way to add new
is not so easy. data and function.
Data Access In POP, Most function uses Global In OOP, data cannot move easily from
data for sharing that can be accessed function to function, it can be kept
freely from function to function in the public or private so we can control the
system. access of data.
Data Hiding POP does not have any proper OOP provides Data Hiding so
way for hiding data so it is less provides more security.
secure.
Overloading In POP, Overloading is not In OOP, overloading is possible in
possible. the form of Function Overloading
and Operator Overloading.
Examples Example of POP is: C, VB, Example of OOP is: C++, JAVA,
FORTRAN, and Pascal. VB.NET, C#.NET.
The Three OOP Principles
All object-oriented programming languages provide mechanisms that
help you implement the object-oriented model. They are

1. Encapsulation
2. Inheritance
3. Polymorphism.

1. Encapsulation

Encapsulation is the mechanism that binds


together code and the data it manipulates, and
keeps both safe from outside interference and
misuse.
I.e. Binding (or wrapping) code and data together into a single unit is
known as encapsulation.

Access to the code and data inside the wrapper is tightly controlled
through a well-defined interface.

Date Hiding + Abstraction

For example:

A capsule, it is wrapped with different medicines

A Power Steering Car (Internally lot of Components tightly Coupled


together)

A java class is the example of encapsulation.

A class defines the structure and behavior (data and code) that will be
shared by a set of objects.
Object: Any entity that has state and behavior is known as an
object.

For example: chair, pen, table, keyboard, bike etc. It can be


physical and logical.

Each object of a given class contains the structure and behavior defined
by the class, Hence objects are sometimes referred to as instances of a
class.

“Thus a class is a logical construct; an object has physical


reality.”

The mechanisms for hiding the complexity of the implementation inside the
class
Each method or variable in a class may be marked private or public.
The public interface of a class represents everything that external users
of the class need to know, or may know.
The private methods and data can only be accessed by code that is a
member of the class. Therefore, any other code that is not a member of the
class cannot access a private method or variable. i.e. Data hiding is possible
with private access specifier.

public interface should be carefully designed not to expose too much of


the inner workings of a class.

Abstraction: Hiding internal details and showing functionality is

known as abstraction. For example: phone call, we don't know the


internal processing, ATM card access etc.

In java, we use “ abstract class and interface” to achieve abstraction.


Exposing only the required essentials characteristics & behavior with respect
to the context.i.e. Shows important things to the user and hide the internals
details.

Encapsulation = Data hiding + Abstraction

****Encapsulation provides Security, But Increases length of the code and time
for execution.

2. Inheritance

“Inheritance is the process by which one object acquires the

properties of another object. This is important because it supports


the concept of hierarchical classification.”

When one object acquires all the properties and behaviors of parent
object i.e. known as inheritance.

It provides code reusability, extensibility, flexible to change


but tight coupling between parent and child classes. If any change in parent
class affects to all sub classes also.

This is one way from top to bottom of hierarchy.

Example:

Property transfer from Grand Parent to Parent – to children.


Without the use of hierarchies, each object would need to define all of
its characteristics explicitly. However, by use of inheritance, an object need
only define those qualities that make it unique within its class. It can inherit its
general attributes from its parent.

3. Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that
allows one interface to be used for a general class of actions. The specific
action is determined by the exact nature of the situation.

Example:
You might have a program that requires three types of stacks. One stack
is used for integer values, one for floating point values, and one for
characters. The algorithm that implements each stack is the same, even
though the data being stored differs. In a non–object-oriented language, you
would be required to create three different sets of stack routines, with each set
using different names.

However, because of polymorphism, in Java you can specify a general


set of stack routines that all share the same names.

Polymorphism is often expressed by the phrase “one interface, multiple


methods.” This means that it is possible to design a generic interface to a
group of related activities. This helps reduce complexity by allowing the same
interface to be used to specify a general class of action. It is the compiler’s job
to select the specific action (that is, method) as it applies to each situation

When one task is performed by different ways i.e. known as


polymorphism.

For example: to convince the customer differently, to draw something e.g.


shape or rectangle etc.

i.e The process of representing one form in multiple forms is known as


polymorphism.

e.g. When we are in class – student ,

When we are in Market – Customer,

When we are in Home – Son / Daughter.


In java, we use method overloading and method overriding to achieve
polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks
woof etc.

When properly applied, polymorphism, encapsulation, and inheritance


combine to produce a programming environment that supports the
development of far more robust and scalable programs than does the process-
oriented model.
A well-designed hierarchy of classes is the basis for reusing the code in
which you have invested time and effort developing and testing.
Encapsulation allows you to migrate your implementations over time
without breaking the code that depends on the public interface of your
classes.

Polymorphism allows you to create clean, sensible, readable, and


resilient code.

Evolution of Java

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-
top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.

Why sun choosed "Oak" name?

5) Why Oak? Oak is a symbol of strength and choosen as a national tree of


many countries like U.S.A., France, Germany, Romania etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark


by Oak Technologies.

Why sun choosed "Java" name?

7) Why they choosed java name for java language? The team gathered to choose a
new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt",
"DNA" etc. They wanted something that reflected the essence of the technology:
revolutionary, dynamic, lively, cool, unique, and easy to spell and fun to say.

According to James Gosling "Java was one of the top choices along with Silk". Since
java was so unique, most of the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java
coffee).

9) Notice that Java is just a name not an acronym.

10) Originally developed by James Gosling at Sun Microsystems (which is now a


subsidiary of Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).

Java Version History

There are many java versions that have been released. Current stable release of
Java is Java SE 8.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

The initial release of Java was nothing short of revolutionary, but it did not mark
the end of Java’s era of rapid innovation.

Java 1.1 added many new library elements, redefined the way events are
handled, and reconfigured many features of the 1.0 library. Java 1.1 both added to
and subtracted from attributes of its original specification.

The next major release of Java was Java 2, where the “2” indicates “second
generation.” With Java 2, Sun repackaged the Java product as J2SE (Java 2
Platform Standard Edition), and the version numbers began to be applied to that
product.

Java 2 added support for a number of new features, such as Swing and the
Collections Framework, and it enhanced the Java Virtual Machine and various
programming tools. Java 2also contained a few deprecations. The most important
affected the Thread class in whichthe methods suspend( ), resume( ), and stop( )
were deprecated.

J2SE 1.3 was the first major upgrade to the original Java 2 release. For the
most part,it added to existing functionality and “tightened up” the development
environment. In general, programs written for version 1.2 and those written for
version 1.3 are source-code compatible. Although version 1.3 contained a smaller
set of changes than the preceding three major releases, it was nevertheless
important.

The release of J2SE 1.4 further enhanced Java. This release contained
several important upgrades, enhancements, and additions. Like it added the new
keyword assert, chained exceptions, and a channel-based I/O subsystem, made
changes to the Collections Framework and the networking classes.

The next release of Java was J2SE 5, and it was revolutionary, J2SE 5
fundamentally expanded the scope, power, and range of the language. To grasp the
magnitude of the
o Generics
o Annotations
o Auto boxing and auto-unboxing
o Enumerations
o Enhanced, for-each style for loop
o Variable-length arguments (varargs)
o Static import
o Formatted I/O
o Concurrency utilities
“5” in J2SE 5 is called the product version number.
The next release of Java was called Java SE 6. Java Platform, Standard
Edition 6.The Java Developer’s Kit was called JDK 6. It enhanced the API libraries,
added several new packages, and offered improvements to the runtime.
Java SE 7 The newest release of Java is called Java SE 7, with the Java
Developer’s Kit being called JDK 7, and an internal version number of 1.7. Java SE 7
is the first major release of Java since Sun Microsystems was acquired by Oracle (a
process that began in April 2009 and that was completed in January 2010).

Java SE 7 contains many new features, including significant additions to the


language and the API libraries. Upgrades to the Java run-time system that support
non-Java languages are also included.
• A String can now control a switch statement.
• Binary integer literals.
• Underscores in numeric literals.
• An expanded try statement, called try-with-resources that
supports automatic resource management.
• Type inference (via the diamond operator) when constructing
a generic instance.
• Enhanced exception handling in which two or more
exceptions can be caught by a
• single catch (multi-catch) and better type checking for
exceptions that are rethrown.
• Simplifying the creation and use of tasks that can execute
concurrently
• Automatically making use of multiple processors

Java SE 7 is the latest release in Java’s ongoing, dynamic history

Java SE 8 , is the Java Platform , Standard Edition 8 which is the latest version of
java with the following features

• forEach() method in Iterable interface


• default and static methods in Interfaces
• Functional Interfaces and Lambda Expressions
• Java Stream API for Bulk Data Operations on Collections
• Java Time API
• Collection API improvements
• Concurrency API improvements
• Java IO improvements
• Miscellaneous Core API improvements

Java Program Structure & Implementing a Java Program

public class Simple


{

public static void main(String args[])


{
System.out.println("Hello Java");
}
}

save this file as Simple.java

The Execution can be done in two ways

1. By Setting class path each time

COMPILATION:

To execute a java program we require setting a class path:


D:\ >set path= C:\Program Files\Java\jdk1.6.0\bin;.;
D:\ >javac Simple.java

EXCEUTION:

D:\ >java Simple

2. By Setting class path permanently

COMPILATION:
D:\ >javac Simple.java

EXCEUTION:

D:\ >java Simple

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents visibility, it means it is
visible to all.
o static is a keyword, if we declare any method as static, it is known as static
method. The core advantage of static method is that there is no need to
create object to invoke the static method. The main method is executed by the
JVM, so it doesn't require to create object to invoke the main method. So it
saves memory.
o void is the return type of the method, it means it doesn't return any value.
o main represents startup of the program.
o String[] args is used for command line argument.
o System.out.println() is used print statement.

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact
with OS) and converts the java code into byte code.

What happens at runtime?

At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
Interpreter: read byte code stream then execute the instructions.
JVM Architecture

JVM (Java Virtual Machine) is an abstract machine. It is a specification


that provides runtime environment in which java byte code can be executed.

JVMs are available for many hardware and software platforms. JVM, JRE
and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent.

JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
2. An implementation its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
1) Classloader
Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime


constant pool, class data , field and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and
plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual


machine instruction currently being executed.
6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine
It contains:
1) A virtual processor
2) Interpreter: Read byte code stream then execute the instructions.
3) Just-In-Time(JIT) compiler: It is used to improve the performance.JIT
compiles parts of the byte code that have similar functionality at the same
time, and hence reduces the amount of time needed for compilation. Here
the term compiler Refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.
4. Garbage Collector: Automatic freeing of Heap Memory.

JRE

JRE is an acronym for Java Runtime Environment. It is used to provide


runtime environment. It is the implementation of JVM. It physically exists. It
contains set of libraries + other files that JVM uses at runtime.

Implementation of JVMs is also actively released by other companies


besides Sun Micro Systems.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains


JRE + development tools.
A Java Runtime Environment (JRE) is a prerequisite for running Java
applications on any computer. A JRE contains a Java Virtual Machine (JVM),
all standard, core java classes and runtime libraries. It does not contain any
development tools such as compiler, debugger, etc.
JDK (Java Development Kit) is a whole package required to Java
Development which essentially contains JRE+JVM, and tools required to
compile and debug, execute Java applications.
Java’s Magic: The Bytecode

The key that allows Java to solve both the security and the portability
problems is that the output of a Java compiler is not executable code. Rather,
it is bytecode.

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). In essence, the original JVM was designed as an interpreter
for bytecode.

Translating a Java program into bytecode makes it much easier to run a


program in a wide variety of environments because only the JVM needs to be
implemented for each platform.

Once the run-time package exists for a given system, any Java program can
run on it. Remember, although the details of the JVM will differ from platform
to platform, all understand the same Java bytecode.
The execution of bytecode by the JVM is the easiest way to create truly
portable programs.

The fact that a Java program is executed by the JVM also helps to make
it secure. Because the JVM is in control, it can contain the program and
prevent it from generating side effects outside of the system.

In general, when a program is compiled to an intermediate form and


then interpreted by a virtual machine, it runs slower than it would run if
compiled to executable code.

However, with Java, the differential between the two is not so great.
Because bytecode has been highly optimized, the use of bytecode enables the
JVM to execute programs much faster than you might expect.

In order to boost performance. For this reason, the HotSpot technology


was introduced a Just-In-Time (JIT) compiler for bytecode. When a JIT
compiler is part of the JVM, selected portions of bytecode are compiled into
executable code in real time, on a piece-by-piece, demand basis.

It is important to understand that it is not practical to compile an entire


Java program into executable code all at once, because Java performs various
run-time checks that can be done only at run time. Instead, a JIT compiler
compiles code as it is needed, JIT compiles parts of the byte code that have
similar functionality at the same time, and hence reduces the amount of time
needed for compilation. during execution.

Furthermore, not all sequences of bytecode are compiled—only those


that will benefit from compilation. The remaining code is simply interpreted.
However, the just-in-time approach still yields a significant performance boost.
Java Buzz words
The Features and characteristics of Java also called Java Buzz words.

1. Simple

Java was designed to be easy for the professional programmer to learn


and use effectively. Because Java inherits the C/C++ syntax and many of the
object-oriented features of C++, most programmers have little trouble learning
Java.

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.

2. 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 simplifies
software development and maintenance by providing some rules.
The concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

3. 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:

1. Runtime Environment
2. 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).

4. Secured

Java is secured because:

o No explicit pointer
o Java Programs run inside virtual machine sandbox

 Classloader: adds security by separating the package for the


classes of the local file system from those that are imported from
network sources.
 Bytecode Verifier: checks the code fragments for illegal code that
can violate access right to objects.
 Security Manager: determines what resources a class can access
such as reading and writing to the local disk.

These securities are provided by java language. Some security can also be
provided by application developer through SSL, JAAS, Cryptography etc.
5. Robust

Robust simply means strong. The ability to create robust programs was
given a high priority in the design of Java. Because the program must
execute reliably in a variety of systems.

Thus, to gain reliability and to be robust it has

a) Java uses strong memory management:


For example, in C/C++, the programmer must manually allocate and free
all dynamic memory. This sometimes leads to problems, because
programmers will either forget to free memory that has been previously
allocated or, worse, try to free some memory that another part of their
code is still using. Java virtually eliminates these problems by
managing memory allocation and deallocation for you. ( deallocation is
completely automatic, because Java provides automatic garbage
collection for unused objects.)

b) Exception handling

Java restricts you in a few key areas to force you to find your mistakes
early in program development. Exceptional conditions in traditional
environments often arise in situations such as division by zero or “file
not found,” and they must be managed with clumsy and hard-to-read
constructs. Java helps in this area by providing object-oriented
exception handling to overcome runtime errors.

c) type checking mechanism


Because Java is a strictly typed language, it checks your code at
compile time. However, it also checks your code at run time.

d) lack of pointers that avoids security problem

6. Architecture-neutral
Operating system upgrades, processor upgrades, and changes in
core system resources can all combine to make a program malfunction.

The Java designers made several hard decisions in the Java


language and the Java Virtual Machine in an attempt to alter this
situation. Their goal was “write once; run anywhere, anytime, forever.”
To a great extent, this goal was accomplished.
There are no implementation dependent features e.g. size of primitive
types is fixed. In C programming, int 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.

7. Portable

We may carry the java byte code to any platform without any
minimal changes.

8. High-performance

The Java bytecode was carefully designed so that it would be easy to


translate directly into native machine code for very high performance by using
a just-in-time compiler. Java run-time systems that provide this
feature lose none of the benefits of the platform-independent code.

9. Distributed

We can create distributed applications in java.


Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols. Java supports Remote Method Invocation (RMI),
Enterprize Java Beans (EJB) This feature enables a program to invoke
methods across a network.

10. 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.

11. Interpreted
The byte code produced after compilation is interpreted by JVM and
produces the native code of the system.

The byte code is optimized set of instructions.

12. Dynamic

Java is widely accepted programming language to communicate with


servers and produce dynamic content needed by the client. (Users).

It supports API (Application Program Interface) to access database or


any server resources.
Data Types in Java
Java is a strongly typed language
1. Every variable has a type, every expression has
a type, and every type is strictly defined.

2. All assignments, whether explicit or via


parameter passing in method calls, are checked
for Type compatibility.

3. There are no automatic coercions or


conversions of conflicting types as in some
languages.

4. The Java compiler checks all expressions and


parameters to ensure that the types are
compatible.

5. Any type mismatches are errors that must be


corrected before the compiler will finish
compiling the class.

“Data types represent the different values to be stored


in the variable”
In java, there are two types of data types:
1. Primitive data types
2. Non – Primitive Data Types
Data Type Default Value Default size (Width)

boolean False 1 bit (0 or 1)


char '\u0000' 2 byte (16 bits)
byte 0 1 byte (8 bits)
short 0 2 byte (16 bits)
int 0 4 byte (32 bits)
long 0L 8 byte (64bits)
float 0.0f 4 byte (32 bits)
double 0.0d 8 byte (64 bits)
 All of integer data types are signed, positive and
negative values. Uses 2’s complement notation for
representing integer values.
 Java does not support unsigned, positive-only integers

 Java implements the standard IEEE–754 for floating-


point types.

 There are two kinds of floating-point types, float and


double which represent single (32bits) - and double
(64bits)-precision numbers.

 Java has a primitive type, called boolean, for logical


values. It can have only one of two
possible values, true or false.

Integer Type Range

Name Width in Bits Range


64 (8 Bytes) –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
long
32 (4 Bytes) –2,147,483,648 to 2,147,483,647
int
16 (2 Bytes) –32,768 to 32,767
short
8 (1 Byte) –128 to 127
byte

Floating Point Range

Name Width in Bits Range


double 64 (8 Bytes) 4.9e–324 to 1.8e+308
float 32 (4 Bytes) 1.4e–045 to 3.4e+038

Character type Range

Name Width in Bits Range


char 16 (2 Bytes) 0 to 65,535 (no negative characters)
UNI – CODE system
Unicode System

Java Character set uses Unicode system.


Unicode is a universal international standard
character encoding that is capable of representing
most of the world's written languages.
Before Unicode, there were many language
standards:
o ASCII (American Standard Code for Information

Interchange) for the United States.

In Unicode, character holds 2 byte, so java also uses


2 byte for characters.

 Java uses Unicode to represent characters.


 Unicode defines a fully international character set
that can represent all of the characters found in
all human languages.
 It is a unification of dozens of character sets, such
as Latin, Greek, Arabic,
 Cyrillic, Hebrew, Katakana, Hangul, and many
more.
 The range of a char is 0 to 65,535.
 There are no negative chars.
 The standard set of characters known as ASCII
still ranges from 0 to 127 as always,
 Since Java is designed to allow programs to be
written for worldwide use, it makes sense that it
would use Unicode to represent characters.
Control Statements

Java if-else Statement

The Java if statement is used to test the condition. It checks boolean


condition: true or false. There are various types of if statement in java.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.

The case constant can be integer constant, character constant or string constant.

switch(expression)
{
case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional
......
default:
// code to be executed if all cases are not matched;
}

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output: 20
Java Switch Statement is fall-through

The java switch statement is fall-through. It means it executes all


statement after first match if break statement is not used with
switch cases.

Example:

public class SwitchExample2


{
public static void main(String[] args)
{
int number=20;
switch(number)
{
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output:

20
30
Not in 10, 20 or 30
//switch using String constants
import java.util.*;
public class SwitchDemo
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the two nos");
int a = sc.nextInt();
int b = sc.nextInt();

System.out.println("Enter your choice");


String ch = sc.next() ; //string
int c=0;
switch(ch)
{
case "add" : c=a+b;break;
case "sub" : c=a-b;break;
case "mul" : c=a*b;break;
case "div" : c=a/b;break;
case "rem" : c=a%b;break;
}
System.out.println("The result is "+ c);
}
}
Java while Loop

The Java while loop is used to iterate a part of the program


several times. If the number of iteration is not fixed, it is
recommended to use while loop.

Syntax:

while(condition)
{
//code to be executed
}

Java Infinitive While Loop

If you pass true in the while loop, it will be infinitive while loop.

while(true)
{
System.out.println("infinitive while loop");
}

Output:

infinitive while loop


infinitive while loop
ctrl+c

Java do-while Loop


The Java do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use do-while loop.

The Java do-while loop is executed at least once because condition


is checked after loop body.

Syntax:
do
{
//code to be executed
}while(condition);

If you pass true in the do-while loop, it will be infinitive do-while


loop.

do{
System.out.println("infinitive do while loop");
}while(true);

Output:

infinitive do while loop


infinitive do while loop
ctrl+c

Java for Loop

The Java for loop is used to iterate a part of the program several
times. If the number of iteration is fixed, it is recommended to use
for loop.

There are three types of for loop in java.

o Simple For Loop


o For-each or Enhanced For Loop

1. Java Simple for Loop

The simple for loop is same as C/C++. We can initialize variable,


check condition and increment/decrement value.

Syntax:

for(initialization;condition;incr/decr)
{
//code to be executed
}
Example:

for(int i=1;i<=10;i++)
{
System.out.println(i);
}

2. Java for-each Loop

The for-each loop is used to traverse array or collection in java. It


is easier to use than simple for loop because we don't need to
increment value and use subscript notation.

It works on elements basis not index. It returns element one by


one in the defined variable.

Syntax:

for(type var :array)


{
//code to be executed
}

Example :

int nums[] = { 11, 2, 3, 14, 5, 62, 7, 8, 9, 10 };


int sum = 0;
for(int x : nums)
{
System.out.println("Value is: " + x);
sum = sum + x;
}

Java Infinitive for Loop

for(;;){
System.out.println("infinitive loop");
}
Output:

infinitive loop
infinitive loop
ctrl+c

Java break Statement

The Java break is used to break loop or switch statement. It


breaks the current flow of the program at specified condition. In
case of inner loop, it breaks only inner loop.

for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
}
System.out.println(i);

Java continue Statement

The Java continue statement is used to continue loop. It continues


the current flow of the program and skips the remaining code at
specified condition. In case of inner loop, it continues only inner
loop.

for(int i=1;i<=10;i++)
{
if(i==5){
continue;
}
System.out.print (i);
}

Output: 1 2 3 4 5 6 7 8 9 10
Java Comments

The java comments are statements that are not executed by the
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for
specific time.

Types of Java Comments

There are 2 types of comments in java.

1. Single Line Comment


2. Multi Line Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

//This is single line comment

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

/*
This
is
multi line
comment
*/
Java Operators
Arithmetic Operators
Operator Result
+ Addition (also unary plus)
– Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus (Applied to both integer and float data)
++ Increment

+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
–– Decrement

X+=1
double y= 25.25 % 10 // y=5.25

Relational Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

The outcome of these operations is a boolean value.


int a = 4;
int b = 1;
boolean c = a < b;
System.out.println(“The C value is “ + c) //false
Boolean Logical Operators
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else

Short-circuit OR & Short-circuit AND

The OR operator results in true when A is true, no matter what B is.


Similarly, the AND operator results in false when A is false, no matter
what B is. If you use the || and && forms, rather than the | and & forms
of these operators, Java will not bother to evaluate the right hand
operand when the outcome of the expression can be determined by
the left operand alone.

if (denom != 0 && num / denom > 10) //Short Circuit &&

int x, y, z;
x = y = z = 100; // set x, y, and z to 100 //Assignment Operator

expression1 ? expression2 : expression3 //Ternary operator


eg: c = a >b ? a : b;
Bitwise Operators
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

Java Unary Operator Example: ~ and !

class Oper1
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a); //-11
System.out.println(~b);//9
System.out.println(!c);//false
System.out.println(!d);//true
}
}
Java bitwise Operators Example: << , >>

public class Oper2


{
public static void main(String args[])
{
byte a=10;
System.out.println(a<<2); //40
byte b=-15;
System.out.println(b<<3); //-120
byte c=10;
System.out.println(c>>2); //2
byte d=-15;
System.out.println(d>>1); //-8

}
}

Java bitwise Operators Example: >> , >>>

class Oper3
{
public static void main(String args[])
{
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);

//For nagative number, >>> changes parity bit (MSB) to 0


System.out.println(-20>>2);
System.out.println(-20>>>2);
}
}
Java logical Operators Example: & , &&

class Oper4
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);
//false && true = false
System.out.println(a<b&a<c);
//false & true = false
}
}

Java logical Operators Example: & , &&

class Oper5
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b && a++<c);
//false && true = false
System.out.println(a);
//10 because second condition is not checked
System.out.println(a<b&a++<c);
//false && true = false
System.out.println(a);
//11 because second condition is checked

}
}
Java logical Operators Example: | , ||

class Oper6
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);
//true || true = true
System.out.println(a>b|a<c);
//true | true = true
System.out.println(a>b||a++<c);
//true || true = true
System.out.println(a);
//10 because second condition is not checked
System.out.println(a>b|a++<c);
//true | true = true
System.out.println(a);
//11 because second condition is checked
}
}

Potrebbero piacerti anche