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

Unit 01 Java Programming

Uploaded by

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

Unit 01 Java Programming

Uploaded by

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

Java Programming

Unit-1
Object-Oriented Thinking
A way of Viewing the World

 Agents and Communities


 Messages and Methods
 Responsibilities
 Classes and Instances
Agents and Communities
Agents and Communities
 An object-oriented program is structured as a
community of interacting agents, called objects.
 Each object has a role to play.
 Each object provides a service, or performs an
action, that is used by other members of the
community.
Messages & Methods
 Actions are initiated in object-oriented programming by the
transmission of a message to an agent (an object) responsible
for the action.
 The message encodes the request for an action.
 It is accompanied by any additional information (arguments)
needed to carry out the request.
 The receiver is the object to whom the message is sent.
 In response to a message, the receiver will perform some
method to satisfy the request
Responsibilities

 A fundamental concept in object-oriented


programming is to describe the behavior in terms of
responsibilities
Object

 It is the basic unit of Object-Oriented Programming


and it represents the real-life entities.
 Examples: student, teacher, fan, dog, pen,….etc.

An object consists of:


 State: It is represented by attributes of an object.
 Behavior: It is represented by methods of an object.
 Identity: It gives a unique name to an object.
Example-Dog object
Class
 A class is a user defined blueprint or prototype
(template) from which objects are created.
 It represents the set of properties or methods
that are common to all objects of one type.
 It has definitions of methods and data.
Class Example - Dog
Class Hierarchies-Inheritance
 Classes are organized into a hierarchical
inheritance structure.
 A child class (or subclass) will inherit attributes
from a parent class higher in the tree
 An abstract parent class for which there are no
direct instances, it is used only to create
subclasses.
Binding, Overriding, and Exceptions
 Determining which method will be invoked at run-time
 Methods of the same name in the class hierarchy is
overriding
 In response to a message, the search for a method begins
with the class of the receiver
 If no method is found, the search is conducted in the parent
class
 The search continues up the parent class chain until either a
method is found or the chain is exhausted
 If the method is found, it will be executed
 If not, an error message is issued
Summary of Object-Oriented
Concepts
 Everything is an object.
 Computation is performed by objects communicating
with each other by sending and receiving messages.
 Each object has its own memory.
 Every object is an instance of a class.
 The class is the repository for behaviour associated with
an object.
 Classes are organized into a singly rooted tree structure,
called the inheritance hierarchy .
An overview of Java
 Java was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle
Corporation)
 1991, first version called “OAK” was released and in 1995
the name “Java” came into existence.
 Oracle Corporation is the current owner of the official
implementation of the Java SE platform.
 The Oracle implementation is available for Microsoft
Windows, Mac OS X, Linux and Solaris.
 Java is reliable, portable and easy to use.
What is Java Programming language

 Java is a general-purpose computer programming language .


 It is intended to let application developers “write once, run
anywhere” (WORA).
 WORA is achieved by compiling a Java program into an
intermediate language called bytecode.
 The format of bytecode is platform-independent.
 A virtual machine, called the Java Virtual Machine (JVM), is
used to run the bytecode on each platform.
 Different JVMs are written specifically for different host
hardware and OS.
What is Java JDK, JRE and JVM?
What is Java JDK, JRE and JVM?
 Java Virtual machine (JVM) is the virtual machine that
runs the Java bytecodes.
 JVM uses two inbuilt interpreter and JIT compiler to
convert the bytecode to machine code and execute it.
 The Java Runtime Environment (JRE) is a software
package which bundles the libraries (jars) and the Java
Virtual Machine to run applications written in the Java.
 JDK is a superset of JRE. JDK contains everything that
JRE has along with development tools for developing,
debugging, and monitoring Java applications.
Java Installation & path setting
• Java oracle:
https://www.oracle.com/in/java/technologies/javase
/javase-jdk8-downloads.html

