0% found this document useful (0 votes)
58 views111 pages

Unit2 - Building Blocks of The Language

The document outlines the fundamental building blocks of the Java programming language, covering topics such as primitive and user-defined data types, variable declarations, type conversion, and scope of variables. It details the characteristics of various data types, including integers, floating-point numbers, characters, and booleans, as well as the use of identifiers, literals, and operators. Additionally, it discusses wrapper classes, comment syntax, and garbage collection in Java.

Uploaded by

Yasmin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views111 pages

Unit2 - Building Blocks of The Language

The document outlines the fundamental building blocks of the Java programming language, covering topics such as primitive and user-defined data types, variable declarations, type conversion, and scope of variables. It details the characteristics of various data types, including integers, floating-point numbers, characters, and booleans, as well as the use of identifiers, literals, and operators. Additionally, it discusses wrapper classes, comment syntax, and garbage collection in Java.

Uploaded by

Yasmin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

UNIT-2

BUILDING BLOCKS OF
THE LANGUAGE
TOPICS TO BE COVERED…
2.1 Primitive Data Types : Integers, Floating Point
type, Characters, Booleans etc
2.2 User Defined Data Type
2.3 Identifiers & Literals
2.4 Declarations of constants & variables
2.5 Type Conversion and Casting
2.6 Scope of variables & default values of variables
declared
2.7 Wrapper classes
2.8 Comment Syntax
2.9 Garbage Collection
TOPICS TO BE COVERED…
2.10 Arrays of Primitive Data Types
2.11 Types of Arrays
2.12 Creation, concatenation and conversion of a string,
changing case of string, character extraction, String
Comparison, String Buffer
2.13DifferentOperators:Arithmetic,bitwise,
Relational,Logical,Assignment,Conditional,ternary,Inc
rement/Decrement, Mathematical Functions
2.14 Decision and control statements: Selection
Statement (if, if...else, switch),Loops while, do-
while, for), Jump statements (break, continue,
return & exit)
2.1 DATA TYPES IN JAVA
Data types

Primitive Non primitive


(built in ) (reference / derived)

Numeric Nonnumeric classes Arrays

Interface

character Boolean

Integer Floating
point
INTEGER TYPES
 Java does not support
Integer
unsigned type, so values
can be positive or
negative.

byte short int long

Type Size Minimum value Maximum value


byte 1 byte -128 127

short 2 byte -32768 32767

int 4 byte -2,147,483,648 2,147,483,647

long 8 byte -9,223,372,036,854,754,808 9,223,372,036,854,754,807


FLOATING TYPES

Floating point

Float Double
(single precision) (double precision)

Type Size Minimum value Maximum value

Float 4 byte 3.4 e -038 3.4 e +038

double 8 byte 1.7 e -308 1.7 e +308


 Floating point no. are treated as double precision ,
so to force them to be in single precision mode ,we
must append f or F.
 Ex: 1.23f , 7.6512F

 NaN: Not a Number

(special value supported by floating point data type)


It is used to represent result of operation such as
dividing by zero ,where actual number is not produced.
CHARACTER TYPE
 char is used
 Size : 2 byte

 It holds single character only.

BOOLEAN TYPE
 It is used to test a particular condition during
execution of program.
 It has two values : true or false

 boolean keyword used

 Size: 1 bit ( 0 or 1)

 All comparison operators return boolean type variable.


 So, there are 8 basic(primitive ) data type in java.

Sr. No. Type Size (in bytes)

1 boolean 1 bit

2 byte 1 byte

3 character 2 bytes

4 short 2 bytes

5 int 4 bytes

6 float 4 bytes

7 long 8 bytes

8 double 8 bytes
2.2 USER DEFINED DATA TYPE
 Class, interface and array are user defined data
type.
 Class encapsulates various variables and methods

 Interface is same as class except it contains methods


without body. It is used to implement multiple
inheritance.
 An array contains same type of elements and provides
sequential access.
2.3 IDENTIFIERS & LITERALS
Java tokens:
 Java program is a collection of classes.

 Class is defined by a set of declaration


statements and methods containing executable
statements.
 Smallest individual unit in program is tokens.

 Compiler recognize them for building up


expressions and statement
 Java program=tokens + comments + white space
ELEMENTS OF JAVA CLASS

Declaration
statement Variable section

tokens

