SlideShare a Scribd company logo
Programming in JAVA
Unit-II
BY
N.RUBA
ASST.PROF/DEPT. OF CA,
BON SECOURS COLLEGE FOR WOMEN,
THANJAVUR.
1
UNIT-II Chapter 3
Java language fundamentals
 Building blocks of Java
 Java as a programming language, follows a set of rules
 Predfefined conventions that specify how syntactically legal
constructs can be formed using the language elements.
 A semantic definition specifies the meaning of syntactically
legal constructs.
2
LEXICAL TOKENS
low level language elements are known as
lexical elements.
3
OPERATORS
SEPARATORS
LITERALS
WHITE SPACE
IDENTIFIER
KEY WORD
JAVA TOKENS
Identifiers
 Identifiers are the names of variables, methods, classes,
packages and interfaces. Unlike literals they are not the
things themselves, just ways of referring to them. In the
HelloWorld
program, HelloWorld, String, args, main and println are
identifiers.
 Identifiers must be composed of letters, numbers, the
underscore _ and the dollar sign $. Identifiers may only
begin with a letter, the underscore or a dollar sign.

4
literals
 Literals in Java – Integral, Floating-Point, Char, String,
Boolean
 Literals are number, text, or anything that represent a
value. In other words, Literals in Java are the constant
values assigned to the variable. It is also called a constant.
 For example,
 int x = 100;
5
Literals
integral
Floating point
Char
string
boolean
6
1. Integral literal
 Hexa-Decimal (Base 16)
 Digits 0-9 are allowed and also characters from a-f are
allowed in this form. Furthermore, both uppercase and
lowercase characters can be used, Java provides an
exception here.e.g A34,76F
 Decimal-(base 10)0-9e.g 598
 Octal (base -8)0-7 e.g 675
7
2.Floating-Point Literals in Java
 Here, datatypes can only be specified in decimal forms
and not in octal or hexadecimal form.
 Decimal (Base 10)
 E.g 5.78
8
3.
Char Literals in Java
These are the four types of char-
 Single Quote
Java Literal can be specified to a char data type as a single character within a single quote.
char ch = 'a';
 Char as Integral
A char literal in Java can specify as integral literal which also represents the Unicode value of a character.
Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535.
char ch = 062;
 Unicode Representation
Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers.
char ch = 'u0061';// Here /u0061 represent a.
 Escape Sequence
Escape sequences can also specify as char literal. E.g-char ch = 'n';
9
 4. String Literals
 Java String literals are any sequence of characters with a
double quote.
 String s = "Hello";
 5. Boolean Literals
 They allow only two values i.e. true and false.
 boolean b = true;
10
Variable declaration in Java
 Variable in Java is a data container that stores the data
values during Java program execution. Every variable is
assigned data type which designates the type and quantity
of value it can hold.
 Variable is a memory location name of the data. The Java
variables have mainly three types :
 Local,
 Instance and
 Static.
 variable in a program can perform 2 steps
 Variable Declaration
 Variable Initialization
11
Variable Declaration:
 To declare a variable, must specify the data type & give the
variable a unique name.
 Examples of other Valid Declarations are
int a,b,c;
float pi;
double d;
char a;
12
Variable initialization
 To initialize a variable, you must assign it a valid value.
 Example of other Valid Initializations are
pi =3.14f;
do =20.22d;
a=’v’;
You can combine variable declaration and initialization.
 Example :
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
13
Types of variables
In Java, there are three types of variables:
 Local Variables
 Instance Variables
 Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the
body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword
.They are defined Outside a method declaration. They are
Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the
program execution. These variables should be initialized
first, before the initialization of any instance variables.
Example: Types of Variables in Java
class sum
{
static int a = 1; //static variable
int data = 99; //instance variable
void method()
{
int b = 90; //local variable
}
}
14
Wrapper classes in Java
 Each primitive data type in java has a corresponding
wrapper class.
 The wrapper class in Java used to represent a primitive
data type as an object. It is used to convert primitive into
object and object into primitive.
 Wrapper class belong to the java.lang.package
 Wrapper classes for integers and floating-point numbers
are sub-classes of the number class in the java.lang
package.
15
Wrapper classes for primitive
datatype
Primitive data type Wrapper classes
int Integer
byte Byte
short Short
long Long
float Float
double Double
16
Operators in Java
An operator takes one or more arguments and produces new value.
 Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc.