• YouTube link:
https://www.youtube.com/watch?v=f7rT0h1Q5Wo
Hello world program
class Test
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Execution of a Java Program
The Java Buzzwords
• Java Is Object-Oriented
• Java Is Simple
• Java Is Secure
• Java Is Platform Independent
• Java Is Robust
• Java Is Portable
• Java Is Architecture-Neutral
• Java Is Dynamic
• Java Is Interpreted and High
performance
• Java Is Multithreaded
• Java Is Distributed
Java Buzzwords (cont.)
• Object-oriented: Java is designed around the
concept of objects, which encapsulate data and
behavior. It supports principles such as Abstraction,
Encapsulation, Inheritance and Polymorphism.
• Simple: Java is designed to be easy to learn and use,
with syntax similar to C++. It avoids complex features
present in other languages like pointers and operator
overloading.
Java Buzzwords (cont.)
• Secure: Java's robust security features include
a bytecode verifier to ensure code integrity,
runtime security checks, and a security manager
to control access to system resources.
• Robust: Java emphasizes reliability through
features like strong memory management,
exception handling, and type checking.
Java Buzzwords (cont.)
• Portable: Java's "Write Once, Run Anywhere" (WORA)
philosophy enables developers to write code once and
deploy it across multiple platforms without modification.
• Platform-independent: Java programs can run on any
device or platform that supports Java Virtual Machine
(JVM), making it highly portable.
• Architecture-neutral: Java is architecture neutral
because there are no implementation dependent
features, for example, the size of primitive types is fixed.
Java Buzzwords (cont.)
• Interpreted: Java source code is initially compiled into
bytecode, which is a platform-independent intermediate
representation. This bytecode is then interpreted by the
Java Virtual Machine (JVM) at runtime. This interpretation
allows Java programs to be executed on any system with a
compatible JVM without the need for recompilation.
• High performance: While Java's performance was initially
a concern, advancements in JVM technology and just-in-
time (JIT) compilation have significantly improved its
execution speed.
Java Buzzwords (cont.)
• Dynamic: Java supports dynamic loading of classes,
which enables applications to dynamically extend their
functionality.
• Distributed: Java is designed to make distributed
computing easy with Technologies like RMI(Remote
Method Invocation) and EJB(Enterprise Java Bean).
• Multithreaded: Java provides built-in support for
multithreading, allowing concurrent execution of
multiple threads within a single program.
Java Scanner class
• Prior to Java 1.5 getting input from the console involved multiple
steps.
• Java 1.5 introduced the Scanner class which simplifies console input.
• It is used to read from files and Strings (among other sources).
• Scanner is in the java.util package. So you must:
import java.util.Scanner;
• Scanner class is used for obtaining the input of the primitive types like
int,double,strings, etc.
• To create an object of Scanner class, we usually pass the predefined
object System.in, which represents the Standard input stream.
Creating Scanner objects
• Constructing a Scanner object to read console
input:
Scanner name = new Scanner(System.in);

– Example:
Scanner s = new Scanner(System.in);

**You make a new object of Scanner class and you store it in


variable s.

**At the same time you are calling the constructor of the
class, with the parameter System.in
Scanner class methods

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Example
import java.util.Scanner;
class Example
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(“Enter your name:”);
String name = s.nextLine();
System.out.println(“Name = “+name);
}
}
How to create real world entity in
Java?
Class Account
{
State
-
-
Behavior
-
-
}
How to create object?
Account a;
• a is used to point an object but still not pointing
a = new Account();
• new is an operator
• a is a pointer reference to object(memory)
• Account is the object

Account a = new Account();


Calling methods using objects
Account a = new Account();
Account a1;
a1=new Account();
a.withdraw();
a1.deposit();
Command line arguments
• Arguments which are given along with commands.
• A command-line argument is the information that directly
follows the program's name on the command line when it is
executed.
• They are stored as strings in a String array passed to the args
parameter of main( ).
• So, accessing the command-line arguments inside
a Java program is quite easy.
Command line arguments
• The command line arguments are given in the following
format:
C:\> java Test 1 2 3
Test is command
1 2 3 are command line arguments
• The number of arguments can be calculated using length
Ex: args.length
• To print arguments, we can use a for loop
Ex:
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
Data types
• Java is statically typed and a strongly typed language.
• Java is strongly typed language because every variable must be
declared with a data type.
• A variable cannot start off life without knowing the range of values it
can hold, and once it is declared, the data type of the variable
cannot change.
• There are 8 types of primitive data types: The size of primitive data
types does not change from one operating system to another.
• Non – primitive data types are called reference types because they
refer to objects.
• E.g. Strings, Arrays, objects, Interfaces, etc.
Data type
Declarations
• Boolean Data type
– boolean a = false;

• Byte Data type


– byte a = 10;
– byte b=-20;

• Short Data type


– short s = 10000;
– short r = -5000;

• Int Data type


– int a = 100000;
– int b = -200000;
Declarations
• Long Data type
– long a = 100000L;
– long b = -200000L;

• Double Data type


– double d = 12.3;
A floating point can also be a scientific
– double d = 12E4d; number with an ‘e’ to indicate the
• Float Data type power of 10.
– float f = 234.5f;
– float f = 35e3f; Character uses 2 bytes because Java
uses Unicode system than ASCII code
• Char Data type
system. The lowest range of Unicode
– char a = ‘A’; system is \u0000
Java Type casting
• Type casting is when you assign a value of one primitive data
type to another type.

• In Java we have 2 types of casting:

– Widening casting (automatically)


• Converting a smaller data type to larger type size

– Narrowing casting (manually)