Expression &
method1
statement
Method section

method2 tokens

Fig. Elements of java class


Five types of tokens :
1) reserved keywords
2) identifiers
3) literals
4) operators
5) separators

Java character set


 Smallest unit of java language are characters.

 Characters are used to write java tokens, this


characters are defined by Unicode character set.
 Unicode is 16-bit character coding system.
KEYWORDS
 Java has 60 reserved keywords.
 We can not use keywords as names for variables,
classes, methods and so on.
 Keywords should be written in small letters.

abstract Boolean break byte byvalue* case cast*


catch char class const* continue default do
double else extends false** final finally float
for future** generic* goto* if implements import
inner* instanceof* int interface long native new
null** operator* outer* package private protected public
rest* return short static super switch try
this threadsafe* throw throws transient true**
var* void volatile while syncronized

* Reserved for future use

** These are values defined by java


IDENTIFIERS
 Identifiers are programmer designed tokens.
 It is used for naming classes ,methods , variables ,
objects , label , package and interface in program.
 Example:
 average , sum ,dayTemprature , totalMarks

LITERALS
 Sequence of characters (digits , letters ,and other
character) that represent constant values to be stored in
variables.
 Five types:
 Integer literals
 Floating point literals
 Character literals
 String literals
 Boolean literals
Operators
 All operator is a symbol that takes one or more
arguments and operates on them to produce a result.

Seperators
 They are symbols used to indicate where groups of code
are divided and arranged.

Sr. No. Name


1 Parentheses ( )
2 Braces { }
3 Brackets [ ]
4 Semicolon ;
5 Comma ,
6 Period .
2.4 DECLARATIONS OF CONSTANTS &
VARIABLES
Constant
 Constant in java refers to fixed values do not change
during execution of program.
1. Integer Constant
2. Real constant
3. Single constant
4. String constant
1) INTEGER CONSTANT
 Integers :
 Decimal : 0 to 9 [ ex. 123, 012 , 16789 ]
 Octal : [ ex. 037 , o ,0435 ]
 Hexadecimal : [ 0x2 , 0x9F , 0x ,oxbcd ]

Java constant

Numeric Non numeric

Real Integer character string


2) REAL CONSTANT
 Floating point / Real point constants
Ex. 0.083 , -0.75 , 215. , .95 , -.71
syntax : mantissa e Exponent
 Ex.

 .65e4 , 12e-4 , 1.5 e+5 , 3.18E3


 Floating point contain 4 parts:

1. A whole number
2. A decimal number
3. A fractional part
4. An exponent
3) SINGLE CHARACTER CONSTANT
Ex.
‘5’ , ‘Y’ , ‘; ‘ , ‘‘

4) STRING CONSTANT
• Sequence of character enclosed between double
quotes.
• Ex.
“hello java” , “1997” ,”?----” , “5+3” , “x”
BACK SLASH CHARACTER SEQUENCE
(ESCAPE SEQUENCE)
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’’ Single quote
‘\\’ Double quote
VARIABLE
 It is a data name used to store a data value.
 Variable may take different values at different times
during execution of program.
 Rules for declaration

1. Not start with digit


2. Upper case and lower case letters are distinct
3. Not should be a keyword
4. No white spaces
5. Variable name can be of any length.
DECLARATION OF VARIABLES
 Syntax:
type variable1, variable2,……;

Ex: int count;


float x , y ;
double p1;
byte b;
char ch;
GIVING VALUES TO VARIABLE
1) By using assignment statement

Syntax : variable name=value;


Ex: i=0,x=0.0f;
int i=0; char ch=‘X’;

2) By using read statement: (readLine() method)

readLine() method reads input from keyboard as a


string which is then converted to corresponding data
type using wrapper classes.
2.5 TYPE CONVERSION AND CASTING
 Process of converting one data type to another is called
type casting
 When we need casting?

it is used when there is need to store a value of one type


into a variable of another type.
 Syntax:

type variable1 = (type) variable2 ;


Example:
int m=5;
byte n=(byte) m; // converts int m into byte type
long count=(long) m; // converts int m into long
type
 float and double type can be converted any except
boolean.
 byte ,short , int and long can be converted in any type
except boolean
 Casting in smaller type may result in loss of data.

 Casting floating point into integer will loss of


fractional part.

