string is one of mostly used object in java. and this is · string is one of mostly used object in...
TRANSCRIPT
String is one of mostly used Object in Java. And this is
the reason why String has unique handling in
Java(String Pool).
The String class represents character strings.
All string literals in Java programs, such as “abc”, are
implemented as instances of this class.
Strings are like constants, once created its value can
not be changed or shared i.e. immutable
String Buffer and String Builder can be used in place of
String if lot of String Operation is to be performed.
String Creation
• String str = new String("Welcome to MSRIT");
• String srt1 = "CSE";
• String s = new String( );
Important Methods
1.intern()
2.length()
3.toString()
4.trim
4
Do not use message[0]
Use message.charAt(index)
Index starts from 0
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.charAt(0) message.charAt(14) message.length() is 15
5
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5
is same as(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
6
You can extract a single character from astring using the charAt method. You can alsoextract a substring from a string using thesubstring method in the String class.
String s1 = "Welcome to Java";String s2 = s1.substring(0, 11) + "HTML";
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.substring(0, 11) message.substring(11)
7
Output:s1 == s2 is false
s1 == s3 is true
A new object is created if you use the new operator.
If you use the string initializer, no new object is created if the interned object is already created.
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));
: String
Interned string object for
"Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
s3
8
java.lang.String
+equals(s1: String): boolean
+equalsIgnoreCase(s1: String):
boolean
+compareTo(s1: String): int
+compareToIgnoreCase(s1: String):
int
+regionMatches(toffset: int, s1: String,
offset: int, len: int): boolean
+regionMatches(ignoreCase: boolean,
toffset: int, s1: String, offset: int,
len: int): boolean
+startsWith(prefix: String): boolean
+endsWith(suffix: String): boolean
Returns true if this string is equal to string s1.
Returns true if this string is equal to string s1 case-
insensitive.
Returns an integer greater than 0, equal to 0, or less than 0
to indicate whether this string is greater than, equal to, or
less than s1.
Same as compareTo except that the comparison is case-
insensitive.
Returns true if the specified subregion of this string exactly
matches the specified subregion in string s1.
Same as the preceding method except that you can specify
whether the match is case-sensitive.
Returns true if this string starts with the specified prefix.
Returns true if this string ends with the specified suffix.
9
java.lang.String
+toLowerCase(): String
+toUpperCase(): String
+trim(): String
+replace(oldChar: char,
newChar: char): String
+replaceFirst(oldString: String,
newString: String): String
+replaceAll(oldString: String, newString: String): String
+split(delimiter: String):
String[]
Returns a new string with all characters converted to lowercase.
Returns a new string with all characters converted to uppercase.
Returns a new string with blank characters trimmed on both sides.
Returns a new string that replaces all matching character in this
string with the new character.
Returns a new string that replaces the first matching substring in
this string with the new substring.
Returns a new string that replace all matching substrings in this string with the new substring.
Returns an array of strings consisting of the substrings split by the
delimiter.
10
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME.
" Welcome ".trim() returns a new string, Welcome.
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string,
WABlcome.
"Welcome".replace("e", "AB") returns a new string,
WABlcomAB.
"Welcome".replace("el", "AB") returns a new string,
WABlcome.String Split:
String[] tokens = "Java#HTML#Perl".split("#", 0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
We use primitive data types char to work with
characters.
Java provides wrapper class Character for primitive
data type char.
If you pass a primitive char into a method that expects
an object, the compiler automatically converts the char
to a Character for you. This feature is called autoboxing
or unboxing for the reverse.
You can create a Character object
with the Character constructor:
Character ch = new Character('a');
12
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('x') returns -1.
"Welcome to Java".indexOf('o', 5) returns 9.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns
11."Welcome to Java".indexOf("java", 5) returns -1.
"Welcome to Java".lastIndexOf('a') returns 14.
13
The String class provides several staticvalueOf methods for converting a character,an array of characters, and numeric valuesto strings. These methods have the samename valueOf with different argument typeschar, char[], double, long, int, and float. Forexample, to convert a double value to astring, use String.valueOf(5.44). The returnvalue is string consists of characters ‘5’, ‘.’,‘4’, and ‘4’.
14
java.lang.Character
+Character(value: char)
+charValue(): char
+compareTo(anotherCharacter: Character): int
+equals(anotherCharacter: Character): boolean
+isDigit(ch: char): boolean
+isLetter(ch: char): boolean
+isLetterOrDigit(ch: char): boolean
+isLowerCase(ch: char): boolean
+isUpperCase(ch: char): boolean
+toLowerCase(ch: char): char
+toUpperCase(ch: char): char
Constructs a character object with char value
Returns the char value from this object
Compares this character with another
Returns true if this character equals to another
Returns true if the specified character is a digit
Returns true if the specified character is a letter
Returns true if the character is a letter or a digit
Returns true if the character is a lowercase letter
Returns true if the character is an uppercase letter
Returns the lowercase of the specified character
Returns the uppercase of the specified character
length: It is a final variable and only applicable
for array. It represent size of array.
length(): It is a final method applicable only for
String objects. It represent number of character
present in String. int[] a=new int[10];
System.out.println(a.length); // 10
String s="Java";
System.out.println(s.length()); // 4
System.out.println(a.length()); // Compile time error
System.out.println(s.length); // Compile time error
Implementing toString method in java is done by
overriding the Object’s toString method. The java
toString() method is used when we need a string
representation of an object.
toString() method is a special method that can be
defined in any class. This method should return a String
argument.
If you print any object, java compiler internally invokes
the toString() method on the object.
The advantage is : by overriding the toString() method
of the Object class, we can return values of the object,
so we don't need to write much code.
without toString() method With Java toString() method
class Student
{
int rollno;
String name;
Student(int rollno, String name)
{
this.rollno=rollno;
this.name=name;
}
public static void main(String args[])
{
Student s1=new Student(101,"Raj”);
Student s2=new Student(102,"Vijay”);
System.out.println(s1.rollno+” “+s1.name);
//compiler writes here s1.toString()
System.out.println(s2.rollno+” “+s2.name);
//compiler writes here s2.toString()
}
}
class Student1{
int rollno;
String name;
Student1(int rollno, String name){
this.rollno=rollno;
this.name=name;
}
//overriding the toString() method
public String toString()
{
return rollno+" "+name+" ";
}
public static void main(String args[])
{
Student1 s1=new Student1(101,"Raj");
Student1 s2=new Student1(102,”Tej");
System.out.println(s1);
//compiler writes here s1.toString()
System.out.println(s2);
//compiler writes here s2.toString()
}
}
Packages can be stated to be a group of related classes.They are just like folders on your computer and the classeswithin these packages are like the files contained in
folders. Packages in Java are the way to organize files when a project
has many modules. All we need to do is put related class files in the same
directory, give the directory a name that relates to thepurpose of the classes, and add a line to the top of eachclass file that declares the package name, which is the sameas the directory name where they reside.
In java there are already many predefined packages that we use while programming.
For example: java.lang, java.io, java.util etc.However one of the most useful feature of java is that we can define our own packages
Reusability: Reusability of code is one of themost important requirements in the softwareindustry. Reusability saves time, effort and alsoensures consistency. A class once developed canbe reused by any number of programs wishingto incorporate the class in that particularprogram.
Easy to locate the files. In real life situation there may arise scenarios
where we need to define files of the same name.This may lead to “name-space collisions”.Packages are a way of avoiding “name-spacecollisions”.
Right Click on Project ->New->Package Name the package as ‘mypack’
Right Click on mypack & create class ‘A’ as A.java
Steps to create a simple package in Java
1. Create Hello class outside the mypack package as Hello.java
2. Right Click on project-> New->Class->Hello
3. Do not forget to remove ‘mypack’ in Packages tab and leave blank to
default, as it is outside the package.
Import above class in below program using import packageName.className
Run Hello.java the out put is
Steps to create a simple package in Java
You can use import mypack.* to import all
the modules in the package, but this
should be avoided.
At most one package declaration can appear ina source file.
The package declaration must be the firststatement in the unit.
Choose an appropriate class name or interfacename and whose modifier must be public.
Any package program can contain only onepublic class or only one public interface but itcan contain any number of normal classes.
Package program should not contain any mainclass (i.e., it should not contain any main())
Every package program should be save eitherwith public class name or public Interface name
Difference between Inheritance and package• Inheritance concept always used to reuse the feature
within the program between class to class, interfaceto interface and interface to class but not accessingthe feature across the program.
• Package concept is to reuse the feature both withinthe program and across the programs between classto class, interface to interface and interface to class.
Difference between package keyword and importkeyword• Package keyword is always used for creating the
undefined package and placing common classesand interfaces.
• import is a keyword which is used for referring orusing the classes and interfaces of a specificpackage.
Access modifiers help you set the level of access youwant for your Class, variables as well as Methods.
These are used to where to access and where not toaccess the data members or methods.
In java programming these are classified into fourtypes:
• Default- Visible to the package. the default. No modifiers are needed.
• Private - Visible to the class only .
• Public - Visible to the world .
• Protected - Visible to the package and all subclasses.
If we are not using private protected and publickeywords then JVM is by default taking as defaultaccess modifiers.
private: private members of class in not accessible any
where in program these are only accessible within the
class. private are also called class level access modifiers.
public: public members of any class is accessible any
where in program inside the same class and outside of
class, within the same package and outside of the
package. public are also called universal access
modifiers.
protected: protected members of class is accessible
within the same class and other class of same package
and also accessible in inherited class of other package.
protected are also called derived level access modifiers.
default: default members of class is accessible only
within same class and other class of same package.
default are also called package level access modifiers.
package mypack;
class Hello
{
private int a=20;
public int b=20;
private void show()
{ System.out.println("Hello java"); }
public void disp()
{ System.out.println("Welcome to java"); }
protected void showdata()
{ System.out.println("Protedted: Hello Java"); }
}
public class Demo {
public static void main(String args[]) {
Hello obj=new Hello();
//System.out.println(obj.a); //Compile Time Error, you can't access private data
//obj.show(); //Compile Time Error, you can't access private methods
System.out.println(obj.b); // Okay
obj.disp(); // Okay
obj.showdata(); // okay if it is in the same package
} }
Example -1
Perform the following String handling exercises usingpackages (write a menu driven program )
1. Write a program to count and display the number of times thatthe entered character appears in the string.
2. Write a program that counts the number of occurrence of eachletter in a string.
3. Write a program to count number of words contained in thestring.
4. Write a program to reverse a string and check whether string isa Palindrome or not
Write a program that will perform binary operations onintegers. The program receives three parameters: anoperator and two integers. Take input from command linearguments. E.g input : 2 + 3, output : 5
Create a package named Shapes. Create some classes in thepackage representing areas of some common geometricshapes like Square, Triangle, rectangle, Circle.