• Converting a larger type to a smaller size type
Widening
• Done automatically when passing a smaller size type to a larger size type.
public class M
{
public static void main(String args[])
{
int i = 9;
double d = i ;
System.out.println(i);
System.out.println(d);
}
}
Narrowing
• Must be done manually by placing the type in parenthesis in front of the
value
public class M
{
public static void main(String args[])
{
double d = 9.78;
int i = (int)d;
System.out.println(d);
System.out.println(i);
}
}
Variables
• The variable is the basic unit of storage in a Java program.
• The basic form of a variable declaration:
type identifier [ = value][, identifier [= value] ...];
• The type is one of Java‘s atomic types, or the name of a class
or interface.
• The identifier is the name of the variable.
Scope of the variables
• Local variables—in scope from declaration to end of
block.
• Instance variables—in scope from declaration until
object garbage collected.
• Class variables (static variables)—in scope from
declaration until program ends.
Expression & Operators
• An expression is a formula in which operands are linked to each other by the use
of operators to compute a value. An operand can be a function reference, a
variable, an array element or a constant.
• Java provides many types of operators that are used to perform operations on
variables and values.
• Types of operators:
– Basic Arithmetic operators
– Assignment operators
– Auto – increment and Auto – decrement operator
– Logical operators
– Comparison (relational) operators
– Bitwise operators
– Ternary operator
– instanceOf opearator
Basic Arithmetic operators
Basic arithmetic operators are: +, -, *, /, %
+ is for addition.

– is for subtraction.

* is for multiplication.

/ is for division.

% is for modulo.
Note: Modulo operator returns remainder, for example
10 % 5 would return 0
Assignment operators
Assignments operators in java are: =, +=, -=, *=, /=, %=
a = b would assign value of variable b to the variable a.

a+=b is equal to a = a+b

a-=b is equal to a = a-b

a*=b is equal to a = a*b

a/=b is equal to a = a/b

a%=b is equal to a = a%b


Auto increment & Auto decrement operators

++ and - -
a++ is equivalent to a=a+1;

a- - is equivalent to a=a-1;
Logical operators
• Logical Operators are used with binary variables.
• They are mainly used in conditional statements and loops for evaluating
a condition.
Logical operators in java are: &&, ||, !
Let’s say we have two boolean variables x and y.
x&&y will return true if both x and y are true else it would return false.
x||y will return false if both x and y are false else it would return true.
!x would return the opposite of x, that means it would be true if x is false
and it would return false if x is true.
Comparison (Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=

== returns true if both the left side and right side are equal

!= returns true if left side is not equal to the right side of operator.

> returns true if left side is greater than right.

< returns true if left side is less than right side.

>= returns true if left side is greater than or equal to right side.

<= returns true if left side is less than or equal to right side.
Bitwise operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
x = 11; /* equal to 00001011*/
y = 22; /* equal to 00010110 */
 Bitwise operator performs bit by bit processing.
x & y compares corresponding bits of x and y and generates 1 if both bits are
equal, else it returns 0. In our case it would return: 2 which is 00000010
because in the binary form of x and y only second last bits are matching.
 x | y compares corresponding bits of x and y and generates 1 if either bit
is 1, else it returns 0. In our case it would return 31 which is 00011111
 x ^ y compares corresponding bits of x and y and generates 1 if they are
not equal, else it returns 0. In our example it would return 29 which is
equivalent to 00011101
Bitwise operators
 ~x is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In
our example it would return -12 which is signed 8 bit equivalent to 11110100
 x << 2 is left shift operator that moves the bits to the left, discards the far left
bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is
equivalent to 00101100
 Note: In the example below we are providing 2 at the right side of this shift
operator that is the reason bits are moving two places to the left side. We can
change this number and bits would be moved by the number of bits specified
on the right side of the operator. Same applies to the right side operator.
 x >> 2 is right shift operator that moves the bits to the right, discards the far
right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which
is equivalent to 00000010
Ternary operator
This operator evaluates a boolean expression and assign the value based on the
result.
Syntax:

variable h = (expression) ? value if true : value if false

If the expression results true then the first value before the colon (:) is assigned to
the variable h else the second value is assigned to the h.
Operator precedence in Java
This determines which operator needs to be evaluated first if an expression has
more than one operator. Operator with higher precedence at the top and lower
precedence at the bottom.
Unary Operators ++ – – ! ~
Multiplicative * /%
Additive + –
Shift << >> >>>
Relational > >= < <=
Equality == !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Ternary ?:
Assignment = += -= *= /= %= > >= < <= &= ^= |=
instanceOf operator
• The java instanceof operator is used to test whether the
object is an instance of the specified type (class or subclass
or interface).
• The instanceof in java is also known as type comparison
operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator
with any variable that has null value, it returns false.

• Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Arrays
• Array is a collection of group of similar data types
• Arrays are used to store multiple values in a single variable, instead
of declaring separate variables for each value.
• Array in java is index-based, the first element of the array is stored at
the 0 index.
4 Steps to use arrays in java

1. Declaring an Array
2. Creating an array/giving memory
3. Initializing the array
4. Using an array/ accessing the array
1. Declaring an Array
class Demo
1.dataType[] arr; {
2.dataType []arr; public static void main(String args[])
3.dataType arr[];
4.dataType[] arr1,arr2,arr3; {
int[] arr;
Example
int []arr;
int[] arr; int arr[];
int []arr;
int arr[]; int[] arr1,arr2,arr3;
int[] arr1,arr2,arr3; }
}
2. Creating an array and giving memory or instantiating array

class Demo
1.Array is an object {
2.It has to created using new operator
public static void main(String args[])
Example
{
int arr[]=new int[10]; int[] arr;
arr=new int[10];

int[] arr=new int[10];


}
}
Declaring and instantiating in single line
3. Initializing the array

import java.util.Scanner;
class Demo class Demo
{ {
public static void main(String args[]) public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
{
int arr[]; int a[]={33,3,4,5};
arr=new int[10]; }
for(int i=1;i<arr.length;i++) }
{
arr[i]=obj.nextInt();

}
} Declaring ,instantiating and initializing in single li
}
3. Initializing the array
class Demo class Demo
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int[] num3; int[] num3;
num3={3,4,5,6}; Not a valid statement num3=new int[]{3,4,5,6};
} }
} }
4. Accessing the elements
class Demo
{
public static void main(String args[])
{
int[] num3;
num3=new int[]{3,4,5,6};
for(int i=0;i<num3.length;i++)
{
System.out.println(num3[i]);
}

}
}
Java program to read n elements and display n
elements using array

