Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Dr.K.Sasidhar
09/05/16
Software
programming
language.
09/05/16
Programming Languages
Machine Language
Assembly Language
09/05/16
Programming Styles
Top-down
Top-down
Bottom Up
Modules
The main method appears at top of the program.
The compilation begins from top.
Bottom-up
09/05/16
what is Java?
Console Applications
09/05/16
Android Apps
Web Applications
Embedded Applications
Scientific Applications
09/05/16
09/05/16
09/05/16
History of Java
09/05/16
History of Java
09/05/16
Now
09/05/16
09/05/16
Green Team
09/05/16
Java Logo
09/05/16
Versions of Java
Version
JDK 1.1
J2SE 1.2
J2SE 1.3
Year
Features Added
Inner classes JavaBeans, JDBC, RMI, Reflection,
Feb19,1997 AWT.
JIT compiler, Collections, IDL & CORBA, strictfp,
Dec8, 1998 Java Plug-in.
HotSpot JVM, JavaSound, Java Naming and
May8,
Directory Interface, Java Platform Debugger
2000
Architecture.
09/05/16
Java Platforms
There are three main platforms for Java:
09/05/16
Java Terminology
Java Development Kit: (Jdk)
09/05/16
Java Terminology
09/05/16
Java Terminology
Java
Runtime Environment:
09/05/16
Inheritance
Polymorphism
Dynamic
Binding
09/05/16
class
object
09/05/16
Polymorphism:
It allows the single method to perform different actions based on
the parameters.
Dynamic Binding: When a method is called within a program, it
associated with the program at run time rather than at compile
time is called dynamic binding.
09/05/16
09/05/16
Benefits of OOP
Through
Object
systems.
Software
09/05/16
Java
operator Doesnt
support
overloading
overloading
Template
classes
operator
are No templates
available.
Supports
09/05/16
Java
Supports ASCII
Destructor
character set.
function is available
09/05/16
Simple
Object Oriented
Distributed
Robust
Secure
Multithreaded
Dynamic
Architecture-Neutral
OOPs through Java -- Dr.K.Sasi
09/05/16
Simple
Java Features
Pointers may crash a program easily. For ex: when we add two
pointers the program crashes immediately.
Object Oriented
09/05/16
Java Features
Distributed
Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols.
Allows objects on two different computers to execute
procedures remotely by using package called Remote Method
Invocation (RMI)
Robust
Robust means strong.
Inbuilt exception handling features.
Memory management feature.
Automatic garbage collection tracks objects usage over time
and deletes if the variable or an object is not used.
OOPs through Java -- Dr.K.Sasi
09/05/16
Java Features
Secure
Access
Portability
Same application runs on all platforms
The sizes of the primitive data types are always the same
OOPs through Java -- Dr.K.Sasi
09/05/16
Java Features
Multithreaded
A thread is an individual process.
JVM supports multithreaded programming.
Need not wait for the application to finish one task before
beginning another one.
OOPs through Java -- Dr.K.Sasi
09/05/16
Java Features
Dynamic
Libraries can freely add new methods and instance
variables without any effect on their clients
Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
Architecture-Neutral
Goal of java designers is write once; run anywhere, any
time, forever.
09/05/16
Suggested
Optional
Essential / optional
Optional
Optional
{
main method definition
}
09/05/16
class First
{
public static void main (String args [])
{
System.out.println (Welcome to Java);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
09/05/16
with classname.
println() is a method which present in PrintStream class
which can call through the PrintStream object return by
static field out present in System class to print a line to
console.
OOPs through Java -- Dr.K.Sasi
09/05/16
Comments
Single Line comments: Starts with // double slash symbol.
Multi Line comments: Stars with /* and ends with */
Java documentation comments: Starts with /** and end with
*/. These comments are used to provide description for
every feature in a java program.
09/05/16
The class name and interface name start with a capital letter
Ex: String
In the method name, first word should be small case and from
second word onwards, it starts with a capital letter.
Ex: readLine()
09/05/16
Next line
\t
\r
Enter key
\b
Back space
\f
Form feed
\\
Displays \
Displays
Displays
09/05/16
Java Tokens
Tokens
Keywords
Data Types
Variables
Constants
09/05/16
Keywords
abstract
continue
synchronized
assert
this
default
boolean
throw
do
break
throws
double
byte
else
transient
case
extends
goto
package
if
implements
private
protected
import
instanceOf
int
public
return
short
try
catch
Data Types
Derived Type
Simple Type
Integer
Non-Numeric
Float Char
User Defined
Type
class
Boolean
float
doubleDouble precision
Single precision
byte short
int
long
09/05/16
Interfa
ce
Data Types
09/05/16
09/05/16
09/05/16
Data Types
Name
long
int
short
byte
double
float
char
Width in bits
Range
64
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
32
2,147,483,648 to 2,147,483,647
16
32,768 to 32,767
8
128 to 127
64
4.9e324 to 1.8e+308
32
1.4e045 to 3.4e+038
16
0 to 65,536.
OOPs through Java -- Dr.K.Sasi
09/05/16
int i1 = Integer.MAX_VALUE;
int i2 = Integer.MIN_VALUE ;
long l1 = Long.MAX_VALUE;
long l2 = Long.MIN_VALUE ;
byte b1 = Byte.MAX_VALUE;
byte b2 = Byte.MIN_VALUE ;
}
}
09/05/16
09/05/16
09/05/16
Variables
The variable is the basic unit of storage in a program.
A variable is defined by the combination of an identifier, a type,
and an optional initializer.
Declaring a Variable
In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;
Types
Instance Variable
Class Variable
Local Variable
Parameters
OOPs through Java -- Dr.K.Sasi
09/05/16
Local variables :
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block
is entered and the variable will be destroyed once it exits the
method, constructor or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method,
constructor or block.
There is no default value for local variables so local variables
should be declared and an initial value should be assigned before
the first use.
09/05/16
Instance variables :
Instance variables are declared in a class, but outside a method,
constructor or any block.
Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and block
in the class.
Instance variables have default values.
Instance variables can be accessed directly by calling the variable name
inside the class.
However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName
OOPs through Java -- Dr.K.Sasi
09/05/16
Class/Static variables :
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
Static variables are stored in static memory.
Static variables are created when the program starts and destroyed when
the program stops.
Visibility is similar to instance variables.
Default values are same as instance variables.
Static variables can be accessed by calling with the class name
ClassName.VariableName
09/05/16
class Variables{
int i;
public int j
static long l=10;
public static float f;
char c;
boolean b;
void display(int a){
i=a;
System.out.println("i value in display: "+i);
}
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
09/05/16
class Variables{
int i;//instance variable
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
09/05/16
Scopes can be nested. The outer scope encloses the inner scope.
09/05/16
Operators
Arithmetic Operators
Unary Operators
Member Operator ( . )
Assignment Operators
instanceof Operator
Relational Operators
new Operator
Logical Operators
cast Operator
Boolean Operators
Bitwise Operators
Ternary Operator
Special Operators
OOPs through Java -- Dr.K.Sasi
09/05/16
Arithmetic Operators
Operator
Result
Addition
Subtraction
Multiplication
Division
Modulus
OOPs through Java -- Dr.K.Sasi
09/05/16
Unary Operator
Decrement Operator
(-)
(--)
09/05/16
Example:
class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Assignment Operator
Result
Addition assignment
Subtraction assignment
*=
Multiplication assignment
/=
Division assignment
%=
Modulus assignment
09/05/16
class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Relational Operators
The relational operators determine the relationship that one
operand has to the other.
They determine equality and ordering.
Operator
==
!=
>
<
>=
<=
Result
Equal to
Not equal to
Greater than
Less than
Greater than or equal to
Less than or equal to
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
Logical Operators
Result
&&
Logical AND
||
Logical OR
09/05/16
Boolean Operator
boolean or operator
boolean a,b;
a= true;
b = false;
a&b
09/05/16
Bitwise Operators
bitwise operators can be applied to the integer types, long,
int, short, byte and char.
These operators act upon the individual bits of their operands.
Operator
Result
&
Bitwise AND
Bitwise OR
Bitwise exclusive OR
>>
Shift right
>>>
<<
Shift left
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
09/05/16
Operator Precedence
09/05/16
Expressions
An expression is a combination of constants (like 10),
operators ( like +), variables (section of memory) and
parentheses ( like ( and ) ) used to calculate a
value.
Ex1:
x = 1;
Ex2:
y = 100 + x;
Ex3:
x = (32 - y) / (x + 5)
09/05/16
Control Statements
Selection Statements:
if & switch
Iteration Statements:
Jump Statements:
09/05/16
Selection Statements
if (condition)
statement1;
else
statement2;
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
09/05/16
09/05/16
Iteration Statements
while(condition)
{
// body of
loop
}
do
{
// body of
loop
} while
(condition);
for(initialization;
condition; iteration)
{
// body
}
OOPs through Java -- Dr.K.Sasidhar
09/05/16
{ Statements;
}
OOPs through Java -- Dr.K.Sasidhar
09/05/16
}
OOPs through Java -- Dr.K.Sasidhar
09/05/16
Jump Statements
continue;
break;
label:
------break label;
statement
return;
09/05/16
break:
Continue:
09/05/16
09/05/16
Types of Conversions:
1.Widening conversion
2.Narrowing conversion
09/05/16
Widening Conversion
The widening conversion is permitted in the
following cases:
09/05/16
09/05/16
class Widening{
public static void main(String args[]){
short s;
int i1,i2;
byte b1=10,b2=20;
s=b1;
i1=b2;
//byte to short
//byte to int
i2=c;
//char to int
09/05/16
Narrowing Conversion
(target-type) value
OOPs through Java -- Dr.K.Sasi
09/05/16
i=(int)d;
//double to int
09/05/16
Arrays
One-Dimensional Arrays:
= {elements list};
09/05/16
Multidimensional Arrays
int twoD[][]=new int[4][5];
09/05/16
Initialization:
char []c = {a, b, c};
double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
09/05/16
3-Dimensional Arrays
09/05/16
class ThreeDdemo
{
public static void main(String args[ ])
{
int dept, student, marks, tot =0;
int arr[ ][ ][ ] = { { { 40,41,42}, {50,70,47}},
{ { 71,81,91}, {43,54,63}},
{ { 99,89,78}, { 91,51,81}} };
for(dept = 0; dept < 3; dept ++)
{
System.out.println(Department + (dept+1)+: );
for(student =0; student<2;student++)
{
System.out.println(Student + (student+1) + marks:);
for(marks =0; marks < 3; marks++)
{
System.out.println(arr[dept] [student] [marks] + marks:);
tot + = arr[dept] [student] [marks];
}
System.out.println(Total: +tot);
tot = 0;
}
System.out.println(); } } }
09/05/16
import java.util.Scanner;
class ArrayEx{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int a[]={10,20,30,40,50};
char []c={'a','b','c','d','e'};
int b[]=new int[5];
for(int i=0;i<5;i++){
System.out.print(a[i]+" ");
System.out.println(c[i]+" ");
}
for(int i=0;i<5;i++){
b[i]=input.nextInt();
}
for(int i=0;i<5;i++){
System.out.print(b[i]+" ");
}
}
}
09/05/16
09/05/16
Ex program
class clargs
{
public static void main(String args[ ])
{
int n = args.length;
System.out.println(No. of arguments = +n);
System.out.println(The arguments are:);
for(int i=0; i<n;i++)
System.out.println(args[i]);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Interpreter
& JIT
Operating System
OOPs through Java -- Dr.K.Sasi
09/05/16
Java
Source
Java
Compiler
Java
Byte codes
Java
Byte
codes
move
locally
or
through
n/w
Java Class
Libraries
Just-in-time
Compiler
Java
Interpreter
Run Time System
Java OS
MAC
Win
W32
Solaris
Others
Hardware
OOPs through Java -- Dr.K.Sasi 09/05/16
09/05/16
Class
09/05/16
class classname
{
type instance variable 1;
type instance- variable 2;
09/05/16
class person
{
String name;
int age;
void talk()
{
System.out.println(Hello my name is
+name );
System.out.println(My age is+age);
}
}
09/05/16
class person
{
String name;
int age;
void talk()
{
System.out.println(Hello I am + name);
System.out.println(My age is+age);
}
}
class Demo
{
public static void main(String args[])
{
person p1 = new person();
p1.name = Anil;
p1.age = 20;
P1.talk();
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Declaring an Object
class Box{
double width;
double height;
double depth;
}
Representation 1:
Box mybox;
mybox=new
Box();
Representation 2:
Box mybox=new
Box();
09/05/16
package
packagename;
import statement;
class classname{
//instance variables;
//class or static
variables;
/*methods(parameter
s){
//local variables;
//object creation
//statements;
}*/
}
import java.util.Scanner;
class Demon{
int i;
static double d;
public static void main(String args[]){
char c=a;
Demon obj=new Demon();
Scanner s=new Scanner(System.in);
d=s.nextDouble();
System.out.println(obj.i);
System.out.println(d);
System.out.println(c);
}
}
09/05/16
class classname{
//instance variables;
//class or static variables;
/*methods(parameters){
//local variables;
//statements;
}*/
}
class MainCLass{
class Test{
char c='a';
static float f;
void display(){
int i=10;
System.out.println("Test:display()");
System.out.println(c value: +c);
System.out.println(i value: +i);
System.out.println(f value: +f);
public static void main(String args[])
}
{
}
//object creation
class Demo{
//invoking methods
public static void main(String args[]){
//statements
Test t=new Test();
}
t.display();
}
System.out.println("Demo:main()");
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Access Control
default :
When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.
private:
A private member is accessible only to the class in which it is
defined.
Use private keyword to create private members.
09/05/16
public:
Any class, in any package has access to a class's public
members.
To declare a public member, use the keyword public.
protected:
Allows the class itself, subclasses, and all classes in the same
package to access the members.
To declare a protected member, use the keyword protected.
09/05/16
// methods to access c
void setc(int i){
c = i; // set c's value
ob.b = 20;
// This is not OK and will cause an error
//ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
}
System.out.println(ob.a + " " +ob.b + " " + ob.getc());
int getc() {
}
return c; // get c's value }
}
}
09/05/16
09/05/16
A constructor has the same name as the class name in which it resides and
is syntactically similar to a method.
09/05/16
Default Constructor
09/05/16
// Default Constructor
//Parameterized Constructor
class Test{
char c='a';
static float f;
Test(){
int i=10;
System.out.println("Test:Test()");
System.out.println(c value: +c);
System.out.println(i value: +i);
System.out.println(f value: +f);
}
}
class ConDemo{
public static void main(String args[]){
Test t=new Test();
//t.Test();
System.out.println(ConDemo:main()");
}
}
class Test{
int x,y;
Test(int a, int b){
x=a;
y=b;
System.out.println(x value: +x);
System.out.println(y value: +y);
}
}
class PConDemo{
public static void main(String args[]){
Test t=new Test(10,20);
System.out.println(PConDemo:main()");
}
}
09/05/16
Methods
General Form:
type name(parameter-list) {
// body of method
}
The type of data returned by a method must be
compatible with the return type specified by the
method.
The variable receiving the value returned by a
method must also be compatible with the return
type specified for the method.
return value;
//Here, value is the value returned.
Ex:
double volume(double w, double h, double d) {
return w*h*d;
}
OOPs through Java -- Dr.K.Sasi 09/05/16
Methods
09/05/16
Types of Methods
Instance Method
Static Method
Instance Method: that act on the instance
variables of the class. Use with object form :
objectname.methodname( );
Static methods dont act upon the instance variables
of a class.
because the JVM first executes static methods
and then only it creates objects.
Declared with static.
Static methods are called using
classname.methodname().
09/05/16
class sample
{
static double sum(double num1, double num2);
{
double res = num1+num2;
return res;
}
}
class smethodex
{
public static void main(String args[])
{
double x = sample.sum(10,23.45);
System.out.println(Sum=+x);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
class class1 {
static String name;
int age;
void printdata()
System.out.println("Name:"+ name);
System.out.println("age:"+ age);
}}
class classex
{
public static void main(String args[])
{
class1 c = new class1();
class1 c1 = new class1();
c.name = ramu";
c.age =20;
c1.name = "anil";
c1.age = 22;
c.printdata();
c1.printdata();
} }
09/05/16
class test
{
static {
System.out.println(From static block);
}
public static void main(String args[ ])
{
System.out.println(From static method);
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
class BoxDemo6{
public static void main(String args[]){
Box mybox1=new Box();
Box mybox2=new Box();
double vol;
Box(){
width=10;
height=10;
depth=10;
}
double volume(){
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
return width*height*depth; }
vol=mybox2.volume();
System.out.println("Volume is: "+vol);
}
}
}
09/05/16
Parameterized Constructor
class Box{
double width;
double height;
double depth;
class BoxDemo7{
public static void main(String args[]){
Box mybox1=new Box(10,20,15);
Box mybox2=new Box(3,6,9);
double vol;
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
vol=mybox2.volume();
System.out.println("Volume is: "+vol);
}
}
09/05/16
Defining two or more methods with the same name and within the
same class is called method overloading.
09/05/16
class OverloadDemo {
//method overloading
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
class Overload {
}
public static void main(String args[]) {
}
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
} OOPs through Java -- Dr.K.Sasi 09/05/16
//Constructor Overloading
this
In java, it is illegal to declare two local variables with the same name inside
the same or enclosing scopes.
But you can have formal parameters to methods, which overlap with the names
of the class instance variables.
this can be used to resolve any name collisions that might occur between
instance variables and formal variables.
When a formal variable has the same name as an instance variable, the formal
variable hides the instance variable.
09/05/16
Output:
Volume is:6.0
09/05/16
Parameter Passing
09/05/16
// pass an object
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
09/05/16
Recursion
Recursion
is the process
something in terms of itself.
of
defining
09/05/16
class Factorial{
int fact(int n){
int result;
if(n==1)
return 1;
else
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
09/05/16
Garbage Collection
System.gc();
09/05/16
System.gc();
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
finalize( ) method
09/05/16
String
Once a String object has been created, we can not change the characters that
comprise in the string.
Strings are unchangeable once they are created so they are called as
immutable.
You can still perform all types of string operations. But, a new String object
is created that contains the modifications. The original string is left
unchanged.
09/05/16
Creating Strings
String s;
s = Hello;
String s = Hello;
We can create an object to String class by allocating
memory using new operator.
09/05/16
String Handling
String
Once an object is created, no modifications can be done on that.
StringBuffer
Modifications can be allowed on created object.
StringTokenizer
Used to divide the string into substrings based on tokens.
09/05/16
String Constructors
String(char chars[])
String(String strobj)
09/05/16
String Constructors
String(char chars[])
//To create a string initialized by an array of characters.
String str = "abcd"; is equivalent to
char chars[]={a,b,c,d};
String s=new String(chars);
String( char chars[], int startIndex, int numChars) //To create a string by specifying
positions from an array of characters
char chars[]={a,b,c,d,e,f};
String s=new String(chars,2,3); //This initializes s with characters cde.
String(String str);
//Construct a string object by passing another string object.
String str = "abcd";
String str2 = new String(str);
09/05/16
class MakeString {
class SubStringCons {
public static void main(String args[])
Output:
Output:
Java
Java
ABCDEF
CDE
OOPs through Java -- Dr.K.Sasi
09/05/16
String Length
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
//it returns 3.
09/05/16
09/05/16
09/05/16
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
// concatenate Box object
System.out.println(b);
// convert Box to string
System.out.println(s);
}
}
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
09/05/16
Character Extraction
char charAt(int where)
//To extract a single character from a String
char ch;
ch = "abc".charAt(1);
//assigns the value b to ch.
void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)
//to extract more than one character at a time.
byte[ ] getBytes( )
//to store the characters in an array of bytes and it
uses the default character-to-byte conversions
provided by the platform.
//String source=hi+how+are+you.
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the
getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println (buf);
}
}
Here is the output of this program: demo
09/05/16
class GetBytesDemo{
public static void main(String[] args){
String str = "abc + ABC;
byte[] b = str.getBytes();
//char[] c=str.toCharArray();
System.out.println(str);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+" ");
//System.out.print(c[i]+" ");
}
}
}
Output:
97
98
99
65
66
//a
b
c
A
B
67
C
09/05/16
String Comparison
System.out.println(s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
true
false
false
true
09/05/16
String Comparison
09/05/16
String Comparison
class RegionTest{
public static void main(String args[]){
String str1 = "This is Test";
String str2 = THIS IS TEST";
if(str1.regionMatches(5,str2,5,3)) {
// Case, pos1,secdString,pos1,len
System.out.println("Strings are Equal");
}
else{
System.out.println("Strings are NOT Equal");
}
}
}
Output:
Strings are NOT Equal
OOPs through Java -- Dr.K.Sasi
09/05/16
String Comparison
boolean startsWith(String str, int startIndex) //to specifies the index into
the invoking string at which point the search will begin.
Ex: "Football".startsWith("ball", 4) returns true.
equals( ) Versus ==
// It compares the characters inside a String object
//To compare two object references to see whether they refer to the same
instance.
OOPs through Java -- Dr.K.Sasi 09/05/16
String Comparison
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
//String s2 = s1;
System.out.println(s1.equals(s2));
System.out.println( s1 == s2);
}
}
Output:
true
false
OOPs through Java -- Dr.K.Sasi
09/05/16
String Comparison
Meaning
The invoking string is less than str.
The invoking string is greater than str.
The two strings are equal.
09/05/16
String Comparison
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now
aid
all
come
country
the the
their
time
to
to
for
good
is
09/05/16
men
of
Searching Strings
indexOf( )
//Searches for the first occurrence of a character or substring.
lastIndexOf( ) //Searches for the last occurrence of a character or substring.
int indexOf(int ch)
//To search for the first occurrence of a character.
int lastIndexOf(int ch) //To search for the last occurrence of a character.
int indexOf(String str) //To search for the first or last occurrence of a substring.
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
In all cases, the methods return the index at which the character or substring
was found, or 1 on failure.
OOPs through Java -- Dr.K.Sasi
09/05/16
}
}
09/05/16
Modifying a String
String substring(int startIndex)
//To extract a substring, startIndex specifies the beginning index
String substring(int startIndex, int endIndex)
// Here endIndex specifies the stopping point.
//endIndex-1
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String result = org.substring(0, 2);
System.out.println(result);
}
}
Output:
Th
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
09/05/16
StringBuffer
09/05/16
StringBuffer Constructors
StringBuffer( )
// The default constructor (the one with no parameters)
reserves room for 16 characters without reallocation.
StringBuffer(int size)
// accepts an integer argument that explicitly sets the size
of the buffer.
StringBuffer(String str)
// str + reserves room for 16 more characters without
reallocation.
09/05/16
Methods
09/05/16
int length( ) //The current length of a StringBuffer can be found via the length( ) method
int capacity( ) //The total allocated capacity can be found through the capacity( ) method.
09/05/16
void setLength(int len) //To set the length of the buffer within a StringBuffer object.
char charAt(int where)
//The value of a single character can be obtained from a StringBuffer via
the charAt( ) method.
void setCharAt(int where, char ch)
//To set the value of a character, ch specifies the new value of that character.
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
}
}
Output:
buffer before = Hello
System.out.println("charAt(1) after = " + sb.charAt(1)); charAt(1) before = e
buffer after = Hi
charAt(1) after = i
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
// Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
Output:
a = 42!
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
StringBuffer reverse( )
// reverse the characters within a StringBuffer object using reverse( )
// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
OOPs through Java -- Dr.K.Sasi
09/05/16
09/05/16
09/05/16
object.
StringTokenizer
To use StringTokenizer
Specify an input string and a delimiter string.
09/05/16
StringTokenizer Constructors
StringTokenizer(String str)
Methods
int countTokens( )
//returns number of tokens in the string.
boolean hasMoreTokens( ) //checks whether tokens are there or
not
String nextToken( )
//returns the token in the string
OOPs through Java -- Dr.K.Sasi
09/05/16
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo{
//static String str = "Hello Welcome to Java Programming";
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
//StringTokenizer st = new StringTokenizer(str);
//StringTokenizer st = new StringTokenizer(str,",");
StringTokenizer st = new StringTokenizer(str,",",true);
while(st.hasMoreTokens()) {
String tokens = st.nextToken();
System.out.println(tokens + "\n");
}
}
}
OOPs through Java -- Dr.K.Sasi
09/05/16
Output:
Hello
,
Welcome
,
to
,
Java
,
Programming
Exercise1:
Write a java program that reads a line of integers and
then displays each integer and find the sum of the
integers (using StringTokenizer)
09/05/16
import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+is: "+sum);
}
}
Output:
Enter sum of integers: 10+20+30+40
Sum of 10+20+30+40 is: 100
09/05/16