byte
short
int
long
float
double
From To
byte short , char , int , long , float , double
short int , long , float , double
char int , long , float , double
int long , float , double
long float , double
float double

Type casting with out loss of data


2.5 AUTOMATIC CONVERSION
 It is possible to assign value of one type to a other type
without casting, is known as automatic type
conversion.
 It is possible only if destination type has enough
precision to store source type.
 Example:

byte b=75;
int a=b;
 Two operations :

1) Widening(promotion)
2) narrowing
AUTOMATIC CONVERSION
Widening: process of assigning smaller type to larger
type is widening or promotion.
Ex: byte b=5;
int a=b;
Narrowing: process of assigning larger type to smaller
type is known as narrowing.
Ex: float c=25.43f;
int a=(int) c;
Narrowing may result in loss of information.
2.6 SCOPE OF VARIABLE & DEFAULT VALUES
Variable classified as
1. instance variable
2. Class variable
3. Local variable
Instance variable:
 Declared inside class

 They are create when object are instantiated and


therefore they are associated with objects.
 It takes different values for different objects.
class A
{ Global or class variable
int a;

sum(int x, int y)
{
int z=x + y;
}
Here, x ,y and z are local
} variable
Block 1

{
int x=0;
Block 2
{
------
-------
int n=5;
-------
}

{
------ Block 3
-------
int m=10;
-------
}

}
Class variable
 Declared inside class

 They are global to class and belongs to the entire set of


object that class creates.
 Only one memory location is created for each class
variable

Local variable
 Variable declared and used inside methods.

 They work only inside that specific method.


2.6 STANDARD DEFAULT VALUES
Type value
byte Zero:(byte) 0
short Zero:(short) 0
int Zero : 0
long Zero: 0L or 0l
double 0.0d
float 0.0f
char Null character
boolean false
Reference null
2.7 WRAPPER CLASS
 Vector class cannot handle primitive data types like int,
float, long, char and double.
Use:
 Primitive data types may be converted into objects types
by using wrapper classes contained in java.lang;
 Wrapper classes for converting simple types

No. Primitive data type Wrapper class


1 boolean Boolean
2 char Character
3 double Double
4 float Float
5 int Integer
6 long Long
 Wrapper classes have number of unique methods for
handling primitive data type.

Converting primitive numbers to object number Using


constructor methods :

Integer intval= new Integer( i Primitive integer to Integer


1
); object
2 Float floatval=new Float( f ); Primitive float to Float
object
3 Double doubleval=new Primitive double to Double
Double(d); object
4 Long longVal=new Long( l ); Primitive long to Long object
CONVERTING OBJECT NUMBERS TO PRIMITIVE
NUMBER USING TYPEVALUE ( ) :

Object to Primitive
1 int i = intval.intValue( );
integer number
2 float f = floatval.floatValue( ); Object to Primitive
float number
3 double d= Object to Primitive
doubleval.doubleValue( ); double number
4 Longl = longVal.longValue( ); Object to Primitive
long number
CONVERTING NUMBERS TO STRING
USING STRING ( ) METHODS:

1 str= Integer.toString ( i ); Primitive int to String

2 str= Float.toString ( f ); Primitive float to String


Primitive double to
3 str= Double.toString ( d );
String
4 str= Long.toString ( l ); Primitive long to String
CONVERTING STRING OBJECTS TO NUMERIC
OBJECTS USING STATIC ( ) METHODS
VALUEOF( ):

Intval=Integer.valueOf ( Convert string to int


1
str ); object
Floatval=Float.valueOf ( Convert string to float
2
str ); object
Doubleval=Double.valueOf Convert string to double
3
( str ); object
Longval=Long .valueOf( Convert string to long
4
str ); object
CONVERTING NUMERIC STRING TO PRIMITIVE
NUMBER USING PARSING METHODS:

int i=Integer.parseInt ( Convert string to


1
str ); primitive integers
long l=Long.parseLong ( Convert string to
2
str ); primitive long
2.8 COMMENT SYNTAX
 Java has three types of comment lines:
1) Single line comments: start with // and extend to
the end of the current line. This comment type is also
present in C++ and in modern C

Syntax: // This is an end-of-line comment


2) Multiline comments: start with /* and end with */,
they may cover multiple lines. This type of comment
was derived from C and C++.
Syntax : /* This is a multi-line comment.
 It may occupy more than one line. */
