Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

JAVA Programming

The document provides an overview of Java programming, covering its history, data types, control flow statements, and object-oriented programming concepts such as classes, methods, inheritance, and polymorphism. It also discusses Java's memory management, arrays, encapsulation, and the use of interfaces and collections. Additionally, it includes practical examples and explanations of various Java features and functionalities.

Uploaded by

harishauppu411
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA Programming

The document provides an overview of Java programming, covering its history, data types, control flow statements, and object-oriented programming concepts such as classes, methods, inheritance, and polymorphism. It also discusses Java's memory management, arrays, encapsulation, and the use of interfaces and collections. Additionally, it includes practical examples and explanations of various Java features and functionalities.

Uploaded by

harishauppu411
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

JAVA PROGRAMMING

JAVA Intro
 Java is a high-level programming
language originally developed by Sun
Microsystems and released in 1995. Java
runs on a variety of platforms, such as
Windows, Mac OS, and the various
versions of UNIX.
JAVA Comments
 Use // for single line comments
 Use /* and */ for multiline comments
JAVA Datatypes
Data types are divided into two groups:
 Primitive data types - includes byte,

short, int, long, float, double, boolean


and char
 Non-primitive data types - such as String

, Arrays and Classes


Memory allocation for
variables
Practice
 Write a program to perform arithmetic
operations
Java Command Line Arguments

 The java command-line argument is an


argument i.e. passed at the time of
running the java program.
 The arguments passed from the console
can be received in the java program and
it can be used as an input.
Conditional Statements
Java provides the following control flow
statements.
 Decision Making statements

 Loop statements
Decision Making
Statements
 These are used to control the flow of
Java program execution.
 Simple If
 If Else
 Else If ladder
 Nested If
 Switch
Simple If
 This statement consists of only one block
of statements. SIMPLE IF evaluates a
condition and if the given condition is
true, then the block gets executed.
Otherwise, the block is ignored.
If Else
 This statement consists of two blocks of
code. It evaluates a condition and if the
condition is true, then IF BLOCK gets
executed, otherwise ELSE BLOCK gets
executed.
Else If Ladder
 Else if ladder consists of multiple IF ELSE
blocks. This helps to verify multiple
conditions and make decision. When any
one condition is true, the rest of the IF
ELSE blocks are ignored.
Nested If
In nested if-statements, the if statement
can contain a if or if-else statement
inside another if or else-if statement.
Switch Statement

The switch
statement allows
us to execute a
block of code
among many
alternatives.
Looping statements
 Looping statements are used for
repetition of execution.
 They are 4 types:
 For loop
 While loop
 Do while
 For each loop
For loop
 For loop executes a block of statements
until the given condition is true. When
ever the condition becomes false, then
loop gets terminated and remaining
statements are executed.
While Loop
 While loop executes a block of code till
the given condition is true.
Do while
 Do while loop executes a block of
statements only once irrespective of the
given condition. It executes a block of
statements first and then verifies the
condition. If the condition is true, the
loop will be repeated otherwise it exits
the loop
For each loop
 In Java, the for-each loop is used to
iterate through elements of arrays and
collections (like ArrayList). It is also
known as the enhanced for loop.

( will be covered in Arrays topic)


Arrays in JAVA
 An array is a collection of similar type of
elements which has contiguous memory
location.
 The elements of an array are stored in a
contiguous memory location.
 Array in Java is index-based, the first
element of the array is stored at the 0th
index, 2nd element is stored on 1st
index and so on.
Advantages of Array
 Code Optimization: It makes the code optimized,
we can retrieve or sort the data efficiently.
 Random access: We can get any data located at
an index position.

 Disadvantage:
 Size Limit: We can store only the fixed size of
elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection
framework is used in Java which grows
automatically.
Types of Arrays
 Single Dimensional Array
 Multi Dimensional Array

 Single Dimensional Array:


 This array stores values in consecutive
memory locations.
Syntax:
Datatype[ ] arrayname;
Reading array elements
from user
Multi dimensional Array
 A multidimensional array is an array of
arrays. Each element of a
multidimensional array is an array itself.
OOPS in JAVA
 OOP stands for Object-Oriented
Programming.
Advantages:
 OOP is faster and easier to execute

 OOP provides a clear structure for the programs

 OOP helps to keep the Java code DRY "Don't

Repeat Yourself", and makes the code easier to


maintain, modify and debug
 OOP makes it possible to create full reusable

applications with less code and shorter


development time
Class and Object
 Java is an object-oriented programming
language.
 Everything in Java is associated with
classes and objects, along with its
attributes and methods.
 A class is a template for objects, and an
object is an instance of a class.
Create a Class
 We use CLASS keyword to create a class.
 Syntax:
public class Class_name
{
statements;
}
Java Class Attributes
 Attributes are members of class. We
use . Operator to access members of
class.
Java Class Methods
 A Method is a function that is defined in
class. It is also known as member
function of class.
 A method is a block of code or