import java.util.*; for(int i=0;i<n;i++)


class ArrayDemo {
{ arr[i]=sc.nextInt();
public static void }
main(String args[]) System.out.println("Elements
{ in Array");
int n; for(int i=0;i<n;i++)
System.out.println("Enter {
the size"); System.out.println(arr[i]);
Scanner sc=new }
Scanner(System.in); }
n=sc.nextInt(); }
int arr[]=new int[n];
System.out.println("Enter
Elements");
The foreach Loops:
• JDK 1.5 introduced a new for loop known as foreach loop or enhanced for
loop, which enables you to traverse the complete array sequentially
without using an index variable.
Example:
public class TestArray1
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList)
{
System.out.println(element);
}
}
}
Passing Arrays to Methods:
• Just as you can pass primitive type values to methods,
• you can also pass arrays to methods.
For example, the following method displays the elements in an int array −
• Example:
public static void printArray(int[] array) //it is a method
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array.
For example, the following statement invokes the printArray method to
display 3, 1, 2, 6, 4, and 2 .
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
• A method may also return an array.
For example, the following method returns an array that is the
reversal of another array −
Example:
public static int[] reverse(int[] list)
{
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--)
{
result[j] = list[i];
}
return result;
}
What is 2-D Array?
• Array of Arrays.

• 2-D array usually represented with rows and columns


2-D Array Declaration
• We can declare 2-D array in following ways
type[][] referencevariable;
or
type referencevariable[][];
For example:
int marks[][];

Each element in the 2-D Array must be the same type.


Creation of 2-D Array

arrayreferencevariable = new type[value][value];

For example :
marks = new int[3][4];
More on 2-D Array Creation
int marks[][] = new int[][]; / / incorrect;
int marks[][] = new int[][4] / / incorrect;

int marks[][] = new int[3][] / / correct;


2-D array in form of rows and columns:

marks=new int[3][4];
Initialization of 2-D Array
• After array creation we can initialize the 2-D array like this :
• Arrayvariable[row][column]= value;

• For example lets initialize the marks array :


marks[0][0]=8; marks[0][1]=9; marks[0][2]=10; marks[0][3]=7;

Col 0 Col 1 Col 3 Col 4

Row 0 8 9 10 7

marks[1][0]=12; marks[1][1]=21; marks[1][2]=30; marks[1][3]=7;

Col 0 Col 1 Col 2 Col 3

Row 1 12 21 30 7

marks[2][0]=31; marks[2][1]=45; marks[2][2]=10; marks[2][3]=40;

Col 0 Col 1 Col 2 Col 3

Row 2 31 45 10 40
Col 0 Col 1 Col 2 Col 3
8 9 10 7
Row 0

12 21 30 7
Row 1

31 45 10 40
Row 2

Now if you want to access any element from 2-D array

System.Out.Println(marks[1][2]);
output = 30

System.Out.Println(marks[0][0]);
output = 8
We can also initialize the array at the time
of array creation
int[][] marks = new int{
{1,2,0,5},
{4,5,1,4},
{7,6,5,9}
}
How we can get array length

marks.length / / tell us rows.


marks[0].length / / tell us columns.
A JAVA program to read and display two dimensional array (Matrix) in java