3)Documentation comments are processed by
Javadoc tool to generate documentation from source
files.
 it starts with /** and follows conventions defined by
the Javadoc tool. Technically these comments are a
special kind of traditional comment and they are not
specifically defined in the language specification.
Syntax :
/**
* This is a documentation comment.
*
* @author John Doe
*/
2.9 GARBAGE COLLECTION
 Java runtime system performs memory management.
 Java uses constructor to initialize object (give space
in memory).
 Java does not have destructor as in C++.

 Java system has garbage collector and finalizer


method for memory de allocation for any object.
FINALIZER METHOD
 Finalizer releases the objects special memory.
 Constructor method is used to initialize an object when
it is declared, this is called initialization. Java also
supports finalization, which is opposite to
initialization.
 Java run time is an automatic garbage collecting
system, which automatically frees up the memory
resources used by objects.
 But if objects may hold other non-object resources
(such as file descriptor or windows character system).
 Garbage collector can’t free these resources, to free
these resources we must use Finalizer methods.
FINALIZER METHOD
 finalize( ) can be added to any class.
 Java calls that method whenever it is about reclaim
space for that object. finalize( ) method should
explicitly define tasks to be performed.
 Before an object gets garbage collected ,the
garbage collector gives the object an
opportunities to clean up itself through call to
the object’s finalize ( ) method , this is called
finalization.
 When there is no more reference to object, object is
finalized and is then garbage collected.
 finalize ( ) method is member of object class.
FINALIZER METHOD
 finalize ( ) is only called just prior to garbage collector.
System . runFinalization ( );
 this method force object’s finalization on it finalize all
objects that are waiting to be garbage collected.
Syntax:
protected void finalize( )
{
//finalization code
}

 Protected prevents access to finalize ( ) by code defined


outside its class.
GARBAGE COLLECTOR
 A Java runtime environment deletes objects
periodically when it determines that they are no longer
being used, this process is called garbage collection.
 It is done by garbage collector of java.

 Garbage collector only knows how to release memory


allocated with new (means dynamically).
 An object is eligible for garbage collection when there
are no more reference to that object.
 When garbage collector is ready to release the storage
used for your object, it will first call finalize ( ) and
only on the next pass garbage collection pass will
reclaim the objects memory.
GARBAGE COLLECTOR
 Before an object gets garbage collected ,garbage
collector gives the object an opportunity to clean up
itself through a call to objects finalize( ) method.
 Running of garbage collector:

 We can ask garbage collector to run at any time by


calling gc( ) method of System class.
System.gc( );
2.10 ARRAYS OF PRIMITIVE DATA TYPES
 Java has eight basic (primitive) data type. We can
create array of any primitive data type.

Syntax: datatype Arrayname[ ] =new datatype[ size ];

Where ,size is any decimal number, it defines no.. of


element you want to store in that array.

Example: int a[ ]=new int [ 100 ];


byte val [ ]=new byte [10] ;
float weight[ ]=new float[10];
ARRAY
 Array is a fixed size sequential collection of elements
having same data type.
 We can declare array without giving its size.

(we do not have to provide array size at the time of


declaration of array.)
Declaration of array:
type arrayname[ ] ; ex.: int a[ ];
or
type[ ] arrayname; ex.: int[ ] a;
Creation of array:
type Arrayname=new type [ size ] ;
Ex: int a=new int [ 10 ] ;

Initialization of array:

1) Arrayname[subscript ]=value;
2) Type arrayname[ ]={ list of values};

Ex 1:
int a [0] =16;
Ex 2:
int a [ ] ={1,2,3,4,5,6};
ARRAY LENGTH
 In java all arrays store the allocated size in variable
named length.

 We can access length of array using length variable.

int size= a.length;


2.11 TYPES OF ARRAYS

 Array is a fixed size sequential collection of


elements having same data type.
 We can declare array without giving its size.(we do
not have to provide array size at the time of
declaration of array.)
 Three types of array :

1) one dimensional
2) two dimensional
3) variable sized array(multi dimensional )
1) ONE DIMENSIONAL ARRAY

Declaration of array:
type arrayname[ ] ;
Example: int a[ ];
OR
type[ ] arrayname;
Example: int[ ] a;