Types of operators in Java which are given below:
 Unary Operator,
 Arithmetic Operator,(or)mathematical
 Shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary if-else Operator
 Comma operator
 Assignment Operator
 String operator +
 Operator precedence
 Casting operators
17
 Ternary if-else operator
 Boolean-exp?value():value1
 Comma operator
 Used in for loops
 E.g for (i=1,j=10;i<10;i++,j--)
 String operator +
 used to concatenate two strings
 Casting operator
 Used to make type conversions
18
Control structures
Control
structures
Selection statements
Iterative statements
Jump statements
19
Selection or branching
 if statement to test a
condition and decide the
execution of a block of
statements based on that
condition result. The if
statement checks, the given
condition then decides the
execution of a block of
statements. If the condition is
True, then the block of
statements is executed and if
it is False, then the block of
statements is ignored.
20
If-else
21
Nested if statement in java
 Writing an if statement inside another if-statement is called
nested if statement.
Syntax
if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}
22
if-else if statement in java
 Writing an if-statement inside else of an if statement is called if-else-if statement.
Syntax
if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}
23
switch statement in java
 Using the switch statement, one can select only one
option from more number of options very easily.
 In the switch statement, we provide a value that is to be
compared with a value associated with each option.
 Whenever the given value matches the value associated
with an option, the execution starts from that option.
 In the switch statement, every option is defined as
a case.
24
25
loop
 while loop
-used to repeat a given statement over and over.
-entry controlled
syntax:
while(boolean-expression)
{
statements
}
26
loop (or) iteration ->do-while statement in java
- is used to execute a single statement or block of statements
repeatedly as long as given the condition is TRUE. The do-while
statement is also known as the Exit control looping statement.
27
for statement
The for statement is used to execute a single statement or a
block of statements repeatedly as long as the given
condition is TRUE.
28
JUMP STATEMENTS IN JAVA
 The java programming language supports jump statements
that used to transfer execution control from one line to
another line. The java programming language provides the
following jump statements.
 break statement
 continue statement
 labelled break and continue statements
 return statement
 break statement in java
 The break statement in java is used to terminate a switch or
looping statement. That means the break statement is used to
come out of a switch statement and a looping statement like
while, do-while, for, and for-each.
29
30
continue statement in java
 The continue statement is used to move the execution control to
the beginning of the looping statement.
 When the continue statement is encountered in a looping
statement, the execution control skips the rest of the statements in
the looping block and directly jumps to the beginning of the loop.
 The continue statement can be used with looping statements like
while, do-while, for, and for-each.
 When we use continue statement with while and do-while
statements, the execution control directly jumps to the condition
 When we use continue statement with for statement the execution
control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop.
31
32
Empty statement
 Consists simply of a semicolon(;)
if(x<0)
{
x=-x;
}; legal –presence of the semicolon the compiler
considers it to be an empty statement, not part of the if
statement.
33
Arrays
 Arrays are data structures that hold data of the same type
in contiguous memory.
 A group of memory cells that are contiguous have same
name and store the same data type.
 Two types
 One dimensional
 Multidimensional
34
Declaring Array Variables
 To use an array in a program, must declare a variable to
reference the array, and must specify the type of array
the variable can reference
Syntax
Int age[ ];
double score[ ];
35
Creating Arrays
Allocation of memory and initialization
create an array by using the new operator with the following
syntax −
Syntax
arrayRefVar = new dataType[arraySize];
age= new int[ 10];
The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable
arrayRefVar.
36
Declaring an array variable, creating an array, and assigning the reference
of the array to the variable can be combined in one statement, as shown
below −
dataType[] arrayRefVar = new dataType[arraySize];
 Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-
based; that is, they start from 0 to arrayRefVar.length-1.
37
Representation of
one dimensional array

38
Multidimensional array
 Can be used to represent tables of data
 It has rows and columns and two subscripts are needed to access the array elements.
 (m-rows & n-column ie. m x n array)
Syntax
 int arrayofnum[ i] [j ];
 arrayname[ i] [j ]=value;
 int[ ] [ ] arrayofnum={{12,12,3},{45,8,90}};
data_type[dimension 1][dimension 2][]…[dimension n] = new data_type[size 1][size 2]…[size n]
 example
int[][] array1 = new int[2][2];//Two dimensional Integer Array with 2 rows and 2 columns
Three Dimensional Array’s Declaration
int[][][] array2 = new int[12][24][36]; //Three dimensional Array
39
Strings
 Represents group of characters
 Strings written in java program are all String class objects.
 String class objects are immutable
 Java defines the String class , which is part of