collection of statements or a set of code
grouped together to perform a certain
task or operation. It is used to achieve
the reusability of code.
Access Specifier:
Access specifier or modifier is the access
type of the method. It specifies the
visibility of the method. Java provides
four types of access specifier:
 Public: The method is accessible by all

classes when we use public specifier in


our application.
 Private: When we use a private access

specifier, the method is accessible only in


the classes in which it is defined.
 Protected: When we use protected
access specifier, the method is
accessible within the same package or
subclasses in a different package.
 Default: When we do not use any
access specifier in the method
declaration, Java uses default access
specifier by default. It is visible only from
the same package only.
 Return Type: Return type is a data type that
the method returns. It may have a primitive data
type, object, collection, void, etc. If the method
does not return anything, we use void keyword.
 Method Name: It is a unique name that is used
to define the name of a method. It must be
corresponding to the functionality of the method.
Suppose, if we are creating a method for
subtraction of two numbers, the method name
must be subtraction(). A method is invoked by
its name.
 Parameter List: It is the list of
parameters separated by a comma and
enclosed in the pair of parentheses. It
contains the data type and variable
name. If the method has no parameter,
left the parentheses blank.
 Method Body: It is a part of the method
declaration. It contains all the actions to
be performed. It is enclosed within the
pair of curly braces.
Types of Method
There are two types of methods in Java:
 Predefined Method

 User-defined Method
Predefined Method
 Predefined methods are the method that
is already defined in the Java class
libraries is known as predefined
methods. It is also known as the
standard library method or built-in
method. We can directly use these
methods just by calling them in the
program at any point. Some pre-defined
methods are length(), equals(),
compareTo(), sqrt(), etc.
User-defined Method
 The method written by the user or
programmer is known as a user-
defined method. These methods are
modified according to the requirement.
Method Overloading in Java

 If a class has multiple methods having


same name but different in parameters,
it is known as Method Overloading.
 If we have to perform only one
operation, having same name of the
methods increases the readability of the
program.
Different ways to overload the
method

There are two ways to overload the


method in java
 By changing number of arguments

 By changing the data type


Changing no. of Arguments
Changing Data type
String Builder
 Java StringBuilder class is used to create
mutable (modifiable) String.
 Append:

It is used to append the specified string


with this string.
Ex: StringBuilder sb=new
StringBuilder("Hello ");
sb.append("CDU");
System.out.println(sb);
insert()
The StringBuilder insert() method
inserts the given string at the given
position.
Ex:
StringBuilder sb=new StringBuilder("Hell
o ");
sb.insert(1,“CDU");
System.out.println(sb);
replace()
 The StringBuilder replace() method replaces
the given string from the specified
beginIndex and endIndex.
Ex:
StringBuilder sb =
new StringBuilder("Hello");
sb.replace(1,3,"Java"); // ignores upper bound
System.out.println(sb);

O/P: HJavalo
Delete()
 The delete() method of StringBuilder class
deletes the string from the specified
beginIndex to endIndex.
 Ex:
StringBuilder sb =
new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);

O/P: Hlo
reverse()
 The reverse() method of StringBuilder
class reverses the current string.
StringBuilder sb =
new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);
capacity()
 The capacity() method of StringBuilder class