Creation of array:
Arrayname=new type [ size ] ;
Example: a=new int [ 10 ] ;
ONE DIMENSIONAL ARRAY
Initialization of array:
Compile time :
1) Arrayname[subscript ]=value;
2) Type arrayname[ ]={ list of values};

Ex: int a [ ] ={1,2,3,4,5,6};


int a[0]=1;
int a[1]=2; and so on

Run time :
Using command line argument , readLine() method
,using Scanner class’s methods
2) TWO DIMENSIONAL ARRAY
 int a[ ] [ ] = new int [3] [4] ;
 3X4 array

 int a[2][3]={0,0,0,1,1,1};

 int a[2][3]={ {0,0,0} , {1,1,1} }; 0 0 0


1 1 1
3) VARIABLE SIZED ARRAYS
 Java treats multidimensional array as “arrays of
arrays”
 It is possible to declare a two dimensional .

 int a[ ][ ]= new int [3][ ]

X[0] = new int[2];


X[1] = new int[4];
X[2] = new int[3];
This statements create a two dimensional array as
having different length for each row as follows:
X[0]
X[1]
X[2]
2.12 STRING CONCEPT
 String represents a sequence of characters. The
easiest way to represent a sequence of character in java
is character array.
E.g. : char charArray[ ]= new char[4];
charArray[ 0]= ‘J’ ,charArray[1 ]=‘a’ ,
charArray[ 2]=‘v’ ,charArray[ 3]=‘a’
 character array have the ability to query their length
,but they are not good enough to support the range of
operations we want to perform on strings.(like to copy
one character array into another array may require a
lot of efforts)
 Java can handle these problem more efficiently using
string.
STRING CONSTRUCTOR
 In java strings are class objects which is implemented
using two classes String and StringBuffer.
 Java string is an instantiated object of the String
class.
 All string literals in Java programs, are implemented
as instances of String class. Strings in Java are 16-bit
Unicode.
 In JDK 1.5+ you can use StringBuilder, which works
exactly like StringBuffer, but it is faster and not
thread-safe
CHARACTERISTICS / BENEFITS OF
JAVA’S STRING:

 More reliable and predictable .


 No problem of bound checking same as in C.

 Java string is not character array and is not


NULL terminated.
STRING DECLARATION
 We can declare and create string as follows:
1) String stringname;
stringname =new String(“string”);

E.g. : String str ;


str= new String (“ VPMP”);
2) String stringname=new String(“string”);
E.g. : String str= new String (“ VPMP”);
STRING DECLARATION
 The easiest way of creating a String object is
using a string literal:
String str1 = “Hello!";
 A string literal is a reference to a String object.

 Since a string literal is a reference, it can be


manipulated like any other String reference. i.e.
it can be used to invoke methods of String class.
 For example,

int myLength = “Hello ”.length( );


or
int myLength=str1.length( );
STRING CONCATENATION
Using ( +) operator:
 The Java string can be concatenated using ( + )
operator, which has been overloaded for Strings
objects.
 String concatenation is implemented through the
StringBuffer class and its append method.
 For example,

String finalString = “Hello” + “World


Would be executed as :
String finalString =
new StringBuffer().append(“Hello”).append(“World”)
.toString();
STRING CONCATENATION

concat() method :
Concatenates str1 and str2.

E.g. : String str1=“Hello “ ;


String str2=“world” ;
s3=str1.concat(str2); //output will be
“HelloWorld”
STRING CONSTRUCTORS
 String class provides various types of constructors to
create String objects.
1) String() :Creates a new String object whose content
is empty i.e. “ ”.
2) String(String s) :Creates a new String object whose
content is same as the String object passed as an
argument.i.e. “str1”
3) String also provides constructors that take byte and
char array as argument and returns String object.

 Note: Constructor creates a new string means


STRING ARRAY
We can create and use array that contain strings,
String itemArray[] =new String[3];
 It will create an itemArray of size 3 to hold three string
constants.
 Strings can be assigned to this array using element
by element or more effectively using for loop.
STRING EQUALITY
1) equals() method
 String class overrides the equals() method of the
Object class. It compares the content of the two string
object and returns the boolean value accordingly.
 If both strings are same then returns “true” else
‘false” .
 Equals( ) method compares actual contents of two
String objects.
 E.g. : String str1=“Hello “