java.lang.package
40
Constructor of string class
String (char array[]);
 String (char array[], int start, int count);
 String (String object);
 Constructor of String class with byte array
 String(byte a[]);
 String (byte a[], int start, int count);
Special type of constructor
 String(StringBuffer a[]);
41
Methods of String class
 Char charAt(int index)
 Void getChars()
 Byte[] getBytes()
 boolean equals(String str)
 boolean equalsIgnoreCase(String str)
 int compareTo(String str)
 int compare ToIgnoreCase (String str)
 Boolean startsWith(String str)
 Boolean startsWith(String str, int index)
 Boolean endsWith(String str)
 Boolean endsWith(String str, int index)
 int indexOf(int ch)
 int indexOf(int ch, int index)
42
 Int lastIndexOf(int ch)
 Int lastIndexOf(int ch, int index)
 String subString(int index)
 String subString(int index1,int index2)
 String concat(String str)
 String replace(char oldcharacter,char newcharacter)
 String trim()
 String toLowerCase()
 String toUpperCase()
 Int length()
43
 valueOf() method
 The java string valueOf() method converts different types of
values into string. By the help of string valueOf() method, you
can convert int to string, long to string, boolean to string,
character to string, float to string, double to string, object to
string and char array to string.
 equals() method
 The java string equals() method compares the two given strings
based on the content of the string. If any character is not
matched, it returns false. If all characters are matched, it returns
true. The String equals() method overrides the equals()
method of Object class.

44
StringBuffer class
 Java provides a class called StringBuffer.
 StringBuffer is a mutable string, which can be changed
during the execution of a program.
 Changeable of set of character
StringBuffer();
StringBuffer(int size):
StringBuffer(String str);
45
Constructor Description
StringBuffer() creates an empty string
buffer with the initial
capacity of 16.
StringBuffer(String str) creates a string buffer with
the specified string.
StringBuffer(int capacity) creates an empty string
buffer with the specified
capacity as length.
46
 StringBuffer append(int value)
 StringBuffer append(char[] str, int start,int length)
 Int capacity()
 StringBuffer delete()
 StringBuffer insert()
 StringBuffer reverse()
 Void setCharAt(int index,char ch)
 Void setLength(int size)
47
 1) StringBuffer append() method
 The append() method concatenates the given argument with this string.
class StringBufferExample{
public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.appen
d("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
48
 StringBuffer insert() method
 The insert() method inserts the given string with this string at
the given position.
class StringBufferExample2
{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
49
 3) StringBuffer replace() method
 The replace() method replaces the given string from the
specified beginIndex and endIndex.
 class StringBufferExample3{
 public static void main(String args[]){ StringBuffer sb=n
ew StringBuffer("Hello"); sb.replace(1,3,"Java");
 System.out.println(sb);//prints HJavalo
 }
 }
50
 4) StringBuffer delete() method
 The delete() method of StringBuffer class deletes the
string from the specified beginIndex to endIndex.
 class StringBufferExample4{
 public static void main(String args[]){ StringBuffer sb=n
ew StringBuffer("Hello"); sb.delete(1,3);
 System.out.println(sb);//prints Hlo
 }
 }
51
 5) StringBuffer reverse() method
 The reverse() method of StringBuilder class reverses the
current string.
 class StringBufferExample5{
 public static void main(String args[]){ StringBuffer sb=n
ew StringBuffer("Hello"); sb.reverse();
 System.out.println(sb);//prints olleH
 }
 }
52
 6) StringBuffer capacity() method
 The capacity() method of StringBuffer class returns the current capacity of the 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.
 class StringBufferExample6{
 public static void main(String args[]){ StringBuffer sb=new StringBuffer(); System.out.printl
n(sb.capacity());//default 16
 sb.append("Hello");
 System.out.println(sb.capacity());//now 16
 sb.append("java is my favourite language");
 System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
 }
 }
