SlideShare a Scribd company logo
Topics Covered:
 Introduction to Java : basic java concepts,
 JDK, JRE and JVM,
 wrapper classes,
 inner and nested classes,
 working with arrays and strings,
 String, StringBuffer and StringBuilder classes,
 access specifiers,
 inheritance
Introduction about the java programming
development tools
What is development tools in Java?
JDK (Java Development Kit)
JDK
JDK is Java Development Kit. The Java
Development Kit (JDK) is a software development
environment which is used to develop Java
applications.
JRE (Java Runtime Environment) is an
installation package that provides an
environment to only run(not develop) the java
program(or application)onto your machine. JRE
is only used by those who only want to run Java
programs.
JVM (Java Virtual Machine) is a very important
part of both JDK and JRE because it is contained
or inbuilt in both. Whatever Java program you
run using JRE or JDK goes into JVM and JVM is
responsible for executing the java program line
by line, hence it is also known as an interpreter.
Working of JVM, JDK and JRE
Java keywords: reserve words
Variables:
Data types in Java
Primitive
‱ boolean
‱ byte
‱ short
‱ int
‱ long
‱ char
‱ float
‱ double
Non primitive
‱ String
‱ Array
‱ Class
‱ Interface
A Wrapper class is a class whose object wraps or contains
primitive data types.
Operators
CAP615-Unit1.pptx
Arithmetic operators
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
Assignment Operators
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison operators
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or
equal to
x >= y
<= Less than or equal to x <= y
Logical operators
Operator Name Description Example
&& Logical
and
Returns true if both
statements are true
x < 5 && x < 10
|| Logical or Returns true if one of the
statements is true
x < 5 || x < 4
! Logical
not
Reverse the result, returns
false if the result is true
!(x < 5 && x <
10)
Bitwise operators
Operator Description
& AND Operator
| OR Operator
^ XOR Operator
~ Ones Complement Operator
<< Left Shift Operator
>> Right Shift Operator
Unary Operators in Java
Java unary operators are the types that need
only one operand to perform any operation like
increment, decrement, negation, etc. It consists
of various arithmetic, logical and other
operators that operate on a single operand.
Ternary Operator
Java ternary operator is the only conditional
operator that takes three operands. It’s a one-
liner replacement for if-then-else statement and
used a lot in Java programming.
Control Statements:
‱ if/else constructs
‱ switch statement
‱ looping controls, nested loops
if/else constructs
If(condition)
{
// statement execute when condition true
}
else
{
// statement execute when condition false
}
switch statement
To select choices/options from user it used:
Switch with choice (integer value like: 1,2,..)
Switch with choice (character value like: A,B,..)
Switch with choice (String value like:
“ADD”,”SUB”,..)
looping controls, nested loops
‱ While loop
‱ Do while loop
‱ For loop
‱ Enhanced or advanced for loop
‱ Nested loops means one loop inside another
loop.
Enhanced For loop
for(data_type variable : array | collection)
{
//body of for-each loop
}
Example:
int myArray[]=new int[]{11,12,13,14,15};
for(int num : myArray)
{
System.out.println(num);
}
inner and nested classes
Define a class within another class, such classes
are known as nested classes
Nested classes are divided into two categories:
static nested class :
Nested classes that are declared static are called
static nested classes.
inner class :
An inner class is a non-static nested class.
CAP615-Unit1.pptx
Difference between Normal inner class and Static
nested class
‱ In normal inner class, we cannot declare any static
members but in the static nested class, we can declare
a static member including the main method.
‱ Since we cannot declare the main method in the
normal inner class, therefore, we cannot run inner
class directly from the command prompt. But we can
declare the main method and can also run the static
nested class directly from the command prompt.
‱ A normal inner class can access both static and non-
static members of the outer class directly but from the
static nested class, we can access only static members.
Array
‱ Array is a collection of similar type of
elements that have contiguous memory
location.
‱ In 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
elements in an array.
‱ Array is index based, first element of the
array is stored at 0 index.
28
Advantage of Array
Code Optimization: It makes the code
optimized, we can retrieve or sort the data
easily.
Random access: We can get any data located
at any index position.
Disadvantage of Array
Size Limit: We can store only 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.
29
Types of Array: There are two types of array.
‱ Single Dimensional Array
‱ Multidimensional Array-
‱ 2D array
‱ 3D array
‱ Jagged array
30
Single Dimensional Array
‱ The syntax for declaring and instantiating
an array:
There are two ways to declare an array,
type[] arrayName;
type arrayName[];
31
‱ How to instantiate an array
arrayName = new type[length];
‱ How to declare and instantiate an array in
one statement
type[] arrayName = new type[length];
32
Examples
‱ Array of integers
int[] num = new int[5];
‱ Array of Strings
String[] nameList = new String[5];
nameList[0] = "Amanda Green";
nameList[1] = "Vijay Arora";
nameList[2] = "Sheila Mann";
nameList[3] = "Rohit Sharma";
nameList[4] = "Mandy Johnson";
33
Array length
‱ The syntax for getting the length of an
array
arrayName.length
e.g-
int[] values = new int[10];
for (int i = 0; i < values.length; i++)
{
values[i] = i;
}
34
Two-dimensional arrays
The syntax for creating a rectangular array-
type[][] arrayName = new
type[rowCount][columnCount];
‱ A statement that creates a 3x2 array
int[][] numbers = new int[3][2];
‱ 3x2 array and initializes it in one
statement
int[][] numbers =new int[][] { { 1, 2 }, { 3, 4 },
{ 5, 6 } };
35
Jagged array
type[][] arrayName = new
type[rowCount][];
e.g:-int num[][]=new int[4][];
num[0]=new int[1];
num[1]=new int[2];
num[2]=new int[3];
num[3]=new int[4];
36
String Class
‱ String is a sequence of characters. But in Java,
string is an object that represents a sequence
of characters.
‱ The java.lang.String class is used to create a
string object.
‱ In java, String objects are immutable which
means a constant and cannot be changed
once created.
string is immutable in java:
public static void main(String args[]){
String s=“Kumar";
s.concat(" Vishal");
System.out.println(s);
}
Output: Kumar
Methods in String class:
‱ length(),
‱ charAt()
‱ Substring()
‱ concat
‱ indexOf()
‱ equals()
‱ compareTo()
‱ trim()
‱ replace()
‱ toUpperCase()
‱ toLowerCase();
length(), charAt()
int length();
char charAt(i);
ïź Returns the number of characters in
the string
ïź Returns the char at position i.
7
’n'
”Problem".length();
”Window".charAt (2);
Returns:
Character positions in strings are numbered
starting from 0 – just like arrays.
Substring()
“lev"
“mutable"
”television".substring (2,5);
“immutable".substring (2);
Returns:
television
i k
television
i
‱ String subs = word.substring (i, k);
– returns the substring of chars in
positions from i to k-1
‱ String subs = word.substring (i);
– returns the substring from the i-th
char to the end
Returns a new String by finding characters from an existing String.
Concatenation()
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
‱ String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
indexOf():The indexOf() method returns the position of the first
occurrence of specified character(s) in a string.
indexOf()
String name =“President George Washington";
name.indexOf (‘P'); 0
name.indexOf (‘e'); 2
name.indexOf (“George"); 10
name.indexOf (‘e', 3); 6
name.indexOf (“Bob"); -1
Returns:
(not found)
(starts searching
at position 3)
index positions
equals()/equalsIgnoreCase()
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, case-
blind
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
Difference between == and .equals() method in Java
‱ equals() is a method and == is a operator
‱ use == operators for reference comparison
(address comparison) and .equals() method
for content comparison.
‱ In simple words, == checks if both objects
point to the same memory location whereas
.equals() evaluates to the comparison of
values in the objects
compareTo()
int diff = word1.compareTo(word2);
returns the “difference” word1 - word2
‱ if string1 > string2, it returns positive number
‱ if string1 < string2, it returns negative number
‱ if string1 == string2, it returns 0
The java string compareTo() method compares the given
string with current string . It returns positive number, negative
number or 0.
It compares strings on the basis of Unicode value of each
character in the strings.
Comparison Examples
//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
Methods — Changing Case
String word2 = word1.toUpperCase();
String word3 = word1.toLowerCase();
returns a new string formed from word1 by
converting its characters to upper (lower) case
String word1 = “HeLLo“;
String word2 = word1.toUpperCase();//”HELLO”
String word3 = word1.toLowerCase();//”hello”
//word1 is still “HeLLo“
trim()
removing white space at both ends
does not affect whites space in the middle
Example:
String word1 = “ Hi Kumar “;
String word2 = word1.trim();
//word2 is “Hi Kumar” – no spaces on either end
//word1 is still “ Hi Kumar “ – with middle spaces
replace()
method returns a string replacing all the old char or
CharSequence to new char or CharSequence.
Syntax:
String replace(char oldChar, char newChar)
String replace(CharSequence target, CharSequence replaceme
nt)
Example:
String str1="hello hello hello";
String str2="hello hello hello";
str1=str1.replace('h', 'H');
str2=str2.replace("hello", "hi");
System.out.println(str1);
System.out.println(str2);
replaceAll()
‱ The java string replaceAll() method returns a string
replacing all the sequence of characters matching
regular expression and replacement string.
Syntax:
String replaceAll(String regex, String replacement)
Example:
replace all occurrences of white spaces in a string:
String str = "how to do in java provides java reading materials";
String newStr = str.replaceAll(“s", "");
System.out.println(newStr);
StringBuffer class
‱ StringBuffer is mutable means one can change
the value of the object .
‱ The object created through StringBuffer is
stored in the heap .
‱ 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 .
StringBuffer StringBuilder
StringBuffer is synchronized i.e.
thread safe. It means two threads
can't call the methods of
StringBuffer simultaneously.
StringBuilder is non-
synchronized i.e. not thread safe.
It means two threads can call the
methods of StringBuilder
simultaneously.
StringBuffer is less efficient than
StringBuilder.
StringBuilder is more efficient than
StringBuffer.
Differences between StringBuffer and StringBuilder
methods of StringBuffer/StringBuilder class
‱ append()
‱ capacity()
‱ ensureCapacity()
‱ insert()
‱ reverse()
‱ replace()
‱ length()
‱ delete()
‱ deleteCharAt()
‱ substring()
append()
‱ is used to append the string from one string to
another string like concat.
Syntax:
StringBufferClassReference.append(any type)
Any type:-
append(char), append(boolean), append(int),
append(float), append(double) etc.
capacity()
‱ is used to return the current capacity of buffer.
‱ The default capacity of the buffer 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.
Condition1:
StringBuffer sb=new StringBuffer();
System.out.println("Current Capacity:"+sb.capacity());
// Current Capacity:16
Condition2:
StringBuffer sb=new StringBuffer(“hello”);
System.out.println("Current Capacity:"+sb.capacity());
// Current Capacity:21
ensureCapacity()
‱ It ensures that the given capacity is the
minimum to the current capacity. If it is
greater than the current capacity, it increases
the capacity by (oldcapacity*2)+2.
Ex:
If current capacity is:70
sb.ensureCapacity(70); // no change
But
sb.ensureCapacity(71); // cahnge now 142
insert()
‱ It is used to inserts the string at the specified
position.
Syntax:
StringBufferClassReference.insert(pos,string)
It is used to reverses the current string
Syntax:
StringBufferClassReference.reverse()
reverse()
‱ replace():
replaces the string from the specified startingIndex
and endingIndex.
Syntax:
StringBufferClassReference.replace(startingIndex,
endingIndex, newstring)
e.g:
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,“kumar");
System.out.println(sb);//Hkumarlo
‱ length() : to find the length of current string
Syntax:
StringBufferClassReference.length()
‱ delete(): deletes the string from the specified
startingIndex to endingIndex.
Syntax:StringBufferClassReference.delete(startin
gIndex,endingIndex)
e.g:
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//Hlo
‱ deleteCharAt():
deletes the character at the index specified
by loc.
Syntax:
StringBufferClassReference.deleteCharAt(int loc)
e.g:
StringBuffer sb=new StringBuffer("Hello");
sb.deleteCharAt(3);
System.out.println(sb);//Helo
substring()
‱ is used to return the substring from the
specified startingIndex and endingIndex.
Syntax:
substring(int startingIndex, int endingIndex)
access specifiers in Java
Access
Modifier
within class within
package
outside
package by
subclass only
outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
overview of inheritance
One class is hiring properties from another class is
called inheritance.
Advantages: Reusability
Class ClassA
{
}
Class ClassB extends ClassA
{
}
Inheritance Types:
‱ Single
‱ Multilevel
‱ Hierarchical
Using interface it is possible:
‱ Hybrid
‱ Multiple
Single inheritance:
‱ One base class and one derived class
‱ One-to-one relationship
Base Class
Derived Class
Bank
protected BankName
Customer
customerName
getDetails()
Multilevel inheritance:
‱ One class is going to become base class for other derived class
Science
private bonus=2000
void disp1(){}
Computer
private bonus=3000
void disp2(){}
Faculty
double salary,totalSalary=0;
Faculty(){ salary=25000}
Base Class for class Science
Derived Class from Faculty and
Base Class for Computer
Derived Class from Science
Hierarchical inheritance:
One base class and multiple derived class, one –to-many relationship
SBI
Private IFSCCode
Bank(){rateofInterest=4.5}
PNB
Private IFSCCode
Bank(){rateofInterest=5.5}
Bank
rateofInterest
Bank(){rateofInterest=0}
Important Notes:-
Default parent class constructor automatically called by child
class but for calling parameterized constructor of base class we
need to use super keyword.
Super keyword
‱ super keyword can be used to access the immediate
parent class constructor.
‱ super keyword can be used to invoke immediate
parent class members and methods.
‱ In some scenario when a derived class and base class
has same data members or methods, in that case
super keyword also used.
interface
‱ Collection of abstract methods.
‱ Use keyword interface
‱ Achieve multiple inheritance
‱ Use implements keyword for calling in derive class
Syntax:
interfcae Bank
{
int rateOfInterest();
}
class SBI implements Bank {
int rateOfInterest()
{
retutn 5;
}
}
CAP615-Unit1.pptx

More Related Content

PPTX
Java introduction
PPTX
arrays.pptx
PPTX
Introduction to Client-Side Javascript
PPTX
JAVA WORKSHOP(DAY 3) 1234567889999999.pptx
PPT
Java Tutorial | My Heart
ODP
Synapseindia reviews.odp.
PPT
Java_Tutorial_Introduction_to_Core_java.ppt
Java introduction
arrays.pptx
Introduction to Client-Side Javascript
JAVA WORKSHOP(DAY 3) 1234567889999999.pptx
Java Tutorial | My Heart
Synapseindia reviews.odp.
Java_Tutorial_Introduction_to_Core_java.ppt

Similar to CAP615-Unit1.pptx (20)

PPT
Java Tutorial
PPT
Java teaching ppt for the freshers in colleeg.ppt
PPTX
Android webinar class_java_review
PPT
Javatut1
PPT
Java tut1 Coderdojo Cahersiveen
PPT
Java tut1
PPT
Java tut1
PPTX
Lecture - 3 Variables-data type_operators_oops concept
PPTX
Object oriented programming2 Week 2.pptx
PPSX
Java Tutorial
PPT
05slide_arrays_creation_searching_sorting.ppt
PPTX
Module 2 Javascript. Advanced concepts of javascript
PPTX
javaArrays.pptx
PPT
cse dse eee btech bsc and more to go on and on.ppt
PDF
Java script introducation & basics
 
PPTX
6 arrays injava
PPTX
DOC-20240812-WA0000 array string and.pptx
PPT
Unit I Advanced Java Programming Course
PPTX
Java
PPTX
CH1 ARRAY (1).pptx
Java Tutorial
Java teaching ppt for the freshers in colleeg.ppt
Android webinar class_java_review
Javatut1
Java tut1 Coderdojo Cahersiveen
Java tut1
Java tut1
Lecture - 3 Variables-data type_operators_oops concept
Object oriented programming2 Week 2.pptx
Java Tutorial
05slide_arrays_creation_searching_sorting.ppt
Module 2 Javascript. Advanced concepts of javascript
javaArrays.pptx
cse dse eee btech bsc and more to go on and on.ppt
Java script introducation & basics
 
6 arrays injava
DOC-20240812-WA0000 array string and.pptx
Unit I Advanced Java Programming Course
Java
CH1 ARRAY (1).pptx

Recently uploaded (20)

PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
medical staffing services at VALiNTRY
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
PDF
Digital Strategies for Manufacturing Companies
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
history of c programming in notes for students .pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
System and Network Administraation Chapter 3
PDF
System and Network Administration Chapter 2
Design an Analysis of Algorithms I-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
medical staffing services at VALiNTRY
Odoo Companies in India – Driving Business Transformation.pdf
Digital Systems & Binary Numbers (comprehensive )
How to Choose the Right IT Partner for Your Business in Malaysia
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
 
Digital Strategies for Manufacturing Companies
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Design an Analysis of Algorithms II-SECS-1021-03
Upgrade and Innovation Strategies for SAP ERP Customers
history of c programming in notes for students .pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
System and Network Administraation Chapter 3
System and Network Administration Chapter 2

CAP615-Unit1.pptx

  • 1. Topics Covered:  Introduction to Java : basic java concepts,  JDK, JRE and JVM,  wrapper classes,  inner and nested classes,  working with arrays and strings,  String, StringBuffer and StringBuilder classes,  access specifiers,  inheritance
  • 2. Introduction about the java programming development tools What is development tools in Java? JDK (Java Development Kit) JDK JDK is Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications.
  • 3. JRE (Java Runtime Environment) is an installation package that provides an environment to only run(not develop) the java program(or application)onto your machine. JRE is only used by those who only want to run Java programs.
  • 4. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line, hence it is also known as an interpreter.
  • 5. Working of JVM, JDK and JRE
  • 8. Data types in Java Primitive ‱ boolean ‱ byte ‱ short ‱ int ‱ long ‱ char ‱ float ‱ double Non primitive ‱ String ‱ Array ‱ Class ‱ Interface
  • 9. A Wrapper class is a class whose object wraps or contains primitive data types.
  • 12. Arithmetic operators Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y
  • 13. Assignment Operators Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 14. Comparison operators Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 15. Logical operators Operator Name Description Example && Logical and Returns true if both statements are true x < 5 && x < 10 || Logical or Returns true if one of the statements is true x < 5 || x < 4 ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)
  • 16. Bitwise operators Operator Description & AND Operator | OR Operator ^ XOR Operator ~ Ones Complement Operator << Left Shift Operator >> Right Shift Operator
  • 17. Unary Operators in Java Java unary operators are the types that need only one operand to perform any operation like increment, decrement, negation, etc. It consists of various arithmetic, logical and other operators that operate on a single operand.
  • 18. Ternary Operator Java ternary operator is the only conditional operator that takes three operands. It’s a one- liner replacement for if-then-else statement and used a lot in Java programming.
  • 19. Control Statements: ‱ if/else constructs ‱ switch statement ‱ looping controls, nested loops
  • 20. if/else constructs If(condition) { // statement execute when condition true } else { // statement execute when condition false }
  • 21. switch statement To select choices/options from user it used: Switch with choice (integer value like: 1,2,..) Switch with choice (character value like: A,B,..) Switch with choice (String value like: “ADD”,”SUB”,..)
  • 22. looping controls, nested loops ‱ While loop ‱ Do while loop ‱ For loop ‱ Enhanced or advanced for loop ‱ Nested loops means one loop inside another loop.
  • 23. Enhanced For loop for(data_type variable : array | collection) { //body of for-each loop }
  • 24. Example: int myArray[]=new int[]{11,12,13,14,15}; for(int num : myArray) { System.out.println(num); }
  • 25. inner and nested classes Define a class within another class, such classes are known as nested classes Nested classes are divided into two categories: static nested class : Nested classes that are declared static are called static nested classes. inner class : An inner class is a non-static nested class.
  • 27. Difference between Normal inner class and Static nested class ‱ In normal inner class, we cannot declare any static members but in the static nested class, we can declare a static member including the main method. ‱ Since we cannot declare the main method in the normal inner class, therefore, we cannot run inner class directly from the command prompt. But we can declare the main method and can also run the static nested class directly from the command prompt. ‱ A normal inner class can access both static and non- static members of the outer class directly but from the static nested class, we can access only static members.
  • 28. Array ‱ Array is a collection of similar type of elements that have contiguous memory location. ‱ In 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 elements in an array. ‱ Array is index based, first element of the array is stored at 0 index. 28
  • 29. Advantage of Array Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. Random access: We can get any data located at any index position. Disadvantage of Array Size Limit: We can store only 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. 29
  • 30. Types of Array: There are two types of array. ‱ Single Dimensional Array ‱ Multidimensional Array- ‱ 2D array ‱ 3D array ‱ Jagged array 30
  • 31. Single Dimensional Array ‱ The syntax for declaring and instantiating an array: There are two ways to declare an array, type[] arrayName; type arrayName[]; 31
  • 32. ‱ How to instantiate an array arrayName = new type[length]; ‱ How to declare and instantiate an array in one statement type[] arrayName = new type[length]; 32
  • 33. Examples ‱ Array of integers int[] num = new int[5]; ‱ Array of Strings String[] nameList = new String[5]; nameList[0] = "Amanda Green"; nameList[1] = "Vijay Arora"; nameList[2] = "Sheila Mann"; nameList[3] = "Rohit Sharma"; nameList[4] = "Mandy Johnson"; 33
  • 34. Array length ‱ The syntax for getting the length of an array arrayName.length e.g- int[] values = new int[10]; for (int i = 0; i < values.length; i++) { values[i] = i; } 34
  • 35. Two-dimensional arrays The syntax for creating a rectangular array- type[][] arrayName = new type[rowCount][columnCount]; ‱ A statement that creates a 3x2 array int[][] numbers = new int[3][2]; ‱ 3x2 array and initializes it in one statement int[][] numbers =new int[][] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 35
  • 36. Jagged array type[][] arrayName = new type[rowCount][]; e.g:-int num[][]=new int[4][]; num[0]=new int[1]; num[1]=new int[2]; num[2]=new int[3]; num[3]=new int[4]; 36
  • 37. String Class ‱ String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. ‱ The java.lang.String class is used to create a string object. ‱ In java, String objects are immutable which means a constant and cannot be changed once created.
  • 38. string is immutable in java: public static void main(String args[]){ String s=“Kumar"; s.concat(" Vishal"); System.out.println(s); } Output: Kumar
  • 39. Methods in String class: ‱ length(), ‱ charAt() ‱ Substring() ‱ concat ‱ indexOf() ‱ equals() ‱ compareTo() ‱ trim() ‱ replace() ‱ toUpperCase() ‱ toLowerCase();
  • 40. length(), charAt() int length(); char charAt(i); ïź Returns the number of characters in the string ïź Returns the char at position i. 7 ’n' ”Problem".length(); ”Window".charAt (2); Returns: Character positions in strings are numbered starting from 0 – just like arrays.
  • 41. Substring() “lev" “mutable" ”television".substring (2,5); “immutable".substring (2); Returns: television i k television i ‱ String subs = word.substring (i, k); – returns the substring of chars in positions from i to k-1 ‱ String subs = word.substring (i); – returns the substring from the i-th char to the end Returns a new String by finding characters from an existing String.
  • 42. Concatenation() String word1 = “re”, word2 = “think”; word3 = “ing”; int num = 2; ‱ String result = word1.concat (word2); //the same as word1 + word2 “rethink“
  • 43. indexOf():The indexOf() method returns the position of the first occurrence of specified character(s) in a string.
  • 44. indexOf() String name =“President George Washington"; name.indexOf (‘P'); 0 name.indexOf (‘e'); 2 name.indexOf (“George"); 10 name.indexOf (‘e', 3); 6 name.indexOf (“Bob"); -1 Returns: (not found) (starts searching at position 3) index positions
  • 45. equals()/equalsIgnoreCase() boolean b = word1.equals(word2); returns true if the string word1 is equal to word2 boolean b = word1.equalsIgnoreCase(word2); returns true if the string word1 matches word2, case- blind b = “Raiders”.equals(“Raiders”);//true b = “Raiders”.equals(“raiders”);//false b = “Raiders”.equalsIgnoreCase(“raiders”);//true
  • 46. Difference between == and .equals() method in Java ‱ equals() is a method and == is a operator ‱ use == operators for reference comparison (address comparison) and .equals() method for content comparison. ‱ In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects
  • 47. compareTo() int diff = word1.compareTo(word2); returns the “difference” word1 - word2 ‱ if string1 > string2, it returns positive number ‱ if string1 < string2, it returns negative number ‱ if string1 == string2, it returns 0 The java string compareTo() method compares the given string with current string . It returns positive number, negative number or 0. It compares strings on the basis of Unicode value of each character in the strings.
  • 48. Comparison Examples //negative differences diff = “apple”.compareTo(“berry”);//a before b diff = “Zebra”.compareTo(“apple”);//Z before a diff = “dig”.compareTo(“dug”);//i before u diff = “dig”.compareTo(“digs”);//dig is shorter //zero differences diff = “apple”.compareTo(“apple”);//equal diff = “dig”.compareToIgnoreCase(“DIG”);//equal //positive differences diff = “berry”.compareTo(“apple”);//b after a diff = “apple”.compareTo(“Apple”);//a after A diff = “BIT”.compareTo(“BIG”);//T after G diff = “huge”.compareTo(“hug”);//huge is longer
  • 49. Methods — Changing Case String word2 = word1.toUpperCase(); String word3 = word1.toLowerCase(); returns a new string formed from word1 by converting its characters to upper (lower) case String word1 = “HeLLo“; String word2 = word1.toUpperCase();//”HELLO” String word3 = word1.toLowerCase();//”hello” //word1 is still “HeLLo“
  • 50. trim() removing white space at both ends does not affect whites space in the middle Example: String word1 = “ Hi Kumar “; String word2 = word1.trim(); //word2 is “Hi Kumar” – no spaces on either end //word1 is still “ Hi Kumar “ – with middle spaces
  • 51. replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence. Syntax: String replace(char oldChar, char newChar) String replace(CharSequence target, CharSequence replaceme nt) Example: String str1="hello hello hello"; String str2="hello hello hello"; str1=str1.replace('h', 'H'); str2=str2.replace("hello", "hi"); System.out.println(str1); System.out.println(str2);
  • 52. replaceAll() ‱ The java string replaceAll() method returns a string replacing all the sequence of characters matching regular expression and replacement string. Syntax: String replaceAll(String regex, String replacement)
  • 53. Example: replace all occurrences of white spaces in a string: String str = "how to do in java provides java reading materials"; String newStr = str.replaceAll(“s", ""); System.out.println(newStr);
  • 54. StringBuffer class ‱ StringBuffer is mutable means one can change the value of the object . ‱ The object created through StringBuffer is stored in the heap . ‱ 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 .
  • 55. StringBuffer StringBuilder StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non- synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer. Differences between StringBuffer and StringBuilder
  • 56. methods of StringBuffer/StringBuilder class ‱ append() ‱ capacity() ‱ ensureCapacity() ‱ insert() ‱ reverse() ‱ replace() ‱ length() ‱ delete() ‱ deleteCharAt() ‱ substring()
  • 57. append() ‱ is used to append the string from one string to another string like concat. Syntax: StringBufferClassReference.append(any type) Any type:- append(char), append(boolean), append(int), append(float), append(double) etc.
  • 58. capacity() ‱ is used to return the current capacity of buffer. ‱ The default capacity of the buffer 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.
  • 59. Condition1: StringBuffer sb=new StringBuffer(); System.out.println("Current Capacity:"+sb.capacity()); // Current Capacity:16 Condition2: StringBuffer sb=new StringBuffer(“hello”); System.out.println("Current Capacity:"+sb.capacity()); // Current Capacity:21
  • 60. ensureCapacity() ‱ It ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. Ex: If current capacity is:70 sb.ensureCapacity(70); // no change But sb.ensureCapacity(71); // cahnge now 142
  • 61. insert() ‱ It is used to inserts the string at the specified position. Syntax: StringBufferClassReference.insert(pos,string) It is used to reverses the current string Syntax: StringBufferClassReference.reverse() reverse()
  • 62. ‱ replace(): replaces the string from the specified startingIndex and endingIndex. Syntax: StringBufferClassReference.replace(startingIndex, endingIndex, newstring) e.g: StringBuffer sb=new StringBuffer("Hello"); sb.replace(1,3,“kumar"); System.out.println(sb);//Hkumarlo
  • 63. ‱ length() : to find the length of current string Syntax: StringBufferClassReference.length() ‱ delete(): deletes the string from the specified startingIndex to endingIndex. Syntax:StringBufferClassReference.delete(startin gIndex,endingIndex) e.g: StringBuffer sb=new StringBuffer("Hello"); sb.delete(1,3); System.out.println(sb);//Hlo
  • 64. ‱ deleteCharAt(): deletes the character at the index specified by loc. Syntax: StringBufferClassReference.deleteCharAt(int loc) e.g: StringBuffer sb=new StringBuffer("Hello"); sb.deleteCharAt(3); System.out.println(sb);//Helo
  • 65. substring() ‱ is used to return the substring from the specified startingIndex and endingIndex. Syntax: substring(int startingIndex, int endingIndex)
  • 66. access specifiers in Java Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y
  • 67. overview of inheritance One class is hiring properties from another class is called inheritance. Advantages: Reusability Class ClassA { } Class ClassB extends ClassA { }
  • 68. Inheritance Types: ‱ Single ‱ Multilevel ‱ Hierarchical Using interface it is possible: ‱ Hybrid ‱ Multiple
  • 69. Single inheritance: ‱ One base class and one derived class ‱ One-to-one relationship Base Class Derived Class Bank protected BankName Customer customerName getDetails()
  • 70. Multilevel inheritance: ‱ One class is going to become base class for other derived class Science private bonus=2000 void disp1(){} Computer private bonus=3000 void disp2(){} Faculty double salary,totalSalary=0; Faculty(){ salary=25000} Base Class for class Science Derived Class from Faculty and Base Class for Computer Derived Class from Science
  • 71. Hierarchical inheritance: One base class and multiple derived class, one –to-many relationship SBI Private IFSCCode Bank(){rateofInterest=4.5} PNB Private IFSCCode Bank(){rateofInterest=5.5} Bank rateofInterest Bank(){rateofInterest=0}
  • 72. Important Notes:- Default parent class constructor automatically called by child class but for calling parameterized constructor of base class we need to use super keyword.
  • 73. Super keyword ‱ super keyword can be used to access the immediate parent class constructor. ‱ super keyword can be used to invoke immediate parent class members and methods. ‱ In some scenario when a derived class and base class has same data members or methods, in that case super keyword also used.
  • 74. interface ‱ Collection of abstract methods. ‱ Use keyword interface ‱ Achieve multiple inheritance ‱ Use implements keyword for calling in derive class Syntax: interfcae Bank { int rateOfInterest(); } class SBI implements Bank { int rateOfInterest() { retutn 5; } }