String str2=“hello”
String Str3 =“Hello”
Then
str1.eqauls(str2); // returns false
str1.eqauls(str3); // returns true
STRING EQUALITY
2) Using “==“ operator
 We can also compare two strings using “==“ .

 “ == “ compares the references not the actual contents of


the String object;
 E.g. :

String str1=“Hello “
String str2=“hello”
String str3 =“Hello”
Then
if(str1==str2); // returns true
if(str1 == str3); // returns true
STRING EQUALITY
3 ) equalsIgnoreCase() :
 This method ignores the case of contents while
comparing.
It returns true if both string are same ,ignoring
the case of characters.
E.g. : String str1=“Hello “
String str2=“hello”
Then
str1.eqaulsIgnoreCase(str2); //returns true
STRING EQUALITY
4) compareTo():
 it compares two Strings and returns an int value.

✓ It returns value 0 (zero), if str1 is equals to


str2.
✓ It returns value negative , if str1 < str2.
✓ It returns value positive , if str1 > str2.
E.g String str1=“Hello “ ;
String str2=“hello” ;
String Str3 =“Hello”;
str1.compareTo(str2); // returns -32
str1.compareTo(str3); //returns 0
str2.compareTo(str1); // returns 32
SEARCHING STRING
 String class provides indexOf( )method which searches
for the specified character inside the string object.
 This method has been overloaded. If the search is
successful, then it returns the index of the char
otherwise -1 is returned.
1) int indexOf(String str) :Finds the start index of the
first occurrence of the substring argument in a String.
E.g.
int position= str1.indexOf(“e”);// for ”hello” it returns
1
SEARCHING STRING
1) int indexOf (String str, int fromIndex)
Finds the start index of the first occurrence of the
substring argument in a String, starting at the index
specified in the second argument.
int position= str1.indexOf(“e”,3); // for ”hello” it
returns -1
3) int indexOf(char c):Returns the index of first
occurrence of the argument char.
int position= str1.indexOf( e ); // for welcome it
returns 1
4) int indexOf(char c, int fromIndex) :Returns the
index of first occurrence of the argument char.
int position= str1.indexOf(e , 3 ); // for welcome it
returns 6
SEARCHING STRING
The String class also provides methods to search
for a character or string in backward direction.

These methods are given below.


1. int lastIndexOf (char ch)

2. int lastIndexOf(char ch, int fromIndex)

3. int lastIndexOf (String str)

4. int lastIndexOf (String str, int fromIndex)

 Example of lastIndexOf
REPLACING CHARACTERS IN STRING
 The replace( ) method of String class can be used to
replace all occurrences of the specified character with
given character.
str. replace(char oldChar, char newchar)
E.g.
String str1=“Hello”;
str1.replace(“H” ,”c”);
//Gives string “cello” instead of “Hello”
GETTING SUBSTRINGS
 String class provides substring( ) method to extract
specified portion of the given String. This method has
been overloaded.
1) String substring(int startIndex)
- gives substring starting from nth character
2) String substring(int startIndex, int endIndex)
- gives substring starting from nth character up to
mth character(not including mth ).
 If the index value is not valid,
StringIndexOutOfBoundsException is thrown.
 Note: A new String object containing the substring is
created and returned. The original String won’t be
affected.
STRING CONVERSIONS
 String class provides set of static overloaded valueOf( )
method to convert primitives and object into strings.
Object to string:
 static String .valueOf (Object obj)

 static String. valueOf (char[] character)

primitive to string:
 static String .valueOf (boolean b)

 static String .valueOf (char c)

 static String .valueOf (int i)

 static String. valueOf (long l)

 static String .valueOf (float f)

 static String .valueOf (double d)


MANIPULATING CHARACTER CASE
 String class provides following methods to manipulate
character case in String.
1) toUpperCase( ) :converts the string str1 to all upper
case .
E.g. str2=str1.toUpperCase ( );
2) toLowerCase( ): converts the string str1 to all lower
case .
E.g.str2=str1.toLowerCase ( );
 Note : Original String object is returned if none of the
