Вы находитесь на странице: 1из 68

JAVA Programming

Introduction

ACTION
program
BY
MOUSITA DHAR
Assistant Technical Head
Ardent Computech Pvt Ltd
Procedural & Object Oriented
Programming Technique
 An object-oriented application uses a collection
of objects, which communicate by passing
messages to request services. Objects are
capable of passing messages, receiving
messages, and processing data. The aim of
object-oriented programming is to try to
increase the flexibility and maintainability of
programs. Because programs created using an
OO language are modular, they can be easier to
develop, and simpler to understand after
development.
 Programs are made up of modules, which
are parts of a program that can be coded
and tested separately, and then assembled
to form a complete program.
 In procedural languages (i.e. C) these
modules are procedures, where a procedure
is a sequence of statements. In C for
example, procedures are a sequence of
imperative statements, such as
assignments, tests, loops and invocations of
sub procedures.
 These procedures are functions, which map
arguments to return statements.
Features of OOPs

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
CLASSES & OBJECTS
 A class is a collection of objects that have common
properties, operations and behaviours. A class is a
combination of state (data) and behaviour
(methods). In object-oriented languages, a class is
a data type, and objects are instances of that data
type
 Eg we may design a class Human, which is a
collection of all humans in the world. Humans have
state, such as height, weight, and hair color. They
also have behaviour, such as walking, talking,
eating. All of the state and behaviour of a human is
encapsulated (contained) within the class human.
 An object is an instance of a class. Objects are units of
abstraction. An object can communicate with other objects
using messages. An object passes a message to another
object, which results in the invocation of a method. Objects
then perform the actions that are required to get a response
from the system.

 DATA ABSTRACTION AND ENCAPSULATION:


Combining data and functions into a single unit called class and
the process is known as Encapsulation.Data encapsulation is
important feature of a class. Class contains both data and
functions. Data is not accessible from the outside world and only
those function which are present in the class can access the
data. The insulation of the data from direct access by the
program is called data hiding or information hiding. Hiding the
complexity of proram is called Abstraction and only essential
features are represented.In short we can say that internal
working is hidden.
 INHERITANCE: it is the process by which
object of one class aquire the properties or
features of objects of another class. The
concept of inheritance provide the idea of
reusability means we can add additional
features to an existing class without
Modifying it.

 POLYMORPHISM: A greek term means ability


to take more than one form. An operation
may exhibite different behaviours in
different instances.
INTRO
 Java programming language was
originally developed by Sun Microsystems
which was initiated by James Gosling and
released in 1995 as core component of
Sun Microsystems' Java platform.The
latest release of the Java Standard
Edition is Java SE 8.
 Java
is guaranteed to be Write Once,
Run Anywhere.
Main Features of JAVA

 Platform independent: when Java is


compiled, it is not compiled into platform
specific machine, rather into platform
independent byte code.
Object-oriented
Object-oriented means we organize our software as
a combination of different types of objects that
incorporates both data and behaviour.

Basic concepts of OOPs are:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Robust

Robust simply means


strong. Java uses strong
memory management.
There is automatic
garbage collection in
java.
Auto Memory Management
 In java no need to think about de-
allocation of garbage
 JVM delegates the job of garbage
collection to a thread called Garbage
Collector
 Working of garbage collector has been
monitored by JVM only
Secure
 untrusted programs are
restricted to run inside
virtual machine,it is strictly
controlled by security
manager
Multi-threaded

 A thread is like a separate program,


executing concurrently.
History of Java
 The history of java starts from Green Team.
Java team members (also known as Green
Team), initiated a revolutionary task to develop
a language for digital devices such as set-top
boxes, televisions etc. Currently, Java is used in
internet programming, mobile devices, games,
e-business solutions etc. There are given the
major points that describes the history of java.
MORE ABOUT JAVA
 Previous name of Java was OAK
 In 1995, Oak was renamed
as "Java" because it was already a
trademark by Oak Technologies.
 Java is an island of Indonesia where first
coffee was produced (called java coffee).
 Originally developed by James Gosling at
Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and
released in 1995.
JAVA APPLICATION

JAVA ME
JAVA SE JAVA EE

Mobile,gam
Console e,small
Applicatio GUI Web Business devices
n applic applicatio
ation n
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 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/embedded
system
JVM (Java Virtual Machine)
 It is a virtual machine which work over your
operating system to provide proper
environment for your compiled Java code.
JVM only works with bytecode. Hence you
need to compile your java application(.java)
so that it can be converted to bytecode
format (.class file). Which then will be used
by JVM to run application. JVM only provide
environment it needs other library to run
application properly.
 The JVM doesn't understand Java typo,
that's why you compile your *.java files to
obtain *.class files that contain the
bytecodes understandable by the JVM.