returns the current capacity of the Builder. The
default capacity of the Builder is 16. If the
number of character increases from its current
capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
 Ex: StringBuilder sb=new StringBuilder();
 System.out.println(sb.capacity());
 sb.append("Hello");
 System.out.println(sb.capacity
 sb.append("Java is my favourite language");
 System.out.println(sb.capacity());
Initialization Blocks
 Initialization blocks are executed
whenever the class is initialized and
before constructors are invoked. They
are typically placed above the
constructors within braces.
Encapsulation
 Encapsulation in Java is a process of
wrapping code and data together into a
single unit, for example, a capsule which
is mixed of several medicines.
To achieve encapsulation in Java −
 Declare the variables of a class as

private.
 Provide public setter and getter methods

to modify and view the variables values.


Aggregation
 If a class have an entity reference, it is
known as Aggregation. Aggregation
represents HAS-A relationship.
Why use Aggregation?
 For Code Reusability.
Inheritance
 Inheritance can be defined as the
process where one class acquires the
properties (methods and fields) of
another. With the use of inheritance the
information is made manageable in a
hierarchical order.
 The class which inherits the properties of
other is known as subclass (derived
class, child class) and the class whose
properties are inherited is known as
superclass (base class, parent class).
Why use inheritance in java

 For Method Overriding (so runtime


polymorphism can be achieved).
 For Code Reusability.
 Sub Class/Child Class: Subclass is a class
which inherits the other class. It is also called a
derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the
class from where a subclass inherits the
features. It is also called a base class or a parent
class.
 Reusability: As the name specifies, reusability
is a mechanism which facilitates you to reuse
the fields and methods of the existing class
when you create a new class. You can use the
same fields and methods already defined in the
previous class.
Syntax:
class childclass extends parentclass
{
//methods and fields
}
Single Inheritance
 If a single class is derived from another
class, it is called single inheritance.
Multi level inheritance
 If a class is derived from another child
class, it is called multi level inheritance.
Hierarchical Inheritance
 When more than one class is derived
from a single class, it is called
hierarchical inheritance.
Multiple Inheritance
 If a subclass is derived from more than
one class, it is known as Multiple
inheritance. Java doesn’t support this.
Hybrid Inheritance
 Combination of hierarchy and multiple
inheritance is called Hybrid Inheritance.
Java doesn’t support this
Abstract class in Java
 A class which is declared with the
abstract keyword is known as an
abstract class in Java. It can have
abstract and non-abstract methods
(method with the body).
 Abstraction is a process of hiding the
implementation details and showing only
functionality to the user.
Ways to achieve
Abstraction
 There are two ways to achieve
abstraction in java
 Abstract class (0 to 100%)
 Interface (100%)
Method overriding
 If subclass (child class) has the same
method as declared in the parent class,
it is known as method overriding in
Java.
 Method overriding is used to provide the
specific implementation of a method
which is already provided by its
superclass.
 Method overriding is used for runtime
polymorphism
Rules for Java Method Overriding

 The method must have the same name


as in the parent class
 The method must have the same
parameter as in the parent class.
 There must be an IS-A relationship
(inheritance).
Polymorphism
 polymorphism is a concept of object-
oriented programming that allows us to
perform a single action in different
forms. In this section, we will discuss
only the dynamic polymorphism in
Java.
Types of Polymorphism
 Static Polymorphism (Compile Time
Polymorphism)
 Dynamic Polymorphism (Run Time
Polymorphism)
Dynamic polymorphism
 Dynamic polymorphism is a process
or mechanism in which a call to an
overridden method is to resolve at
runtime rather than compile-time. It is
also known as runtime polymorphism
or dynamic method dispatch. We can
achieve dynamic polymorphism by using
the method overriding.
Interface in Java
 The interface in Java is a mechanism to achieve
abstraction. There can be only abstract methods
in the Java interface, not method body. It is used
to achieve abstraction and multiple inheritance in
Java.
 An interface is declared by using the interface
keyword. It provides total abstraction; means all
the methods in an interface are declared with the
empty body, and all the fields are public, static
and final by default. A class that implements an
interface must implement all the methods
declared in the interface.
Relation B/w CLASS & INTERFACE

 A class extends another class, an


interface extends another interface, but
a class implements an interface.
Multiple inheritance in Java By
Interface
Collections in JAVA
 A Collection represents a single unit of
objects, i.e., a group.
 The Collection in Java is a framework
that provides an architecture to store
and manipulate the group of objects.
 Java Collection framework provides
many interfaces (Set, List, Queue,
Deque) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).
Array List
 Java ArrayList class uses a dynamic
array for storing the elements. It is like
an array, but there is no size limit. We
can add or remove elements anytime.
 The ArrayList in Java can have the
duplicate elements also. It implements
the List interface so we can use all the
methods of the List interface here. The
ArrayList maintains the insertion order
internally.
 Java ArrayList class can contain duplicate
elements.
 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because
the array works on an index basis.
 In ArrayList, manipulation is a little bit slower
than the LinkedList in Java because a lot of
shifting needs to occur if any element is
removed from the array list.
 We can not create an array list of the
primitive types, such as int, float, char,
etc. It is required to use the required
wrapper class in such cases. For
example:
 ArrayList<int> al = ArrayList<int>(); // d
oes not work
 ArrayList<Integer> al = new ArrayList<I
nteger>(); // works fine
Set in JAVA
 The set is an interface available in the
java.util package. The set interface
extends the Collection interface. An
unordered collection or list in which
duplicates are not allowed is referred to
as a collection interface. The set
interface is used to create the
mathematical set.
Map in JAVA
 A map contains values on the basis of
key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map
contains unique keys.
 A Map is useful if you have to search,
update or delete elements on the basis
of a key.
 A Map doesn't allow duplicate keys, but
you can have duplicate values. HashMap
and LinkedHashMap allow null keys and
values, but TreeMap doesn't allow any
JDBC in JAVA
 JDBC stands for Java Database Connectivity.
JDBC is a Java API to connect and execute
the query with the database. It is a part of
JavaSE (Java Standard Edition). JDBC API uses
JDBC drivers to connect with the database.
There are four types of JDBC drivers:
 JDBC-ODBC Bridge Driver,

 Native Driver,

 Network Protocol Driver, and

 Thin Driver
Why Should We Use JDBC

 We can use JDBC API to handle database


using Java program and can perform the
following activities:
 Connect to the database
 Execute queries and update statements
to the database
 Retrieve the result received from the
database.
 Abstract class
 Dynamic polymorphism
 inheritance
 Interface
 Collections
 Data base

You might also like