53
Method Description
char charAt(int index) returns char value for the
particular index
int length() returns string length
static String format(String format,
Object... args)
returns a formatted string.
static String format(Locale l, String
format, Object... args)
returns formatted string with given
locale.
String substring(int beginIndex) returns substring for given begin
index.
String substring(int beginIndex, int
endIndex)
returns substring for given begin
index and end index.
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.
54
static String join(CharSequence
delimiter, Iterable<? extends
CharSequence> elements)
returns a joined string.
boolean equals(Object another) checks the equality of
string with the given
object.
boolean isEmpty() checks if string is empty.
String concat(String str) concatenates the specified
string.
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.
static String
equalsIgnoreCase(String
another)
compares another string.
It doesn't check case.
String[] split(String regex) returns a split string
matching regex.
55
String[] split(String regex,
int limit)
returns a split string
matching regex and limit.
String intern() returns an interned string.
int indexOf(int ch) returns the specified char value
index.
int indexOf(int ch, int
fromIndex)
returns the specified char value
index starting with given index.
int indexOf(String substring) returns the specified substring
index.
int indexOf(String substring, int
fromIndex)
returns the specified substring
index starting with given index.
String toLowerCase() returns a string in lowercase.
String toLowerCase(Locale l) returns a string in lowercase
using specified locale.
String toUpperCase() returns a string in uppercase.
String toUpperCase(Locale l) returns a string in uppercase
using specified locale.
String trim() removes beginning and ending
56
THANK YOU
57

More Related Content

What's hot

Overview of c language
Overview of c languageOverview of c language
Overview of c languageshalini392
 
C presentation book
C presentation bookC presentation book
C presentation book
krunal1210
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
Professional Guru
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variablesTony Apreku
 
Variables and data types in C++
Variables and data types in C++Variables and data types in C++
Variables and data types in C++
Ameer Khan
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
A Brief Introduction to Type Constraints
A Brief Introduction to Type ConstraintsA Brief Introduction to Type Constraints
A Brief Introduction to Type Constraints
Raffi Khatchadourian
 
Visual c sharp
Visual c sharpVisual c sharp
Visual c sharp
Palm Palm Nguyễn
 
Opps concept
Opps conceptOpps concept
Opps concept
divyalakshmi77
 
C presentation! BATRA COMPUTER CENTRE
C presentation! BATRA  COMPUTER  CENTRE C presentation! BATRA  COMPUTER  CENTRE
C presentation! BATRA COMPUTER CENTRE
jatin batra
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and VariablesTommy Vercety
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYRajeshkumar Reddy
 
Automata Theory
Automata TheoryAutomata Theory
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 

What's hot (17)

Overview of c language
Overview of c languageOverview of c language
Overview of c language
 
Ma3696 Lecture 3
Ma3696 Lecture 3Ma3696 Lecture 3
Ma3696 Lecture 3
 
C presentation book
C presentation bookC presentation book
C presentation book
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Lecture 2 variables
Lecture 2 variablesLecture 2 variables
Lecture 2 variables
 
Ch6
Ch6Ch6
Ch6
 
Variables and data types in C++
Variables and data types in C++Variables and data types in C++
Variables and data types in C++
 
Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
 
C reference manual
C reference manualC reference manual
C reference manual
 
A Brief Introduction to Type Constraints
A Brief Introduction to Type ConstraintsA Brief Introduction to Type Constraints
A Brief Introduction to Type Constraints
 
Visual c sharp
Visual c sharpVisual c sharp
Visual c sharp
 
Opps concept
Opps conceptOpps concept
Opps concept
 
C presentation! BATRA COMPUTER CENTRE
C presentation! BATRA  COMPUTER  CENTRE C presentation! BATRA  COMPUTER  CENTRE
C presentation! BATRA COMPUTER CENTRE
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
 
Automata Theory
Automata TheoryAutomata Theory
Automata Theory
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to Java Programming

java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
RajkumarHarishchandr1
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
rnkhan
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
Marwa Ali Eissa
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
Ashita Agrawal
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in javaShashwat Shriparv
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
VeerannaKotagi1
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 
Java Basics
Java BasicsJava Basics
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
İbrahim Kürce
 
dizital pods session 2.pptx
dizital pods session 2.pptxdizital pods session 2.pptx
dizital pods session 2.pptx
VijayKumarLokanadam
 
Basic
BasicBasic
Java_Roadmap.pptx
Java_Roadmap.pptxJava_Roadmap.pptx
Java_Roadmap.pptx
ssuser814cf2
 
2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment
CarlosPineda729332
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
BG Java EE Course
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
data types.pdf
data types.pdfdata types.pdf
data types.pdf
HarshithaGowda914171
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
TANUJ ⠀
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
Kajal Kashyap
 

Similar to Java Programming (20)

java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
dizital pods session 2.pptx
dizital pods session 2.pptxdizital pods session 2.pptx
dizital pods session 2.pptx
 
Basic
BasicBasic
Basic
 