import java.util.Scanner;
public class Ex2DArray
{ //To print matrix
public static void main(String args[]) System.out.print("The Array is :\n");
{ for(i=0; i<row; i++)
int row, col, i, j;
{
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in); for(j=0; j<col; j++)
System.out.print("Enter row for the array (max 10) : "); {
row = scan.nextInt(); System.out.print(arr[i][j]+ " ");
System.out.print("Enter column for the array (max 10) : "); }
col = scan.nextInt(); System.out.println();
//To Read matrix elements
}
System.out.println("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
}
{ }
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextInt();
}
}
Jagged Array (non-rectangular array)

• A jagged array is an array of arrays such that member arrays can be of


different sizes, i.e., we can create a 2-D array but with a variable
number of columns in each row.
• Example:
int[][] num = new int[4][];
num[0] = new int[1];
num[1] = new int[5];
num[2] = new int[2];
num[3] = new int[3];
So here we are defining columns explicitly.
Another Way:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
For Accessing:
for (int i=0; i<num.length; i++ )
{
for (int j=0; j<num[i].length; j++)
System.out.println(num[i][j]);
}
Alternatively:
for (int[] a : num)
{
for (int i : a)
System.out.println(i);
}
Advantages & disadvantages
Advantages
• 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.

Disadvantages
• 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.
Heap & Stack
 Basically objects are stored in heap and local variables, methods are
stored in stack

Heap Stack

Local
variables
Objects
Primitive
data types 3
Strings
• Strings in Java are different, right from the start. You may have
noticed that all of the primitive types are written in all lower
case letters. String needs a capital S.
• A primitive data type can be changed again and again by
reassigning the value, a string can’t be changed once it set.
WAYS OF CREATING STRING IN JAVA
• Using String Literal.
• Using “new” keyword.
USING STRING LITERAL
• To check this, you can compare two String references using ==
operator to check whether two references are referring to the
same String object in the memory.