characters changed, otherwise new String object is
constructed and returned.
MANIPULATING CHARACTER CASE
3) trim()
This method removes white space from the front
and the end of a String.
4) int length()
Returns length of the String.
5) charAt()
Gives nth character of str1.
6) p.toString():
creates a string representation of the object p.
STRING EXAMPLE
class StringOrdering
{
static String name[ ]= {“mumbai” , “Delhi” ,”Aagra”
,”Calcutta” , “Bombay
“ };
public static void main(String args[ ])
{
int size =name. length ;
String temp =null;
for(int i=0;i<size ; i++)
{
for(int j=i+1;j<size ; j++)
{
STRING EXAMPLE
if(name[j].compareTo(name[i] < 0)
{
temp=name[ i];
name [i] =name [j];
name [j] =temp;
}
}
}
for( int i=0; i<size ;i++ )
{
System.out.println(name[i]);
}}}
OUTPUT OF THE PROGRAM
Output:
Aagra
Bombay
Calcutta
Delhi
Mumbai
DIFFERENCE :STRING VS. STRINGBUFFER

String class StringBuffer class


 It creates fixed length string.  It creates strings of flexible
(variable ) length.
 It can not be changed.
 It can modified in terms of
length and content.
 We can not insert characters
and substrings in the middle  We can insert characters
of string. and substrings in the
middle of a string ,or
append another string to
the end.
STRINGBUFFER CLASS
 StringBuffer class is peer class of String.
 It enables us to create flexible length string allow us to
perform manipulation on string whenever we want.
 Commonly used StringBuffer Methods:

1) str1.setCharAt( n, ‘x’ ) :
It Modifies the nth character to x .
2) str1.append(str2):
Appends the string str2 at the end of str1.
3) str1.insert(n,s2):
it inserts the string str2 at the position n of the
string str1.
4) str1.setLength( n) :
sets the length of the string str1 to n.
STRINGBUFFER CLASS

If n < str1.length( ) then str1 is truncated.


If n > str1 .length( ) then zeros are added to
str1.
EXAMPLE OF STRINGBUFFER CLASS METHOD
class StringManipulation
{
public static void main(String args[ ])
{
StringBuffer str=new StringBuffer(“Hello class”);
System.out.println(“Original string :” + str );
//get string length
System.out.println( “length of string =“ + str.length() );
//Accessing characters in astring
for( int i=0 ;i< str.length ( ) ; i++ )
{ int p = i + 1 ;
System.out.println(“character at position :”+ p + “is “
+ str.charAt(i) );
}
//Inserting a string in the middle
String str1 =new String (str . toString());
int pos = str1 . indexOf(“ class”);
str . insert (pos , “ce “);
System .out.println( “Modified string : “+ str );

//Modifying characters
str .setCharAt( 7 , ‘-’);
System.out.println( “string now : “ + str );

//Appending a string at the end


str . append (“ Good Morning“);
System.out.println( “Appended string :“ + str );
}}
Original String : Hello class
Length of string = 11
Character at position : 1 is H
Character at position : 2 is e
Character at position : 3 is l
Character at position : 4 is l
Character at position : 5 is o
Character at position : 6 is
Character at position : 7 is c
Character at position : 8 is l
Character at position : 9 is a
Character at position : 10 is s
Character at position : 11 is s
Modified string : Helloce class
String now : Helloce-class
Appended string : Helloce-class Good Morning
2.13 OPERATORS
 Arithmetic operators
 Relational operators

 Logical operators

 Assignment operators

 Increment / decrement operators

 conditional operators

 Bitwise operators

 Special operators
ARITHMETIC OPERATORS
 +,-,*,/,%
 For Example a=14 ,b=9

 a - b =10
 a + b =18
 a * b =56
 a / b =3
 a % b=2
 -14 % 3=-2 (a%b=(a-(a/b)*b)
 14 % 3=2
 15/10=1
 15/10.0=1.5
RELATIONAL OPERATOR
 < , <= , >= , > , == , !=
 returns true or false

 Arithmetic operator has higher priority then


relational operator.
 Example:

 if a>b

 if a<b

 if a==b etc
LOGICAL OPERATOR
 && : logical AND
 || : logical Or
! : logical not
 Example:

if (a>b)&&(a>c)
if (a>b)||(a>c)
ASSIGNMENT OPERATOR
 V op= exp ;
 X+=1;

Or
 V = v op (exp);

 Example:

 a=a+5;
INCREMENT / DECREMENT
 Pre increment : ++m
 Post increment : m++
 Pre decrement : --m
 Post decrement: m—
 Example:

 B=++a;

 C=a++;

 D=a--;
CONDITIONAL OPERATOR
 It is also known as Ternary Operator.
 Syntax:

(Condition)?True Statement:Fasle Statement.


 Example:

Max=(a>b)?a:b;
BITWISE OPERATOR
 & : bitwise AND
! : bitwise OR
^ : bitwise exclusive OR
v : one’s complement
 << : shift left

 >> : shift right

 >>>: shift right with zero fill


SPECIAL OPERATOR
1) instanceof operator :
 It is an object reference operator.
 It returns true if object on left side is instance of