Java_Roadmap.pptx
Java_Roadmap.pptxJava_Roadmap.pptx
Java_Roadmap.pptx
 
2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
GUI Programming in JAVA (Using Netbeans) - A Review
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
data types.pdf
data types.pdfdata types.pdf
data types.pdf
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
 

More from RubaNagarajan

Computer graphics-CRT.pptx
Computer graphics-CRT.pptxComputer graphics-CRT.pptx
Computer graphics-CRT.pptx
RubaNagarajan
 
Matrix representation- CG.pptx
Matrix representation- CG.pptxMatrix representation- CG.pptx
Matrix representation- CG.pptx
RubaNagarajan
 
Personality development.pptx
Personality development.pptxPersonality development.pptx
Personality development.pptx
RubaNagarajan
 
TRANSFORMATION-CG.pptx
TRANSFORMATION-CG.pptxTRANSFORMATION-CG.pptx
TRANSFORMATION-CG.pptx
RubaNagarajan
 
dda algorithm-cg.pptx
dda algorithm-cg.pptxdda algorithm-cg.pptx
dda algorithm-cg.pptx
RubaNagarajan
 
line attributes.pptx
line attributes.pptxline attributes.pptx
line attributes.pptx
RubaNagarajan
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
RubaNagarajan
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
RubaNagarajan
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
RubaNagarajan
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Risks in cc
Risks in ccRisks in cc
Risks in cc
RubaNagarajan
 
Dreamweaver
DreamweaverDreamweaver
Dreamweaver
RubaNagarajan
 
Working principles of internet
Working principles of internetWorking principles of internet
Working principles of internet
RubaNagarajan
 
Coreldraw
CoreldrawCoreldraw
Coreldraw
RubaNagarajan
 
C programming
C programmingC programming
C programming
RubaNagarajan
 
OPERATING SYSTEM
OPERATING SYSTEMOPERATING SYSTEM
OPERATING SYSTEM
RubaNagarajan
 
Virtualization in cloud computing
Virtualization in cloud computingVirtualization in cloud computing
Virtualization in cloud computing
RubaNagarajan
 
Cloud computing technology
Cloud computing technologyCloud computing technology
Cloud computing technology
RubaNagarajan
 

More from RubaNagarajan (19)

Computer graphics-CRT.pptx
Computer graphics-CRT.pptxComputer graphics-CRT.pptx
Computer graphics-CRT.pptx
 
Matrix representation- CG.pptx
Matrix representation- CG.pptxMatrix representation- CG.pptx
Matrix representation- CG.pptx
 
Personality development.pptx
Personality development.pptxPersonality development.pptx
Personality development.pptx
 
TRANSFORMATION-CG.pptx
TRANSFORMATION-CG.pptxTRANSFORMATION-CG.pptx
TRANSFORMATION-CG.pptx
 
dda algorithm-cg.pptx
dda algorithm-cg.pptxdda algorithm-cg.pptx
dda algorithm-cg.pptx
 
line attributes.pptx
line attributes.pptxline attributes.pptx
line attributes.pptx
 
Java files and io streams
Java files and io streamsJava files and io streams
Java files and io streams
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
Risks in cc
Risks in ccRisks in cc
Risks in cc
 
Dreamweaver
DreamweaverDreamweaver
Dreamweaver
 
Working principles of internet
Working principles of internetWorking principles of internet
Working principles of internet
 
Coreldraw
CoreldrawCoreldraw
Coreldraw
 
C programming
C programmingC programming
C programming
 
OPERATING SYSTEM
OPERATING SYSTEMOPERATING SYSTEM
OPERATING SYSTEM
 
Virtualization in cloud computing
Virtualization in cloud computingVirtualization in cloud computing
Virtualization in cloud computing
 
Cloud computing technology
Cloud computing technologyCloud computing technology
Cloud computing technology
 

Recently uploaded

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