The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
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 are also actively
released by other companies besides Sun
Micro Systems.
JDK
 The JDK also called Java
Development Kit is a superset of
the JRE, and contains everything
that is in the JRE, plus tools such
as the compilers and debuggers
necessary for developing applets
and applications.
FIRST JAVA PROGRAM
 We can write a simple hello java program
easily after installing the JDK in any
editor like notepad, notepad ++ etc
 For executing any java program, you need
to install the JDK
 set path of the jdk/bin directory.
 create the java program
 compile and run the java program
How to set path in Java
 The path is required to be set for using
tools such as javac, java etc.
 Ifyou are saving the java source file
inside the jdk/bin directory, path is not
required to be set because all the tools
will be available in the current directory.
 But If you are having your java file
outside the jdk/bin folder, it is necessary
to set path of JDK.
DIFFERENCE BETWEEN SET PATH AND
SET CLASSPATH
path classpath

path variable is set for provide path classpath variable is set for provide
for all java tools like java, javac, path of all java classes which is used
javap, javah, jar, appletviewer in our application.
Creating hello java example

class Simple{
public static void main(String args[]){

System.out.println("Hello Java");
}
}
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory
where you saved the class. Assume it's C:\.
 Type ' javac MyFirstJavaProgram.java' and press enter to