class given on right side.
 It defines whether object belongs to particular
class or not.
 Example:
person instanceof Student
if object person belongs to class
Student then returns true , else returns false.
SPECIAL OPERATOR
2) Dot ( . ) operator :
 It is used to access the instance variable and method
of class objects.
 It is also access classes and sub package from
package.
 Example:

 person1.age;
 person1.salary();
MATHEMATICAL FUNCTION
Function Description
abs(int a) Returns the absolute integer value of a
Returns the "ceiling," or smallest whole number
ceil(double a)
greater than or equal to a
cos(double x) Returns the cosine value of an angle in radians
Returns the exponential number ex raised to the
exp(double x)
power of a
floor(double Returns the "floor," or largest whole number less than
a) or equal to a
log(double a) Returns the natural logarithm (base e) of a
Takes two values, a and b, and returns the greater of
max(a,b)
the two
Takes two values, a and b, and returns the smaller of
min( a, b)
the two
pow(a, b) Returns the number a raised to the power of b (a^b)
sin(double) Returns the trigonometric sine of an angle
MATHEMATICAL FUNCTION
Function Description
sqrt(double a) Returns the square root of a
Returns the trigonometric tangent of an
tan(double a)
angle
toDegrees(double) Translates radians to degrees
toRadians(double) Translates degrees to radians
Returns the arc cosine of a, in the range
acos(double a)
of 0.0 through pi
Returns the arc sine of a, in the range of
asin(double a)
-pi/2 through pi/2
Returns the arc tangent of a, in the
atan(double a)
range of -pi/2 through pi/2
Returns the closest integer to the
rint(double) argument, but as a floating-point
number
2.14 JAVA STATEMENTS
 Empty statement: used as a place holder
 Labeled statement: used as a label
 Expression statement:
Seven types
1. Assignment
2. Pre-Increment
3. Pre-decrement
4. Post-Increment
5. Post-decrement
6. Method call
7. Allocation expression
 Selection statement:
Three types
 If , If-else , switch
2.14 JAVA STATEMENTS
 Iteration statement:
Three types
 While , do , For
 Jump statement:

Four types
 Break , Continue , Return , throw
 Synchronization statement: used for handling issues
with multithreading
 Guarding statement: used for safe handling of code that
may cause exceptions
 Try, catch , finally
Java statement

expression guarding

labeled synchronization

control

selection iteration jump

if switch break return

else continue
while do for
JAVA CONTROL STATEMENTS
Java control statements are of three type:
1) Selection Statement (if, if...else, switch)
2) Loops while, do-while, for)
3) Jump statements (break, continue, return &
exit)
SELECTION STATEMENT:
1) simple if statement :

if ( test expression)
{
//statement block;
}
SELECTION STATEMENT:

2) if...else statement :
if ( test expression)
{
//true block statement block;
}
else
{
// false block statement;
}
SELECTION STATEMENT:
3) nesting of if.....else statement:
if ( test condition-1)
{ if(condition-2)
{
statement-1;
else
{
Statement-2;
}}
else
{
Statement-3;
}
SELECTION STATEMENT:
4) else....if ladder
if ( condition-1)
{
statement-1;}
else if ( condition 2)
{
statement-2;
}
else if ( condition 3)
{
statement-3;}
else
default: default statement;
SELECTION STATEMENT:
5) switch statement :
switch(integer or character value or expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
.........
default :
default block;
break; }
ITERATION STATEMENT:
1) while statement:

while(test condition)
{
Body of the loop
}
2) do..while statement:

do
{
Body of the loop
}while(test condition);
ITERATION STATEMENT:
3) for loop:
for ( initialization ; test expression ; increment or
decrement )
{
Body of the loop

}
JUMP STATEMENT
1) break: It is used to exit from a loop or block
2) continue :it is used to skip some part of code
and causes loop to be continued with the next
iteration.
3) return :it is used to return values to calling
function

You might also like