• Example:
String s1 = “Java";
String s2 = “Java";
if(s1 == s2)
System.out.println("s1 and s2 referring to the same
object.");
USING “new” KEYWORD
• In Java, strings are objects. As with other objects, we can
create an instance of a string with the new keyword, as
follows:
String s = new String(“Java”);
• This line of code creates a new object of class String and
assigns it to the reference variable s
• So far, String objects seem just like other objects. Now, let's
give the string a value:
s = “java";
Strings are immutable objects
String x = "Java";
x.concat(" Rules!");
System.out.println("x = " + x);

Output: x = Java
 String is immutable object .
 Immutable means once created cannot be changed
 The object created as a String is stored in the Constant String
Pool.
 Every immutable object in Java is thread safe, that implies String is
also thread safe .
 String cannot be used by two threads simultaneously.
 String once assigned cannot be changed.
String a=“Hello World”;
//The above object is stored in constant String pool and its value
cannot be modified
a+=“Java Programming”;
//“Hello World" string still exists in string constant pool and its
value is not overrided but we lost reference to the “Hello World“
String. 4
Example with CODE
Heap

Hello World

Heap

Hello World Java


Programming

Hello 5

World
Example with CODE

:String
Life is a tale told by an
idiot

It can no longer be
accessed

:String
Shakespeare
Life is a tale told by an
idiot
6
Important Methods in String Class
 char charAt(int index): Returns the character at the specified index
 String concat(Sring str): Appends a string to the end of another
string
 int length(): Returns the length of a specified string
 String substring(int beginindex): returns substring for given begin
index
 String substring(int begin, int end): returns substring for given begin
index and end index
 String toLowerCase(): returns a string in lowercase
 String toUpperCase(): returns a string in uppercase
 String trim(): removes beginning and ending spaces of this string
 boolean contains(CharSequence s): returns true or false after
matching the sequence of char value
 static String join(CharSequence delimiter, CharSequence...
elements): returns a joined string
 boolean equals(Object another): checks the equality of string with
the given object
 static String equalsIgnoreCase(String another): compares another
string. It doesn't check case
 boolean isEmpty(): checks if string is empty
 String replace(char old, char new): replaces all occurrences of the
specified char value
 String replace(CharSequence old, CharSequence new): replaces all
occurrences of the specified CharSequence
 int indexOf(char ch): returns the specified char value index
 String[] split(String regex): returns a split string matching regex
Disadvantage of String
String Builder
 StringBuilder is same as the StringBuffer , that is it stores the
object in heap and it can also be modified .
 The main difference between the StringBuffer and
StringBuilder is that StringBuilder is also not thread safe.

StringBuilder is fast as it is not thread safe.


StringBuilder object= new StringBuilder("Hello");
object=new StringBuilder("Bye");

//Above statement is right as it modifies the value which is


allowed in the StringBuilder.
Advantage of StringBuilder
StringBuilder alpha = new StringBuilder();
for(char current = 'a'; current <= 'z'; current++)
alpha.append(current);
System.out.println(alpha);
String Buffer
 StringBuffer is mutable. ( mutable means one can change the
value of the object)
 The object created through StringBuffer is stored in the
heap . StringBuffer has the same methods as the
StringBuilder , but each method in StringBuffer is
synchronized that is StringBuffer is thread safe .
 Due to this it does not allow two threads to simultaneously
access the same method . Each method can be accessed by
one thread at a time .
 But being thread safe has disadvantages too as the
performance of the StringBuffer hits due to thread safe
property .
 String Buffer can be converted to the string by using
toString() method
 Thus StringBuilder is faster than the StringBuffer when
calling the same methods of each class.
 StringBuffer value can be changed , it means it can be
assigned to the new value .
 Example
StringBuffer s = new StringBuffer("Hello World");
s.append(“ Java Programming");

// The Above statement is right in the StringBuffer


Example
Overview

String StringBuffer StringBuilder

Constant String Pool Heap Heap


Storage
Area

Yes Yes No
Thread
Safe
Modifi
able immutable mutable mutable
Process of Concatenation of String And
StringBuffer
 String can be concatenated by using “+” operator or .concat() method.
 StringBuffer can be concatenated by using append().
 While concatenating StringBuffer is faster than String
StringTokenizer
• StringTokenizer class is used for creating tokens in Java. It
allows an application to break or split into small parts. Each
split string part is called Token.
StringTokenizer Constructors
 StringTokenizer(String str): str is a string to be tokenized and it
considers default delimiters like newline, space, tab, carriage
return and form feed which can be further tokenized.
 StringTokenizer(String str, String delim): delim is set of
delimiters that are used to tokenize the given string.
 StringTokenizer(String str, String delim, boolean flag): Since
the first two parameters have the same meaning. If the flag is
false, delimiter characters serve to separate tokens and if the
flag is true, delimiter characters are considered to be tokens.
StringTokenizer Methods
• hasMoreTokens(): return True if and only if next token to the
current position in the string exists, else false.
• nextToken(): returns next token from the given
StringTokenizer.
• countTokens(): returns total number of tokens which are
present
• nextElement(): This method returns Object rather than String.
Works similar to nextToken exists so that this class can
implement the Enumeration interface.
• hasMoreElements(): returns True if tokens are present in the
string, else false.
Inheritance
Introduction
• In Java it is possible to inherit attributes and methods
from one class to another

• Inheritance
– Subclass (Child): The class that inherits from another

– Superclass(Parent): The class being inherited from

To inherit from a class, use the extends keyword.


Introduction
• Why use Inheritance in Java?
– For method overriding

– For code reusability

• Terms in Inheritance
– Class

– Subclass/Child class

– Super class/Parent class

– Reusability
Introduction
• Syntax
Class subclass_name extends superclass_name

//methods and fields

/*The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of “extends” is to increase
the functionality*/
Introduction
• Types of Inheritance
– Single Class A

Class B

– Multilevel
Class A

Class B

Class C
Introduction
• Types of Inheritance
– Hierarchical
Class A

Class B Class C

– Multiple
Class A Class B

Class C

– Java does not support Multiple Inheritance to avoid ambiguity


this keyword
• There can be a lot of usage of Java this
keyword. In Java, this is a reference variable
that refers to the current object.
Usage of Java this keyword
• this can be used to refer current class instance variable.
• this can be used to invoke current class method
(implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from
the method.
static keyword
• The static keyword in Java is used for memory
management mainly. We can apply static keyword with
variables, methods, blocks and nested classes. The static
keyword belongs to the class than an instance of the
class.
• The static can be:
– Variable (also known as a class variable)
– Method (also known as a class method)
– Block
– Nested class
Constructors and Inheritance
• Default constructor of parent class can be called
directly at the time of object creation of child class

• But, to call a parameterized constructor we need to


use the super keyword

• Note:
– The base class constructor call must be the first line in
derived class constructor
super keyword
• The super keyword in Java is a reference variable
which is used to refer immediate parent class object.
• Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
• Usage of Java super Keyword
1. super can be used to refer immediate parent class
instance variable.
2. super can be used to invoke immediate parent class
method.
3. super() can be used to invoke immediate parent
class constructor.
Static Initialization Block &
Instance Initialization Block
Static Initialization Block Instance Initialization Block
No keyword is required to define an
To define a static initialization block
instance initialization block.
we use the keyword static
A static initialization block loads as
An instance initialization block is only
soon as a class loads and it is not
executed when there is a call to the
associated with a call to the
constructor for creating an object.
constructor of a class for object
creation.
An instance initialization block can
not only access static variables and
Static block can only access static
static methods but also instance
variables and static methods of its
variables and instance methods of
class
the class.
An instance initialization block
always makes an automatic call to
There is no automatic call to
superclass constructor by calling
superclass constructor from the
super() before executing any other
static initialization block.
statement in it.

Static block is called just once


Instance initialization block can run
during the entire execution of
many times, whenever there is a call
the program when the class
to the constructor of the class
loads.
Polymorphism
Introduction
• ‘Poly’ means many, ‘morphs’ means forms

• Polymorphism means many forms

• It is concept by which one can perform a single action


Ad-Hoc
in different ways. Or
Compile time (Static)
Or
Method overloading
Polymorphism
Pure
Or
Dynamic method dispatch (runtime)
Or
Method overridding
Introduction
• Overloading Overridding

Base
Test

void fun(int a)
void fun(int a)
void fun(int a,int b)
void fun(char a)

Derived

void fun(int a)
Ad-Hoc Polymorphism
• Method overloading is an example of Ad-hoc or compile time polymorphism.
class Overload
{
void demo()
{ In this example, demo() method is
}
void demo(int a) overloaded 3 times, which method
{
} is to be called is determined by the
void demo(int a,int b)
{ arguments we pass while calling
}
public static void main(String args[]) methods, this happens in compile
{
Overload p=new Overload(); time so it is known as compile
p.demo();
p.demo(10); time polymorphism
p.demo(10,20);
} }
Pure Polymorphism
• Method overriding is an example of pure or run time polymorphism.
class A
{
void demo()
{
} In this example, demo() method of
}
class B extends A parent class A is override by child
{
void demo() class B. We can access the method
{
} in either A or B at the time of
}
class Overridde object creation using parent class
{
public static void main(String args[]) reference and this is done at run
{
A a=new b(); time
a.demo();
}
}
Rules for overriding
• Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.

• There must be an IS-A relationship (inheritance).

• We cannot override the method declared as final and static.

• We should always override abstract methods of the superclass

• Overriding and Access-Modifiers : The access modifier for an overriding method can
allow more, but not less, access than the overridden method. For example, a
protected instance method in the super-class can be made public, but not private, in
the subclass. Doing so, will generate compile-time error.

• Private methods can not be overridden : Private methods cannot be overridden as


they are bonded during compile time. Therefore we can’t even override private
methods in a subclass
Rules for overriding
• Using @Override annotation while overriding a method is considered as a best
practice for coding in java because of the following two advantages:

• 1) If programmer makes any mistake such as wrong method name, wrong parameter
types while overriding, you would get a compile time error.

• 2) It improves the readability of the code. So if you change the signature of


overridden method then all the sub classes that overrides the particular method
would throw a compilation error, which would eventually help you to change the
signature in the sub classes. If you have lots of classes in your application then this
annotation would really help you to identify the classes that require changes when
you change the signature of a method.
Rules for overriding
class ParentClass
{
public void displayMethod(String msg)
{
System.out.println(msg);
}
}
class SubClass extends ParentClass
{
@Override
public void displayMethod(String msg)
{
System.out.println("Message is: "+ msg);
}
public static void main(String args[])
{
SubClass obj = new SubClass();
obj.displayMethod("Hey!!");
}
}
Abstract class
Abstraction in Java
• Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
• It shows only essential things to the user and hides the internal
details, for example, you insert the key to open a door, but you
do not know the process inside (i.e. how the door is getting
opened).
• Abstraction lets you focus on what the object does instead of
how it does it.
• Ways to achieve Abstraction:
There are two ways to achieve abstraction in java
– Abstract class
– Interface
Abstract class in Java
• A class which is declared as abstract is known as
an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its
method implemented. It cannot be instantiated.
• Points to Remember
– An abstract class must be declared with an abstract keyword.
– It can have abstract and non-abstract methods.
– It cannot be instantiated.
– It can have constructors and static methods also.
Abstract Method in Java
• A method which is declared as abstract and does not have implementation is known as an abstract
method.
• Example of abstract method
abstract void Hello();//no method body and abstract
Example:
abstract class Car
{
abstract void run();
}
class Brezza extends Car
{
void run()
{
System.out.println("running safely");
}
public static void main(String args[])
{
Car obj = new Brezza();
obj.run();
}
}
Abstract class having constructor, data member and methods
abstract class Car {
{ System.out.println("running safely..");
Car() }
{ }
System.out.println(“Car has started"); //Creating a Test class which calls abstra
} ct and non-abstract methods
abstract void run(); class TestAbstraction2
void changeGear() {
{ public static void main(String args[])
System.out.println("gear changed"); {
} Car obj = new Brezza();
} obj.run();
//Creating a Child class which inherits A obj.changeGear();
bstract class }
class Brezza extends Car }
{
void run()
Abstract Class Definition Rules:
1. Abstract classes cannot be instantiated directly.
2. Abstract classes may be defined with any number,
including zero, of abstract and nonabstract methods.
3. Abstract classes may not be marked as private or final.
4. An abstract class that extends another abstract class
inherits all of its abstract methods as its own abstract
methods.
5. The first concrete class that extends an abstract class
must provide an implementation for all of the
inherited abstract methods.
Abstract Method Definition Rules:
1. Abstract methods may only be defined in abstract classes.
2. Abstract methods may not be declared private or final.
3. Abstract methods must not provide a method
body/implementation in the abstract class for which is it
declared.
4. Implementing an abstract method in a subclass follows
the same rules for overriding a method.
For Ex:- The name and signature must be the same, and the
visibility of the method in the subclass must be at least as
accessible as the method in the parent class.
Rules

• If there is an abstract method in a class, that class must be abstract.


• An instance of an abstract class cannot be created, we can have references
of abstract class type though.
• An abstract class can contain constructors in Java. And a constructor of
abstract class is called when an instance of a inherited class is created.
• In Java, we can have an abstract class without any abstract method. This
allows us to create classes that cannot be instantiated, but can only be
inherited.
• If you are extending an abstract class that has an abstract method, you must
either provide the implementation of the method or make this class
abstract.
• It can have constructors and static methods also.
• Abstract classes can also have final methods (methods that cannot be
overridden), which will force the subclass not to change the body of the
method.
Inheritance continued..
Forms of Inheritance
1. Specialization:
The subclass is special case of the parent class
Example:

Person class

Employee class

Manager class  Specialized class


Forms of Inheritance
2. Specification:

The super class just specifies which methods should


be available but does not give code

Example:

Abstract classes and Interfaces


Forms of Inheritance
3. Construction:

The super class is just used to provide behavior, but


instances of the subclass don’t really act like the
super class. (Overriding)

Example:

Base Derived

M1() M1() Defined with new code


M2() M2()
redefined with new code
Forms of Inheritance
4. Extension:

Sub class adds new methods and perhaps defines


inherited ones as well

Example:

Base Derived
M1() Defined with new
M1() M2()
M2() code
M3()
New method
Forms of Inheritance
5. Limitation:

The sub class restricts the inherited behavior

Example:

Defining Queue as a subclass of Dequeue

6. Combination:

Multiple Inheritance, provided in terms of


implementing multiple interfaces
Benefits of Inheritance
Minimizes the amount of duplicate code in an application by sharing common code
amongst several subclasses
1) Reusability
Facility to use public methods of base class without rewriting the same

2) Extensibility
Extending the base class logic as per business logic of the derived class
3) Data binding
Base class can decide to keep some data private so that it cannot be altered by
the derived class
4) Overriding
Override methods of the base class so that meaningful implementation can be
designed in the derived class based on business logic
Disadvantages
1) Increased time/effort to jump through all the levels of overloaded classes
Example:
If a given class has 10 levels of abstraction then it has to take 10 jumps
to run through a function defined in each of their classes
2) During maintenance adding new features will effect both base class and
derived class. They both required to be changed. Example: change in
method signature
3) In case of deleting a particular method in base class, things get a bit
complicated in case of inheritance, because our programs will still compile,
but methods of sub class will no longer be overriding base class methods.
These methods will become like independent methods.
Cost of Inheritance
1) Execution speed

