Java contains plenty of built in packages. A package is similar to the header file in ‘C’ and ‘C++’. They contain a host of built in classes and interfaces. To include a built in package into your program you can use the ‘ import’.
General format: import package_name;
Examples:
- import java.lang.*; imports all the classes from the package “java.lang”.
- import java.lang.string; imports just class string from the package “java lang”.
java.lang
- String class: Allows you to manipulate with strings in java.
Constructors:
- String(); Construct an empty string object.
- String(char array[]); Constructs a string object for the contents of a character array.
- String(char array[], int start_index, int numchars); Constructs a string object from the partial contents of a character array.
- String(String str); Constructs a string object from another string object.
import java.lang.*;
class App30
{
public static void main(String yck[])
{
String s1=new String();
char x[]={'C','H','A','I','T','A','N','Y','A'};
String s2=new String(x);
String s3=new String(x,2,5);
String s4=new String(s2);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
output:
\>javac App30.java
\>java App30
CHAITANYA
AITAN
CHAITANYA
import java.lang.*;
class App31
{
public static void main(String yck[])
{
String s=new String("CHAITANYA");
int len;
len=s.length();
System.out.println("Length of the String is = "+len);
}
}
output:
\>javac App31.java
\>java App31
Length of the String is = 9
char charAt(int where); Returns the character at a specified position.
import java.lang.*;
class App32
{
public static void main(String yck[])
{
String s=new String("CHAITANYA");
char ch=s.charAt(2);
System.out.println(ch);
}
}
output:
\>javac App32.java
\>java App32
A
import java.lang.*;
class App33
{
public static void main(String yck[])
{
String s=new String("CHAITANYA");
char x[]=new char[s.length()];
s.getChars(0,3,x,3);
System.out.println(s);
for(int i=0;i System.out.println(x[i]);
}
}
output:
\>javac App33.java
\>java App33
CHAITANYA
C
H
A
char[] toCharArray(); Converts the contents of the entire string object into a character array.
import java.lang.*;
class App34
{
public static void main(String yck[])
{
String s=new String("CHAITANYA");
char x[]=s.toCharArray();
System.out.println(s);
System.out.println(x);
for(int i=0;i System.out.println(x[i]);
}
}
output:
\>javac App34.java
\>java App34
CHAITANYA
CHAITANYA
C
H
A
I
T
A
N
Y
A