compile your code. If there are no errors in your code,
the command prompt will take you to the next line
(Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your
program.
 You will be able to see ' Hello World ' printed on the
window.
Can you save a java source file by
other name than the class name?

 Yes,if the class is not public. If class is


public then class name and file name
must be same.
 There must be only one public class in a
java source file and that class name is
the file name normally
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it
means it is visible to all.
 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.
 void is the return type of the method, it means it doesn't return
any value.
 main represents startup of the program.
 String[] args is used for command line argument. We will learn it
later.
 System.out.println() is used print statement. We will learn about
the internal working of System.out.println statement later.
Valid java main method signature
 public static void main(String[] args)
 public static void main(String []args)
 public static void main(String args[])
 public static void main(String... args)
 static public void main(String[] args)
 public static final void main(String[] args)
 final public static void main(String[] args)
 final strictfp public static void main(String[] args)
Basic Syntax:
 Case Sensitivity - Java is case sensitive, which means
identifier Helloand hello would have different meaning in Java.
 Class Names - For all class names the first letter should be in
Upper Case.

If several words are used to form a name of the class, each inner
word's first letter should be in Upper Case.

Example class MyFirstJavaClass


 Method Names - All method names should start with a Lower Case
letter.

If several words are used to form the name of the method, then
each inner word's first letter should be in Upper Case.

Example public void myMethodName()


 Program File Name - Name of the program file should
exactly match the class name.

When saving the file, you should save it using the class
name (Remember Java is case sensitive) and append
'.java' to the end of the name (if the file name and the
class name do not match your program will not compile).

Example: Assume 'MyFirstJavaProgram' is the class name.


Then the file should be saved
as 'MyFirstJavaProgram.java'
 public static void main(String args[]) - Java program
processing starts from the main() method which is a
mandatory part of every Java program.
Java Identifiers:
 All identifiers should begin with a letter (A to Z or
a to z), currency character ($) or an underscore
(_).
 After the first character identifiers can have any
combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary,
_value, __1_value
 Examples of illegal identifiers: 123abc, -salary
Java Keywords:

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while
Comments in Java
/* This is my first java program.
* This will print 'Hello World' as the output
* This is an example of multi-line
comments.
*/

// This is an example of single line


comment
Java Variables:

We would see following type of


variables in Java:
 Local Variables
 Class Variables (Static Variables)
 InstanceVariables (Non-static
variables)
Primitive Data Types:
 There are 8 primitive data types are there in
java-
 1. byte – size 1 byte
 2. short – 2 byte
 3. int – 4 bytes
 4. long – 8 bytes
 5. float – 4 bytes
 6. double – 8 bytes
 7.char – 2 bytes
 8. boolean – 1 bit
OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table


etc. Object-Oriented Programming is a methodology or
paradigm to design a program using classes and objects. It
simplifies the software development and maintenance by
providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
 Anyentity that has state and
behavior is known as an object. For
example: chair, pen, table,
keyboard, bike etc. It can be
physical and logical.
Class

 Collection of objects is called


class. It is a logical entity.
Inheritance

 When one object acquires all the


properties and behaviours of
parent object i.e. known as
inheritance. It provides code
reusability. It is used to achieve
runtime polymorphism.
Polymorphism
 When one task is performed by different
ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw
something e.g. shape or rectangle etc.
 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.
Abstraction

 Hiding internal details and showing


functionality is known as abstraction. For
example: phone call, we don't know the
internal processing.
 In java, we use abstract class and interface
to achieve abstraction.
Encapsulation

 Binding (or wrapping) code and data


together into a single unit is known as
encapsulation. For example: capsule, it
is wrapped with different medicines.
 A java class is the example of
encapsulation. Java bean is the fully
encapsulated class because all the data
members are private here.
Object in Java
 An entity that has state and behavior is known as an object e.g.
chair, bike, marker, pen, table, car etc. It can be physical or
logical (tengible and intengible). The example of integible object
is banking system.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such
as deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID.
The value of the ID is not visible to the external user. But,it is used
internally by the JVM to identify each object uniquely.
 Object is an instance of a class. Class is a template or blueprint
from which objects are created. So object is the instance(result)
of a class.
Class in Java
 A class is a group of objects that has common
properties. It is a template or blueprint from
which objects are created.
A class in java can contain:
 data member
 method
 constructor
 block
 class and interface
Syntax to declare a class:
and an object
class <class_name>{
data member;
method;
}

Class_name obj_name=new class_name();

The new keyword is used to allocate memory at


runtime.
Access Modifiers in java
The access modifiers in java specifies
accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
 private
 default
 protected
 public
Visibility Public Protected Default Private
From the Yes Yes Yes Yes
same class
From any Yes Yes Yes No
class in the
same package
From subclass Yes Yes Yes No
in the same
package
From the Yes Yes No No
subclass from
the package
outside
From any Yes No No No
nonsubclass
class outside
the package
Instance variable in Java

A variable that is created inside the


class but outside the method, is
known as instance variable.Instance
variable doesn't get memory at
compile time.It gets memory at
runtime when object(instance) is
created.That is why, it is known as
instance variable.
Local variables:

 Variablesdefined inside methods,


constructors or blocks are called
local variables. The variable will
be declared and initialized within
the method and the variable will
be destroyed when the method has
completed.
Class variables(or Static variable):

 Class variables are variables declared


with in a class, outside any method, with
the static keyword.
 There would only be one copy of each
class variable per class, regardless of how
many objects are created from it.
 Static variables can be accessed by
calling with the class
nameClassName.VariableName.
Constructor in Java
 Constructor in java is a special type of
method that is used to initialize the
object at the time of creation.
 Java constructor is invoked
automatically at the time of object
creation. It constructs the values i.e.
provides data for the object that is why
it is known as constructor.
Rules for creating java constructor
 Constructor name must be same as its class
name
 Constructor must have no explicit return type
Types of java constructors
 Default constructor (no-arg constructor)
 Parameterized constructor
NOTE
If there is no constructor in a class, compiler
automatically creates a default constructor.
Constructor Overloading in Java

 Constructor overloading is a technique in


Java in which a class can have any
number of constructors that differ in
parameter lists. The compiler
differentiates these constructors by
taking into account the number of
parameters in the list and their type.
Difference between constructor and
method in java
Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to


expose behaviour
of an object.
Constructor must not have return type. Method may or
may not have
return type.
Constructor is invoked implicitly. Method is invoked
explicitly.
The java compiler provides a default constructor if you Method is not
don't have any constructor. provided by
compiler in any
case.
Constructor name must be same as the class name. Method name
must not be same
as class name.
ACCESS SPECIFIER IN JAVA

 1. public
 2. private
 3. default
 4. protected
ENCAPSULATION
 Encapsulation in Java is a mechanism of
wrapping the data (variables) and code
acting on the data (methods) together
as a single unit. In encapsulation, the
variables of a class will be hidden from
other classes, and can be accessed only
through the methods of their current
class. Therefore, it is also known as
data hiding.
To achieve encapsulation in Java −
 Declare the variables of a class as
private.
 Providepublic setter and getter
methods to modify and view the
variables values.
The static keyword in java is used for
memory management mainly. We can apply
java static keyword with variables,
methods. The static keyword belongs to the
class than instance of the class.
The static can be:
• variable (also known as class variable)
• method (also known as class method)
Java static variable
If you declare any variable as static, it is known
static variable.
The static variable can be used to refer the common
property of all objects (that is not unique for each
object) e.g. company name of employees,college
name of students etc.
The static variable gets memory only once in class
area at the time of class loading
Java static method
If you apply static keyword with any
method, it is known as static method.
A static method belongs to the class
rather than object of a class.
A static method can be invoked without
the need for creating an instance of a
class.
static method can access static data
member and can change the value of it.
JAVA ARRAY
 Java array is an object the contains elements of similar
data type. It is a data structure where we store similar
elements. We can store only fixed set of elements in a java
array.

Types of Array in java


There are two types of array.
 Single Dimensional Array
 Multidimensional Array
Syntax to declare an Array
 Int arr[]=new int[20];

Name Type of array Size of the


array

twoD array
Int arr[][]=new int[2][4];
Created an array with two raw and 4 column

Вам также может понравиться