2) Program size

3) Message passing Overhead

4) Program complexity (in overuse of inheritance)


Object Class
• Object class is present in java.lang package.
• The Object class is the parent class of all the classes in java by
default.
• Every class in Java is directly or indirectly derived from
the Object class.
• In other words, it is the topmost class of java.
• Therefore the Object class methods are available to all Java classes.
• The Object class provides some common behaviors to all the
objects such as
– object can be compared
– object can be cloned
– object can be notified
Methods of Object class
toString()
• toString() provides String representation of an Object and used to convert an
object to String.
• The default toString() method for class Object returns
public String toString()
{
return getClass().getName() + "@" +Integer.toHexString(hashCode());
}

hashCode() :
• For every object, JVM generates a unique number which is hashcode. It
returns distinct integers for distinct objects.
• It convert the internal address of object to an integer by using an algorithm.
• Use of hashCode() method : Returns a hash value that is used to search object
in a collection which is an advantage.
• JVM uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc
equals(Object obj) :
• Compares the given object to current object (the object on which
the method is called).
• It gives a generic way to compare objects for equality.
• It is recommended to override equals(Object obj) method to get
our own equality condition on Objects.
• It is generally necessary to override the hashCode() method
whenever this method is overridden.

getClass() :
• Returns the class object of current object.
• As it is final so we don’t override it.
finalize()
• This method is called just before an object is garbage collected.
• Garbage collector destroys the unreferenced objects.
• finalize method is called just once on an object even though that
object is eligible for garbage collection multiple times.

Clone()
• Object cloning refers to creation of exact copy of an object.
• It creates a new instance of the class of current object and initializes
all its fields with exactly the contents of the corresponding fields of
this object.

The remaining three methods wait(), notify() notifyAll() are related


to Concurrency in threads.

You might also like