Java Programming

  • 1. Programming in JAVA Unit-II BY N.RUBA ASST.PROF/DEPT. OF CA, BON SECOURS COLLEGE FOR WOMEN, THANJAVUR. 1
  • 2. UNIT-II Chapter 3 Java language fundamentals  Building blocks of Java  Java as a programming language, follows a set of rules  Predfefined conventions that specify how syntactically legal constructs can be formed using the language elements.  A semantic definition specifies the meaning of syntactically legal constructs. 2
  • 3. LEXICAL TOKENS low level language elements are known as lexical elements. 3 OPERATORS SEPARATORS LITERALS WHITE SPACE IDENTIFIER KEY WORD JAVA TOKENS
  • 4. Identifiers  Identifiers are the names of variables, methods, classes, packages and interfaces. Unlike literals they are not the things themselves, just ways of referring to them. In the HelloWorld program, HelloWorld, String, args, main and println are identifiers.  Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.  4
  • 5. literals  Literals in Java – Integral, Floating-Point, Char, String, Boolean  Literals are number, text, or anything that represent a value. In other words, Literals in Java are the constant values assigned to the variable. It is also called a constant.  For example,  int x = 100; 5
  • 7. 1. Integral literal  Hexa-Decimal (Base 16)  Digits 0-9 are allowed and also characters from a-f are allowed in this form. Furthermore, both uppercase and lowercase characters can be used, Java provides an exception here.e.g A34,76F  Decimal-(base 10)0-9e.g 598  Octal (base -8)0-7 e.g 675 7
  • 8. 2.Floating-Point Literals in Java  Here, datatypes can only be specified in decimal forms and not in octal or hexadecimal form.  Decimal (Base 10)  E.g 5.78 8
  • 9. 3. Char Literals in Java These are the four types of char-  Single Quote Java Literal can be specified to a char data type as a single character within a single quote. char ch = 'a';  Char as Integral A char literal in Java can specify as integral literal which also represents the Unicode value of a character. Furthermore, an integer can specify in decimal, octal and even hexadecimal type, but the range is 0-65535. char ch = 062;  Unicode Representation Char literals can specify in Unicode representation ‘uxxxx’. Here XXXX represents 4 hexadecimal numbers. char ch = 'u0061';// Here /u0061 represent a.  Escape Sequence Escape sequences can also specify as char literal. E.g-char ch = 'n'; 9
  • 10.  4. String Literals  Java String literals are any sequence of characters with a double quote.  String s = "Hello";  5. Boolean Literals  They allow only two values i.e. true and false.  boolean b = true; 10
  • 11. Variable declaration in Java  Variable in Java is a data container that stores the data values during Java program execution. Every variable is assigned data type which designates the type and quantity of value it can hold.  Variable is a memory location name of the data. The Java variables have mainly three types :  Local,  Instance and  Static.  variable in a program can perform 2 steps  Variable Declaration  Variable Initialization 11
  • 12. Variable Declaration:  To declare a variable, must specify the data type & give the variable a unique name.  Examples of other Valid Declarations are int a,b,c; float pi; double d; char a; 12
  • 13. Variable initialization  To initialize a variable, you must assign it a valid value.  Example of other Valid Initializations are pi =3.14f; do =20.22d; a=’v’; You can combine variable declaration and initialization.  Example : int a=2,b=4,c=6; float pi=3.14f; double do=20.22d; char a=’v’; 13
  • 14. Types of variables In Java, there are three types of variables:  Local Variables  Instance Variables  Static Variables 1) Local Variables Local Variables are a variable that are declared inside the body of a method. 2) Instance Variables Instance variables are defined without the STATIC keyword .They are defined Outside a method declaration. They are Object specific and are known as instance variables. 3) Static Variables Static variables are initialized only once, at the start of the program execution. These variables should be initialized first, before the initialization of any instance variables. Example: Types of Variables in Java class sum { static int a = 1; //static variable int data = 99; //instance variable void method() { int b = 90; //local variable } } 14
  • 15. Wrapper classes in Java  Each primitive data type in java has a corresponding wrapper class.  The wrapper class in Java used to represent a primitive data type as an object. It is used to convert primitive into object and object into primitive.  Wrapper class belong to the java.lang.package  Wrapper classes for integers and floating-point numbers are sub-classes of the number class in the java.lang package. 15
  • 16. Wrapper classes for primitive datatype Primitive data type Wrapper classes int Integer byte Byte short Short long Long float Float double Double 16
  • 17. Operators in Java An operator takes one or more arguments and produces new value.  Operator in Java is a symbol which is used to perform operations. For example: +, -, *, / etc. Types of operators in Java which are given below:  Unary Operator,  Arithmetic Operator,(or)mathematical  Shift Operator,  Relational Operator,  Bitwise Operator,  Logical Operator,  Ternary if-else Operator  Comma operator  Assignment Operator  String operator +  Operator precedence  Casting operators 17
  • 18.  Ternary if-else operator  Boolean-exp?value():value1  Comma operator  Used in for loops  E.g for (i=1,j=10;i<10;i++,j--)  String operator +  used to concatenate two strings  Casting operator  Used to make type conversions 18
  • 20. Selection or branching  if statement to test a condition and decide the execution of a block of statements based on that condition result. The if statement checks, the given condition then decides the execution of a block of statements. If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored. 20
  • 22. Nested if statement in java  Writing an if statement inside another if-statement is called nested if statement. Syntax if(condition_1){ if(condition_2){ inner if-block of statements; ... } ... } 22
  • 23. if-else if statement in java  Writing an if-statement inside else of an if statement is called if-else-if statement. Syntax if(condition_1){ condition_1 true-block; ... } else if(condition_2){ condition_2 true-block; condition_1 false-block too; ... } 23
  • 24. switch statement in java  Using the switch statement, one can select only one option from more number of options very easily.  In the switch statement, we provide a value that is to be compared with a value associated with each option.  Whenever the given value matches the value associated with an option, the execution starts from that option.  In the switch statement, every option is defined as a case. 24
  • 25. 25
  • 26. loop  while loop -used to repeat a given statement over and over. -entry controlled syntax: while(boolean-expression) { statements } 26
  • 27. loop (or) iteration ->do-while statement in java - is used to execute a single statement or block of statements repeatedly as long as given the condition is TRUE. The do-while statement is also known as the Exit control looping statement. 27
  • 28. for statement The for statement is used to execute a single statement or a block of statements repeatedly as long as the given condition is TRUE. 28
  • 29. JUMP STATEMENTS IN JAVA  The java programming language supports jump statements that used to transfer execution control from one line to another line. The java programming language provides the following jump statements.  break statement  continue statement  labelled break and continue statements  return statement  break statement in java  The break statement in java is used to terminate a switch or looping statement. That means the break statement is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each. 29
  • 30. 30
  • 31. continue statement in java  The continue statement is used to move the execution control to the beginning of the looping statement.  When the continue statement is encountered in a looping statement, the execution control skips the rest of the statements in the looping block and directly jumps to the beginning of the loop.  The continue statement can be used with looping statements like while, do-while, for, and for-each.  When we use continue statement with while and do-while statements, the execution control directly jumps to the condition  When we use continue statement with for statement the execution control directly jumps to the modification portion (increment/decrement/any modification) of the for loop. 31
  • 32. 32
  • 33. Empty statement  Consists simply of a semicolon(;) if(x<0) { x=-x; }; legal –presence of the semicolon the compiler considers it to be an empty statement, not part of the if statement. 33
  • 34. Arrays  Arrays are data structures that hold data of the same type in contiguous memory.  A group of memory cells that are contiguous have same name and store the same data type.  Two types  One dimensional  Multidimensional 34
  • 35. Declaring Array Variables  To use an array in a program, must declare a variable to reference the array, and must specify the type of array the variable can reference Syntax Int age[ ]; double score[ ]; 35
  • 36. Creating Arrays Allocation of memory and initialization create an array by using the new operator with the following syntax − Syntax arrayRefVar = new dataType[arraySize]; age= new int[ 10]; The above statement does two things −  It creates an array using new dataType[arraySize].  It assigns the reference of the newly created array to the variable arrayRefVar. 36
  • 37. Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − dataType[] arrayRefVar = new dataType[arraySize];  Alternatively you can create arrays as follows − dataType[] arrayRefVar = {value0, value1, ..., valuek}; The array elements are accessed through the index. Array indices are 0- based; that is, they start from 0 to arrayRefVar.length-1. 37
  • 39. Multidimensional array  Can be used to represent tables of data  It has rows and columns and two subscripts are needed to access the array elements.  (m-rows & n-column ie. m x n array) Syntax  int arrayofnum[ i] [j ];  arrayname[ i] [j ]=value;  int[ ] [ ] arrayofnum={{12,12,3},{45,8,90}}; data_type[dimension 1][dimension 2][]…[dimension n] = new data_type[size 1][size 2]…[size n]  example int[][] array1 = new int[2][2];//Two dimensional Integer Array with 2 rows and 2 columns Three Dimensional Array’s Declaration int[][][] array2 = new int[12][24][36]; //Three dimensional Array 39
  • 40. Strings  Represents group of characters  Strings written in java program are all String class objects.  String class objects are immutable  Java defines the String class , which is part of java.lang.package 40
  • 41. Constructor of string class String (char array[]);  String (char array[], int start, int count);  String (String object);  Constructor of String class with byte array  String(byte a[]);  String (byte a[], int start, int count); Special type of constructor  String(StringBuffer a[]); 41
  • 42. Methods of String class  Char charAt(int index)  Void getChars()  Byte[] getBytes()  boolean equals(String str)  boolean equalsIgnoreCase(String str)  int compareTo(String str)  int compare ToIgnoreCase (String str)  Boolean startsWith(String str)  Boolean startsWith(String str, int index)  Boolean endsWith(String str)  Boolean endsWith(String str, int index)  int indexOf(int ch)  int indexOf(int ch, int index) 42
  • 43.  Int lastIndexOf(int ch)  Int lastIndexOf(int ch, int index)  String subString(int index)  String subString(int index1,int index2)  String concat(String str)  String replace(char oldcharacter,char newcharacter)  String trim()  String toLowerCase()  String toUpperCase()  Int length() 43
  • 44.  valueOf() method  The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.  equals() method  The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. The String equals() method overrides the equals() method of Object class.  44
  • 45. StringBuffer class  Java provides a class called StringBuffer.  StringBuffer is a mutable string, which can be changed during the execution of a program.  Changeable of set of character StringBuffer(); StringBuffer(int size): StringBuffer(String str); 45
  • 46. Constructor Description StringBuffer() creates an empty string buffer with the initial capacity of 16. StringBuffer(String str) creates a string buffer with the specified string. StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length. 46
  • 47.  StringBuffer append(int value)  StringBuffer append(char[] str, int start,int length)  Int capacity()  StringBuffer delete()  StringBuffer insert()  StringBuffer reverse()  Void setCharAt(int index,char ch)  Void setLength(int size) 47
  • 48.  1) StringBuffer append() method  The append() method concatenates the given argument with this string. class StringBufferExample{ public static void main(String args[]){ StringBuffer sb=new StringBuffer("Hello "); sb.appen d("Java");//now original string is changed System.out.println(sb);//prints Hello Java } } 48
  • 49.  StringBuffer insert() method  The insert() method inserts the given string with this string at the given position. class StringBufferExample2 { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello "); sb.insert(1,"Java");//now original string is changed System.out.println(sb);//prints HJavaello } } 49
  • 50.  3) StringBuffer replace() method  The replace() method replaces the given string from the specified beginIndex and endIndex.  class StringBufferExample3{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.replace(1,3,"Java");  System.out.println(sb);//prints HJavalo  }  } 50
  • 51.  4) StringBuffer delete() method  The delete() method of StringBuffer class deletes the string from the specified beginIndex to endIndex.  class StringBufferExample4{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.delete(1,3);  System.out.println(sb);//prints Hlo  }  } 51
  • 52.  5) StringBuffer reverse() method  The reverse() method of StringBuilder class reverses the current string.  class StringBufferExample5{  public static void main(String args[]){ StringBuffer sb=n ew StringBuffer("Hello"); sb.reverse();  System.out.println(sb);//prints olleH  }  } 52
  • 53.  6) StringBuffer capacity() method  The capacity() method of StringBuffer class returns the current capacity of the 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.  class StringBufferExample6{  public static void main(String args[]){ StringBuffer sb=new StringBuffer(); System.out.printl n(sb.capacity());//default 16  sb.append("Hello");  System.out.println(sb.capacity());//now 16  sb.append("java is my favourite language");  System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  }  } 53
  • 54. Method Description char charAt(int index) returns char value for the particular index int length() returns string length static String format(String format, Object... args) returns a formatted string. static String format(Locale l, String format, Object... args) returns formatted string with given locale. String substring(int beginIndex) returns substring for given begin index. String substring(int beginIndex, int endIndex) returns substring for given begin index and end index. 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. 54
  • 55. static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string. boolean equals(Object another) checks the equality of string with the given object. boolean isEmpty() checks if string is empty. String concat(String str) concatenates the specified string. 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. static String equalsIgnoreCase(String another) compares another string. It doesn't check case. String[] split(String regex) returns a split string matching regex. 55
  • 56. String[] split(String regex, int limit) returns a split string matching regex and limit. String intern() returns an interned string. int indexOf(int ch) returns the specified char value index. int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index. int indexOf(String substring) returns the specified substring index. int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index. String toLowerCase() returns a string in lowercase. String toLowerCase(Locale l) returns a string in lowercase using specified locale. String toUpperCase() returns a string in uppercase. String toUpperCase(Locale l) returns a string in uppercase using specified locale. String trim() removes beginning and ending 56